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#![warn(clippy::pedantic)]
6// Three pedantic lints this crate declines, with the reason for each.
7// Everything else pedantic reported is fixed rather than allowed.
8//
9// `items_after_statements`: a local helper type or fn declared next to
10// the statement that uses it reads better than one hoisted to the top
11// of a long function. Two sites, both DER/serde helpers.
12//
13// `needless_pass_by_value`: `SignatureVerifier::verify_signature` takes
14// `SubjectPublicKeyInfoRef<'_>` by value because it is already a borrow
15// wrapper -- `&SubjectPublicKeyInfoRef` would be a reference to a
16// reference -- and the signature belongs to the trait, so changing it
17// breaks every implementor. `TrustAnchor::from_cert` takes an owned
18// `Certificate` deliberately, as the counterpart to `from_cert_ref`.
19//
20// `match_same_arms`: arms stay one-per-case where the cases are what is
21// being audited. `Utf8Chars::next` has one arm per row of Unicode
22// Table 3-7, with the surrogate exclusion (`0xED`) sitting between two
23// arms that would otherwise merge -- collapsing them would destroy the
24// row-by-row correspondence that makes the decoder checkable against
25// the table. `anchor_profile_deviation` keeps an `Err(_)` arm its own
26// comment calls unreachable, and `AnchorCrlSign` keeps "parsed but not
27// asserted" separate from "malformed" because both failing closed is a
28// statement worth being able to see.
29#![allow(clippy::items_after_statements)]
30#![allow(clippy::needless_pass_by_value)]
31#![allow(clippy::match_same_arms)]
32// Documentation links to `DefaultVerifier`, which needs at least one
33// signature backend enabled. With none of them the item does not exist,
34// so the link cannot resolve and `cargo doc` on a consumer's own
35// feature selection reports an error.
36//
37// Allowing the lint only where it cannot tell a gated item from a
38// mistake loses no signal: a mistyped link is broken with every feature
39// enabled too, and the all-features doc build is what the quality gate
40// runs under RUSTDOCFLAGS=-D warnings. Demoting the links to code spans
41// instead would cost every docs.rs reader a working link, to spare a
42// configuration nobody publishes documentation from.
43// `RsaPssVerifier` and `RsaPkcs1v15Sha1Verifier` are gated on `rsa`,
44// and `rsa` is itself one of the features that brings `DefaultVerifier`
45// into existence — so every link in this crate's docs resolves exactly
46// when `rsa` is on, and the five-feature condition this replaced was
47// both wider than needed and, for a single-signature-feature build like
48// `--features p256`, not wide enough.
49#![cfg_attr(not(feature = "rsa"), allow(rustdoc::broken_intra_doc_links))]
50//! RFC 5280 X.509 certificate path validation — pure Rust, `no_std`.
51//!
52//! Implements certificate path building and validation per
53//! [RFC 5280 §6](https://www.rfc-editor.org/rfc/rfc5280#section-6).
54//!
55//! # Architecture
56//!
57//! Cryptographic signature verification is pluggable via [`SignatureVerifier`].
58//! The default feature set wires in `RustCrypto` backends for RSA
59//! (PKCS#1 v1.5 and RSASSA-PSS with SHA-256/384/512; `rsa` feature) and
60//! ECDSA on P-256 (`p256` feature). The optional `p384`, `p521` and
61//! `ed25519` features add ECDSA on P-384 and P-521 and Ed25519;
62//! `rustcrypto` enables all of them. [`DefaultVerifier`] dispatches over
63//! whatever is enabled, taking the ECDSA curve from the issuer's key.
64//! For FIPS-validated crypto, implement [`SignatureVerifier`] against
65//! `wolfcrypt-rustcrypto` and disable the `rustcrypto` feature.
66//!
67//! Revocation checking is handled by `pkix-revocation`. This crate never
68//! touches the network — use `pkix_chain::verify_chain` for the combined API.
69//!
70//! [`validate_path`] takes anything implementing [`PathCertificate`], which
71//! is how it gets the bytes an issuer signed. Hand it
72//! [`CertificateWithDer`] and the signed message is a subslice of the
73//! certificate's own DER; hand it a bare [`Certificate`] and the message is
74//! rebuilt by re-encoding the parse, which is slower and correct only while
75//! the encoder is byte-faithful for every field — an assumption that has
76//! already failed once, for pre-2050 `GeneralizedTime` validity dates. Any
77//! caller who still has the bytes should pass them; see [`tbs_der_slice`].
78//!
79//! # Scope: what §6.1 asks, and what it does not
80//!
81//! §6.1 is an algorithm over the certificates in a path: it maintains a
82//! working issuer name, public key and policy state, and checks each
83//! certificate against that state. It does not ask whether any
84//! certificate *conforms* to §4.1 and §4.2, the sections that tell a CA
85//! how to issue one.
86//!
87//! So a rule of the form "conforming CAs MUST …" is generally **not**
88//! enforced here. A certificate missing the `subjectKeyIdentifier` that
89//! §4.2.1.2 requires of every conforming CA certificate validates, as
90//! does one whose `commonName` is not a character-for-character copy of a
91//! `dNSName` in its `subjectAltName`, which CA/B Forum BR 7.1.4.3
92//! requires. Those rules are real; they belong to `pkix-lint` (the RFC
93//! 5280 profile) and `pkix-lint-cabf` (the CA/B Forum Baseline
94//! Requirements), which exist to check exactly this and can report every
95//! finding on a certificate rather than stopping at the first.
96//!
97//! Rejecting a chain because its issuer broke an issuance rule is doing
98//! lint work inside path validation, and it costs something real: the
99//! caller learns "this chain is invalid" when the truth is "this
100//! certificate is non-conforming in a way that does not affect whether
101//! the chain is valid". Those want different responses.
102//!
103//! ## "Belongs to the lint layer" is now also where it is
104//!
105//! Stated plainly, because the sentence above is easy to read as a
106//! promise that something else here catches these: **it does, for all
107//! 33.** Each has an owning lint in `pkix-lint` or `pkix-lint-cabf` that
108//! fires on it, out of an implemented catalogue of 27 lints.
109//!
110//! The thirty-third was added last, and the order is worth recording.
111//! `webpki::explicit-curve` is an EC key conveyed as an X9.62
112//! `SpecifiedECDomain` instead of a `namedCurve` OID -- which CA/B Forum
113//! BR 7.1.3.1.2 forbids and RFC 5480 §2.1.1 permits, so this crate reads
114//! it deliberately and the refusal belongs to the forum layer. For a
115//! while nothing there implemented it: the entry was classified as the
116//! lint layer's while `pkix-lint-cabf` had no `namedCurve` check, making
117//! "belongs to the lint layer" mean nothing checked it. `PKIX-mxj4`
118//! wrote `cabf.br.tls.spki.ec_named_curve`, and Mark's call was to write
119//! it before the release rather than ship the gap.
120//!
121//! The count read 32 of 32 before that entry existed at all, which looks
122//! like a regression and is not one. The row had been a ground-truth
123//! disagreement with no ledger entry ever since this crate gained
124//! `specifiedCurve` support, because a committed baseline was not
125//! regenerated when the behaviour changed. Classifying it moved the
126//! denominator; writing the lint moved the numerator back.
127//!
128//! It was 4 of 32 when the claim was first measured, under `PKIX-x2gx`.
129//! 27 entries named a rule no lint here implemented and 1 named a lint
130//! that existed and missed its case; `PKIX-9kag` wrote the missing ones.
131//! The gap is recorded rather than quietly closed, because the stance
132//! above was asserted for some time before anyone checked it, and the
133//! check is the only reason it is true.
134//!
135//! What it still does not mean. It is not a claim about CA/B Forum
136//! conformance in general: 32 entries of one corpus is not the Baseline
137//! Requirements, and a consumer who needs that should run zlint or
138//! pkilint.
139//!
140//! The measurement is `pkix-difftest/lint-coverage.json`, re-derivable
141//! with `pkix-difftest lint-limbo --features lint-oracles`, and the
142//! per-entry table is in
143//! `pkix-difftest/disagreement-classification.md`. Three of the twelve
144//! lints are not the ones `PKIX-9kag` planned, because the plan named
145//! the wrong owning document or called a check unreachable that is not;
146//! the corrections are recorded next to the entries they apply to.
147//!
148//! This is measured, not asserted. Of the 37 chains where this crate
149//! currently disagrees with x509-limbo's expected result, 33 are this —
150//! CA/B Forum BR 7.1.4.3 (9), 6.1.5 key sizes (2), RFC 5280 §4.2.1.1 and
151//! §4.2.1.2 `authorityKeyIdentifier` and `subjectKeyIdentifier` (4),
152//! §4.2.1.6 `subjectAltName` shape (2), §4.2.1.10 `nameConstraints` in an
153//! end-entity certificate and degenerate encodings (4), leaf `keyUsage`
154//! and `basicConstraints` profile rules (3), and `authorityKeyIdentifier`
155//! treated as a path-building hint rather than a filter (6). Each is
156//! classified with its rule named in
157//! `pkix-difftest/disagreement-classification.md`.
158//!
159//! ## Three places the line is drawn the other way
160//!
161//! "§6.1 does not ask for it" is a reason, not a licence, and these are
162//! the cases that show where it stops being one. Each enforces something
163//! §6.1 does not mention, and each was a real defect found by reading the
164//! corpus disagreements rather than by reasoning from the specification.
165//!
166//! 1. **The trust anchor is validated.** §6.1 treats the anchor as a
167//! trusted input and never examines its extensions or its validity
168//! dates. This crate checks both, reporting [`AnchorDefect`] — because
169//! "the operator chose this anchor" is a decent argument for ignoring
170//! its contents and a poor one for ignoring its expiry, and a trust
171//! store is precisely where an expired or malformed root sits
172//! unnoticed for years.
173//!
174//! 2. **A CA's `extendedKeyUsage` constrains what it may issue.** §6.1
175//! has no EKU step at all. Without this, a CA restricted to
176//! `emailProtection` could issue a TLS server certificate and the
177//! chain would validate, which is the cross-purpose confusion EKU on a
178//! CA exists to prevent. See [`ValidationPolicy::enforce_ca_eku`].
179//!
180//! 3. **A CA certificate must have a non-empty subject.** This one *is*
181//! an issuance MUST — §4.1.2.6 — and it is enforced anyway, because it
182//! changes what §6.1 itself computes: §6.1.3(a)(4) chains a
183//! certificate to its issuer by comparing distinguished names, and an
184//! empty name compares equal to an empty name. An unnamed CA therefore
185//! issues certificates that chain to *any* unnamed CA, and name
186//! chaining stops distinguishing issuers.
187//!
188//! ## The test, stated so it can be applied again
189//!
190//! Does the non-conformance change what §6.1 computes, or create a
191//! confusion §6.1's state machine cannot see? If so it is this crate's
192//! problem, wherever the requirement happens to be written down. If it is
193//! non-conformance with no effect on the algorithm's output, it is the
194//! linter's.
195//!
196//! Stated that way because the shorter version — "path validation does
197//! not enforce issuance-profile MUSTs" — is the formulation that would
198//! have licensed all three cases above. Two of them were live defects
199//! when that stance was first proposed.
200//!
201//! # Limitations
202//!
203//! The following are **not** currently implemented:
204//! - **`UTCTime` before 1970.** The supported range is **1970-2049**,
205//! where RFC 5280 §4.1.2.5.1 allows 1950-2049. A certificate whose
206//! `notBefore` or `notAfter` falls in the missing twenty years is
207//! refused, and refused at the DER layer — the error reads "malformed
208//! ASN.1 DER value for `UTCTime`" and comes back before validation runs.
209//!
210//! This is a deliberate scope decision, not an accident. The floor is
211//! the Unix epoch because `der` 0.8 puts it there ("due to common
212//! operations working on `UNIX_EPOCH`, `UtcTime`s are only supported
213//! for the years 1970-2049"), and lifting it would mean forking the DER
214//! layer every consumer of this crate depends on. No conforming CA
215//! issues certificates dated before 1970, so the trade is a fork of a
216//! foundational dependency against twenty years of dates nobody uses.
217//!
218//! It is fail-closed: such a certificate is refused, never misread.
219//! OpenSSL does read them, so expect a genuine disagreement rather than
220//! a difference of strictness — NIST PKITS §4.2.3 "Valid pre2000 UTC
221//! notBefore Date Test3" is exactly this shape, and is the one PKITS
222//! vector this crate does not evaluate.
223//! - **Legacy SHA-1** — shipped, but behind `rsa-sha1` and `ecdsa-sha1`,
224//! which are deliberately outside `default` and outside the
225//! `rustcrypto` umbrella: that umbrella means "algorithms we
226//! recommend" and these are not. Verification only; nothing here
227//! signs with SHA-1. RSA moduli outside 1024–8192 bits are refused by
228//! the bundled RSA backend.
229//! - **DSA** — not implemented. The recorded stance is verify-only and
230//! opt-in, following FIPS 186-5, which retains DSA "only for the
231//! purposes of verifying existing signatures"; a chain issued under
232//! DSA before it was retired either verifies or it does not, and
233//! saying which is more useful than refusing to look. When it lands
234//! it will sit outside `default` and outside `rustcrypto`, as the
235//! SHA-1 features do. Until then such a certificate is refused as an
236//! unsupported algorithm, never misread. NIST PKITS `4.1.4` and
237//! `4.1.5` are the two vectors this affects, and RFC 3279 §2.3.2
238//! domain-parameter inheritance is the awkward half of `4.1.5`.
239//! - **RFC 4518 full Unicode NFKC DN normalization** — ASCII case-folding
240//! plus insignificant-whitespace collapsing is applied. `BMPString` AVA
241//! values are transcoded UCS-2-BE → UTF-8 and then compared via the same
242//! ASCII-only normalization pipeline, so two AVAs that share Unicode
243//! code points but differ only in DER string-type (e.g. `BMPString`
244//! "Foo Co" vs `UTF8String` "Foo Co") compare equal. Full RFC 4518 prep
245//! (NFKC, non-ASCII Unicode case fold, prohibit/bidi steps) is future
246//! work tracked under `PKIX-l63j`; until it lands, two `BMPString` values
247//! that contain the same Unicode code points but differ in canonical
248//! decomposition (e.g. precomposed U+00E9 'é' vs decomposed U+0065 U+0301
249//! 'e'+ combining acute) compare unequal. `UniversalString` AVA values
250//! are rejected by the `der` crate at parse time (tag 0x1C is not in
251//! `der::Tag`, in 0.8 as in 0.7) and never reach the path validator.
252//! `NumericString` AVAs go through the same ASCII pipeline: X.680 limits
253//! the type to digits and space, and LDAP's `numericStringMatch`
254//! (RFC 4517 §4.2.22) prescribes the same preparation. `TeletexString`
255//! AVAs go through it only when every octet lies in the ISO 646
256//! invariant set, where T.61 and ASCII cannot disagree; outside that —
257//! a non-spacing diacritic at 0xC0–0xCF, or one of the twelve
258//! nationally-variable positions — they fall back to raw DER byte
259//! comparison, because `pkix-path` deliberately does not transcode T.61
260//! to Unicode. See `teletex_is_iso646_invariant` for where the line sits
261//! and why.
262//! - **`privateKeyUsagePeriod` (2.5.29.16)** — not processed. RFC 3280
263//! deprecated it and RFC 5280 dropped it from the profile, so a CA
264//! asserting a key-usage window narrower than the certificate's own
265//! validity is saying something this crate does not enforce. It is
266//! common in the wild rather than vestigial: 495 of the 609 ePassport
267//! CSCA certificates vendored under `third_party/trust-stores/` carry
268//! it, as do two Russian national roots that declare an eight-year key
269//! window inside an eighteen-year certificate.
270//!
271//! It is non-critical in every one of those, which is why none is
272//! refused — a critical instance would hit the §6.1.4 rule and come
273//! back as [`AnchorDefect::UnhandledCriticalExtension`], correctly but
274//! to the surprise of anyone whose root suddenly stopped loading. The
275//! corpus measuring the extension's presence is the early warning for
276//! that. A fractional-seconds `GeneralizedTime` inside one is also
277//! unreachable for the same reason; `tests/fractional_generalizedtime.rs`
278//! pins both halves.
279//! - **Path building** — converting an unordered bag of certificates into a
280//! validated chain is handled by `pkix-path-builder`. This crate validates
281//! a caller-ordered `&[Certificate]` only.
282//! - **AIA fetching** — chains with missing intermediates are not
283//! reassembled from `AuthorityInfoAccess` URIs here. Callers supply a
284//! complete chain, or go through `pkix-chain`, which follows
285//! `caIssuers` URIs via `pkix-aia` / `pkix-aia-http` (`PKIX-zkjb`).
286
287// For no_std builds, pull in the alloc crate explicitly so `alloc::` paths
288// and the `vec!` macro resolve. `#[macro_use]` re-exports alloc macros
289// (vec!, format!, etc.) into the crate root, making them available everywhere
290// without qualifying them as `alloc::vec!(...)`.
291#[cfg(not(feature = "std"))]
292#[macro_use]
293extern crate alloc;
294
295// Unified Vec import: alloc::vec::Vec in no_std, std::vec::Vec under std.
296// Both map to the same concrete type; this alias lets the rest of the file
297// write `Vec<_>` without cfg-gating every use site.
298#[cfg(not(feature = "std"))]
299use alloc::vec::Vec;
300#[cfg(feature = "std")]
301use std::vec::Vec;
302// Same shape for `String`, used only by the RFC 4518 preparation tests,
303// which collect a `char` stream to compare it. Gated the same way and for
304// the same reason: `extern crate alloc` is no_std-only here, so naming
305// `alloc` directly fails whenever `std` is on.
306#[cfg(all(test, not(feature = "std")))]
307use alloc::string::String;
308#[cfg(all(test, feature = "std"))]
309use std::string::String;
310
311// Unified Cow import: same cfg-gate pattern as Vec. `Cow` is owned by
312// `alloc` but `std` re-exports it; we can't write `alloc::borrow::Cow`
313// unconditionally because `extern crate alloc` is gated to no_std mode.
314// Only the serde wire helper uses it (DN comparison is allocation-free).
315#[cfg(all(feature = "serde", not(feature = "std")))]
316use alloc::borrow::Cow;
317#[cfg(all(feature = "serde", feature = "std"))]
318use std::borrow::Cow;
319
320use der::Tagged;
321// Re-exported, not merely imported: both types appear in
322// `SignatureVerifier::verify_signature`'s signature, so an out-of-crate
323// implementor has to name them. Reachable only as `spki::...` they meant
324// reading this crate's source to discover the origin and taking a direct
325// dependency on a matching `spki` version to say it.
326pub use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
327pub use x509_cert::Certificate;
328
329/// Helper module for format-adaptive serde serialization of DER-encodable
330/// types. Public so downstream crates (`pkix-chain`, `pkix-revocation`,
331/// `pkix-truststore`) can reuse the same wire form on their own result
332/// types without redefining the helpers.
333#[cfg(feature = "serde")]
334#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
335pub mod serde_der;
336
337mod policy_graph;
338
339/// Recognizing an X9.62 `SpecifiedECDomain` as a named curve.
340///
341/// Public because every [`SignatureVerifier`] implementation needs it,
342/// not just the one in this crate: a backend built on wolfCrypt, or on
343/// a hardware token, reads an EC key's curve the same way and hits the
344/// same `specifiedCurve` form in the same certificates.
345pub mod specified_curve;
346
347/// brainpoolP512r1, implemented here for want of an upstream crate.
348///
349/// See the module docs: it is a stopgap, it is every German CSCA
350/// certificate, and it costs no new dependencies.
351#[cfg(feature = "bp512")]
352#[cfg_attr(docsrs, doc(cfg(feature = "bp512")))]
353pub mod brainpool_p512r1;
354
355/// brainpoolP224r1, implemented here for want of an upstream crate.
356///
357/// Two of Germany's CSCA document signers use it. Same recipe as
358/// [`brainpool_p512r1`], and the same stopgap status.
359#[cfg(feature = "bp224")]
360#[cfg_attr(docsrs, doc(cfg(feature = "bp224")))]
361pub mod brainpool_p224r1;
362
363/// GOST R 34.10 signature verification, implemented here for want of an
364/// upstream crate.
365///
366/// Its own signature equation, not ECDSA on another curve. See the
367/// module docs on why there was an argument against doing it and what
368/// replaced the missing oracle.
369#[cfg(feature = "gost")]
370#[cfg_attr(docsrs, doc(cfg(feature = "gost")))]
371pub mod gost_r3410;
372
373/// Ed521 (EdDSA over E-521), for one ICP-Brasil certificate.
374///
375/// **Read the module docs before enabling `ed521`.** It has no test
376/// vectors, no second implementation to check against, and one real
377/// signature exercising it. Not for general use.
378#[cfg(feature = "ed521")]
379#[cfg_attr(docsrs, doc(cfg(feature = "ed521")))]
380pub mod ed521;
381
382mod verification_error;
383pub use verification_error::{VerificationError, VerificationErrorKind};
384
385mod verifiers;
386#[cfg(any(
387 feature = "p256",
388 feature = "p384",
389 feature = "p521",
390 feature = "rsa",
391 feature = "ed25519"
392))]
393pub use verifiers::DefaultVerifier;
394#[cfg(feature = "p256")]
395pub use verifiers::EcdsaP256Verifier;
396#[cfg(feature = "p384")]
397pub use verifiers::EcdsaP384Verifier;
398#[cfg(feature = "p521")]
399pub use verifiers::EcdsaP521Verifier;
400#[cfg(feature = "ecdsa-sha1")]
401#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
402pub use verifiers::EcdsaSha1Verifier;
403#[cfg(feature = "ed448")]
404#[cfg_attr(docsrs, doc(cfg(feature = "ed448")))]
405pub use verifiers::Ed448Verifier;
406#[cfg(feature = "ed521")]
407#[cfg_attr(docsrs, doc(cfg(feature = "ed521")))]
408pub use verifiers::Ed521Verifier;
409#[cfg(feature = "ed25519")]
410pub use verifiers::Ed25519Verifier;
411#[cfg(feature = "gost")]
412#[cfg_attr(docsrs, doc(cfg(feature = "gost")))]
413pub use verifiers::GostR3410Verifier;
414#[cfg(feature = "ml-dsa")]
415#[cfg_attr(docsrs, doc(cfg(feature = "ml-dsa")))]
416pub use verifiers::MlDsa87Verifier;
417#[cfg(feature = "rsa-ripemd160")]
418#[cfg_attr(docsrs, doc(cfg(feature = "rsa-ripemd160")))]
419pub use verifiers::RsaPkcs1v15Ripemd160Verifier;
420#[cfg(feature = "rsa-sha1")]
421#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
422pub use verifiers::RsaPkcs1v15Sha1Verifier;
423#[cfg(feature = "sm2")]
424#[cfg_attr(docsrs, doc(cfg(feature = "sm2")))]
425pub use verifiers::Sm2WithSm3Verifier;
426/// Reading an RSA public key whose DER INTEGERs are not minimal, and
427/// saying what had to be forgiven. See [`rsa_public_key_lenient`].
428///
429/// The link carries no explicit target: this `pub use` re-exports
430/// `rsa_public_key_lenient`, so the label resolves on its own and an
431/// explicit one is redundant. rustdoc says so under `-D warnings` and
432/// cannot say where, because a doc comment on a multi-item `pub use` is
433/// attached to each item -- one link, two warnings, no single span.
434#[cfg(feature = "rsa")]
435pub use verifiers::{RsaKeyDeviation, rsa_public_key_lenient};
436#[cfg(feature = "rsa")]
437pub use verifiers::{
438 RsaPkcs1v15Sha256Verifier, RsaPkcs1v15Sha384Verifier, RsaPkcs1v15Sha512Verifier, RsaPssVerifier,
439};
440
441/// Re-exported for use with [`TrustAnchor::name_constraints`].
442pub use x509_cert::ext::pkix::constraints::name::NameConstraints;
443
444// --- Upstream types this crate's public API names ---------------------------
445//
446// Re-exported so a caller never declares `x509-cert` or `der` themselves, and
447// so an upstream major bump is "update the pkix crates" rather than lockstep
448// coordination across every direct dependency. These are re-exported rather
449// than wrapped because a caller reads their fields: there is nothing to wrap
450// them in that is not a reimplementation of x509-cert. Contrast `DerError`,
451// which a caller only reads a message from and which is therefore opaque.
452// AGENTS.md non-negotiable #9 has the rule.
453pub use der::Decode;
454pub use der::asn1::ObjectIdentifier;
455
456/// Private shorthand for the `GeneralSubtrees` type used throughout NC processing.
457type GeneralSubtrees = x509_cert::ext::pkix::constraints::name::GeneralSubtrees;
458
459/// Opaque wrapper around an underlying ASN.1 / DER error.
460///
461/// Carries a [`Display`] message identical to the wrapped `der::Error` so
462/// diagnostic output is preserved, but does not expose the underlying type
463/// in the public API. This insulates callers from semver-breaking changes
464/// in the `der` crate's error variants.
465///
466/// Construct via [`DerError::new`] (or implicitly via
467/// [`From<der::Error> for Error`]). Sibling workspace crates that wrap
468/// DER decoding failures in their own `Error` enums (`pkix-revocation`,
469/// `pkix-truststore`) call [`DerError::new`] directly.
470///
471/// # Serde wire form
472///
473/// When the `serde` feature is enabled, `DerError` (de)serializes via its
474/// `Display` message as a single `String` field. Because `der::Error` does
475/// not itself carry a textual message — its `Display` is derived from
476/// `der::ErrorKind` — round-trip is **lossy**: a deserialized `DerError`
477/// preserves the original `Display` output verbatim but its
478/// [`core::error::Error::source`] is `None` because the original
479/// `der::Error` value cannot be reconstructed from a free-form string.
480/// This trade is acceptable for diagnostic error types; the success type
481/// (`ValidatedPath`) round-trips losslessly because all its fields are
482/// canonically DER-encodable.
483///
484/// [`Display`]: core::fmt::Display
485#[derive(Clone, Debug)]
486pub struct DerError {
487 /// Original `der::Error` value, when available.
488 ///
489 /// Populated by [`DerError::new`] from a real `der::Error`. `None`
490 /// only when the `DerError` was reconstructed from serialized form;
491 /// in that case [`core::error::Error::source`] returns `None` and the
492 /// Display message is taken from the preserved [`Self::message`].
493 ///
494 /// Under `no_std` builds the `core::error::Error::source` impl is
495 /// not available, so this field is only read for its `Debug`
496 /// representation; `#[allow(dead_code)]` silences the lint in
497 /// that configuration.
498 #[cfg_attr(not(feature = "std"), allow(dead_code))]
499 inner: Option<der::Error>,
500 /// Cached Display rendering of `inner`, preserved across serde
501 /// round-trips so that the diagnostic message survives even when
502 /// `inner` cannot be reconstructed.
503 message: BoxStr,
504}
505
506// Hand-written `PartialEq` / `Eq` compare only the cached Display
507// message. Pre-refactor (tuple struct over `der::Error`) PartialEq was
508// structural over `der::Error`'s `{kind, position}` fields; two
509// `der::Error`s with identical `{kind, position}` always produce
510// identical Display output, so comparing on `message` preserves the
511// pre-refactor equality verdicts in practice. This also makes serde
512// round-trip preserve `Eq` even though deserialize drops the `inner`
513// field (it cannot be reconstructed from the rendered message).
514impl PartialEq for DerError {
515 fn eq(&self, other: &Self) -> bool {
516 self.message == other.message
517 }
518}
519impl Eq for DerError {}
520
521/// Hashes `message`, the one field [`PartialEq`] compares.
522///
523/// That correspondence is the whole argument for correctness: `Hash`
524/// requires that equal values hash equally, and since equality here is
525/// defined solely by `message`, hashing solely `message` cannot violate
526/// it. Hashing `inner` as well would break the contract, because
527/// `inner` is dropped on a serde round-trip while equality is preserved
528/// — two equal values would then hash differently.
529///
530/// Written out rather than derived for that reason: a derive would
531/// include `inner`.
532///
533/// This exists so [`Error`] can derive `Hash`. `Der(DerError)` was the
534/// only variant standing in the way, which in turn is why
535/// `pkix_path_builder::Error::NoValidPath` stores its inner error as a
536/// rendered `String` — the builder's own enum derives `Hash` and could
537/// not hold a non-`Hash` field. That storage choice is now a semver
538/// question rather than a technical obstacle.
539impl core::hash::Hash for DerError {
540 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
541 self.message.hash(state);
542 }
543}
544
545// Internal: use a Box<str> so the struct is `Clone` cheaply and we keep
546// the heap allocation small. A type alias keeps the `#[cfg(not(feature
547// = "std"))]` use-statements in the rest of the file unchanged. Defined
548// here to localise the no_std-vs-std import.
549#[cfg(not(feature = "std"))]
550type BoxStr = alloc::boxed::Box<str>;
551#[cfg(feature = "std")]
552type BoxStr = std::boxed::Box<str>;
553
554impl DerError {
555 /// Construct a `DerError` from a real `der::Error`.
556 ///
557 /// The original `der::Error` is preserved internally so
558 /// [`core::error::Error::source`] returns it; the rendered
559 /// `Display` message is cached so the diagnostic survives serde
560 /// round-trips. See the type-level rustdoc for the round-trip
561 /// fidelity contract.
562 ///
563 /// Exposed to permit sibling workspace crates (`pkix-revocation`,
564 /// `pkix-truststore`) to construct their own `Error::Der`-equivalent
565 /// variants from `der::Error` results without going through the
566 /// `pkix_path::Error::from(der::Error)` conversion (which would
567 /// produce a `pkix_path::Error`, not the sibling crate's `Error`).
568 #[must_use]
569 pub fn new(e: der::Error) -> Self {
570 // Pre-render the Display message so it survives serde round-trips
571 // even when `inner` cannot be reconstructed on the deserialize side.
572 #[cfg(feature = "std")]
573 let message = e.to_string().into_boxed_str();
574 #[cfg(not(feature = "std"))]
575 let message = {
576 use core::fmt::Write as _;
577 let mut s = alloc::string::String::new();
578 // Display on der::Error is infallible (uses core::fmt::Result
579 // = (), no I/O); write! against a String returns Ok unless
580 // allocation fails.
581 let _ = write!(&mut s, "{}", e);
582 s.into_boxed_str()
583 };
584 Self {
585 inner: Some(e),
586 message,
587 }
588 }
589}
590
591impl core::fmt::Display for DerError {
592 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
593 f.write_str(&self.message)
594 }
595}
596
597impl core::error::Error for DerError {
598 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
599 self.inner.as_ref().map(|e| e as &dyn core::error::Error)
600 }
601}
602
603#[cfg(feature = "serde")]
604#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
605const _: () = {
606 use serde::{Deserializer, Serializer};
607
608 // Local helper struct that carries only the message; both branches
609 // of the serde impl re-use the same field-name shape so wire form
610 // is stable between encoder and decoder.
611 #[derive(serde::Serialize, serde::Deserialize)]
612 struct Wire<'a> {
613 // Use Cow to avoid allocating on the serialize side. The
614 // deserialize side always owns the recovered String.
615 #[serde(borrow)]
616 message: Cow<'a, str>,
617 }
618
619 impl serde::Serialize for DerError {
620 fn serialize<S: Serializer>(&self, s: S) -> core::result::Result<S::Ok, S::Error> {
621 Wire {
622 message: Cow::Borrowed(&self.message),
623 }
624 .serialize(s)
625 }
626 }
627
628 impl<'de> serde::Deserialize<'de> for DerError {
629 fn deserialize<D: Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
630 let Wire { message } = Wire::deserialize(d)?;
631 Ok(Self {
632 inner: None,
633 message: message.into_owned().into_boxed_str(),
634 })
635 }
636 }
637};
638
639/// What RFC 5280 §6.3.3(f) can be determined about a trust anchor that
640/// also signs CRLs.
641///
642/// Step (f) of the CRL validation algorithm asks whether the CRL
643/// issuer's certificate is certified for CRL signing. When the CRL
644/// issuer is a certificate in the path, the answer is read from that
645/// certificate. When it is the trust anchor, there may be no certificate
646/// to read: RFC 5280 §6.1.1 permits an anchor to be supplied as a name,
647/// a key and an algorithm, and [`TrustAnchor::new`] does exactly that.
648///
649/// So the question has five answers rather than two, and collapsing them
650/// into `Option<bool>` loses the one that matters —
651/// [`KeyUsageMissing`](Self::KeyUsageMissing) is a *violation* under RFC
652/// 10007 while [`Unknown`](Self::Unknown) is silence. Mapping them onto
653/// one `None` is how an anchor with no certificate and an anchor whose
654/// certificate omits a required extension come to look alike.
655///
656/// Retained on [`TrustAnchor`] for the same reason as
657/// [`name_constraints`][TrustAnchor::name_constraints],
658/// [`validity_unix`][TrustAnchor::validity_unix] and
659/// [`extended_key_usage`][TrustAnchor::extended_key_usage]: RFC 5280
660/// §6.1 never examines the anchor, so if the anchor does not carry what
661/// its certificate said, nothing downstream can ask.
662///
663/// `pkix-revocation` is the consumer. See `PKIX-1y95`.
664#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
665#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
666#[non_exhaustive]
667pub enum AnchorCrlSign {
668 /// The anchor was built from a name and a key, with no certificate,
669 /// so step (f) has nothing to read.
670 ///
671 /// Treated as permission rather than refusal: a caller who supplied
672 /// no certificate has stated no restriction, exactly as
673 /// [`TrustAnchor::new`] states no validity window and no name
674 /// constraints. Refusing every such anchor's CRLs would break the
675 /// §6.1.1 anchor form the RFC explicitly allows.
676 Unknown,
677 /// The anchor's certificate is X.509 v1 or v2.
678 ///
679 /// RFC 10007 §4 exempts these outright, because those versions "do
680 /// not have an extensions field where the key usage extension can be
681 /// included". The exemption is the document's, not this crate's.
682 Exempt,
683 /// The anchor's certificate is v3 and carries no `KeyUsage`
684 /// extension at all.
685 ///
686 /// A violation of RFC 5280 §4.2.1.3 for a CA that issues CRLs, and
687 /// since RFC 10007 §4 a violation step (f) is required to catch.
688 KeyUsageMissing,
689 /// `KeyUsage` is present and asserts `cRLSign`.
690 Asserted,
691 /// `KeyUsage` is present and withholds `cRLSign`.
692 Withheld,
693}
694
695/// Why a trust anchor certificate was refused.
696///
697/// See [`Error::TrustAnchorRejected`] for why the anchor is examined at
698/// all, given that RFC 5280 §6.1 does not.
699#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
700#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
701#[non_exhaustive]
702pub enum AnchorDefect {
703 /// No `BasicConstraints` extension. RFC 5280 §4.2.1.9 requires one
704 /// in every CA certificate whose key signs certificates.
705 BasicConstraintsMissing,
706 /// `BasicConstraints` present but not marked critical, which
707 /// §4.2.1.9 requires for a CA certificate.
708 BasicConstraintsNotCritical,
709 /// `BasicConstraints` present with `cA=FALSE`: the certificate says
710 /// it is not a CA, so it cannot be one.
711 NotCa,
712 /// The certificate is a CA and its subject names nothing. RFC 5280
713 /// §4.1.2.6: "If the subject is a CA [...], then the subject field
714 /// MUST be populated with a non-empty distinguished name".
715 ///
716 /// §4.1.2.6 also lets an *end entity* carry its name only in a
717 /// critical `subjectAltName`, with an empty subject. That exception
718 /// does not extend to a CA, and the reason is structural rather than
719 /// stylistic: §6.1.3(a)(4) chains a certificate to its issuer by
720 /// comparing the issuer field against the working issuer name, and an
721 /// empty DN matches an empty DN. A CA named by nothing therefore
722 /// issues certificates whose issuer field is also empty, and any such
723 /// CA chains to any other -- name chaining stops distinguishing
724 /// issuers at all. The SAN cannot stand in, because §6.1.3 never
725 /// reads a SAN as the working issuer name.
726 ///
727 /// Reported for a CA whatever its `subjectAltName` says, including a
728 /// critical one.
729 EmptySubject,
730 /// `KeyUsage` is present and does not assert `keyCertSign`, so the
731 /// key is not permitted to sign certificates. Absent `KeyUsage` is
732 /// not a defect -- §4.2.1.3 leaves every usage permitted then.
733 KeyCertSignMissing,
734 /// A critical extension this implementation does not process. §6.1.4
735 /// would reject such a certificate inside the path; the same rule is
736 /// applied to the anchor.
737 UnhandledCriticalExtension,
738 /// An extension's DER could not be parsed, so what it requires
739 /// cannot be known.
740 MalformedExtension,
741 /// An extension holds a `BOOLEAN` that is valid BER and not valid
742 /// DER, so a strict parser cannot read it even though what it says is
743 /// not in doubt.
744 ///
745 /// X.690 §11.1 requires a DER `BOOLEAN` with the value TRUE to have
746 /// every bit of its content octet set, that is `0xFF`. BER permits any
747 /// non-zero octet, and RFC 5280 §4.1 requires certificates to be
748 /// DER-encoded, so `0x01` is a non-conforming encoding of TRUE.
749 ///
750 /// Reported instead of [`MalformedExtension`] because the two call for
751 /// different responses. A malformed extension is unreadable and might
752 /// say anything; this one is readable by every lenient parser in the
753 /// world and says `TRUE`. A caller seeing this knows the certificate
754 /// is salvageable by its issuer re-encoding it, and knows that peers
755 /// using OpenSSL or NSS accept it today -- neither of which
756 /// [`MalformedExtension`] conveys.
757 ///
758 /// The certificate is still refused. Reading a non-DER encoding
759 /// generously would mean deciding that `cA` is TRUE on the strength of
760 /// an encoding the profile forbids. Three real certificates in
761 /// `third_party/trust-stores/` encode `basicConstraints` `cA` this
762 /// way, out of 1,923 that encode the boolean at all: two eIDAS roots
763 /// and Ukraine's ePassport CSCA.
764 ///
765 /// Detected for `basicConstraints`, the only extension in this
766 /// profile carrying a `BOOLEAN` in its own value.
767 ///
768 /// [`MalformedExtension`]: AnchorDefect::MalformedExtension
769 NonDerBoolean,
770 /// The same extension OID appears more than once. RFC 5280 §4.2:
771 /// "A certificate MUST NOT include more than one instance of a
772 /// particular extension."
773 ///
774 /// Reported in preference to every other defect here, because the
775 /// extension list is what the rest of the profile check reads and a
776 /// duplicate makes those reads arbitrary: this crate takes the first
777 /// instance of an OID, another validator may take the last, and a
778 /// certificate with two `basicConstraints` or two `KeyUsage` values
779 /// then means different things to different implementations. A real
780 /// Lenovo UEFI Platform Key carries two critical `KeyUsage`
781 /// extensions whose values disagree, one permitting `keyCertSign`
782 /// and one permitting only `digitalSignature`.
783 ///
784 /// `validate_path` has always rejected such a certificate inside a
785 /// path, as [`Error::MalformedCertificate`]; this is the same rule
786 /// applied to the anchor.
787 DuplicateExtension,
788 /// The anchor's `notAfter` is before the validation time.
789 Expired,
790 /// The anchor's `notBefore` is after the validation time.
791 NotYetValid,
792}
793
794/// Errors returned by path validation.
795#[derive(Clone, Debug, PartialEq, Eq, Hash)]
796#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
797#[non_exhaustive]
798pub enum Error {
799 /// Certificate signature verification failed at the given chain index:
800 /// the signature does not verify, or is not a well-formed signature
801 /// value ([`VerificationErrorKind::InvalidSignature`]).
802 SignatureInvalid {
803 /// Zero-based index into the `chain` slice of the failing certificate.
804 index: usize,
805 },
806 /// The certificate's signature could not be checked at the given chain
807 /// index: the [`SignatureVerifier`] does not support its algorithm or
808 /// the issuer's key, or the issuer's key is malformed. `reason` says
809 /// which; it is never [`VerificationErrorKind::InvalidSignature`].
810 SignatureNotVerified {
811 /// Zero-based index into the `chain` slice of the certificate.
812 index: usize,
813 /// Why the verifier could not check the signature.
814 reason: VerificationErrorKind,
815 },
816 /// A structural encoding error was found in a certificate.
817 ///
818 /// Returned when the outer `signatureAlgorithm` OID differs from the
819 /// inner `TBSCertificate.signature` OID (RFC 5280 §4.1.1.2; parameters
820 /// are not compared, see `check_oid_consistency` for rationale), when a
821 /// certificate carries more than one instance of an extension (RFC 5280
822 /// §4.2), and when a security-relevant extension fails to decode.
823 MalformedCertificate {
824 /// Zero-based index into the `chain` slice of the malformed certificate.
825 ///
826 /// The underlying `der::Error` is intentionally not stored here to keep
827 /// this variant `no_std`-compatible and to preserve the stable API shape.
828 /// Callers that need the root-cause parse error should validate the
829 /// DER certificate independently before calling [`validate_path`].
830 index: usize,
831 },
832 /// Certificate validity period check failed (expired or not yet valid).
833 ValidityPeriod {
834 /// Zero-based index into the `chain` slice of the failing certificate.
835 index: usize,
836 },
837 /// Issuer/subject name linkage is broken at the given chain index.
838 ChainBroken {
839 /// Zero-based index into the `chain` slice where the break was found.
840 index: usize,
841 },
842 /// The trust anchor certificate itself does not satisfy the profile a
843 /// CA certificate must meet, or is outside its validity period.
844 ///
845 /// RFC 5280 §6.1 treats the anchor as an input and never examines it,
846 /// so the literal algorithm accepts an expired root, a root with no
847 /// `BasicConstraints`, and a root bearing an unrecognised critical
848 /// extension. This workspace checks it anyway: a certificate's own
849 /// constraints are the issuer's statement about what it may be used
850 /// for, and honouring them belongs here rather than being left to
851 /// whoever assembled the trust store.
852 ///
853 /// Structural defects are caught when the anchor is built
854 /// ([`TrustAnchor::from_cert`]), so a root that cannot be a CA never
855 /// enters a trust store. [`AnchorDefect::Expired`] and
856 /// [`AnchorDefect::NotYetValid`] depend on the clock and are
857 /// therefore reported by [`validate_path`].
858 ///
859 /// # Which anchor this describes
860 ///
861 /// The error names a defect, not an anchor, and several anchors may
862 /// share a subject name. When more than one is outside its window --
863 /// a rollover pair straddling the clock, with the old root past its
864 /// `notAfter` and the new one short of its `notBefore` --
865 /// [`AnchorDefect::Expired`] is reported, so the answer does not
866 /// depend on the order the trust store supplied its anchors in.
867 ///
868 /// An anchor skipped for its window is reported only when no anchor
869 /// produced a more specific failure. A trust store holding an expired
870 /// root beside an unrelated root of the same name whose signature
871 /// check fails reports the signature failure, and the expiry does not
872 /// appear. The specific error is the more useful one, but the expiry
873 /// is not additionally reported.
874 TrustAnchorRejected {
875 /// Which requirement the anchor fails.
876 defect: AnchorDefect,
877 },
878 /// No path from the subject certificate to any trust anchor was found.
879 NoTrustedPath,
880 /// Path length exceeds [`ValidationPolicy::max_path_len`].
881 PathTooLong,
882 /// A CA in the path has an `ExtendedKeyUsage` that does not permit
883 /// what is being asked of the chain below it. See
884 /// [`ValidationPolicy::enforce_ca_eku`].
885 EkuNotPermittedByIssuer {
886 /// Position of the CA whose `ExtendedKeyUsage` excludes it. This
887 /// is the certificate that narrowed the permitted set to the
888 /// point of failure, not the leaf that asked.
889 index: usize,
890 },
891 /// A certificate that issues another in the path is a CA whose
892 /// subject names nothing, against RFC 5280 §4.1.2.6.
893 ///
894 /// Distinct from [`NotCA`] because the certificate does claim to be a
895 /// CA; what it lacks is a name to be one under. See
896 /// [`AnchorDefect::EmptySubject`] for why an empty DN on a CA is not
897 /// merely non-conforming: §6.1.3(a)(4) name chaining compares DNs,
898 /// and an empty DN matches an empty DN, so such a CA chains to any
899 /// other certificate issued by any other unnamed CA.
900 ///
901 /// [`NotCA`]: Error::NotCA
902 CaEmptySubject {
903 /// Position of the offending certificate in the chain.
904 index: usize,
905 },
906 /// An intermediate certificate is missing `BasicConstraints` `cA=TRUE`.
907 NotCA {
908 /// Zero-based index into the `chain` slice of the failing certificate.
909 index: usize,
910 },
911 /// An intermediate certificate has a `KeyUsage` extension with `keyCertSign` not set.
912 ///
913 /// This error is only returned when a `KeyUsage` extension is **present** and the
914 /// `keyCertSign` bit is explicitly absent or zero (RFC 5280 §6.1.4(n): "If a `KeyUsage`
915 /// extension is present, verify that the keyCertSign bit is set.").
916 ///
917 /// Certificates with **no** `KeyUsage` extension are not rejected by this check;
918 /// RFC 5280 does not require the extension to be present on CA certificates.
919 KeyUsageMissing {
920 /// Zero-based index into the `chain` slice of the failing certificate.
921 index: usize,
922 },
923 /// An intermediate certificate has a `KeyUsage` extension with `cRLSign` not set.
924 ///
925 /// This error is only returned when
926 /// [`ValidationPolicy::require_crl_sign_on_cas`] is `true` **and** the
927 /// intermediate's `KeyUsage` extension is **present** with the `cRLSign` bit
928 /// explicitly absent or zero. Certificates with **no** `KeyUsage` extension
929 /// are not rejected by this check (RFC 5280 does not require the extension
930 /// to be present on CA certificates).
931 ///
932 /// RFC 5280 §6.1 does not mandate this check; it is an opt-in policy that
933 /// restores PKITS §4.7.4 / §4.7.5 conformance for callers who treat a CA
934 /// cert without `cRLSign` as non-issuable. Default is off.
935 ///
936 /// **Disambiguation:** [`pkix_revocation::Error::CrlSignMissing`] (same
937 /// variant name, different crate) fires during CRL verification when the
938 /// CRL *signer* cert lacks `cRLSign` (RFC 5280 §6.3.3(f)). This variant
939 /// fires during *path validation* when an intermediate CA cert in the
940 /// chain lacks `cRLSign` and the caller opted into the policy check.
941 ///
942 /// [`pkix_revocation::Error::CrlSignMissing`]: https://docs.rs/pkix-revocation/latest/pkix_revocation/enum.Error.html#variant.CrlSignMissing
943 CrlSignMissing {
944 /// Zero-based index into the `chain` slice of the failing certificate.
945 index: usize,
946 },
947 /// A critical extension is present that this implementation does not handle.
948 UnhandledCriticalExtension {
949 /// Zero-based index into the `chain` slice of the failing certificate.
950 index: usize,
951 },
952 /// A certificate carries `noRevAvail` together with something RFC 9608
953 /// §3 forbids alongside it.
954 ///
955 /// RFC 9608 §3 lists four prohibitions and ends: "If any of the above
956 /// are violated in a certificate, then the relying party MUST
957 /// consider the certificate invalid." That sentence is addressed to a
958 /// relying party rather than to an issuer, which is why this is a
959 /// path-validation error and not only a lint finding.
960 ///
961 /// # Why this is enforced even though `pkix-path` checks no revocation
962 ///
963 /// `noRevAvail` asserts that no revocation information will ever be
964 /// published. RFC 9608 §4 accordingly skips RFC 5280 §6.1.3 step
965 /// (a)(3) for such a certificate, and `pkix-chain` implements that
966 /// skip. §3 is the only thing that makes the skip safe: without it,
967 /// any certificate carrying `noRevAvail` would escape revocation
968 /// checking permanently. Enforcing it here — before any revocation
969 /// work is driven, and whether or not the caller does any — keeps
970 /// the guard with the thing it guards.
971 ///
972 /// A certificate that contradicts itself this way is also one §6.1's
973 /// state machine cannot otherwise see: it asserts that no revocation
974 /// information exists while naming where to fetch it, and two
975 /// relying parties reading different halves reach different
976 /// verdicts.
977 NoRevAvailProfileViolation {
978 /// Zero-based index into the `chain` slice of the failing certificate.
979 index: usize,
980 /// Which of RFC 9608 §3's prohibitions the certificate violates.
981 prohibition: NoRevAvailProhibition,
982 },
983 /// Certificate name constraints violated (RFC 5280 §4.2.1.10); `index` is the 0-based chain position.
984 ///
985 /// Also returned when a constraint is in effect for a name the validator
986 /// cannot evaluate: a URI without an authority or with an IP-address
987 /// host, a name of an unsupported form (`otherName`, `ediPartyName`,
988 /// `registeredID`) under a constraint of that form, a non-IA5String
989 /// subject `emailAddress`, or a `SmtpUTF8Mailbox` whose domain is not
990 /// ASCII.
991 NameConstraintViolation {
992 /// Zero-based index into the `chain` slice of the failing certificate.
993 index: usize,
994 },
995 /// Certificate policy validation failed (RFC 5280 §6.1.5(g)).
996 ///
997 /// Returned when `explicit_policy` reaches zero and the valid policy tree
998 /// is empty, meaning no acceptable certificate policy exists for the chain.
999 PolicyViolation {
1000 /// Zero-based index of the certificate where the violation was detected.
1001 index: usize,
1002 },
1003 /// ASN.1 / DER encoding or decoding error.
1004 ///
1005 /// Returned when a structural encoding error is found in a certificate or
1006 /// when re-encoding `TBSCertificate` for signature verification fails.
1007 /// Signature verification now uses heap-allocated encoding (no fixed size
1008 /// limit), so this error reflects a genuine DER encoding defect in the
1009 /// certificate, not an implementation size constraint.
1010 ///
1011 /// The inner [`DerError`] is an opaque newtype; the underlying `der::Error`
1012 /// is intentionally not exposed so a future major-version bump in the
1013 /// `der` crate cannot cascade into a semver break here.
1014 Der(DerError),
1015 /// A certificate's validity period (notAfter − notBefore) exceeds
1016 /// [`ValidationPolicy::max_validity_secs`].
1017 ///
1018 /// This check fires for every certificate in the chain, not just the leaf.
1019 ValidityPeriodExceedsMax {
1020 /// Zero-based index into the `chain` slice of the failing certificate.
1021 index: usize,
1022 },
1023 /// A certificate's signature algorithm OID is not in
1024 /// [`ValidationPolicy::allowed_signature_algs`].
1025 ///
1026 /// The check fires before signature verification so the error is diagnostic
1027 /// rather than a confusing `SignatureInvalid`.
1028 AlgorithmNotAllowed {
1029 /// Zero-based index into the `chain` slice of the failing certificate.
1030 index: usize,
1031 },
1032 /// An RSA public key's modulus is smaller than
1033 /// [`ValidationPolicy::min_rsa_key_bits`] bits.
1034 ///
1035 /// Non-RSA keys (EC, Ed25519, …) are not affected by this check.
1036 KeyTooSmall {
1037 /// Zero-based index into the `chain` slice of the failing certificate.
1038 index: usize,
1039 },
1040 /// The leaf certificate (chain index 0) has no `SubjectAltName` extension,
1041 /// or the extension is present but empty.
1042 ///
1043 /// Only checked when [`ValidationPolicy::require_subject_alt_name`] is `true`.
1044 /// Intermediate CA certificates are not subject to this check.
1045 MissingSan,
1046 /// The leaf certificate (chain index 0) has a `SubjectAltName` extension but
1047 /// none of its entries is an `rfc822Name` (email address).
1048 ///
1049 /// Only checked when [`ValidationPolicy::require_rfc822_san`] is `true`.
1050 /// Intermediate CA certificates are not subject to this check.
1051 MissingRfc822San,
1052 /// The leaf certificate (chain index 0) does not assert all OIDs required
1053 /// by [`ValidationPolicy::required_leaf_eku`].
1054 ///
1055 /// `anyExtendedKeyUsage` (2.5.29.37.0) does not satisfy a specific OID
1056 /// requirement — each required OID must be listed explicitly.
1057 MissingEku,
1058 /// The leaf certificate's `CertificatePolicies` extension does not assert
1059 /// a required policy OID from
1060 /// [`ValidationPolicy::required_leaf_policy_oids`].
1061 ///
1062 /// `anyPolicy` (2.5.29.32.0) does not satisfy a specific OID requirement;
1063 /// each required OID must be listed explicitly in the leaf's
1064 /// `CertificatePolicies` extension.
1065 ///
1066 /// Distinct from [`Error::PolicyViolation`], which signals failure of the
1067 /// RFC 5280 §6.1 policy tree (`initial_policy_set` /
1068 /// `initial_explicit_policy`). `MissingLeafPolicyOid` signals a leaf-only
1069 /// assertion check that is independent of the policy tree.
1070 MissingLeafPolicyOid {
1071 /// The required policy OID that the leaf does not assert.
1072 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1073 required: der::asn1::ObjectIdentifier,
1074 },
1075 /// The leaf certificate's Subject DN does not satisfy
1076 /// [`ValidationPolicy::required_leaf_subject_dn_attrs`].
1077 ///
1078 /// This variant carries no payload; richer "which branch of the rule
1079 /// failed" diagnostics are a non-breaking follow-up.
1080 SubjectDnAttrRuleUnmet,
1081 /// Two certificates in the chain share the same `(issuer DN, serial number)`.
1082 ///
1083 /// Per RFC 5280 §4.1.2.2, the combination of issuer DN and serial number
1084 /// uniquely identifies a certificate. A cert appearing twice at different
1085 /// chain positions is a construction error. Returned as a diagnostic rather
1086 /// than a confusing [`Error::SignatureInvalid`] or [`Error::ChainBroken`].
1087 ///
1088 /// Note: two certificates with the same public key but different
1089 /// issuer+serial are *distinct* certificates (e.g. cross-signed CAs) and
1090 /// are **not** rejected by this check.
1091 ///
1092 /// `first` and `second` are the zero-based chain indices of the two duplicates.
1093 DuplicateCertificate {
1094 /// First occurrence index.
1095 first: usize,
1096 /// Second occurrence index.
1097 second: usize,
1098 },
1099}
1100
1101impl core::fmt::Display for Error {
1102 // One match arm per `Error` variant. Splitting it would scatter
1103 // message text that belongs together; PKIX-als9 recorded the decision
1104 // to leave it.
1105 #[allow(clippy::too_many_lines)]
1106 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1107 match self {
1108 Self::SignatureInvalid { index } => {
1109 write!(f, "signature invalid at chain index {index}")
1110 }
1111 Self::SignatureNotVerified { index, reason } => {
1112 write!(f, "signature not verified at chain index {index}: {reason}")
1113 }
1114 Self::TrustAnchorRejected { defect } => {
1115 let what = match defect {
1116 AnchorDefect::BasicConstraintsMissing => "no BasicConstraints extension",
1117 AnchorDefect::BasicConstraintsNotCritical => {
1118 "BasicConstraints is not marked critical"
1119 }
1120 AnchorDefect::NotCa => "BasicConstraints says cA=FALSE",
1121 AnchorDefect::EmptySubject => "a CA certificate's subject is empty",
1122 AnchorDefect::KeyCertSignMissing => "KeyUsage does not permit keyCertSign",
1123 AnchorDefect::UnhandledCriticalExtension => {
1124 "an unhandled critical extension is present"
1125 }
1126 AnchorDefect::MalformedExtension => "an extension could not be parsed",
1127 AnchorDefect::NonDerBoolean => {
1128 "an extension holds a BER-encoded BOOLEAN, which DER forbids"
1129 }
1130 AnchorDefect::DuplicateExtension => "the same extension appears more than once",
1131 AnchorDefect::Expired => "the anchor has expired",
1132 AnchorDefect::NotYetValid => "the anchor is not yet valid",
1133 };
1134 write!(f, "trust anchor rejected: {what}")
1135 }
1136 Self::ValidityPeriod { index } => {
1137 write!(f, "validity period check failed at chain index {index}")
1138 }
1139 Self::MalformedCertificate { index } => {
1140 write!(f, "malformed certificate at chain index {index}")
1141 }
1142 Self::ChainBroken { index } => {
1143 write!(f, "issuer/subject linkage broken at chain index {index}")
1144 }
1145 Self::NoTrustedPath => write!(f, "no path to a trusted anchor"),
1146 Self::PathTooLong => write!(f, "path length exceeds maximum"),
1147 Self::EkuNotPermittedByIssuer { index } => {
1148 write!(
1149 f,
1150 "ExtendedKeyUsage of the CA at index {index} does not permit this use"
1151 )
1152 }
1153 Self::CaEmptySubject { index } => {
1154 write!(f, "CA certificate at index {index} has an empty subject")
1155 }
1156 Self::NotCA { index } => write!(f, "certificate at index {index} is not a CA"),
1157 Self::KeyUsageMissing { index } => {
1158 write!(f, "keyCertSign missing at chain index {index}")
1159 }
1160 Self::CrlSignMissing { index } => {
1161 write!(f, "cRLSign missing at chain index {index}")
1162 }
1163 Self::UnhandledCriticalExtension { index } => {
1164 write!(f, "unhandled critical extension at chain index {index}")
1165 }
1166 Self::NoRevAvailProfileViolation { index, prohibition } => {
1167 write!(
1168 f,
1169 "certificate at chain index {index} carries noRevAvail and {}, \
1170 which RFC 9608 §3 forbids",
1171 prohibition.as_str()
1172 )
1173 }
1174 Self::NameConstraintViolation { index } => {
1175 write!(f, "name constraints violated at certificate index {index}")
1176 }
1177 Self::PolicyViolation { index } => {
1178 write!(f, "certificate policy violation at chain index {index}")
1179 }
1180 Self::Der(e) => write!(f, "DER error: {e}"),
1181 Self::ValidityPeriodExceedsMax { index } => {
1182 write!(f, "validity period exceeds maximum at chain index {index}")
1183 }
1184 Self::AlgorithmNotAllowed { index } => {
1185 write!(f, "signature algorithm not allowed at chain index {index}")
1186 }
1187 Self::KeyTooSmall { index } => {
1188 write!(f, "RSA key too small at chain index {index}")
1189 }
1190 Self::MissingSan => write!(f, "leaf certificate is missing SubjectAltName"),
1191 Self::MissingRfc822San => write!(
1192 f,
1193 "leaf certificate SubjectAltName contains no rfc822Name entry"
1194 ),
1195 Self::MissingEku => {
1196 write!(
1197 f,
1198 "leaf certificate is missing required ExtendedKeyUsage OID(s)"
1199 )
1200 }
1201 Self::MissingLeafPolicyOid { required } => {
1202 write!(
1203 f,
1204 "leaf certificate is missing required CertificatePolicies OID {required}"
1205 )
1206 }
1207 Self::SubjectDnAttrRuleUnmet => {
1208 write!(
1209 f,
1210 "leaf certificate Subject DN does not satisfy the required attribute rule"
1211 )
1212 }
1213 Self::DuplicateCertificate { first, second } => {
1214 write!(
1215 f,
1216 "duplicate certificate (issuer+serial) at chain indices {first} and {second}"
1217 )
1218 }
1219 }
1220 }
1221}
1222
1223impl core::error::Error for Error {
1224 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1225 match self {
1226 Self::Der(e) => Some(e),
1227 Self::SignatureInvalid { .. }
1228 | Self::SignatureNotVerified { .. }
1229 | Self::MalformedCertificate { .. }
1230 | Self::ValidityPeriod { .. }
1231 | Self::TrustAnchorRejected { .. }
1232 | Self::ChainBroken { .. }
1233 | Self::NoTrustedPath
1234 | Self::PathTooLong
1235 | Self::NotCA { .. }
1236 | Self::CaEmptySubject { .. }
1237 | Self::EkuNotPermittedByIssuer { .. }
1238 | Self::KeyUsageMissing { .. }
1239 | Self::CrlSignMissing { .. }
1240 | Self::UnhandledCriticalExtension { .. }
1241 | Self::NoRevAvailProfileViolation { .. }
1242 | Self::NameConstraintViolation { .. }
1243 | Self::PolicyViolation { .. }
1244 | Self::ValidityPeriodExceedsMax { .. }
1245 | Self::AlgorithmNotAllowed { .. }
1246 | Self::KeyTooSmall { .. }
1247 | Self::MissingSan
1248 | Self::MissingRfc822San
1249 | Self::MissingEku
1250 | Self::MissingLeafPolicyOid { .. }
1251 | Self::SubjectDnAttrRuleUnmet
1252 | Self::DuplicateCertificate { .. } => None,
1253 }
1254 }
1255}
1256
1257impl From<der::Error> for Error {
1258 fn from(e: der::Error) -> Self {
1259 Self::Der(DerError::new(e))
1260 }
1261}
1262
1263/// Result alias for this crate.
1264pub type Result<T> = core::result::Result<T, Error>;
1265
1266/// Pluggable signature verification backend.
1267///
1268/// Implement this trait to provide algorithm-specific signature verification.
1269/// The trait is OID-dispatched: the `algorithm` argument carries the OID and
1270/// any parameters from the certificate's `signatureAlgorithm` field.
1271///
1272/// This trait is object-safe and can be used as `dyn SignatureVerifier`.
1273/// All method arguments are either `&self` or borrows, so no `Sized` bound
1274/// is implied.
1275///
1276/// # Implementing a custom backend
1277///
1278/// ```rust,no_run
1279/// use der::asn1::ObjectIdentifier;
1280/// const MY_RSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
1281/// const MY_ECDSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
1282///
1283/// struct MyVerifier;
1284///
1285/// impl pkix_path::SignatureVerifier for MyVerifier {
1286/// fn verify_signature(
1287/// &self,
1288/// algorithm: spki::AlgorithmIdentifierRef<'_>,
1289/// _issuer_spki: spki::SubjectPublicKeyInfoRef<'_>,
1290/// _message: &[u8],
1291/// _signature: &[u8],
1292/// ) -> Result<(), pkix_path::VerificationError> {
1293/// match algorithm.oid {
1294/// MY_RSA_OID => { Ok(()) /* RSA verification */ }
1295/// MY_ECDSA_OID => { Ok(()) /* ECDSA verification */ }
1296/// _ => Err(pkix_path::VerificationError::unsupported_algorithm()),
1297/// }
1298/// }
1299/// }
1300/// ```
1301pub trait SignatureVerifier {
1302 /// Verify `signature` over `message`.
1303 ///
1304 /// - `algorithm` — from the subject cert's `signatureAlgorithm` field
1305 /// - `issuer_spki` — SPKI extracted from the issuer or trust anchor cert
1306 /// - `message` — DER-encoded `TBSCertificate` (the bytes that were signed)
1307 /// - `signature` — raw signature bytes (`BitString` content, not the wrapper)
1308 ///
1309 /// Returns `Ok(())` when the signature verifies. The caller
1310 /// ([`validate_path`]) adds the chain index: an error of kind
1311 /// [`VerificationErrorKind::InvalidSignature`] becomes
1312 /// [`Error::SignatureInvalid`], any other kind
1313 /// [`Error::SignatureNotVerified`] — the verifier does not need to know
1314 /// the index.
1315 ///
1316 /// # Errors
1317 ///
1318 /// Returns a [`VerificationError`] whose kind says why the signature
1319 /// was not accepted: the algorithm is not supported
1320 /// ([`UnsupportedAlgorithm`](VerificationErrorKind::UnsupportedAlgorithm)),
1321 /// the issuer key is unsupported or does not fit the algorithm
1322 /// ([`UnsupportedKey`](VerificationErrorKind::UnsupportedKey)) or does
1323 /// not decode ([`MalformedKey`](VerificationErrorKind::MalformedKey)),
1324 /// or the signature is malformed or does not verify
1325 /// ([`InvalidSignature`](VerificationErrorKind::InvalidSignature)).
1326 fn verify_signature(
1327 &self,
1328 algorithm: AlgorithmIdentifierRef<'_>,
1329 issuer_spki: SubjectPublicKeyInfoRef<'_>,
1330 message: &[u8],
1331 signature: &[u8],
1332 ) -> core::result::Result<(), VerificationError>;
1333}
1334
1335/// Forwarding impl so a shared reference to a verifier is itself a
1336/// verifier.
1337///
1338/// This is what makes a verifier that cannot be `Clone` usable.
1339/// [`crate::validate_path`] and the `CrlChecker` / `OcspChecker` types in
1340/// `pkix-revocation` take a verifier by value and require `Clone`, since
1341/// they hold it and may be cloned themselves. A verifier that owns a
1342/// hardware token handle, an open session, or anything else not
1343/// duplicable therefore could not be used at all.
1344///
1345/// With this impl it can: pass `&verifier` and the type parameter
1346/// becomes `&V`, which is `Copy`, so the `Clone` bound is satisfied for
1347/// free and nothing is duplicated. The borrow is the only cost, and it
1348/// is what a scoped validation wants anyway.
1349///
1350/// For a verifier shared by something outliving a borrow — a fetcher
1351/// held for the life of a process — use the `Arc` impl below instead.
1352impl<T: SignatureVerifier + ?Sized> SignatureVerifier for &T {
1353 fn verify_signature(
1354 &self,
1355 algorithm: AlgorithmIdentifierRef<'_>,
1356 issuer_spki: SubjectPublicKeyInfoRef<'_>,
1357 message: &[u8],
1358 signature: &[u8],
1359 ) -> core::result::Result<(), VerificationError> {
1360 (**self).verify_signature(algorithm, issuer_spki, message, signature)
1361 }
1362}
1363
1364/// Forwarding impl so an `Arc`-shared verifier is itself a verifier.
1365///
1366/// The owned counterpart to the `&T` impl above, for a verifier that has
1367/// to outlive any particular borrow. `Arc<V>` is `Clone` whatever `V` is,
1368/// and cloning it is a refcount bump rather than a duplication of
1369/// whatever the verifier holds.
1370///
1371/// # Why this is gated on `std`
1372///
1373/// `Arc` lives in `alloc::sync`, which exists only on targets with
1374/// atomic compare-and-swap. Implementing it unconditionally would make
1375/// this crate stop compiling for a `no_std` target without atomics
1376/// (`thumbv6m-none-eabi`, for instance) in exchange for a convenience.
1377/// Under `std` those atomics are guaranteed, so the impl is free there.
1378/// A `no_std` consumer that does have atomics and wants this shape can
1379/// write the same four-line forwarding impl over its own newtype.
1380#[cfg(feature = "std")]
1381#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1382impl<T: SignatureVerifier + ?Sized> SignatureVerifier for std::sync::Arc<T> {
1383 fn verify_signature(
1384 &self,
1385 algorithm: AlgorithmIdentifierRef<'_>,
1386 issuer_spki: SubjectPublicKeyInfoRef<'_>,
1387 message: &[u8],
1388 signature: &[u8],
1389 ) -> core::result::Result<(), VerificationError> {
1390 (**self).verify_signature(algorithm, issuer_spki, message, signature)
1391 }
1392}
1393
1394/// A trust anchor used to terminate path validation.
1395///
1396/// A trust anchor is typically either a self-signed root CA certificate
1397/// or a raw (name, SPKI) pair extracted from a platform trust store.
1398/// The trust anchor itself is **not** signature-verified — it is trusted
1399/// by definition (RFC 5280 §6.1.1(c)).
1400///
1401/// **Validity period**: RFC 5280 §6.1.1(c) explicitly excludes the trust
1402/// anchor's notBefore/notAfter from path validation. An expired root CA
1403/// certificate used as a trust anchor will still anchor valid paths — this
1404/// is intentional behavior, not a bug. Callers are responsible for ensuring
1405/// their trust store contains the anchors they intend to trust.
1406///
1407/// **`PartialEq` is byte-level, not semantic**: The derived `PartialEq`
1408/// compares fields verbatim. Two anchors representing the same CA may compare
1409/// unequal if their DER encodings differ — for example, one `AlgorithmIdentifier`
1410/// with explicit `NULL` parameters and another with absent parameters are both
1411/// valid for RSA (RFC 3279 §2.3.1) but will not be equal under `==`. Do not use
1412/// `==` to deduplicate a trust store; use [`names_match`] and compare
1413/// `algorithm.oid` plus `subject_public_key` bytes directly. Path validation
1414/// already handles this internally, so it is not affected by this encoding difference.
1415///
1416/// # Stability
1417///
1418/// `TrustAnchor` is `#[non_exhaustive]`: new fields may be added in minor
1419/// versions. Construct via [`TrustAnchor::new`], [`TrustAnchor::from_cert`],
1420/// or [`TrustAnchor::from_cert_ref`]; `TryFrom` delegates to the same
1421/// checks. There is deliberately no infallible conversion -- see
1422/// [`Error::TrustAnchorRejected`]. Do not use struct literal syntax.
1423#[derive(Clone, Debug, PartialEq, Eq)]
1424#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1425#[non_exhaustive]
1426pub struct TrustAnchor {
1427 /// The subject distinguished name of the trust anchor.
1428 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1429 pub subject: x509_cert::name::Name,
1430 /// The subject public key info of the trust anchor.
1431 ///
1432 /// Must be a valid SPKI for the chosen signature algorithm. An empty or
1433 /// malformed SPKI will cause signature verification to fail with
1434 /// `Error::NoTrustedPath` (no anchor matched), not a panic.
1435 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1436 pub subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
1437 /// `NameConstraints` from the trust anchor certificate, if present.
1438 ///
1439 /// When set, `chain_walk` seeds the initial `permitted_subtrees` and
1440 /// `excluded_subtrees` state from this value before walking the chain.
1441 /// Populated automatically by `from_cert`; `None` for programmatically
1442 /// constructed anchors unless explicitly set.
1443 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option"))]
1444 pub name_constraints: Option<x509_cert::ext::pkix::constraints::name::NameConstraints>,
1445 /// The anchor certificate's validity window, as Unix seconds.
1446 ///
1447 /// Retained because RFC 5280 §6.1 never examines the anchor, so
1448 /// nothing else would: the algorithm checks the certificates in the
1449 /// path and the anchor is an input. A root's `notAfter` is its
1450 /// issuer's statement about how long it may be used, and a trust
1451 /// store is exactly where an expired root sits unnoticed for years.
1452 ///
1453 /// Retaining it is not merely permitted but named as an option.
1454 /// [RFC 6818][rfc6818] §4 replaced §6.2's third paragraph, and the
1455 /// replacement ends: "Implementations are free to make use of any
1456 /// additional information that is included in a trust anchor
1457 /// representation, or to ignore such information." The four fields
1458 /// this type keeps from an anchor certificate — this one,
1459 /// [`name_constraints`][Self::name_constraints],
1460 /// [`extended_key_usage`][Self::extended_key_usage] and
1461 /// [`crl_sign`][Self::crl_sign] — are that choice exercised, and
1462 /// `PKIX-2mof` made it before anyone here had read RFC 6818.
1463 ///
1464 /// [rfc6818]: https://www.rfc-editor.org/rfc/rfc6818#section-4
1465 ///
1466 /// [`validate_path`] compares [`ValidationPolicy::current_time_unix`] against
1467 /// this and reports [`AnchorDefect::Expired`] or
1468 /// [`AnchorDefect::NotYetValid`]. The structural requirements are
1469 /// checked when the anchor is built instead, since they do not
1470 /// depend on the clock.
1471 pub validity_unix: (u64, u64),
1472
1473 /// `ExtendedKeyUsage` from the trust anchor certificate, if present.
1474 ///
1475 /// Retained for the same reason as [`name_constraints`]: RFC 5280
1476 /// §6.1 never examines the anchor, so a root restricted to one
1477 /// purpose would otherwise constrain nothing below it. 245 of the
1478 /// 2,872 CA certificates in `third_party/trust-stores` carry an EKU,
1479 /// and some of those are roots.
1480 ///
1481 /// When set, [`validate_path`] seeds the permitted-purpose set from it
1482 /// before walking the chain, so the anchor narrows exactly as an
1483 /// intermediate would. See [`ValidationPolicy::enforce_ca_eku`].
1484 ///
1485 /// Populated automatically by [`from_cert`]; `None` for
1486 /// programmatically constructed anchors, which have no certificate to
1487 /// read and so state no restriction.
1488 ///
1489 /// [`name_constraints`]: Self::name_constraints
1490 /// [`from_cert`]: Self::from_cert
1491 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1492 pub extended_key_usage: Option<Vec<der::asn1::ObjectIdentifier>>,
1493
1494 /// What the anchor's certificate says about signing CRLs — RFC 5280
1495 /// §6.3.3(f) as amended by RFC 10007 §4.
1496 ///
1497 /// A root that anchors a path commonly also signs the CRL covering
1498 /// the certificates it issued, and then it *is* the CRL issuer that
1499 /// step (f) asks about. Nothing else can answer: §6.1 does not
1500 /// examine the anchor, and by the time a revocation checker holds a
1501 /// [`TrustAnchor`] the certificate is gone.
1502 ///
1503 /// [`AnchorCrlSign::Unknown`] for an anchor built by
1504 /// [`new`](Self::new), which has no certificate to read; computed
1505 /// from the certificate by [`from_cert`](Self::from_cert).
1506 pub crl_sign: AnchorCrlSign,
1507
1508 /// `pathLenConstraint` from the anchor certificate's
1509 /// `BasicConstraints`, if present.
1510 ///
1511 /// Retained for the reason the four fields above are: RFC 5280 §6.1
1512 /// never examines the anchor, so a root that restricted the depth
1513 /// below it would otherwise restrict nothing. A root asserting
1514 /// `pathLen 0` is saying "I issue end entities only", and that is the
1515 /// same kind of statement as "I issue only for these names", which
1516 /// [`name_constraints`] already carries.
1517 ///
1518 /// 820 of the 2,409 self-signed CA certificates in
1519 /// `third_party/trust-stores` assert one and 692 assert zero, so this
1520 /// is a statement issuers make constantly. OpenSSL has enforced it
1521 /// for decades; leaving it unenforced made `pkix-path` accept chains
1522 /// `openssl verify` rejects. PKIX-zr0n has the measurement and Mark's
1523 /// ruling.
1524 ///
1525 /// Counted the way §6.1.4(l) and §4.2.1.9 count: only
1526 /// non-self-issued intermediates below the anchor, so a key-rollover
1527 /// certificate does not consume depth.
1528 ///
1529 /// `None` for an anchor built by [`new`](Self::new), which has no
1530 /// certificate to read and therefore states no limit; read from the
1531 /// certificate by [`from_cert`](Self::from_cert).
1532 ///
1533 /// [`name_constraints`]: Self::name_constraints
1534 pub path_len_constraint: Option<u8>,
1535}
1536
1537impl TrustAnchor {
1538 /// Create a trust anchor from raw subject name and SPKI.
1539 #[must_use]
1540 pub const fn new(
1541 subject: x509_cert::name::Name,
1542 subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
1543 ) -> Self {
1544 Self {
1545 subject,
1546 subject_public_key_info,
1547 // A caller supplying a bare subject and key has stated no
1548 // validity window, so there is none to enforce. An anchor
1549 // built from a certificate carries that certificate's.
1550 validity_unix: (0, u64::MAX),
1551 name_constraints: None,
1552 extended_key_usage: None,
1553 // No certificate, so nothing to read. See AnchorCrlSign::Unknown
1554 // for why that is permission and not refusal.
1555 crl_sign: AnchorCrlSign::Unknown,
1556 // Likewise: a caller supplying a bare subject and key has
1557 // stated no depth limit.
1558 path_len_constraint: None,
1559 }
1560 }
1561
1562 /// Build a trust anchor from a root CA certificate, checking that the
1563 /// certificate can be one.
1564 ///
1565 /// This is the typical constructor when your trust store contains full
1566 /// self-signed root CA certificates. Use
1567 /// [`from_cert_ref`](Self::from_cert_ref) when you need to keep `cert`
1568 /// alive after building the anchor.
1569 ///
1570 /// RFC 5280 §6.1 takes the trust anchor as given and specifies no
1571 /// checks on it, so an implementation that reads only the subject name
1572 /// and public key will accept any certificate at all as a root --
1573 /// including one that says `cA=FALSE`, one whose `KeyUsage` withholds
1574 /// `keyCertSign`, and one carrying a critical extension the
1575 /// implementation cannot process. The certificate's own statements
1576 /// about what it may be used for are checked here instead.
1577 ///
1578 /// # Errors
1579 ///
1580 /// [`Error::TrustAnchorRejected`], carrying the [`AnchorDefect`] that
1581 /// disqualified the certificate:
1582 ///
1583 /// * [`BasicConstraintsMissing`] or [`BasicConstraintsNotCritical`] --
1584 /// §4.2.1.9 requires the extension, marked critical, in a CA
1585 /// certificate.
1586 /// * [`NotCa`] -- `cA` is `FALSE`.
1587 /// * [`KeyCertSignMissing`] -- `KeyUsage` is present and withholds
1588 /// `keyCertSign`. An absent `KeyUsage` is not a defect: §4.2.1.3
1589 /// leaves every usage permitted then.
1590 /// * [`UnhandledCriticalExtension`] -- a critical extension this
1591 /// implementation does not process. §6.1.4 would reject such a
1592 /// certificate inside the path; the anchor is held to the same rule.
1593 /// * [`MalformedExtension`] -- an extension's DER could not be parsed,
1594 /// so what it requires cannot be known.
1595 /// * [`NonDerBoolean`] -- `basicConstraints` holds a `cA` `BOOLEAN`
1596 /// encoded as valid BER and invalid DER, `0x01` rather than the
1597 /// `0xFF` X.690 §11.1 requires for TRUE. Reported apart from
1598 /// `MalformedExtension` because the certificate is readable by
1599 /// lenient parsers and says `TRUE`; it is refused anyway, since
1600 /// honouring it would mean trusting an encoding the profile forbids.
1601 /// * [`DuplicateExtension`] -- the same extension OID appears more than
1602 /// once, which §4.2 forbids. Reported in preference to the others,
1603 /// because every check above finds an extension by OID and reads the
1604 /// first match: on a certificate with two of something, those checks
1605 /// would be answering about whichever copy came first. `validate_path`
1606 /// has always refused such a certificate inside a path, as
1607 /// [`Error::MalformedCertificate`]; this is that rule applied to the
1608 /// anchor.
1609 ///
1610 /// [`Expired`] and [`NotYetValid`] are not produced here. They depend
1611 /// on the validation time, which this constructor is not given;
1612 /// [`validate_path`] checks [`validity_unix`] against its policy's
1613 /// clock. A trust store is typically loaded once and used for a long
1614 /// time, so an anchor's window is re-examined per validation rather
1615 /// than fixed at load.
1616 ///
1617 /// # Algorithm support is not checked here
1618 ///
1619 /// A certificate whose public key algorithm this build cannot verify
1620 /// with still becomes an anchor. That is deliberate, and this
1621 /// constructor could not do otherwise: it is given no
1622 /// [`SignatureVerifier`], and which algorithms are supported is a
1623 /// property of the verifier rather than of the certificate. The
1624 /// trait is public, so a caller may supply one that handles an
1625 /// algorithm this crate's own backends do not; screening anchors
1626 /// against the default set here would make that configuration
1627 /// impossible to express.
1628 ///
1629 /// Note the asymmetry with [`AnchorDefect::NonDerBoolean`], which
1630 /// refuses a certificate over a single mis-encoded octet. The two are
1631 /// different kinds of problem. A BER boolean means the certificate's
1632 /// own claim cannot be read, and the profile check needs `cA`, so
1633 /// refusing is the only way to avoid guessing a security-relevant
1634 /// value. An unsupported key algorithm means everything the
1635 /// certificate says is legible and satisfied, and what is missing is
1636 /// a capability of this build. Refuse when the certificate is
1637 /// unreadable; do not refuse when the limitation is ours.
1638 ///
1639 /// The cost is discoverability: a trust store can hold anchors that
1640 /// cannot verify anything, and `pkix-truststore`'s loaders will not
1641 /// list them as rejected, because nothing about them is wrong. Loading
1642 /// `third_party/trust-stores/ru-national/` gives eight anchors of
1643 /// which six are GOST, and a caller counting usable anchors from the
1644 /// length of the list over-counts by six.
1645 ///
1646 /// What bounds that cost is the error at the point of use.
1647 /// [`validate_path`] reports
1648 /// [`Error::SignatureNotVerified`] carrying
1649 /// [`VerificationErrorKind::UnsupportedAlgorithm`] and the chain
1650 /// index -- not [`Error::NoTrustedPath`], which would hide that an
1651 /// anchor matched, and not [`Error::SignatureInvalid`], which would
1652 /// turn a missing feature into an accusation that the issuer did not
1653 /// sign the certificate. `tests/unsupported_key_algorithm.rs` pins
1654 /// all of that against two real Russian national roots.
1655 ///
1656 /// # `NameConstraints` are read fail-closed
1657 ///
1658 /// A certificate whose `NameConstraints` extension cannot be parsed is
1659 /// refused with [`MalformedExtension`] rather than accepted with the
1660 /// constraint dropped. Dropping it would be a fail-open: the
1661 /// deployment asserted through that extension that this root may sign
1662 /// only for certain names, and an anchor without it may sign for any.
1663 /// RFC 5280 §4.2 requires rejection when a critical extension cannot
1664 /// be processed, and the strongest form of "cannot process" is
1665 /// "cannot parse".
1666 ///
1667 /// A subtree encoding a non-zero `minimum` or any `maximum` is refused
1668 /// for the same reason. §4.2.1.10 forbids both, so such a constraint
1669 /// has a scope that cannot be honoured as written: enforcing it as
1670 /// though `minimum` were zero applies it to more names than the issuer
1671 /// wrote, and discarding it applies it to none.
1672 ///
1673 /// [`BasicConstraintsMissing`]: AnchorDefect::BasicConstraintsMissing
1674 /// [`BasicConstraintsNotCritical`]: AnchorDefect::BasicConstraintsNotCritical
1675 /// [`NotCa`]: AnchorDefect::NotCa
1676 /// [`KeyCertSignMissing`]: AnchorDefect::KeyCertSignMissing
1677 /// [`UnhandledCriticalExtension`]: AnchorDefect::UnhandledCriticalExtension
1678 /// [`MalformedExtension`]: AnchorDefect::MalformedExtension
1679 /// [`NonDerBoolean`]: AnchorDefect::NonDerBoolean
1680 /// [`DuplicateExtension`]: AnchorDefect::DuplicateExtension
1681 /// [`Expired`]: AnchorDefect::Expired
1682 /// [`NotYetValid`]: AnchorDefect::NotYetValid
1683 /// [`validity_unix`]: Self::validity_unix
1684 pub fn from_cert(cert: Certificate) -> crate::Result<Self> {
1685 Self::from_cert_ref(&cert)
1686 }
1687
1688 /// As [`from_cert`](Self::from_cert), borrowing the certificate.
1689 ///
1690 /// # Errors
1691 ///
1692 /// The same [`Error::TrustAnchorRejected`] defects as
1693 /// [`from_cert`](Self::from_cert); the two differ only in ownership.
1694 pub fn from_cert_ref(cert: &Certificate) -> crate::Result<Self> {
1695 Self::from_cert_ref_admitting(cert, AnchorAdmission::Strict).map(|(a, _)| a)
1696 }
1697
1698 /// Build an anchor under a stated [`AnchorAdmission`], returning any
1699 /// profile deviation alongside it.
1700 ///
1701 /// [`from_cert_ref`](Self::from_cert_ref) and
1702 /// [`from_cert`](Self::from_cert) are this with
1703 /// [`AnchorAdmission::Strict`], discarding the deviation because
1704 /// under that mode a deviation is an error instead.
1705 ///
1706 /// Under [`AsPublished`](AnchorAdmission::AsPublished) the returned
1707 /// `Option<AnchorDefect>` is the thing a caller wants to log: the
1708 /// anchor is usable, and this says what is odd about the certificate
1709 /// that carried it. Ignoring it is a choice, not an accident -- see
1710 /// that variant on why the certificate's profile is not what decides
1711 /// whether an anchor exists.
1712 ///
1713 /// # Errors
1714 ///
1715 /// Under `Strict`, any [`AnchorDefect`]. Under `AsPublished`, only
1716 /// [`AnchorDefect::EmptySubject`], because §6.1.1(d)(1) requires a
1717 /// trusted issuer name and an empty subject supplies none; plus the
1718 /// name-constraint failures below, which are refused under both
1719 /// modes because a constraint that cannot be parsed cannot be
1720 /// honoured and dropping it would silently widen the anchor.
1721 pub fn from_cert_ref_admitting(
1722 cert: &Certificate,
1723 admission: AnchorAdmission,
1724 ) -> crate::Result<(Self, Option<AnchorDefect>)> {
1725 let deviation = anchor_profile_deviation(cert);
1726 match admission {
1727 AnchorAdmission::Strict => check_anchor_profile(cert)?,
1728 AnchorAdmission::AsPublished => anchor_is_structurally_usable(cert)?,
1729 }
1730 Self::from_cert_ref_unchecked(cert).map(|a| (a, deviation))
1731 }
1732
1733 fn from_cert_ref_unchecked(cert: &Certificate) -> crate::Result<Self> {
1734 // Read fail-closed, with `try_find_cert_ext` rather than
1735 // `find_cert_ext`: the lenient lookup returns `None` on a parse
1736 // failure, which would drop the extension and accept the anchor.
1737 // The deployment said "this root may only sign for these names",
1738 // and silently discarding that removes the constraint at
1739 // validation time. RFC 5280 §4.2 requires rejection when a
1740 // critical extension cannot be processed, and the strongest
1741 // form of "cannot process" is "cannot parse".
1742 //
1743 // §4.2.1.10 also forbids a `minimum` other than 0 and forbids
1744 // `maximum` entirely, so a constraint carrying either has a
1745 // scope that cannot be honoured as written.
1746 let name_constraints: Option<NameConstraints> =
1747 try_find_cert_ext(cert, OID_NAME_CONSTRAINTS).map_err(|_| {
1748 Error::TrustAnchorRejected {
1749 defect: AnchorDefect::MalformedExtension,
1750 }
1751 })?;
1752 if name_constraints
1753 .as_ref()
1754 .is_some_and(|nc| !subtrees_are_conformant(nc))
1755 {
1756 return Err(Error::TrustAnchorRejected {
1757 defect: AnchorDefect::MalformedExtension,
1758 });
1759 }
1760 let v = cert.tbs_certificate().validity();
1761 let extended_key_usage = try_find_cert_ext::<x509_cert::ext::pkix::ExtendedKeyUsage>(
1762 cert,
1763 OID_EXTENDED_KEY_USAGE,
1764 )
1765 .map_err(|_| Error::TrustAnchorRejected {
1766 defect: AnchorDefect::MalformedExtension,
1767 })?
1768 .map(|eku| eku.0);
1769 Ok(Self {
1770 subject: cert.tbs_certificate().subject().clone(),
1771 subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
1772 name_constraints,
1773 validity_unix: (
1774 time_to_unix_secs(&v.not_before),
1775 time_to_unix_secs(&v.not_after),
1776 ),
1777 extended_key_usage,
1778 crl_sign: anchor_crl_sign(cert),
1779 path_len_constraint: anchor_path_len(cert),
1780 })
1781 }
1782}
1783
1784/// The requirements a certificate must meet to be usable as a trust
1785/// anchor, excluding the clock-dependent ones.
1786///
1787/// RFC 5280 §6.1 never examines the anchor, so none of this is required
1788/// by the path-validation algorithm. It is checked because a
1789/// certificate's own extensions are its issuer's statement about what
1790/// the key may be used for, and a root that says `cA=FALSE` or carries a
1791/// critical extension nobody can process should not become a trust
1792/// anchor on the strength of someone having put it in a file.
1793///
1794/// Measured against the 122 roots in a current system CA bundle, these
1795/// rules refuse one: a root whose `BasicConstraints` is not marked
1796/// critical. None lacks `BasicConstraints`, none asserts `cA=TRUE`
1797/// without `keyCertSign`, and the only critical extensions present are
1798/// `BasicConstraints` and `KeyUsage`, both of which are handled.
1799/// How much of the CA-certificate profile an anchor must satisfy.
1800///
1801/// # Why this is a choice at all
1802///
1803/// RFC 5280 §6.1.1(d) defines what a trust anchor *is*, and it is not a
1804/// certificate:
1805///
1806/// > trust anchor information, describing a CA that serves as a trust
1807/// > anchor for the certification path. The trust anchor information
1808/// > includes: (1) the trusted issuer name, (2) the trusted public key
1809/// > algorithm, (3) the trusted public key, and (4) optionally, the
1810/// > trusted public key parameters associated with the public key.
1811///
1812/// A certificate is one optional carrier for that tuple, and when one is
1813/// used the section names exactly which two fields are consumed:
1814///
1815/// > The trust anchor information may be provided to the path processing
1816/// > procedure in the form of a self-signed certificate. When the trust
1817/// > anchor information is provided in the form of a certificate, the
1818/// > name in the subject field is used as the trusted issuer name and
1819/// > the contents of the subjectPublicKeyInfo field is used as the
1820/// > source of the trusted public key algorithm and the trusted public
1821/// > key.
1822///
1823/// `basicConstraints`, its criticality, the `cA` boolean and its
1824/// encoding, `keyUsage`, the validity window -- none of them is an
1825/// input. So refusing an anchor over one of them is a policy choice
1826/// this crate may offer and must not impose.
1827///
1828/// # Why the default changed
1829///
1830/// It was imposed, and measurably so. Across the 28 bundles vendored in
1831/// `third_party/trust-stores/` -- `DoD`, Microsoft, UEFI, eIDAS, 24
1832/// national and sectoral PKIs -- strict admission refuses **735**
1833/// anchors, and **734** of those are over fields §6.1.1(d) does not
1834/// read. 650 are `basicConstraints` presence or criticality alone.
1835///
1836/// Each of those publishers is a body the operator already decided to
1837/// trust by installing its bundle. Refusing a third of it on a field
1838/// the specification ignores is not caution; it is substituting our
1839/// profile judgement for their curation, and then reporting the result
1840/// as if the certificate were unusable.
1841///
1842/// [`AnchorDefect`] exists so a caller learns what is odd about an
1843/// anchor. It should not have to choose between learning that and
1844/// having the anchor.
1845#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1846pub enum AnchorAdmission {
1847 /// Admit every certificate from which the §6.1.1(d) tuple can be
1848 /// taken, and report profile deviations rather than refusing them.
1849 ///
1850 /// The default, and what a bundle from a publisher you already
1851 /// trust wants: a root program, a national CSCA list, `DoD`'s PKI.
1852 ///
1853 /// Still refused: a certificate that cannot be parsed, and one
1854 /// whose subject names nothing. The second is structural rather
1855 /// than stylistic -- §6.1.1(d)(1) requires a trusted issuer name,
1856 /// and an empty subject means there is none, so the tuple cannot be
1857 /// formed. See [`AnchorDefect::EmptySubject`].
1858 #[default]
1859 AsPublished,
1860 /// Additionally require the full CA-certificate profile, refusing
1861 /// any [`AnchorDefect`].
1862 ///
1863 /// For auditing a bundle rather than consuming one: answering "does
1864 /// this publisher emit conforming CA certificates?" instead of "can
1865 /// I validate paths against these?".
1866 ///
1867 /// Reachable per-certificate through
1868 /// [`TrustAnchor::from_cert`], [`from_cert_ref`][Self::Strict] and
1869 /// `TryFrom<Certificate>`, all of which are strict. The bundle
1870 /// loaders in `pkix-truststore` admit as published and report, which
1871 /// answers the audit question just as well from
1872 /// `LoadedAnchors::deviations` -- the same set, without costing the
1873 /// caller the anchors to learn it.
1874 Strict,
1875}
1876
1877/// Every way `cert` deviates from the CA-certificate profile, ignoring
1878/// whether any of them disqualifies it as an anchor.
1879///
1880/// Returns at most one defect, because the checks are ordered and the
1881/// first is reported -- `DuplicateExtension` before anything that reads
1882/// an extension by OID, since on a certificate with two of something
1883/// every later check would be answering about whichever copy came
1884/// first.
1885///
1886/// `None` means the certificate satisfies the profile.
1887#[must_use]
1888pub fn anchor_profile_deviation(cert: &Certificate) -> Option<AnchorDefect> {
1889 match check_anchor_profile(cert) {
1890 Ok(()) => None,
1891 Err(Error::TrustAnchorRejected { defect, .. }) => Some(defect),
1892 // `check_anchor_profile` constructs no other error.
1893 Err(_) => None,
1894 }
1895}
1896
1897/// Whether the §6.1.1(d) tuple can be formed from `cert` at all.
1898///
1899/// The only structural requirement, and the one defect
1900/// [`AnchorAdmission::AsPublished`] still refuses: §6.1.1(d)(1) needs a
1901/// trusted issuer name, and a subject that names nothing does not
1902/// supply one. Everything else in [`AnchorDefect`] is a statement about
1903/// the certificate rather than about whether an anchor exists.
1904fn anchor_is_structurally_usable(cert: &Certificate) -> crate::Result<()> {
1905 if dn_names_nothing(cert.tbs_certificate().subject()) {
1906 return Err(Error::TrustAnchorRejected {
1907 defect: AnchorDefect::EmptySubject,
1908 });
1909 }
1910 Ok(())
1911}
1912
1913fn check_anchor_profile(cert: &Certificate) -> crate::Result<()> {
1914 use der::Decode as _;
1915 use x509_cert::ext::pkix::{BasicConstraints, KeyUsage};
1916
1917 let reject = |d: AnchorDefect| Err(Error::TrustAnchorRejected { defect: d });
1918
1919 // First, before anything reads the extension list. RFC 5280 §4.2
1920 // forbids a repeated extension, and every check below finds an
1921 // extension by OID and takes the first match -- so on a certificate
1922 // with two of something, the rest of this function would be
1923 // answering about whichever copy happens to come first. Order the
1924 // checks the other way and a duplicate could be reported as a
1925 // verdict on one of its copies instead.
1926 if has_duplicate_extensions(cert) {
1927 return reject(AnchorDefect::DuplicateExtension);
1928 }
1929
1930 // An unhandled critical extension is refused for the anchor on the
1931 // same grounds as §6.1.4 refuses one inside the path: an extension
1932 // marked critical that nothing processes may be saying something
1933 // that changes the answer.
1934 if let Some(exts) = cert.tbs_certificate().extensions() {
1935 for ext in exts {
1936 if ext.critical && !HANDLED_CRITICAL_OIDS.contains(&ext.extn_id) {
1937 return reject(AnchorDefect::UnhandledCriticalExtension);
1938 }
1939 }
1940 }
1941
1942 let raw = |oid: der::asn1::ObjectIdentifier| {
1943 cert.tbs_certificate()
1944 .extensions()
1945 .map_or(&[][..], |v| v.as_slice())
1946 .iter()
1947 .find(move |e| e.extn_id == oid)
1948 };
1949
1950 let Some(bc_ext) = raw(OID_BASIC_CONSTRAINTS) else {
1951 return reject(AnchorDefect::BasicConstraintsMissing);
1952 };
1953 if !bc_ext.critical {
1954 return reject(AnchorDefect::BasicConstraintsNotCritical);
1955 }
1956 let Ok(bc) = BasicConstraints::from_der(bc_ext.extn_value.as_bytes()) else {
1957 // Separate the one non-conforming encoding that occurs in practice
1958 // from genuine malformation: they call for different responses
1959 // from a caller. See `AnchorDefect::NonDerBoolean`.
1960 if has_non_der_boolean(bc_ext.extn_value.as_bytes()) {
1961 return reject(AnchorDefect::NonDerBoolean);
1962 }
1963 return reject(AnchorDefect::MalformedExtension);
1964 };
1965 if !bc.ca {
1966 return reject(AnchorDefect::NotCa);
1967 }
1968
1969 // After cA is known, because the rule is about CAs: §4.1.2.6 permits
1970 // an end entity to carry its name only in a critical SAN, and an
1971 // anchor that is not a CA has already been refused above.
1972 if dn_names_nothing(cert.tbs_certificate().subject()) {
1973 return reject(AnchorDefect::EmptySubject);
1974 }
1975
1976 // Absent `KeyUsage` leaves every usage permitted (RFC 5280
1977 // §4.2.1.3), so only a present-and-contradictory one is a defect.
1978 if let Some(ku_ext) = raw(OID_KEY_USAGE) {
1979 let Ok(ku) = KeyUsage::from_der(ku_ext.extn_value.as_bytes()) else {
1980 return reject(AnchorDefect::MalformedExtension);
1981 };
1982 if !ku.key_cert_sign() {
1983 return reject(AnchorDefect::KeyCertSignMissing);
1984 }
1985 }
1986
1987 Ok(())
1988}
1989
1990/// Read RFC 5280 §6.3.3(f)'s input out of an anchor certificate.
1991///
1992/// Mirrors `pkix_revocation::crl::check_crl_sign`, which does the same
1993/// reading for a CRL issuer that is a path certificate. The duplication
1994/// is deliberate and small: `pkix-path` cannot depend on
1995/// `pkix-revocation` (the dependency runs the other way), and the
1996/// alternative is for `TrustAnchor` to retain the whole certificate so
1997/// that the other crate can re-read it — which is the thing this type
1998/// exists not to do.
1999///
2000/// A malformed `KeyUsage` reports `Withheld` rather than erroring.
2001/// `check_anchor_profile` has already run by the time this is called and
2002/// rejects a malformed `KeyUsage` with `AnchorDefect::MalformedExtension`,
2003/// so this branch is unreachable through `from_cert_ref`; reporting the
2004/// refusing value keeps it fail-closed if a future caller reorders that.
2005/// `pathLenConstraint` from `cert`'s `BasicConstraints`, if it states one.
2006///
2007/// Reads the extension rather than taking it from
2008/// [`check_anchor_profile`], because an anchor admitted under
2009/// [`AnchorAdmission::AsPublished`] skipped that check and still has a
2010/// depth limit its issuer wrote. A missing or unreadable
2011/// `BasicConstraints` yields `None`: an anchor that states no limit, which
2012/// is the same answer a root without the field gives. Nothing is hidden
2013/// by that -- the strict constructors already refuse both cases before
2014/// this is reached.
2015fn anchor_path_len(cert: &Certificate) -> Option<u8> {
2016 use der::Decode as _;
2017 use x509_cert::ext::pkix::BasicConstraints;
2018
2019 let ext = cert
2020 .tbs_certificate()
2021 .extensions()
2022 .map_or(&[][..], |v| v.as_slice())
2023 .iter()
2024 .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)?;
2025 BasicConstraints::from_der(ext.extn_value.as_bytes())
2026 .ok()?
2027 .path_len_constraint
2028}
2029
2030fn anchor_crl_sign(cert: &Certificate) -> AnchorCrlSign {
2031 use der::Decode as _;
2032 use x509_cert::certificate::Version;
2033 use x509_cert::ext::pkix::KeyUsage;
2034
2035 let ku_ext = cert
2036 .tbs_certificate()
2037 .extensions()
2038 .map_or(&[][..], |v| v.as_slice())
2039 .iter()
2040 .find(|e| e.extn_id == OID_KEY_USAGE);
2041
2042 match ku_ext {
2043 // RFC 10007 §4 scopes the presence requirement to v3, because v1
2044 // and v2 have no extensions field to put KeyUsage in. Matching on
2045 // the version and not on "are there any extensions" is the point:
2046 // a v3 certificate with an empty extensions list is still v3.
2047 None if cert.tbs_certificate().version() == Version::V3 => AnchorCrlSign::KeyUsageMissing,
2048 None => AnchorCrlSign::Exempt,
2049 Some(ext) => match KeyUsage::from_der(ext.extn_value.as_bytes()) {
2050 Ok(ku) if ku.crl_sign() => AnchorCrlSign::Asserted,
2051 Ok(_) => AnchorCrlSign::Withheld,
2052 Err(_) => AnchorCrlSign::Withheld,
2053 },
2054 }
2055}
2056
2057// No infallible `From<&Certificate>`: it would be a door into a trust
2058// store that skips `check_anchor_profile`, which is the whole point of
2059// checking. Use `TrustAnchor::from_cert_ref`.
2060impl TryFrom<&Certificate> for TrustAnchor {
2061 type Error = crate::Error;
2062
2063 fn try_from(cert: &Certificate) -> crate::Result<Self> {
2064 Self::from_cert_ref(cert)
2065 }
2066}
2067
2068/// Fail-closed construction from an owned certificate.
2069///
2070/// Returns `Err(`[`DerError`]`)` if the certificate contains a `NameConstraints`
2071/// extension with malformed DER. Use this when building a trust store that
2072/// must reject certificates with unparseable critical extensions per
2073/// RFC 5280 §4.2.
2074///
2075/// The error type is the opaque [`DerError`] newtype rather than `der::Error`
2076/// so that a future major-version bump in the `der` crate does not cascade
2077/// into a semver break here.
2078///
2079/// # Why only `TryFrom<Certificate>` and not `TryFrom<&Certificate>`
2080///
2081/// `TryFrom<&Certificate>` would conflict with the blanket impl
2082/// `impl<T, U: Into<T>> TryFrom<U>` provided by Rust core, because
2083/// `From<&Certificate>` is already implemented (and `From` implies `Into`).
2084/// Use `TrustAnchor::try_from(cert.clone())` if you need to keep `cert`.
2085impl TryFrom<Certificate> for TrustAnchor {
2086 type Error = crate::Error;
2087
2088 fn try_from(cert: Certificate) -> crate::Result<Self> {
2089 // Delegates so there is one fallible path and one error type.
2090 // This impl used to return `DerError` and check only that
2091 // `NameConstraints` parsed and satisfied §4.2.1.10's
2092 // minimum/maximum rule; `from_cert_ref` subsumes that and adds
2093 // the CA-profile checks, and `Error::Der` still carries the
2094 // opaque `DerError` so nothing is lost.
2095 Self::from_cert_ref(&cert)
2096 }
2097}
2098/// Compositional rule for asserting required Subject DN attributes on a leaf cert.
2099///
2100/// Designed to express CA/B Forum S/MIME BR tier rules such as "must have
2101/// `organizationName`" or "must have `pseudonym` OR (`givenName` AND
2102/// `surname`)" without committing the workspace to a fixed list of attribute
2103/// requirements.
2104///
2105/// The [`Field`][Self::Field] variant matches when the named OID appears at
2106/// least once in the leaf's Subject DN RDN sequence (any RDN, any
2107/// `AttributeTypeAndValue` within an RDN). [`AllOf`][Self::AllOf] and
2108/// [`AnyOf`][Self::AnyOf] compose subordinate rules.
2109///
2110/// # Vacuity
2111///
2112/// - `AllOf(vec![])` accepts every Subject DN (vacuously true).
2113/// - `AnyOf(vec![])` rejects every Subject DN (vacuously false).
2114///
2115/// Callers writing `AnyOf` should not pass an empty list unless that is the
2116/// intended semantics.
2117///
2118/// # Example
2119///
2120/// Express "Subject must have `pseudonym`, or both `givenName` and
2121/// `surname`":
2122///
2123/// ```rust
2124/// use pkix_path::DnAttrRule;
2125/// use der::asn1::ObjectIdentifier;
2126///
2127/// const PSEUDONYM: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.65");
2128/// const GIVEN_NAME: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.42");
2129/// const SURNAME: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.4");
2130///
2131/// let rule = DnAttrRule::AnyOf(vec![
2132/// DnAttrRule::Field(PSEUDONYM),
2133/// DnAttrRule::AllOf(vec![
2134/// DnAttrRule::Field(GIVEN_NAME),
2135/// DnAttrRule::Field(SURNAME),
2136/// ]),
2137/// ]);
2138/// # let _ = rule;
2139/// ```
2140#[non_exhaustive]
2141#[derive(Clone, Debug, PartialEq, Eq)]
2142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2143pub enum DnAttrRule {
2144 /// Match when the named attribute OID appears at least once in the
2145 /// leaf's Subject DN.
2146 Field(
2147 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
2148 der::asn1::ObjectIdentifier,
2149 ),
2150 /// Match when every subordinate rule matches. `AllOf(vec![])` is
2151 /// vacuously true.
2152 AllOf(Vec<DnAttrRule>),
2153 /// Match when at least one subordinate rule matches. `AnyOf(vec![])`
2154 /// is vacuously false.
2155 AnyOf(Vec<DnAttrRule>),
2156}
2157
2158/// Walk the Subject DN once and report whether the named OID appears in any
2159/// `AttributeTypeAndValue` within any `RelativeDistinguishedName`.
2160///
2161/// OID equality is exact byte-for-byte comparison; no aliasing or
2162/// canonicalization is performed.
2163fn dn_contains_oid(subject: &x509_cert::name::Name, oid: &der::asn1::ObjectIdentifier) -> bool {
2164 subject.iter().any(|ava| ava.oid == *oid)
2165}
2166
2167/// Evaluate a [`DnAttrRule`] against a Subject DN, returning `true` when the
2168/// rule is satisfied.
2169fn evaluate_dn_attr_rule(subject: &x509_cert::name::Name, rule: &DnAttrRule) -> bool {
2170 match rule {
2171 DnAttrRule::Field(oid) => dn_contains_oid(subject, oid),
2172 DnAttrRule::AllOf(rules) => rules.iter().all(|r| evaluate_dn_attr_rule(subject, r)),
2173 DnAttrRule::AnyOf(rules) => rules.iter().any(|r| evaluate_dn_attr_rule(subject, r)),
2174 }
2175}
2176
2177/// Policy parameters controlling path validation.
2178///
2179/// # Stability
2180///
2181/// `ValidationPolicy` is `#[non_exhaustive]`.
2182/// Construct via [`ValidationPolicy::new`] or [`Default`] + field assignment.
2183/// Do not use struct literal syntax.
2184///
2185/// # Performance note
2186///
2187/// Policy objects are intended to be constructed once (e.g., at server startup)
2188/// and reused for the lifetime of the application. Repeated construction is
2189/// unnecessary.
2190///
2191/// Policy enforcement (`CertificatePolicies`, `PolicyMappings`, `PolicyConstraints`,
2192/// `InhibitAnyPolicy`) is implemented per RFC 5280 §6.1. Use the
2193/// `initial_explicit_policy`, `initial_any_policy_inhibit`,
2194/// `initial_policy_mapping_inhibit`, and `initial_policy_set` fields to
2195/// configure the initial policy state.
2196///
2197/// # Limitations
2198///
2199/// Path-building (RFC 4158 — cross-signed certificates, multiple candidate
2200/// issuers) is **out of scope** for this crate. The caller must supply the
2201/// complete, ordered chain (see `pkix-path-builder` for path discovery).
2202///
2203/// Revocation checking (CRL / OCSP) is out of scope for `pkix-path`; see
2204/// `pkix-revocation` for that functionality.
2205// `clippy::struct_excessive_bools` would prefer enum-typed groupings here,
2206// but the bools map directly to RFC 5280 §6.1.1 named inputs
2207// (`initial-explicit-policy`, `initial-any-policy-inhibit`,
2208// `initial-policy-mapping-inhibit`) and to the SAN-presence and
2209// EKU-presence policy gates. Substituting an enum cluster would obscure the
2210// 1:1 mapping to the spec text and force callers through a pattern-match
2211// adapter for each field. The current shape is the most direct expression
2212// of the spec inputs.
2213#[expect(clippy::struct_excessive_bools)]
2214#[non_exhaustive]
2215#[derive(Clone, Debug, PartialEq, Eq)]
2216#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2217pub struct ValidationPolicy {
2218 /// Maximum chain depth, not counting the trust anchor. Default: 10.
2219 ///
2220 /// A chain of `[leaf]` is depth 0. `[leaf, intermediate, root]` is depth 1
2221 /// (one intermediate). Validation fails if depth exceeds this value.
2222 ///
2223 /// Self-issued certificates do not count towards the depth (RFC 5280
2224 /// §4.2.1.9), but they are not unlimited either: a chain longer than
2225 /// `2 * max_path_len + 3` certificates (the leaf, `max_path_len`
2226 /// intermediates, and up to one self-issued certificate per CA in the
2227 /// path plus one more at the top for an included root) is rejected with
2228 /// [`Error::PathTooLong`] before any other processing. This bounds the
2229 /// work done on an attacker-supplied chain.
2230 pub max_path_len: u8,
2231
2232 /// Current time as seconds since the Unix epoch (1970-01-01T00:00:00Z).
2233 ///
2234 /// Used to check `notBefore` ≤ `now` ≤ `notAfter` on every certificate.
2235 /// **Must be set by the caller** — there is no platform clock in `no_std`.
2236 ///
2237 /// **Warning — the default is 0 (1970-01-01):** Any certificate issued
2238 /// after 1970 has `notBefore > 0` and will fail the validity check with
2239 /// [`Error::ValidityPeriod`]. If you see unexpected `ValidityPeriod`
2240 /// errors, check that `current_time_unix` is set to the current time.
2241 ///
2242 /// **Warning**: passing `u64::MAX` causes all `notAfter` checks to pass.
2243 /// This effectively disables expiry checking — only use it in contexts
2244 /// where you explicitly want permissive (clock-free) validation.
2245 pub current_time_unix: u64,
2246
2247 /// Enforce the `KeyUsage` extension when present. Default: `true`.
2248 ///
2249 /// When `true`, an intermediate certificate whose `KeyUsage` extension is
2250 /// **present** but does not include `keyCertSign` will be rejected with
2251 /// [`Error::KeyUsageMissing`], per RFC 5280 §6.1.4(n).
2252 ///
2253 /// Certificates with **no** `KeyUsage` extension are not affected; RFC 5280
2254 /// only mandates the check when the extension is present.
2255 pub enforce_key_usage: bool,
2256
2257 /// Whether a CA's `ExtendedKeyUsage` constrains what it may issue.
2258 /// Default: `true`.
2259 ///
2260 /// RFC 5280 §6.1 has no EKU step, and §4.2.1.12 says only that the
2261 /// extension "will appear only in end entity certificates" "in
2262 /// general". EKU nesting is therefore not an RFC 5280 path validation
2263 /// rule; it is the `WebPKI` profile's, and it is what every other
2264 /// verifier does — rustls-webpki enforces it, OpenSSL enforces it
2265 /// under `-purpose`, browsers enforce it.
2266 ///
2267 /// It is on by default because without it a CA restricted to one
2268 /// purpose can issue for another, which is the cross-purpose
2269 /// confusion EKU on a CA exists to prevent. The check is chain
2270 /// self-consistency rather than caller policy: a leaf claiming a
2271 /// purpose its own issuer forbids is contradictory whatever the
2272 /// caller asked about, so it does not depend on
2273 /// [`required_leaf_eku`][Self::required_leaf_eku] being set.
2274 ///
2275 /// What it does:
2276 ///
2277 /// * A CA with no `ExtendedKeyUsage` extension constrains nothing.
2278 /// This is the common case and stays free.
2279 /// * A CA whose EKU contains `anyExtendedKeyUsage` constrains
2280 /// nothing.
2281 /// * Otherwise the permitted set narrows by intersection down the
2282 /// chain. Two CAs with disjoint EKUs leave nothing issuable and the
2283 /// path is refused.
2284 /// * A leaf carrying an EKU must share at least one purpose with the
2285 /// permitted set. *Intersection*, not containment: a leaf listing
2286 /// `serverAuth` and `clientAuth` under a `serverAuth`-only
2287 /// intermediate is accepted, because the unusable extra claim is
2288 /// not a reason to refuse a chain that works for what it is being
2289 /// used for. That pattern is common in the real `WebPKI`.
2290 /// * A leaf with no EKU is not refused by this check — it claims no
2291 /// purpose to contradict. `required_leaf_eku` is what rejects such
2292 /// a leaf where a purpose is demanded, and it is additionally
2293 /// checked against the permitted set.
2294 ///
2295 /// Turn it off for a PKI that puts EKUs on CA certificates
2296 /// decoratively rather than restrictively.
2297 ///
2298 /// # Known tension: delegated OCSP responders
2299 ///
2300 /// RFC 6960 §4.2.2.2 has a CA designate a responder by issuing it a
2301 /// certificate carrying `id-kp-OCSPSigning`. It does not require the
2302 /// CA itself to carry that purpose — so a CA restricted to
2303 /// `serverAuth`, which is what the CA/B Forum requires of a TLS
2304 /// subordinate, cannot designate a responder without failing this
2305 /// check. Other implementations carve `id-kp-OCSPSigning` out of
2306 /// nesting for exactly this reason.
2307 ///
2308 /// No carve-out is made here, because nothing in this workspace needs
2309 /// one: `pkix_revocation`'s OCSP code establishes a CA-designated
2310 /// responder by checking the responder certificate's own EKU and its
2311 /// issuance by the subject's CA, and never validates the responder as
2312 /// a path through this function. A caller who *does* validate a
2313 /// delegated responder certificate as a path under an EKU-restricted
2314 /// CA will see [`Error::EkuNotPermittedByIssuer`], and wants this flag
2315 /// off for that call. Said here rather than carved out silently, so
2316 /// the choice is visible to whoever hits it.
2317 pub enforce_ca_eku: bool,
2318
2319 /// Require `cRLSign` in `KeyUsage` on every intermediate CA. Default: `false`.
2320 ///
2321 /// When `true`, an intermediate certificate whose `KeyUsage` extension is
2322 /// **present** but does not include `cRLSign` will be rejected with
2323 /// [`Error::CrlSignMissing`]. Certificates with **no** `KeyUsage` extension
2324 /// are not affected.
2325 ///
2326 /// RFC 5280 §6.1 does not mandate this check — it conflates path validation
2327 /// with revocation infrastructure. PKITS §4.7.4 and §4.7.5 nonetheless
2328 /// expect such chains to fail because a CA cert without `cRLSign` cannot
2329 /// revoke certs it issued. Enable this flag to restore PKITS conformance
2330 /// or to enforce a stricter "every CA must be able to sign CRLs" rule.
2331 ///
2332 /// This check is independent of [`enforce_key_usage`][Self::enforce_key_usage]:
2333 /// `enforce_key_usage` governs the RFC-mandated `keyCertSign` check, while
2334 /// `require_crl_sign_on_cas` adds a separate cRLSign requirement.
2335 pub require_crl_sign_on_cas: bool,
2336
2337 /// Initial explicit-policy indicator (RFC 5280 §6.1.1).
2338 ///
2339 /// When `true`, path validation requires that at least one valid policy exists
2340 /// from the initial policy set. When `false` (the default), any valid path is
2341 /// accepted even if no certificate policy is asserted.
2342 pub initial_explicit_policy: bool,
2343
2344 /// Initial any-policy inhibit indicator (RFC 5280 §6.1.1).
2345 ///
2346 /// When `true`, the `anyPolicy` OID is not considered a match for any other
2347 /// policy at the start of the path. When `false` (the default), `anyPolicy`
2348 /// is accepted as a wildcard unless later inhibited by a CA certificate.
2349 pub initial_any_policy_inhibit: bool,
2350
2351 /// Initial policy-mapping inhibit indicator (RFC 5280 §6.1.1).
2352 ///
2353 /// When `true`, policy mappings are not permitted in any certificate in the
2354 /// chain. When `false` (the default), policy mappings are allowed.
2355 pub initial_policy_mapping_inhibit: bool,
2356
2357 /// Initial user-requested policy set (RFC 5280 §6.1.1).
2358 ///
2359 /// The set of certificate policies acceptable to the relying party. An empty
2360 /// vec, or any set that contains `anyPolicy` (2.5.29.32.0), is the RFC's
2361 /// any-policy value: all policies are acceptable and the policy graph is
2362 /// not intersected (§6.1.5(g)(ii)). Otherwise the final graph keeps only
2363 /// policies in this set (§6.1.5(g)(iii)).
2364 ///
2365 /// Note: this is `pub` but clones the OID set, so prefer constructing once
2366 /// and reusing the `ValidationPolicy`.
2367 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
2368 pub initial_policy_set: Vec<der::asn1::ObjectIdentifier>,
2369
2370 /// If `Some(n)`, reject any certificate whose (notAfter − notBefore) exceeds
2371 /// `n` seconds. `None` means unconstrained (the default).
2372 ///
2373 /// Applied to every certificate in the chain, not just the leaf.
2374 /// Violations produce [`Error::ValidityPeriodExceedsMax`].
2375 pub max_validity_secs: Option<u64>,
2376
2377 /// If `Some(list)`, reject any certificate whose signature algorithm OID is
2378 /// not in `list`. `None` means any algorithm is accepted (the default).
2379 ///
2380 /// Applied to every certificate in the chain. The check fires **before**
2381 /// signature verification so the error is diagnostic rather than a confusing
2382 /// [`Error::SignatureInvalid`].
2383 /// Violations produce [`Error::AlgorithmNotAllowed`].
2384 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
2385 pub allowed_signature_algs: Option<Vec<der::asn1::ObjectIdentifier>>,
2386
2387 /// If `Some(bits)`, reject any certificate carrying an RSA public key whose
2388 /// modulus is fewer than `bits` bits. Both `rsaEncryption` and
2389 /// `id-RSASSA-PSS` subject keys count as RSA; other keys are not affected.
2390 /// `None` means unconstrained (the default).
2391 ///
2392 /// Applied to the subject key of every certificate in the chain, leaf
2393 /// included. The trust anchor's key is **not** checked: it is caller
2394 /// configuration, not path input, so filter weak anchors when building
2395 /// the trust store.
2396 /// Violations produce [`Error::KeyTooSmall`].
2397 pub min_rsa_key_bits: Option<u32>,
2398
2399 /// If `true`, the leaf certificate (chain index 0) must have a non-empty
2400 /// `SubjectAltName` extension. `false` means no SAN requirement (the default).
2401 ///
2402 /// Intermediate CA certificates are not checked by this field.
2403 /// Violations produce [`Error::MissingSan`].
2404 pub require_subject_alt_name: bool,
2405
2406 /// If `true`, at least one `rfc822Name` entry must be present in the leaf's
2407 /// `SubjectAltName` extension.
2408 ///
2409 /// Only meaningful when [`require_subject_alt_name`][Self::require_subject_alt_name]
2410 /// is also `true`. When `require_subject_alt_name` is `false`, this field has
2411 /// no effect.
2412 ///
2413 /// Default: `false` (backward compatible).
2414 /// Violations produce [`Error::MissingRfc822San`].
2415 pub require_rfc822_san: bool,
2416
2417 /// If `Some(oids)`, the leaf certificate must explicitly assert every OID in
2418 /// `oids` via its `ExtendedKeyUsage` extension. `None` means no EKU requirement
2419 /// (the default).
2420 ///
2421 /// `anyExtendedKeyUsage` (2.5.29.37.0) does **not** satisfy a specific OID
2422 /// check — each required OID must be listed in the cert's EKU extension.
2423 /// Violations produce [`Error::MissingEku`].
2424 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
2425 pub required_leaf_eku: Option<Vec<der::asn1::ObjectIdentifier>>,
2426
2427 /// If `Some(oids)`, the leaf certificate must explicitly assert every OID
2428 /// in `oids` via its `CertificatePolicies` extension. `None` means no
2429 /// policy-OID assertion requirement (the default).
2430 ///
2431 /// Distinct from [`initial_policy_set`][Self::initial_policy_set]:
2432 /// `initial_policy_set` is the relying party's *acceptable* policy set
2433 /// (RFC 5280 §6.1.1, `user-initial-policy-set`).
2434 /// `required_leaf_policy_oids` requires *assertion* — the OID must appear
2435 /// on the leaf cert's `CertificatePolicies` extension, independent of the
2436 /// policy tree.
2437 ///
2438 /// `anyPolicy` (2.5.29.32.0) does **not** satisfy a specific OID check.
2439 /// Violations produce [`Error::MissingLeafPolicyOid`].
2440 ///
2441 /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
2442 /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
2443 /// subscriber-profile tier disambiguation where a tier mandates assertion
2444 /// of a specific reserved policy OID.
2445 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
2446 pub required_leaf_policy_oids: Option<Vec<der::asn1::ObjectIdentifier>>,
2447
2448 /// If `Some(rule)`, the leaf certificate's Subject DN must satisfy
2449 /// `rule`. `None` means no Subject DN requirement (the default).
2450 ///
2451 /// Violations produce [`Error::SubjectDnAttrRuleUnmet`]. See
2452 /// [`DnAttrRule`] for the expression grammar and vacuity rules.
2453 ///
2454 /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
2455 /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
2456 /// subscriber-profile tier disambiguation (e.g., S/MIME
2457 /// Organization-validated tier requires `organizationName`).
2458 pub required_leaf_subject_dn_attrs: Option<DnAttrRule>,
2459}
2460
2461impl ValidationPolicy {
2462 /// Construct a policy with the given time and sensible defaults.
2463 ///
2464 /// This is the only constructor: it forces the caller to supply a timestamp,
2465 /// preventing the silent validity failures that a `Default` with
2466 /// `current_time_unix = 0` would cause.
2467 ///
2468 /// # What `now_unix` selects, and what it does not
2469 ///
2470 /// `now_unix` is **the moment at which validity periods are
2471 /// evaluated**: `notBefore <= now_unix <= notAfter` for every
2472 /// certificate in the chain, and the freshness of any CRL or OCSP
2473 /// response a revocation checker consults.
2474 ///
2475 /// It does **not** select which version of any rule set is in force.
2476 /// The rules applied are the ones encoded in this
2477 /// `ValidationPolicy`'s own fields at the moment you build it, which
2478 /// are this workspace's current reading of the specifications.
2479 /// Passing a `now_unix` of 2019 does not validate the chain against
2480 /// the CA/B Forum Baseline Requirements as they stood in 2019; it
2481 /// validates against today's rules, asking whether the certificates
2482 /// were within their validity periods in 2019.
2483 ///
2484 /// The distinction has a sharp edge, which is why it is spelled out
2485 /// rather than left to be inferred: a chain whose certificates have
2486 /// expired fails for the clock, and a chain issued under a rule this
2487 /// workspace now enforces more strictly fails for the rules, and
2488 /// moving `now_unix` changes only the first.
2489 ///
2490 /// # A third thing, easy to confuse with the second
2491 ///
2492 /// Some rules are themselves written to change on a date, and those
2493 /// dates belong to the rule rather than to `now_unix`. CA/B Forum
2494 /// Ballot SC-081's validity cap steps down on fixed dates, and
2495 /// `pkix_profiles_cabf::sc081_validity_cap` takes the certificate's
2496 /// **`notBefore`** for exactly that reason: SC-081 says the cap in
2497 /// force at issuance governs a certificate for its whole life, so a
2498 /// relying party's clock is the wrong input and would reject
2499 /// certificates issued legitimately under an earlier cap. That is
2500 /// the current rule set being date-dependent, not an older rule set
2501 /// being selected.
2502 ///
2503 /// # Evaluating against the rules of a past date
2504 ///
2505 /// This workspace does not offer that, deliberately: it evaluates
2506 /// against the current regime only. For a version-pinned historical
2507 /// judgement, use `pkix-policy-zlint` with a pinned lint set, which
2508 /// is an out-of-process oracle and can carry a rule set this one
2509 /// does not.
2510 #[must_use]
2511 pub fn new(now_unix: u64) -> Self {
2512 Self {
2513 max_path_len: 10,
2514 current_time_unix: now_unix,
2515 enforce_key_usage: true,
2516 enforce_ca_eku: true,
2517 require_crl_sign_on_cas: false,
2518 initial_explicit_policy: false,
2519 initial_any_policy_inhibit: false,
2520 initial_policy_mapping_inhibit: false,
2521 initial_policy_set: Vec::new(),
2522 max_validity_secs: None,
2523 allowed_signature_algs: None,
2524 min_rsa_key_bits: None,
2525 require_subject_alt_name: false,
2526 require_rfc822_san: false,
2527 required_leaf_eku: None,
2528 required_leaf_policy_oids: None,
2529 required_leaf_subject_dn_attrs: None,
2530 }
2531 }
2532}
2533
2534/// A PKI regime profile that bundles identity, citation, and a validation policy.
2535///
2536/// # Design rationale
2537///
2538/// `ValidationPolicy` is the *mechanism*. A `Profile` is the *policy authority*: it
2539/// records *who* mandates the policy (e.g., CA/B Forum TLS BR §7.1), supplies a
2540/// stable machine-readable identifier, and produces the appropriate
2541/// [`ValidationPolicy`] for a given point in time.
2542///
2543/// Placing the trait in `pkix-path` rather than `pkix-profiles` means that third-party
2544/// profile crates (e.g., `pkix-fpki`, `pkix-etsi`) can implement `Profile` by depending
2545/// only on `pkix-path` — they do not need to pull in `pkix-profiles`, which would create
2546/// a circular coupling between reference implementations and the trait definition.
2547///
2548/// # `no_std` compatibility
2549///
2550/// The trait is `no_std`-safe: it uses only `&str`, `&[ObjectIdentifier]`, and
2551/// `ValidationPolicy` (all of which are available without `std`).
2552/// Implementors on embedded targets may return static `&'static str` slices and
2553/// construct `ValidationPolicy` without allocation.
2554///
2555/// # Implementing `Profile`
2556///
2557/// ```rust,no_run
2558/// use pkix_path::{Profile, ValidationPolicy};
2559///
2560/// struct MyCorpProfile;
2561///
2562/// impl Profile for MyCorpProfile {
2563/// fn id(&self) -> &'static str { "example.corp.internal" }
2564/// fn version(&self) -> &'static str { "2024-01" }
2565/// fn policy(&self, now_unix: u64) -> ValidationPolicy {
2566/// let mut p = ValidationPolicy::new(now_unix);
2567/// p.max_validity_secs = Some(365 * 86_400);
2568/// p
2569/// }
2570/// fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier] { &[] }
2571/// }
2572/// ```
2573pub trait Profile {
2574 /// Stable, dot-separated identifier for this profile.
2575 ///
2576 /// The identifier MUST be unique across all deployed profiles and MUST NOT
2577 /// change between versions of the same profile. Use reverse-DNS or
2578 /// CABF/IETF-style naming conventions, e.g.:
2579 /// - `"cabf.br.tls"` — CA/B Forum TLS Baseline Requirements
2580 /// - `"cabf.smime.mailbox"` — CA/B Forum S/MIME Baseline Requirements
2581 /// - `"fpki.common-policy"` — US Federal PKI Common Policy
2582 ///
2583 /// Lint engines use this ID as a namespace prefix for finding IDs.
2584 fn id(&self) -> &'static str;
2585
2586 /// Human-readable version string for this profile.
2587 ///
2588 /// Typically the ballot or specification version that last changed the
2589 /// policy rules, e.g., `"SC-081"`, `"2024-01"`, or `"v2.0.1"`.
2590 /// Used for diagnostic messages and audit logs; not parsed by the engine.
2591 fn version(&self) -> &'static str;
2592
2593 /// Produce the [`ValidationPolicy`] for the given point in time.
2594 ///
2595 /// `now_unix` is seconds since the Unix epoch, and carries the same
2596 /// meaning here as in [`ValidationPolicy::new`], whose rustdoc states
2597 /// it in full: the moment validity periods are evaluated at, and
2598 /// **not** a selector for which version of the rules applies. The
2599 /// returned `ValidationPolicy` MUST have `current_time_unix` set to
2600 /// `now_unix`.
2601 ///
2602 /// A profile *may* key a rule on `now_unix`, and this doc said so for
2603 /// a long time by naming "phased validity caps or algorithm
2604 /// retirement schedules" as the use. That was aspirational and in one
2605 /// case actively misleading, so it is stated precisely instead: no
2606 /// profile in this workspace keys anything on `now_unix`, every one
2607 /// of them passes it to `ValidationPolicy::new` and sets its other
2608 /// fields unconditionally -- and the phased cap people reach for,
2609 /// CA/B Forum SC-081, **must not** key on it. `sc081_validity_cap`
2610 /// takes the certificate's `notBefore`, because SC-081 fixes the cap
2611 /// at issuance for the certificate's whole life; feeding it a
2612 /// relying party's clock would reject certificates issued
2613 /// legitimately under an earlier, more permissive cap.
2614 #[must_use]
2615 fn policy(&self, now_unix: u64) -> ValidationPolicy;
2616
2617 /// The certificate policy OIDs that this profile recognises as its own.
2618 ///
2619 /// Used by registry and composition tools to detect when two profiles
2620 /// claim overlapping policy space. Returns an empty slice if the profile
2621 /// does not restrict certificate policy OIDs.
2622 fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier];
2623}
2624
2625/// The result of a successful certificate path validation.
2626///
2627/// A `ValidatedPath` is only produced when [`validate_path`] succeeds, which
2628/// requires the input `chain` to contain at least one certificate. Callers
2629/// may therefore rely on `chain[0]` being valid after a successful validation.
2630///
2631/// Fields are `pub` for direct read access. `#[non_exhaustive]` prevents external
2632/// code from constructing `ValidatedPath` directly and from pattern-matching
2633/// exhaustively, preserving the ability to add fields in future minor versions
2634/// without a breaking change.
2635///
2636/// # `Copy` removal in 0.3.0
2637///
2638/// `ValidatedPath` is no longer `Copy`. The struct now carries owned
2639/// heap-backed fields exposing RFC 5280 §6.1.5 wrap-up outputs (the leaf's
2640/// subject DN, issuer DN, serial number, and `SubjectPublicKeyInfo`) so
2641/// consumers can read the validated leaf identity without re-parsing
2642/// `chain[0]`. These fields cannot satisfy the `Copy` bound; pre-0.3
2643/// callers that relied on bit-copy semantics need to add `.clone()` or
2644/// pass `&ValidatedPath` instead.
2645///
2646/// # §6.1.5 wrap-up outputs
2647///
2648/// RFC 5280 §6.1.5 specifies that successful path validation produces
2649/// several outputs identifying the validated leaf certificate. The four
2650/// leaf-intrinsic outputs (subject, issuer, serial, SPKI) are surfaced
2651/// here as convenience accessors; consumers no longer need to re-parse
2652/// `chain[0]` to obtain them.
2653///
2654/// The final `valid_policy_tree` is surfaced as
2655/// [`valid_policy_tree`][Self::valid_policy_tree]. The final
2656/// `working_public_key_parameters` is not yet surfaced; future minor
2657/// versions may add it, so callers should pattern match with `..` rest
2658/// patterns on this `#[non_exhaustive]` struct.
2659///
2660/// `Hash` is no longer derived because none of the new field types
2661/// (`x509_cert::name::Name`, `x509_cert::serial_number::SerialNumber`,
2662/// `spki::SubjectPublicKeyInfoOwned`) implement `Hash` upstream. No
2663/// in-tree consumer used `ValidatedPath` as a `HashMap`/`HashSet` key,
2664/// so dropping the derive is observable but should not require code
2665/// changes for any existing user.
2666#[derive(Clone, Debug, PartialEq, Eq)]
2667#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2668#[non_exhaustive]
2669pub struct ValidatedPath {
2670 /// Index into the `anchors` slice of the trust anchor that terminated the path.
2671 pub anchor_index: usize,
2672 /// Number of intermediate certificates in the validated chain, excluding
2673 /// both the leaf and the trust anchor.
2674 ///
2675 /// Computed as `chain.len().saturating_sub(1)` where `chain` is the
2676 /// `[leaf, intermediate_0, ..., intermediate_n]` slice passed to
2677 /// [`validate_path`]. A single leaf certificate yields `depth == 0`;
2678 /// a leaf plus one intermediate yields `depth == 1`.
2679 ///
2680 /// Note: this counts all certificates except the trust anchor — including
2681 /// self-issued intermediates that RFC 5280 §4.2.1.9 excludes from the
2682 /// `pathLenConstraint` count. For chains with self-issued intermediates the
2683 /// `depth` field may be larger than the RFC 5280 path length.
2684 ///
2685 /// **Do not** compare `depth` directly against a certificate's
2686 /// [`BasicConstraints`] `pathLenConstraint` value. RFC 5280 §4.2.1.9
2687 /// defines `pathLenConstraint` as the number of non-self-issued
2688 /// intermediates below the issuing CA, which differs from this field's
2689 /// total certificate count. Use the RFC 5280 §6.1.4(b) accounting
2690 /// performed by `chain_walk` instead.
2691 ///
2692 /// [`BasicConstraints`]: x509_cert::ext::pkix::BasicConstraints
2693 pub depth: usize,
2694
2695 /// Subject DN of the validated leaf certificate (`chain[0].subject`).
2696 ///
2697 /// RFC 5280 §6.1.5 names this output indirectly: a successful path
2698 /// validation produces the leaf's identity (subject + serial uniquely
2699 /// identify a certificate). This field is a convenience accessor —
2700 /// callers could equivalently read `chain[0].tbs_certificate().subject()`,
2701 /// but threading the chain to every consumer that needs the leaf's DN
2702 /// is awkward. The clone is owned to free the validated value from any
2703 /// lifetime tie to the input chain.
2704 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
2705 pub leaf_subject: x509_cert::name::Name,
2706
2707 /// Issuer DN of the validated leaf certificate (`chain[0].issuer`).
2708 ///
2709 /// This is the §6.1.5(f) `working_issuer_name` output as observed at
2710 /// the leaf cert (which is the first cert processed by the §6.1
2711 /// algorithm, so the leaf's `issuer` is the initial value of
2712 /// `working_issuer_name` before iteration begins; for a successfully
2713 /// validated chain it identifies the directly-signing CA).
2714 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
2715 pub leaf_issuer: x509_cert::name::Name,
2716
2717 /// Serial number of the validated leaf certificate
2718 /// (`chain[0].serial_number`).
2719 ///
2720 /// Together with [`Self::leaf_issuer`] this forms the RFC 5280
2721 /// §4.1.2.2 unique certificate identifier (`{ issuer, serial }`),
2722 /// which downstream code commonly needs for revocation lookups,
2723 /// audit logging, or de-duplication.
2724 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
2725 pub leaf_serial: x509_cert::serial_number::SerialNumber,
2726
2727 /// `SubjectPublicKeyInfo` of the validated leaf certificate.
2728 ///
2729 /// This is the §6.1.5(c)(d)(e) `working_public_key` /
2730 /// `working_public_key_algorithm` / `working_public_key_parameters`
2731 /// outputs, bundled into the canonical SPKI form. Downstream code
2732 /// (e.g. application-layer signature verification using the validated
2733 /// leaf as a trust delegate) needs the full SPKI rather than only the
2734 /// algorithm identifier or only the public-key bits.
2735 ///
2736 /// Note: this field reflects the leaf's *encoded* SPKI as it appeared
2737 /// in the certificate, not a normalized/canonicalized form. PSS
2738 /// parameters, RSA `parameters: NULL` vs `parameters: absent`
2739 /// ambiguities, etc. are preserved verbatim.
2740 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
2741 pub leaf_spki: spki::SubjectPublicKeyInfoOwned,
2742
2743 /// The final RFC 5280 §6.1.5 `valid_policy_tree` (held as the RFC 9618
2744 /// policy graph, see [`PolicyTreeNode`]), or `None` if it was reduced to
2745 /// NULL during validation.
2746 ///
2747 /// `Some(tree)` is the post-§6.1.5(g)(iii) state (i.e. after
2748 /// intersection with `initial_policy_set` and post-pruning), listed
2749 /// depth by depth starting with the depth-0 root.
2750 /// `None` means the path validated only because `explicit_policy`
2751 /// stayed above 0 (no explicit policy was required) — semantically "no
2752 /// acceptable policy is valid for this path". Callers that want to enforce a specific policy OID
2753 /// (or extract qualifiers attached to a specific policy) should
2754 /// inspect this field and treat `None` as "no policy information
2755 /// available", not as a validation failure.
2756 ///
2757 /// Each node carries its policy qualifiers (RFC 5280 §6.1.2(a)) in
2758 /// the upstream `PolicyQualifierInfo` form (a `(qualifier_id_oid,
2759 /// raw_any_value)` pair, no decoding of `qualifier`). See
2760 /// [`PolicyTreeNode`] for the per-node shape.
2761 ///
2762 /// For convenience, [`Self::policy_qualifiers`] iterates
2763 /// `(policy_oid, qualifier)` pairs across all tree nodes.
2764 pub valid_policy_tree: Option<Vec<PolicyTreeNode>>,
2765}
2766
2767/// A node of the final policy graph, exposed for post-validation qualifier
2768/// extraction on [`ValidatedPath::valid_policy_tree`].
2769///
2770/// Policy processing uses the RFC 9618 `valid_policy_graph` in place of the
2771/// RFC 5280 §6.1.2(a) `valid_policy_tree`: there is at most one node per
2772/// `(depth, valid_policy)`, and a node that the RFC 5280 tree would copy
2773/// once per parent appears once, listing every parent in
2774/// [`parent_policies`][Self::parent_policies]. The set of valid policies is
2775/// the same (RFC 9618 §3); the graph's size stays linear in the size of the
2776/// path's policy extensions, where the tree can grow exponentially.
2777///
2778/// This is the public mirror of an internal node type, kept separate so the
2779/// internal representation is not part of the public API surface.
2780#[derive(Clone, Debug, PartialEq, Eq)]
2781#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2782#[non_exhaustive]
2783pub struct PolicyTreeNode {
2784 /// Depth at which this node appears in the tree.
2785 ///
2786 /// `0` is the synthetic anyPolicy root sentinel (always present
2787 /// while the tree is alive; carries no qualifiers). `1` is the
2788 /// trust-anchor-adjacent CA. `n` is the leaf.
2789 pub depth: usize,
2790
2791 /// The policy OID this node represents.
2792 ///
2793 /// May be `id-ce-certificatePolicies-anyPolicy` (2.5.29.32.0) for
2794 /// nodes that survived an anyPolicy expansion or were not yet
2795 /// materialized into specific policies.
2796 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
2797 pub valid_policy: der::asn1::ObjectIdentifier,
2798
2799 /// Set of policies in the next certificate that are consistent with
2800 /// this node, per RFC 5280 §6.1.2(a) `expected_policy_set`.
2801 ///
2802 /// Initialized to `{valid_policy}` and updated by `PolicyMappings`
2803 /// extensions during the walk.
2804 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
2805 pub expected_policy_set: Vec<der::asn1::ObjectIdentifier>,
2806
2807 /// Policy qualifiers attached to this node, in the upstream
2808 /// `PolicyQualifierInfo` form: a `(policy_qualifier_id, qualifier)`
2809 /// pair where `qualifier` is a raw `der::Any`. The two standard
2810 /// qualifier IDs are `id-qt-cps` (1.3.6.1.5.5.7.2.1, qualifier is a
2811 /// `CPSuri` / `IA5String`) and `id-qt-unotice` (1.3.6.1.5.5.7.2.2,
2812 /// qualifier is a `UserNotice`).
2813 ///
2814 /// # Why the qualifier is passed through undecoded
2815 ///
2816 /// `x509_cert::ext::pkix::certpolicy` cannot decode two of the shapes
2817 /// RFC 5280 §4.2.1.4 defines, as of x509-cert 0.3.1:
2818 ///
2819 /// - `UserNotice::notice_ref` is declared `Option<GeneralizedTime>`.
2820 /// RFC 5280 says `NoticeReference`, which is a `SEQUENCE` of a
2821 /// `DisplayText` and a `SEQUENCE OF INTEGER`. The crate defines
2822 /// `NoticeReference` correctly in the same module and never uses
2823 /// it, so a `UserNotice` that actually carries a `noticeRef` fails
2824 /// to decode.
2825 /// - `DisplayText` implements only the `ia5String` and `utf8String`
2826 /// alternatives of a four-way CHOICE; `visibleString` and
2827 /// `bmpString` are absent, and the type's own documentation says
2828 /// so. `der` has carried `Tag::VisibleString` and `Tag::BmpString`
2829 /// since RustCrypto/formats#160, so the tags are available.
2830 ///
2831 /// The second defect became the more consequential one with RFC 6818
2832 /// §3, which replaced §4.2.1.4's encoding guidance: `visibleString`
2833 /// and `bmpString` went from MUST NOT to "acceptable but less
2834 /// preferred", and `ia5String` went from MAY to MUST NOT. So the
2835 /// upstream `DisplayText` now decodes exactly the one encoding the
2836 /// profile prohibits and neither of the two it newly permits.
2837 ///
2838 /// Passing the `Any` through costs a caller the decode and keeps both
2839 /// defects out of this crate's results. `rfc5280.cert.policies.explicit_text_encoding`
2840 /// reads the `DisplayText` tag directly for the same reason.
2841 ///
2842 /// An earlier version of this comment called the first defect a
2843 /// "typo on `notice_ref`" and cited
2844 /// `github.com/RustCrypto/formats/issues/x509-cert`, which is not an
2845 /// issue URL. No upstream issue exists for either defect; searching
2846 /// RustCrypto/formats for `UserNotice` and `NoticeReference` returns
2847 /// nothing.
2848 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
2849 pub qualifiers: Vec<x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo>,
2850
2851 /// `valid_policy` of each parent node at `depth - 1` (nodes are unique
2852 /// per depth, so the OID identifies the parent). Empty for the depth-0
2853 /// root. A node's parents are either exactly `[anyPolicy]` or a set of
2854 /// specific policies.
2855 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
2856 pub parent_policies: Vec<der::asn1::ObjectIdentifier>,
2857}
2858
2859impl ValidatedPath {
2860 /// Iterate `(policy_oid, qualifier)` pairs across every node in the
2861 /// final policy tree.
2862 ///
2863 /// Returns an empty iterator if the tree is `None` (it was reduced to
2864 /// NULL during validation, which is only accepted while no explicit
2865 /// policy is required).
2866 ///
2867 /// Each yielded pair is `(node.valid_policy, &qualifier)` — the
2868 /// qualifier is a reference into the tree, valid for the borrow
2869 /// duration. Multiple qualifiers attached to the same policy yield
2870 /// multiple pairs with equal first elements; multiple nodes with the
2871 /// same policy OID at different depths also yield multiple pairs.
2872 ///
2873 /// Callers commonly need to:
2874 ///
2875 /// 1. Filter by `policy_qualifier_id` to find a specific qualifier
2876 /// type (CPS pointer or user notice).
2877 /// 2. Read `qualifier.qualifier` (an `Option<der::Any>`) and decode
2878 /// according to the `policy_qualifier_id`. See [`PolicyTreeNode::qualifiers`]
2879 /// for why we do not decode upstream-side.
2880 pub fn policy_qualifiers(
2881 &self,
2882 ) -> impl Iterator<
2883 Item = (
2884 &der::asn1::ObjectIdentifier,
2885 &x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo,
2886 ),
2887 > + '_ {
2888 self.valid_policy_tree
2889 .as_ref()
2890 .into_iter()
2891 .flat_map(|tree| tree.iter())
2892 .flat_map(|node| node.qualifiers.iter().map(move |q| (&node.valid_policy, q)))
2893 }
2894}
2895
2896/// Validate a certificate chain from subject to a trust anchor.
2897///
2898/// `chain` must be ordered leaf-first:
2899/// - `chain[0]` is the subject (end-entity) certificate
2900/// - `chain[1..]` are intermediates in issuer order
2901/// - The last element of `chain` must be issued by one of `anchors`
2902///
2903/// Validation follows RFC 5280 §6.1. Each certificate's signature is verified
2904/// using `verifier`, with the signing key taken from the next certificate in
2905/// the chain (or the matching trust anchor for the last cert).
2906///
2907/// # Including the root certificate
2908///
2909/// The self-signed certificate of the trust anchor may be passed as the last
2910/// element of `chain`. It is then processed as path certificate 1 of
2911/// RFC 5280 §6.1 rather than skipped: its own signature, validity period,
2912/// `BasicConstraints`, `KeyUsage`, name constraints and policy extensions all
2913/// apply. In particular a root without a `CertificatePolicies` extension
2914/// (the common case) reduces the policy tree to NULL (§6.1.3(e)), so a
2915/// path that requires an explicit policy fails when the root is included
2916/// and succeeds when it is supplied only as the anchor. Pass the root only
2917/// in `anchors` unless its constraints are meant to apply as a path
2918/// certificate.
2919///
2920/// # Errors
2921///
2922/// Returns `Err(Error::NoTrustedPath)` if `chain` is empty or `anchors` is
2923/// empty. On success, `chain` is therefore guaranteed to contain at least one
2924/// certificate.
2925///
2926/// Returns `Err` on the first RFC 5280 §6.1 check failure. The error variant
2927/// includes the chain index of the failing certificate where applicable.
2928///
2929/// # The validation moment is already fixed
2930///
2931/// This takes a `&ValidationPolicy`, so the moment validity periods are
2932/// evaluated at was chosen when that policy was built. See
2933/// [`ValidationPolicy::new`] for what `now_unix` does and does not
2934/// select -- in short, it is the clock and not a selector for which
2935/// version of the rules applies.
2936///
2937/// # Limitations
2938///
2939/// See crate-level documentation for current scope limits.
2940pub fn validate_path<V, C>(
2941 chain: &[C],
2942 anchors: &[TrustAnchor],
2943 policy: &ValidationPolicy,
2944 verifier: &V,
2945) -> Result<ValidatedPath>
2946where
2947 V: SignatureVerifier,
2948 C: PathCertificate,
2949{
2950 // (0) Cheap length bound before anything that is super-linear in the
2951 // chain length (the pairwise duplicate scan in `check_inputs`, and
2952 // the DN comparisons it and the self-issued count perform). See the
2953 // `max_path_len` rustdoc for how the bound is derived.
2954 if chain.len() > max_chain_certs(policy.max_path_len) {
2955 return Err(Error::PathTooLong);
2956 }
2957
2958 // (1) Input guards: reject empty chain or anchors, check OID consistency.
2959 check_inputs(chain, anchors)?;
2960 check_oid_consistency(chain)?;
2961
2962 // (2) Path-length check (anchor-independent).
2963 // RFC 5280 §4.2.1.9: pathLen counts non-self-issued intermediates only.
2964 let num_non_si_intermediates = chain[1..]
2965 .iter()
2966 .map(PathCertificate::certificate)
2967 .filter(|c| !is_self_issued_cert(c))
2968 .count();
2969 if num_non_si_intermediates > policy.max_path_len as usize {
2970 return Err(Error::PathTooLong);
2971 }
2972
2973 // (3) Try each name-matching anchor. Iterating all candidates handles key
2974 // rollover: multiple anchors may share a DN but have different keys
2975 // (e.g., during a root CA rotation). The first anchor that passes the
2976 // full chain walk is used; the last error is returned if none succeed.
2977 //
2978 // Complexity: O(A × N) where A = number of anchors, N = chain length.
2979 // For the common case of O(1) matching anchors this is effectively O(N).
2980 //
2981 // A caller validating many candidate chains against a large anchor
2982 // store pays that A per candidate, and the obvious optimisation --
2983 // identify the matching anchor once, outside the loop, and hand it
2984 // in -- IS NOT AVAILABLE. Two reasons, and the second is a
2985 // correctness one:
2986 //
2987 // - candidates differ in their deepest certificate, so they do
2988 // not share an issuer DN to match against;
2989 // - more than one anchor may match a single DN, which is the
2990 // rollover case this loop exists to handle. Pre-selecting one
2991 // index would pick a key and fail when the other anchor holds
2992 // the one that signed.
2993 //
2994 // What the A actually costs is a DN comparison under RFC 4518
2995 // string prep, not a signature verification; only an anchor whose
2996 // name matches reaches the expensive work. So the loop is wide and
2997 // shallow by design. See PKIX-wnnn.9.
2998 let last_cert = chain.last().ok_or(Error::NoTrustedPath)?.certificate();
2999 let is_self_issued = names_match(
3000 last_cert.tbs_certificate().issuer(),
3001 last_cert.tbs_certificate().subject(),
3002 );
3003 let mut last_err = Error::NoTrustedPath;
3004 // An anchor outside its validity window is recorded and skipped
3005 // rather than returned immediately: with several anchors, one being
3006 // expired must not stop a live one from matching. If nothing else
3007 // matches, the expiry is the better answer than `NoTrustedPath`,
3008 // because it says what is actually wrong.
3009 //
3010 // `Expired` outranks `NotYetValid` when both are seen, so that the
3011 // reported defect does not depend on the order the trust store
3012 // happened to supply its anchors in. A rollover pair straddling the
3013 // clock -- the old root past its `notAfter`, the new one not yet at
3014 // its `notBefore` -- is the case where both arise, and there the
3015 // expired root is the one the deployment was relying on.
3016 let mut expired_anchor: Option<AnchorDefect> = None;
3017 //: Reported in preference to an expiry, because it does not depend on
3018 //: the clock and because it is the graver of the two: an expired
3019 //: anchor is the wrong answer for a while, an unnamed one is the
3020 //: wrong answer for everything.
3021 let mut unnamed_anchor = false;
3022
3023 for (anchor_index, anchor) in anchors.iter().enumerate() {
3024 // An anchor that names nothing cannot be the issuer of anything in
3025 // particular. §6.1.3(a)(4) chains on DN equality, so an empty
3026 // subject matches every certificate whose own issuer field is
3027 // empty -- which is every certificate an unnamed CA issues, from
3028 // any unnamed CA. `TrustAnchor::from_cert_ref` already refuses
3029 // such a certificate as `AnchorDefect::EmptySubject`, but
3030 // `TrustAnchor::new` takes a bare name and key with no certificate
3031 // to check, so a caller holding a name and a key from a trust
3032 // store reaches here instead. RFC 5280 §4.1.2.6.
3033 if dn_names_nothing(&anchor.subject) {
3034 unnamed_anchor = true;
3035 continue;
3036 }
3037 if !names_match(&anchor.subject, last_cert.tbs_certificate().issuer()) {
3038 continue;
3039 }
3040 // RFC 5280 §6.1 never checks this; see `TrustAnchor::validity_unix`.
3041 let (not_before, not_after) = anchor.validity_unix;
3042 if policy.current_time_unix < not_before {
3043 if expired_anchor.is_none() {
3044 expired_anchor = Some(AnchorDefect::NotYetValid);
3045 }
3046 continue;
3047 }
3048 if policy.current_time_unix > not_after {
3049 expired_anchor = Some(AnchorDefect::Expired);
3050 continue;
3051 }
3052 // A self-issued top certificate whose key differs from this
3053 // same-name anchor's is either a key-rollover certificate issued by
3054 // the anchor (valid: its signature verifies under the anchor key) or
3055 // a certificate of an unrelated same-name CA (RFC 5280 §3.2 name
3056 // collision). `chain_walk` tells them apart by verifying the top
3057 // signature with the anchor key; in the collision case that
3058 // signature check is the first failure and is reported as
3059 // `NoTrustedPath` below, since this anchor simply is not the issuer.
3060 let top_key_differs = is_self_issued
3061 && !spki_key_matches(
3062 &anchor.subject_public_key_info,
3063 last_cert.tbs_certificate().subject_public_key_info(),
3064 );
3065 match chain_walk(chain, anchor, policy, verifier) {
3066 Ok(final_policy_tree) => {
3067 // §6.1.5 leaf-intrinsic outputs. `chain[0]` is guaranteed
3068 // non-empty by `check_inputs` at the top of this function.
3069 // The four `leaf_*` fields are direct clones of the leaf's
3070 // `tbs_certificate` fields; populating them from `chain[0]`
3071 // (rather than threading them out of `chain_walk`) avoids
3072 // adding more entries to the walker's return tuple.
3073 let leaf_tbs = chain[0].certificate().tbs_certificate();
3074 // Flatten the internal RFC 9618 policy graph into the
3075 // public `PolicyTreeNode` list. The internal shape stays
3076 // private so it can evolve without a public-API break.
3077 let valid_policy_tree =
3078 final_policy_tree.map(policy_graph::PolicyGraph::into_public);
3079 return Ok(ValidatedPath {
3080 anchor_index,
3081 depth: chain.len().saturating_sub(1),
3082 leaf_subject: leaf_tbs.subject().clone(),
3083 leaf_issuer: leaf_tbs.issuer().clone(),
3084 leaf_serial: leaf_tbs.serial_number().clone(),
3085 leaf_spki: leaf_tbs.subject_public_key_info().clone(),
3086 valid_policy_tree,
3087 });
3088 }
3089 Err(Error::SignatureInvalid { index } | Error::SignatureNotVerified { index, .. })
3090 if top_key_differs && index == chain.len() - 1 =>
3091 {
3092 // Name collision, not a rollover: keep the previous error
3093 // (initially `NoTrustedPath`) and try the next anchor.
3094 }
3095 Err(e) => last_err = e,
3096 }
3097 }
3098 // Nothing matched. If an anchor was skipped only because of its own
3099 // validity window, say so: `NoTrustedPath` would be true but
3100 // useless, and an expired root in a trust store is precisely the
3101 // thing nobody notices.
3102 if matches!(last_err, Error::NoTrustedPath) {
3103 if unnamed_anchor {
3104 return Err(Error::TrustAnchorRejected {
3105 defect: AnchorDefect::EmptySubject,
3106 });
3107 }
3108 if let Some(defect) = expired_anchor {
3109 return Err(Error::TrustAnchorRejected { defect });
3110 }
3111 }
3112 Err(last_err)
3113}
3114
3115/// Validate a certificate chain using a [`Profile`] to produce the policy.
3116///
3117/// This is a convenience wrapper around [`validate_path`] for callers that
3118/// work with a `Profile` implementation rather than constructing a
3119/// [`ValidationPolicy`] directly.
3120///
3121/// The profile's [`Profile::policy`] method is called with `now_unix` to
3122/// produce the `ValidationPolicy`. The returned policy's `current_time_unix`
3123/// is then unconditionally overwritten with `now_unix`, so that a buggy
3124/// `Profile` implementation that returns the wrong clock value cannot silently
3125/// cause validity checks to run against the wrong time.
3126///
3127/// See [`validate_path`] for full documentation of the remaining parameters
3128/// and error semantics.
3129///
3130/// # Errors
3131///
3132/// Returns `Err(Error::...)` for each validation failure. See [`Error`] for the full list of failure conditions.
3133pub fn validate_path_with_profile<V, P, C>(
3134 chain: &[C],
3135 anchors: &[TrustAnchor],
3136 profile: &P,
3137 now_unix: u64,
3138 verifier: &V,
3139) -> Result<ValidatedPath>
3140where
3141 V: SignatureVerifier,
3142 P: Profile,
3143 C: PathCertificate,
3144{
3145 let mut policy = profile.policy(now_unix);
3146 // Defense-in-depth: overwrite current_time_unix with the caller's value.
3147 // A correct Profile implementation already sets this in policy(), but
3148 // an incorrect implementation might use a stale or wrong clock. This
3149 // overwrite is a belt-and-suspenders guard — it does not compensate for a
3150 // known bug; no existing Profile impl is incorrect.
3151 policy.current_time_unix = now_unix;
3152 validate_path(chain, anchors, &policy, verifier)
3153}
3154
3155// ---------------------------------------------------------------------------
3156// validate_path helpers — input guards and OID consistency (PKIX-6vu)
3157// ---------------------------------------------------------------------------
3158
3159/// Compare two SPKIs for the purpose of the self-issued anchor guard.
3160///
3161/// Compares algorithm OID and key bytes only — not the parameters field.
3162/// This is intentional: for RSA, explicit NULL parameters and absent
3163/// parameters are both valid encodings of the same algorithm (RFC 3279
3164/// §2.3.1); comparing the full `AlgorithmIdentifier` would wrongly reject
3165/// a valid anchor whose SPKI parameter encoding differs from the cert's.
3166/// For ECDSA, the parameters carry the curve OID, but two keys on different
3167/// curves also differ in their raw key bytes, so OID + key comparison is
3168/// still sufficient to distinguish them.
3169/// Upper bound on `chain.len()` for a given `max_path_len`: the leaf,
3170/// `max_path_len` non-self-issued intermediates, one self-issued certificate
3171/// (key rollover) per CA in the path including the anchor's, and an included
3172/// self-signed root.
3173const fn max_chain_certs(max_path_len: u8) -> usize {
3174 2 * (max_path_len as usize) + 3
3175}
3176
3177fn spki_key_matches(
3178 a: &spki::SubjectPublicKeyInfoOwned,
3179 b: &spki::SubjectPublicKeyInfoOwned,
3180) -> bool {
3181 a.algorithm.oid == b.algorithm.oid && a.subject_public_key == b.subject_public_key
3182}
3183
3184fn check_inputs<C: PathCertificate>(chain: &[C], anchors: &[TrustAnchor]) -> Result<()> {
3185 if chain.is_empty() || anchors.is_empty() {
3186 return Err(Error::NoTrustedPath);
3187 }
3188 // Duplicate detection: check all pairs for (issuer DN, serial number) identity.
3189 // Per RFC 5280 §4.1.2.2, issuer+serial uniquely identifies a certificate.
3190 // A cert appearing twice in the chain is a construction error; reporting
3191 // DuplicateCertificate is cleaner than the confusing SignatureInvalid or
3192 // ChainBroken that would otherwise result.
3193 //
3194 // SPKI equality is intentionally NOT used here: cross-signed CAs legitimately
3195 // have two distinct certificates sharing the same public key (same SPKI, different
3196 // issuer+serial). Using issuer+serial avoids false positives in those chains.
3197 //
3198 // O(n²) over chain.len() — acceptable for chains of typical length (2–5 certs).
3199 //
3200 // Serial numbers are compared first because `&&` short-circuits and the
3201 // two operands cost very different amounts: a serial is a byte compare,
3202 // while `names_match` normalises both DNs under RFC 4518 before
3203 // comparing them attribute by attribute. Two certificates in one chain
3204 // practically never share a serial, so the expensive half practically
3205 // never runs. Both operands are pure, so the order is free to choose.
3206 for i in 0..chain.len() {
3207 for j in (i + 1)..chain.len() {
3208 let a = chain[i].certificate().tbs_certificate();
3209 let b = chain[j].certificate().tbs_certificate();
3210 if a.serial_number() == b.serial_number() && names_match(a.issuer(), b.issuer()) {
3211 return Err(Error::DuplicateCertificate {
3212 first: i,
3213 second: j,
3214 });
3215 }
3216 }
3217 }
3218 Ok(())
3219}
3220
3221/// RFC 5280 §4.1.1.2: outer signatureAlgorithm OID must equal inner TBSCertificate.signature OID.
3222///
3223/// Only OIDs are compared, not parameters. RFC 5280 says the two
3224/// `AlgorithmIdentifiers` MUST be identical, but many production CAs
3225/// generate certs where one field has explicit NULL parameters and the other
3226/// omits them — a mismatch that OpenSSL and other validators accept in
3227/// practice. OID-only comparison preserves the security intent (the same
3228/// algorithm must be named in both places) without rejecting otherwise-valid
3229/// certs from common PKI deployments.
3230fn check_oid_consistency<C: PathCertificate>(chain: &[C]) -> Result<()> {
3231 for (index, cert) in chain.iter().map(PathCertificate::certificate).enumerate() {
3232 if cert.signature_algorithm().oid != cert.tbs_certificate().signature().oid {
3233 return Err(Error::MalformedCertificate { index });
3234 }
3235 }
3236 Ok(())
3237}
3238
3239// ---------------------------------------------------------------------------
3240// Critical extension guard (PKIX-ad6)
3241// ---------------------------------------------------------------------------
3242
3243const OID_KEY_USAGE: der::asn1::ObjectIdentifier =
3244 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.15");
3245
3246const OID_BASIC_CONSTRAINTS: der::asn1::ObjectIdentifier =
3247 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.19");
3248
3249const OID_SUBJECT_ALT_NAME: der::asn1::ObjectIdentifier =
3250 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.17");
3251
3252const OID_EXTENDED_KEY_USAGE: der::asn1::ObjectIdentifier =
3253 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.37");
3254
3255const OID_NAME_CONSTRAINTS: der::asn1::ObjectIdentifier =
3256 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.30");
3257
3258const OID_CERTIFICATE_POLICIES: der::asn1::ObjectIdentifier =
3259 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32");
3260
3261const OID_POLICY_MAPPINGS: der::asn1::ObjectIdentifier =
3262 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.33");
3263
3264const OID_POLICY_CONSTRAINTS: der::asn1::ObjectIdentifier =
3265 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.36");
3266
3267const OID_INHIBIT_ANY_POLICY: der::asn1::ObjectIdentifier =
3268 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.54");
3269
3270/// `id-ce-noRevAvail` — RFC 9608 §2, `{ id-ce 56 }`.
3271pub(crate) const OID_NO_REV_AVAIL: der::asn1::ObjectIdentifier =
3272 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.56");
3273
3274const OID_CRL_DISTRIBUTION_POINTS: der::asn1::ObjectIdentifier =
3275 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.31");
3276
3277const OID_FRESHEST_CRL: der::asn1::ObjectIdentifier =
3278 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.46");
3279
3280const OID_AUTHORITY_INFO_ACCESS: der::asn1::ObjectIdentifier =
3281 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.1.1");
3282
3283/// `id-ad-ocsp` — the one AIA accessMethod RFC 9608 §3 forbids
3284/// alongside `noRevAvail`.
3285const OID_AD_OCSP: der::asn1::ObjectIdentifier =
3286 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.48.1");
3287
3288/// OID for the `anyPolicy` wildcard (2.5.29.32.0 — a child of id-ce-certificatePolicies).
3289pub(crate) const OID_ANY_POLICY: der::asn1::ObjectIdentifier =
3290 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32.0");
3291
3292/// OID for the emailAddress attribute in Distinguished Names (PKCS #9 §5.2.1).
3293/// Used when enforcing RFC 5280 §4.2.1.10 rfc822Name constraints against DN attributes.
3294const OID_EMAIL_ADDRESS: der::asn1::ObjectIdentifier =
3295 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1");
3296
3297/// `anyExtendedKeyUsage`, RFC 5280 §4.2.1.12.
3298///
3299/// In a CA certificate this means "no restriction", which is how
3300/// [`ValidationPolicy::enforce_ca_eku`] reads it. On a *leaf* it does
3301/// **not** satisfy a specific [`ValidationPolicy::required_leaf_eku`]
3302/// requirement, and the two rules are deliberately different: a CA using
3303/// it is declining to constrain its subtree, while a leaf using it is
3304/// claiming every purpose at once, which is not evidence of the one
3305/// purpose a caller asked about.
3306const OID_ANY_EXTENDED_KEY_USAGE: der::asn1::ObjectIdentifier =
3307 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.37.0");
3308
3309/// OIDs of extensions that this implementation handles; all others, if critical, cause rejection.
3310///
3311/// `OID_SUBJECT_ALT_NAME` is listed here so that certs with critical SAN extensions
3312/// (e.g. TLS server certs) do not fail with `UnhandledCriticalExtension`.
3313/// An end entity may be named only by its critical SAN over an empty
3314/// Subject (RFC 5280 §4.2.1.6); a CA may not (§4.1.2.6), and is refused as
3315/// [`AnchorDefect::EmptySubject`] or [`Error::CaEmptySubject`].
3316///
3317/// `OID_EXTENDED_KEY_USAGE` is listed here so that certs with critical EKU
3318/// (common in CA/B Forum TLS and code-signing certificates) do not fail with
3319/// `UnhandledCriticalExtension`. RFC 5280 §6.1 path validation does not require
3320/// inspecting EKU values; the extension is accepted and its content is not verified.
3321const HANDLED_CRITICAL_OIDS: &[der::asn1::ObjectIdentifier] = &[
3322 OID_KEY_USAGE,
3323 OID_BASIC_CONSTRAINTS,
3324 OID_SUBJECT_ALT_NAME,
3325 OID_EXTENDED_KEY_USAGE,
3326 OID_NAME_CONSTRAINTS,
3327 OID_CERTIFICATE_POLICIES,
3328 OID_POLICY_MAPPINGS,
3329 OID_POLICY_CONSTRAINTS,
3330 OID_INHIBIT_ANY_POLICY,
3331];
3332
3333/// RFC 5280 §4.2: "A certificate MUST NOT include more than one instance of
3334/// a particular extension." Reject such certificates with
3335/// [`Error::MalformedCertificate`].
3336///
3337/// The extension lookups in this crate read only the first instance of an
3338/// OID, while other validators may read the last or reject the certificate;
3339/// accepting duplicates would let one certificate mean different things to
3340/// different validators (e.g. two `basicConstraints` with cA TRUE then FALSE).
3341///
3342/// Sorts a copy of the OIDs, so the cost is O(e log e) in the extension
3343/// count `e` rather than quadratic.
3344fn check_duplicate_extensions(cert: &Certificate, index: usize) -> Result<()> {
3345 if has_duplicate_extensions(cert) {
3346 return Err(Error::MalformedCertificate { index });
3347 }
3348 Ok(())
3349}
3350
3351/// Whether `basicConstraints`' leading `cA` `BOOLEAN` is encoded as valid
3352/// BER but invalid DER.
3353///
3354/// `BasicConstraints ::= SEQUENCE { cA BOOLEAN DEFAULT FALSE,
3355/// pathLenConstraint INTEGER (0..MAX) OPTIONAL }`, so the `BOOLEAN` is the
3356/// first member when present. Only that position is examined: this is a
3357/// diagnostic refinement on a certificate being refused either way, not a
3358/// parser, and walking arbitrary DER to find every `BOOLEAN` would be more
3359/// machinery than the distinction is worth.
3360///
3361/// Returns `false` for anything it cannot confidently read, including a
3362/// truncated value or a `BOOLEAN` of the wrong length, so the caller falls
3363/// through to [`AnchorDefect::MalformedExtension`]. A wrong answer here
3364/// would relabel a genuinely malformed extension as a merely
3365/// non-canonical one, which is the error that matters.
3366fn has_non_der_boolean(value: &[u8]) -> bool {
3367 // SEQUENCE header: tag 0x30, then a single-octet short-form length.
3368 // Every conforming `BasicConstraints` is a handful of bytes, so a
3369 // long-form length is itself a sign of something this need not read.
3370 let [0x30, seq_len, rest @ ..] = value else {
3371 return false;
3372 };
3373 if usize::from(*seq_len) != rest.len() {
3374 return false;
3375 }
3376 // BOOLEAN header: tag 0x01, length 1, then the content octet. DER
3377 // permits only 0x00 and 0xFF there; BER permits any non-zero value
3378 // for TRUE.
3379 matches!(rest, [0x01, 0x01, b, ..] if *b != 0x00 && *b != 0xFF)
3380}
3381
3382/// Whether any extension OID appears more than once.
3383///
3384/// Shared with [`check_anchor_profile`], which reports the same fact as
3385/// [`AnchorDefect::DuplicateExtension`] because a trust anchor has no chain
3386/// index to name. The rule and its reasoning are one; only the error shape
3387/// differs.
3388fn has_duplicate_extensions(cert: &Certificate) -> bool {
3389 let exts = cert
3390 .tbs_certificate()
3391 .extensions()
3392 .map_or(&[][..], |v| v.as_slice());
3393 if exts.len() < 2 {
3394 return false;
3395 }
3396 let mut oids: Vec<der::asn1::ObjectIdentifier> = exts.iter().map(|e| e.extn_id).collect();
3397 oids.sort_unstable();
3398 oids.windows(2).any(|w| w[0] == w[1])
3399}
3400
3401/// RFC 5280 §6.1.3(a)(3): reject any critical extension not in the handled set.
3402/// Which of [RFC 9608][rfc9608] §3's four prohibitions a `noRevAvail`
3403/// certificate violates.
3404///
3405/// §3 says a certificate carrying `noRevAvail` asserts that no revocation
3406/// information will ever be published for it, and so must not also be a
3407/// CA or name anywhere revocation information could be fetched. Each
3408/// variant is one of the four, in the order §3 lists them.
3409///
3410/// Carried by [`Error::NoRevAvailProfileViolation`] so a caller can tell
3411/// a self-contradicting end-entity certificate from a CA that must never
3412/// have carried the extension at all — the second is the more serious,
3413/// because a CA whose revocation status can never be published cannot be
3414/// withdrawn once issued.
3415///
3416/// [rfc9608]: https://www.rfc-editor.org/rfc/rfc9608#section-3
3417#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3418#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3419#[non_exhaustive]
3420pub enum NoRevAvailProhibition {
3421 /// `basicConstraints` asserts `cA=TRUE`. RFC 9608 §3: "Certificates
3422 /// for CAs MUST NOT include the noRevAvail extension."
3423 CertificateAuthority,
3424 /// A `cRLDistributionPoints` extension is present.
3425 CrlDistributionPoints,
3426 /// A `freshestCRL` extension is present.
3427 FreshestCrl,
3428 /// An `authorityInfoAccess` extension carries an `id-ad-ocsp`
3429 /// accessMethod. §3 permits the extension and forbids only that
3430 /// accessMethod.
3431 OcspAccessMethod,
3432 /// An `authorityInfoAccess` extension is present but does not decode,
3433 /// so §3's prohibition on an `id-ad-ocsp` accessMethod cannot be
3434 /// shown to hold.
3435 ///
3436 /// Reported rather than passed over because §3's consequence is that
3437 /// the certificate is invalid, and a prohibition that cannot be
3438 /// checked has not been met. Fail-closed.
3439 UndecodableAuthorityInfoAccess,
3440}
3441
3442impl NoRevAvailProhibition {
3443 /// A short phrase naming what the certificate carries, for
3444 /// [`Error`]'s `Display`.
3445 #[must_use]
3446 pub fn as_str(self) -> &'static str {
3447 match self {
3448 Self::CertificateAuthority => "asserts cA=TRUE",
3449 Self::CrlDistributionPoints => "a cRLDistributionPoints extension",
3450 Self::FreshestCrl => "a freshestCRL extension",
3451 Self::OcspAccessMethod => "an authorityInfoAccess with an id-ad-ocsp accessMethod",
3452 Self::UndecodableAuthorityInfoAccess => {
3453 "an authorityInfoAccess that does not decode, so the prohibition on an \
3454 id-ad-ocsp accessMethod cannot be shown to hold"
3455 }
3456 }
3457 }
3458}
3459
3460/// RFC 9608 §3: a certificate carrying `noRevAvail` must not also be a CA
3461/// or point at revocation information.
3462///
3463/// > Certificates for CAs MUST NOT include the noRevAvail extension.
3464/// > Certificates that include the noRevAvail extension MUST NOT include
3465/// > certificate extensions that point to CRL repositories or provide
3466/// > locations of OCSP responders. [...] If any of the above are violated
3467/// > in a certificate, then the relying party MUST consider the
3468/// > certificate invalid.
3469///
3470/// That last sentence is why this runs in `chain_walk` rather than only
3471/// in the lint layer: it is addressed to a relying party, and this is the
3472/// relying party.
3473///
3474/// # This is the guard that makes RFC 9608 §4's skip safe
3475///
3476/// §4 skips RFC 5280 §6.1.3 step (a)(3) — "the certificate is not
3477/// revoked" — for a certificate carrying `noRevAvail`, and `pkix-chain`
3478/// implements that skip. A certificate therefore gets to tell a relying
3479/// party not to check its revocation status. §3's prohibitions are the
3480/// whole of what keeps that from being an escape hatch: a conforming
3481/// `noRevAvail` certificate names nowhere revocation information could be
3482/// published, so skipping the check costs nothing, while one that names a
3483/// CRL or an OCSP responder is asserting two incompatible things and is
3484/// refused here before any skip can apply.
3485///
3486/// Ordering is not incidental. `chain_walk` runs for every certificate
3487/// before `pkix-chain` drives any revocation work, so the guard cannot be
3488/// skipped by a caller who does no revocation checking, and
3489/// `pkix_chain::sans_io::revocation_targets` can drop a `noRevAvail`
3490/// certificate knowing this has already run.
3491///
3492/// # Errors
3493///
3494/// [`Error::NoRevAvailProfileViolation`], carrying which of the four
3495/// prohibitions was violated and the certificate's chain index.
3496/// Does this certificate carry `noRevAvail` ([RFC 9608][rfc9608] §2)?
3497///
3498/// Exported because [`pkix_chain`]'s revocation scheduling needs it to
3499/// implement RFC 9608 §4, which skips RFC 5280 §6.1.3 step (a)(3) — "the
3500/// certificate is not revoked" — for such a certificate.
3501///
3502/// # The skip is only safe because `validate_path` enforces §3
3503///
3504/// Honouring §4 means a certificate tells a relying party not to check
3505/// its revocation status and the relying party complies. §3's
3506/// prohibitions are what keep that from being an escape hatch, and
3507/// [`validate_path`] refuses a certificate that violates them with
3508/// [`Error::NoRevAvailProfileViolation`] before any revocation work is
3509/// scheduled. A caller that reads this predicate and skips a check
3510/// *without* having validated the path first has removed the guard and
3511/// kept the hole.
3512///
3513/// This reads only for the extension's presence. Its criticality (§2
3514/// requires `FALSE`) is enforced separately and earlier: `noRevAvail` is
3515/// not in this crate's handled-critical set, so a critical one fails
3516/// `check_critical_extensions` with
3517/// [`Error::UnhandledCriticalExtension`] and never reaches here.
3518///
3519/// [rfc9608]: https://www.rfc-editor.org/rfc/rfc9608#section-4
3520/// [`pkix_chain`]: https://docs.rs/pkix-chain
3521#[must_use]
3522pub fn has_no_rev_avail(cert: &Certificate) -> bool {
3523 cert.tbs_certificate()
3524 .extensions()
3525 .map_or(&[][..], |v| v.as_slice())
3526 .iter()
3527 .any(|e| e.extn_id == OID_NO_REV_AVAIL)
3528}
3529
3530fn check_no_rev_avail_profile(cert: &Certificate, index: usize) -> Result<()> {
3531 use der::Decode as _;
3532
3533 let exts = cert
3534 .tbs_certificate()
3535 .extensions()
3536 .map_or(&[][..], |v| v.as_slice());
3537 if !exts.iter().any(|e| e.extn_id == OID_NO_REV_AVAIL) {
3538 return Ok(());
3539 }
3540
3541 let violation = |prohibition| Error::NoRevAvailProfileViolation { index, prohibition };
3542
3543 // §3's first prohibition. Checked first because it is the most
3544 // serious: a CA whose revocation status can never be published
3545 // cannot be withdrawn once issued.
3546 //
3547 // A `basicConstraints` that does not decode is not read as asserting
3548 // `cA` here; `check_duplicate_extensions` and the step (k) basic
3549 // constraints processing in `chain_walk` own that, and this function
3550 // is not where a malformed extension is reported.
3551 let asserts_ca = exts
3552 .iter()
3553 .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)
3554 .and_then(|e| {
3555 x509_cert::ext::pkix::BasicConstraints::from_der(e.extn_value.as_bytes()).ok()
3556 })
3557 .is_some_and(|bc| bc.ca);
3558 if asserts_ca {
3559 return Err(violation(NoRevAvailProhibition::CertificateAuthority));
3560 }
3561
3562 if exts
3563 .iter()
3564 .any(|e| e.extn_id == OID_CRL_DISTRIBUTION_POINTS)
3565 {
3566 return Err(violation(NoRevAvailProhibition::CrlDistributionPoints));
3567 }
3568 if exts.iter().any(|e| e.extn_id == OID_FRESHEST_CRL) {
3569 return Err(violation(NoRevAvailProhibition::FreshestCrl));
3570 }
3571
3572 // §3 permits an authorityInfoAccess and forbids one accessMethod
3573 // inside it, so the extension's presence is not itself a violation.
3574 if let Some(aia_ext) = exts.iter().find(|e| e.extn_id == OID_AUTHORITY_INFO_ACCESS) {
3575 let Ok(aia) = x509_cert::ext::pkix::AuthorityInfoAccessSyntax::from_der(
3576 aia_ext.extn_value.as_bytes(),
3577 ) else {
3578 // Fail closed: §3's consequence is invalidity, and a
3579 // prohibition that cannot be shown to hold has not been met.
3580 return Err(violation(
3581 NoRevAvailProhibition::UndecodableAuthorityInfoAccess,
3582 ));
3583 };
3584 if aia.0.iter().any(|d| d.access_method == OID_AD_OCSP) {
3585 return Err(violation(NoRevAvailProhibition::OcspAccessMethod));
3586 }
3587 }
3588
3589 Ok(())
3590}
3591
3592fn check_critical_extensions(cert: &Certificate, index: usize) -> Result<()> {
3593 for ext in cert
3594 .tbs_certificate()
3595 .extensions()
3596 .map_or(&[][..], |v| v.as_slice())
3597 {
3598 if ext.critical && !HANDLED_CRITICAL_OIDS.contains(&ext.extn_id) {
3599 return Err(Error::UnhandledCriticalExtension { index });
3600 }
3601 }
3602 Ok(())
3603}
3604
3605// ---------------------------------------------------------------------------
3606// Policy processing (RFC 5280 §6.1) — see `policy_graph` (RFC 9618 graph)
3607// ---------------------------------------------------------------------------
3608
3609// ---------------------------------------------------------------------------
3610// KeyUsage extraction (PKIX-8ae)
3611// ---------------------------------------------------------------------------
3612
3613/// Returns whether the `keyCertSign` bit is set in the `KeyUsage` extension.
3614///
3615/// - `None` — `KeyUsage` extension absent (no constraint)
3616/// - `Ok(Some(true))` — keyCertSign is set
3617/// - `Ok(Some(false))` — `KeyUsage` present, keyCertSign NOT set
3618/// - `Ok(None)` — `KeyUsage` extension absent
3619/// - `Err(_)` — `KeyUsage` present but DER-malformed (fail-closed)
3620fn has_key_cert_sign(cert: &Certificate) -> der::Result<Option<bool>> {
3621 use x509_cert::ext::pkix::KeyUsage;
3622
3623 try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.key_cert_sign()))
3624}
3625
3626/// Returns whether the `cRLSign` bit is set in the `KeyUsage` extension.
3627///
3628/// Same shape as [`has_key_cert_sign`]; used by the
3629/// [`ValidationPolicy::require_crl_sign_on_cas`] opt-in check (PKITS §4.7.4 / §4.7.5).
3630///
3631/// - `Ok(Some(true))` — cRLSign is set
3632/// - `Ok(Some(false))` — `KeyUsage` present, cRLSign NOT set
3633/// - `Ok(None)` — `KeyUsage` extension absent
3634/// - `Err(_)` — `KeyUsage` present but DER-malformed (fail-closed)
3635fn has_crl_sign(cert: &Certificate) -> der::Result<Option<bool>> {
3636 use x509_cert::ext::pkix::KeyUsage;
3637
3638 try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.crl_sign()))
3639}
3640
3641// ---------------------------------------------------------------------------
3642// Extension extraction helpers
3643// ---------------------------------------------------------------------------
3644
3645/// Look up and decode an X.509 extension from `cert` by OID.
3646///
3647/// **Fail-closed**: propagates DER decoding errors to the caller rather than
3648/// discarding them. This is appropriate for security-critical extensions where
3649/// a malformed value must not be silently ignored.
3650///
3651/// Returns:
3652/// - `Ok(None)` — extension absent.
3653/// - `Ok(Some(T))` — extension present and decoded successfully.
3654/// - `Err(der::Error)` — extension present but DER decoding failed.
3655///
3656/// For non-critical extensions where a parse failure should be treated as
3657/// absent, decode the extension directly: there is deliberately no
3658/// fail-open helper any more, because the only caller that wanted one
3659/// was the trust-anchor path, where dropping an unparseable
3660/// `NameConstraints` was a fail-open.
3661fn try_find_cert_ext<T: for<'a> der::Decode<'a, Error = der::Error>>(
3662 cert: &Certificate,
3663 oid: der::asn1::ObjectIdentifier,
3664) -> der::Result<Option<T>> {
3665 cert.tbs_certificate()
3666 .extensions()
3667 .map_or(&[][..], |v| v.as_slice())
3668 .iter()
3669 .find(|e| e.extn_id == oid)
3670 .map_or(Ok(None), |e| T::from_der(e.extn_value.as_bytes()).map(Some))
3671}
3672
3673/// Decode the `SubjectAltName` extension from `cert`.
3674///
3675/// **Fail-closed**: a present-but-malformed SAN returns `Err` rather than being
3676/// silently treated as absent. Treating a malformed SAN as absent during name
3677/// constraint checking would allow a cert to bypass NC exclusion/permission
3678/// constraints when the SAN extension is present but cannot be decoded (vjc.20).
3679fn cert_subject_alt_names(
3680 cert: &Certificate,
3681 index: usize,
3682) -> crate::Result<Option<x509_cert::ext::pkix::SubjectAltName>> {
3683 try_find_cert_ext(cert, OID_SUBJECT_ALT_NAME).map_err(|_| Error::MalformedCertificate { index })
3684}
3685
3686/// Decode the `NameConstraints` extension from `cert`.
3687///
3688/// Returns `Err(MalformedCertificate)` if the extension is present but:
3689/// - its DER cannot be decoded (vjc.7: fail-closed on security-critical extension),
3690/// - any `GeneralSubtree` has a non-zero `minimum` or a present `maximum` field
3691/// (vjc.8: RFC 5280 §4.2.1.10 MUST require minimum=0, maximum=absent), or
3692/// - either subtree set is present and empty (PKIX-mg8u).
3693///
3694/// Returns `Ok(None)` if the extension is absent.
3695/// Is every `GeneralSubtrees` in `nc` one RFC 5280 §4.2.1.10 can express?
3696///
3697/// Two rules, both from the same paragraph of §4.2.1.10, and both about a
3698/// constraint whose scope cannot be honoured as written.
3699///
3700/// **minimum and maximum.** "Within this profile, the minimum and maximum
3701/// fields are not used with any name forms, thus minimum MUST be zero, and
3702/// maximum MUST be absent." A certificate that encodes either is asking for
3703/// semantics this implementation does not have.
3704///
3705/// **An empty set.** `GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF
3706/// GeneralSubtree`, so a present-but-empty one is not a valid encoding at
3707/// all. It still decodes here, because a `SEQUENCE OF` reader reaching the
3708/// end of the value immediately yields an empty `Vec` rather than an error,
3709/// and the result used to be adopted as a permitted set constraining no
3710/// name type — so a critical extension saying "permit nothing" was read as
3711/// "permit everything", which is the fail-open direction on the one
3712/// extension this function exists to be fail-closed about. Refusing it is
3713/// also the only answer available: the two readings of an empty permitted
3714/// set are "no name is acceptable" and "every name is", and nothing in the
3715/// RFC chooses between them because the ASN.1 was meant to make the
3716/// question impossible.
3717///
3718/// Found by the generated-chain harness (PKIX-mg8u), though not because
3719/// the chain was new. x509-limbo has it as
3720/// `webpki::nc::intermediate-permitted-excluded-subtrees-both-empty-sequences`,
3721/// and `baseline-limbo.json` recorded the old accepting verdict as a
3722/// ground-truth disagreement, justified in the ledger as deliberate
3723/// scope -- the encoding being a syntax matter for `pkix-lint`. That
3724/// rationale held for the sibling case where both subtree sets are
3725/// *absent*, which is vacuous and still accepted here. It did not hold
3726/// for an empty SEQUENCE: §6.1.4(b) intersects the certificate's
3727/// permitted set into the running state, and intersecting with the empty
3728/// set leaves the empty set, after which §6.1.3(b) can admit no name.
3729/// The rejection follows from path validation and never needed the
3730/// syntax check.
3731///
3732/// One predicate because three paths need the same answer —
3733/// [`cert_name_constraints`] for intermediates, and both fallible trust-anchor
3734/// constructors. They used to disagree: the rule was applied to intermediates
3735/// and to neither anchor path, so the same extension was grounds for rejection
3736/// in the middle of a chain and accepted at its root.
3737fn subtrees_are_conformant(nc: &NameConstraints) -> bool {
3738 // A closure rather than `Vec::is_empty` as a function path: `Vec` here
3739 // is the cfg-gated alias above, and naming `alloc::vec::Vec` would not
3740 // resolve under `std`, where `extern crate alloc` is not declared.
3741 let empty_set_present = nc.permitted_subtrees.as_ref().is_some_and(Vec::is_empty)
3742 || nc.excluded_subtrees.as_ref().is_some_and(Vec::is_empty);
3743 if empty_set_present {
3744 return false;
3745 }
3746 nc.permitted_subtrees
3747 .iter()
3748 .flatten()
3749 .chain(nc.excluded_subtrees.iter().flatten())
3750 .all(|st| st.minimum == 0 && st.maximum.is_none())
3751}
3752
3753fn cert_name_constraints(
3754 cert: &Certificate,
3755 index: usize,
3756) -> crate::Result<Option<NameConstraints>> {
3757 let nc = try_find_cert_ext::<NameConstraints>(cert, OID_NAME_CONSTRAINTS)
3758 .map_err(|_| Error::MalformedCertificate { index })?;
3759
3760 if let Some(nc) = &nc
3761 && !subtrees_are_conformant(nc)
3762 {
3763 return Err(Error::MalformedCertificate { index });
3764 }
3765
3766 Ok(nc)
3767}
3768
3769/// RFC 5280 §4.2.1.10 conformance of a `NameConstraints`, at the predicate
3770/// all three call sites share.
3771///
3772/// The empty-set cases are tested here rather than only through a chain
3773/// because the predicate is what the anchor constructors and the chain
3774/// walk have in common: a rule enforced in one and not the others was
3775/// how PKIX-vjc.8 happened, and the comment on `subtrees_are_conformant`
3776/// records that history. An end-to-end chain carrying an empty set, with
3777/// a real signature over it, is in `pkix-difftest`'s generated-chain
3778/// suite (PKIX-mg8u).
3779#[cfg(test)]
3780mod tests_subtree_conformance {
3781 use super::subtrees_are_conformant;
3782 use x509_cert::ext::pkix::constraints::name::{
3783 GeneralSubtree, GeneralSubtrees, NameConstraints,
3784 };
3785 use x509_cert::ext::pkix::name::GeneralName;
3786
3787 fn dns_subtree(name: &str) -> GeneralSubtree {
3788 GeneralSubtree {
3789 base: GeneralName::DnsName(
3790 der::asn1::Ia5String::new(name).expect("an ASCII host name is IA5"),
3791 ),
3792 minimum: 0,
3793 maximum: None,
3794 }
3795 }
3796
3797 fn nc(
3798 permitted: Option<GeneralSubtrees>,
3799 excluded: Option<GeneralSubtrees>,
3800 ) -> NameConstraints {
3801 NameConstraints {
3802 permitted_subtrees: permitted,
3803 excluded_subtrees: excluded,
3804 }
3805 }
3806
3807 /// The control. Without it the rejections below would pass for a
3808 /// predicate that refused everything.
3809 #[test]
3810 fn a_conforming_constraint_is_accepted() {
3811 let one = || Some(vec![dns_subtree("example.com")]);
3812 assert!(subtrees_are_conformant(&nc(one(), None)));
3813 assert!(subtrees_are_conformant(&nc(None, one())));
3814 assert!(subtrees_are_conformant(&nc(one(), one())));
3815 }
3816
3817 /// Absent is not empty: a `NameConstraints` with neither field is
3818 /// vacuous but well-formed, and both `OPTIONAL` fields may be absent.
3819 #[test]
3820 fn absent_subtree_sets_are_accepted() {
3821 assert!(subtrees_are_conformant(&nc(None, None)));
3822 }
3823
3824 /// `GeneralSubtrees ::= SEQUENCE SIZE (1..MAX)`, so a present-but-empty
3825 /// set is not a valid encoding. It used to be read as a constraint on
3826 /// no name type at all, which on a permitted set means "permit
3827 /// everything" — fail-open on a critical extension.
3828 #[test]
3829 fn a_present_but_empty_subtree_set_is_refused() {
3830 assert!(
3831 !subtrees_are_conformant(&nc(Some(GeneralSubtrees::new()), None)),
3832 "an empty permittedSubtrees must not be read as no constraint"
3833 );
3834 assert!(
3835 !subtrees_are_conformant(&nc(None, Some(GeneralSubtrees::new()))),
3836 "an empty excludedSubtrees is the same violation"
3837 );
3838 assert!(
3839 !subtrees_are_conformant(&nc(
3840 Some(GeneralSubtrees::new()),
3841 Some(GeneralSubtrees::new())
3842 )),
3843 "both empty"
3844 );
3845 }
3846
3847 /// One empty set does not become acceptable by sitting beside a
3848 /// populated one. `||` rather than `&&`, which is the mutation that
3849 /// survived the suite last time this predicate grew a rule.
3850 #[test]
3851 fn an_empty_set_beside_a_populated_one_is_still_refused() {
3852 let one = Some(vec![dns_subtree("example.com")]);
3853 assert!(!subtrees_are_conformant(&nc(
3854 Some(GeneralSubtrees::new()),
3855 one.clone()
3856 )));
3857 assert!(!subtrees_are_conformant(&nc(
3858 one,
3859 Some(GeneralSubtrees::new())
3860 )));
3861 }
3862
3863 /// The pre-existing rule, still enforced: the empty-set check returns
3864 /// early, so it must not shadow this one.
3865 #[test]
3866 fn a_non_zero_minimum_or_present_maximum_is_still_refused() {
3867 let mut min = dns_subtree("example.com");
3868 min.minimum = 1;
3869 assert!(!subtrees_are_conformant(&nc(Some(vec![min]), None)));
3870
3871 let mut max = dns_subtree("example.com");
3872 max.maximum = Some(4);
3873 assert!(!subtrees_are_conformant(&nc(None, Some(vec![max]))));
3874 }
3875}
3876
3877// ---------------------------------------------------------------------------
3878// Validity period checker (PKIX-047)
3879// ---------------------------------------------------------------------------
3880
3881/// Convert an `x509_cert::time::Time` to seconds since the Unix epoch.
3882fn time_to_unix_secs(t: &x509_cert::time::Time) -> u64 {
3883 t.to_unix_duration().as_secs()
3884}
3885
3886/// RFC 5280 §6.1.3(a)(2): check notBefore ≤ now ≤ notAfter.
3887fn check_validity(cert: &Certificate, now_unix: u64, index: usize) -> Result<()> {
3888 let not_before = time_to_unix_secs(&cert.tbs_certificate().validity().not_before);
3889 let not_after = time_to_unix_secs(&cert.tbs_certificate().validity().not_after);
3890 if now_unix >= not_before && now_unix <= not_after {
3891 Ok(())
3892 } else {
3893 Err(Error::ValidityPeriod { index })
3894 }
3895}
3896
3897// ---------------------------------------------------------------------------
3898// Name comparison — RFC 4518 string prep (PKIX-drv)
3899// ---------------------------------------------------------------------------
3900
3901/// Maximum number of attribute-value assertions in one RDN that
3902/// [`names_match`] will compare.
3903///
3904/// RFC 5280 does not limit multi-valued RDNs, but real certificates use
3905/// one AVA per RDN (occasionally two or three). The cap bounds the
3906/// quadratic AVA matching in [`names_match`], which runs on unauthenticated
3907/// input; an RDN above the cap matches nothing.
3908pub const MAX_AVAS_PER_RDN: usize = 64;
3909
3910/// Compare two distinguished names per RFC 4518 string prep rules.
3911///
3912/// Currently implements ASCII case-fold and insignificant-whitespace
3913/// collapsing. `BMPString`-tagged AVAs are transcoded UCS-2-BE → UTF-8
3914/// before normalization, so a `BMPString` AVA and a `UTF8String` (or
3915/// `PrintableString`/`IA5String`/`VisibleString`) AVA that share Unicode
3916/// code points compare equal. Full Unicode NFKC normalization is future
3917/// work.
3918///
3919/// Returns `true` if the names are equivalent.
3920///
3921/// # Ordering
3922///
3923/// RFC 5280 §4.1.2.4 defines `Name` as `SEQUENCE OF RDN`, so RDNs are
3924/// compared positionally (index 0 with index 0, etc.). Within each RDN —
3925/// which is a `SET OF AttributeTypeAndValue` — comparison is order-independent:
3926/// each AVA in one RDN is matched against any AVA in the other.
3927///
3928/// # Limitations
3929///
3930/// - **No NFKC / non-ASCII case fold.** Two AVA values that contain the
3931/// same Unicode characters but differ in canonical decomposition
3932/// (precomposed vs combining, e.g. U+00E9 vs U+0065 U+0301) compare
3933/// unequal even though RFC 4518 says they should match. Non-Latin
3934/// case differences (e.g. Greek lowercase σ vs final σ) are also not
3935/// folded.
3936/// - **`UniversalString` is parser-rejected upstream.** `der` 0.7 omits
3937/// tag 0x1C from `Tag::try_from`, so any cert with a `UniversalString`
3938/// AVA fails to parse before reaching this comparator. This is an
3939/// upstream limitation; the same `BMPString` transcoding applied here
3940/// would generalize to `UniversalString` (UCS-4-BE → UTF-8) once the
3941/// parser accepts it.
3942/// - **`TeletexString` (`T61String`) uses raw DER byte comparison.**
3943/// `pkix-path` deliberately does not transcode T.61 to Unicode; no
3944/// canonical mapping exists (RFC 4518 §2.1 leaves it "a local matter"
3945/// and OpenSSL, NSS, and `GnuTLS` use mutually incompatible vendor
3946/// tables). Byte-equal `TeletexString` AVAs match; `TeletexString`
3947/// never matches any other string type. Well-formed chains that copy
3948/// the issuer DN bytes per RFC 5280 §4.1.2.4 are unaffected.
3949///
3950/// # Work bound
3951///
3952/// AVA matching within an RDN is quadratic in the RDN's size. To bound the
3953/// work an attacker-supplied name can cause, an RDN with more than
3954/// [`MAX_AVAS_PER_RDN`] attribute-value assertions never matches anything
3955/// (`names_match` returns `false`), so such a name cannot chain.
3956#[must_use]
3957pub fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool {
3958 if a.len() != b.len() {
3959 return false;
3960 }
3961 let a_rdns = a.iter_rdn();
3962 let b_rdns = b.iter_rdn();
3963
3964 for (a_rdn, b_rdn) in a_rdns.zip(b_rdns) {
3965 if a_rdn.len() != b_rdn.len() {
3966 return false;
3967 }
3968 // Work bound: the AVA matching below is quadratic in the RDN size,
3969 // and names_match runs on attacker-supplied names before any
3970 // signature has been checked. Real-world RDNs carry one AVA (rarely
3971 // two or three), so an RDN above the cap is treated as matching
3972 // nothing (fail-closed).
3973 if a_rdn.len() > MAX_AVAS_PER_RDN {
3974 return false;
3975 }
3976 // Bijective AVA matching: every AVA in a_rdn must match some AVA in b_rdn,
3977 // AND every AVA in b_rdn must match some AVA in a_rdn (both directions).
3978 //
3979 // The bidirectional check is equivalent to set equality for well-formed RDNs
3980 // (RFC 5280 §5.1.2.4 SHOULD NOT contain duplicate OIDs), and also correctly
3981 // handles the malformed-cert case where an RDN has duplicate OIDs:
3982 // a={CN=Alice, CN=Alice}, b={CN=Bob, CN=Alice} → both len=2, forward pass
3983 // finds CN=Alice for each a_ava, but the reverse pass finds no match for
3984 // CN=Bob → returns false (correct).
3985 // The reverse pass is O(n²) on AVA count; n is 1–5 in practice.
3986 for a_ava in a_rdn.iter() {
3987 let found = b_rdn.iter().any(|b_ava| {
3988 b_ava.oid == a_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
3989 });
3990 if !found {
3991 return false;
3992 }
3993 }
3994 for b_ava in b_rdn.iter() {
3995 let found = a_rdn.iter().any(|a_ava| {
3996 a_ava.oid == b_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
3997 });
3998 if !found {
3999 return false;
4000 }
4001 }
4002 }
4003 true
4004}
4005
4006/// Returns `Ok(true)` if `cert` is a CA certificate per its `BasicConstraints`
4007/// extension (RFC 5280 §4.2.1.9), `Ok(false)` if the extension is absent or
4008/// `cA = FALSE`, and `Err(DerError)` if the extension is present but cannot be
4009/// DER-decoded.
4010///
4011/// Propagating decode failure rather than treating a malformed extension as
4012/// "not a CA" is a fail-closed defense-in-depth choice: silently skipping a
4013/// malformed `BasicConstraints` could mask a topologically valid CA whose CRL
4014/// scope or path-building should be honored.
4015///
4016/// This helper is shared by `pkix-path-builder` (path construction) and
4017/// `pkix-revocation::crl` (IDP scope checking) to avoid maintaining two
4018/// parallel implementations of the same RFC 5280 §4.2.1.9 decode.
4019///
4020/// # Errors
4021///
4022/// Returns [`DerError`] if the `BasicConstraints` extension is present but
4023/// fails to DER-decode.
4024pub fn cert_is_ca(cert: &Certificate) -> core::result::Result<bool, DerError> {
4025 use der::Decode as _;
4026 use x509_cert::ext::pkix::BasicConstraints;
4027
4028 let Some(ext) = cert
4029 .tbs_certificate()
4030 .extensions()
4031 .map_or(&[][..], |v| v.as_slice())
4032 .iter()
4033 .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)
4034 else {
4035 return Ok(false);
4036 };
4037
4038 let bc = BasicConstraints::from_der(ext.extn_value.as_bytes()).map_err(DerError::new)?;
4039 Ok(bc.ca)
4040}
4041
4042/// Whether a distinguished name names nothing at all.
4043///
4044/// RFC 5280 §4.1.2.4 and §4.1.2.6 both speak of a "non-empty
4045/// distinguished name". The obvious reading is an `RDNSequence` of zero
4046/// `RelativeDistinguishedName`s, and that is the encoding seen in
4047/// practice. But an `RDNSequence` holding RDNs that are themselves empty
4048/// names nothing either, and X.501 defines an RDN as `SET SIZE (1..MAX)`
4049/// so such a thing is already malformed -- it should not be treated as a
4050/// name merely because it survived parsing. Both shapes answer `true`
4051/// here, which is why this is a function and not a call to
4052/// `Name::is_empty`.
4053fn dn_names_nothing(name: &x509_cert::name::Name) -> bool {
4054 name.iter_rdn()
4055 .all(x509_cert::name::RelativeDistinguishedName::is_empty)
4056}
4057
4058/// RFC 5280 §3.3: a certificate is self-issued if subject == issuer and neither is empty.
4059fn is_self_issued_cert(cert: &Certificate) -> bool {
4060 !cert.tbs_certificate().subject().is_empty()
4061 && names_match(
4062 cert.tbs_certificate().subject(),
4063 cert.tbs_certificate().issuer(),
4064 )
4065}
4066
4067/// RFC 5280 §7.1 DN comparison, and §4.2.1.10 subtree containment.
4068///
4069/// Both functions here are private and were reached only through whole-chain
4070/// fixtures, which left several of their decisions untested — a mutation
4071/// sweep flipped the `&&` in both `names_match` AVA loops and both
4072/// comparisons in `dn_within_subtree`'s length guard, and every one
4073/// survived. Unit tests, because the inputs that distinguish these cases
4074/// are DNs no certificate generator produces on the way to anything else.
4075#[cfg(test)]
4076mod tests_dn_comparison {
4077 use super::{dn_within_subtree, names_match};
4078 use der::Decode as _;
4079 use x509_cert::name::Name;
4080
4081 // Hand-built DER. Each is a Name whose RDNs hold one PrintableString AVA.
4082 const CN_ALICE: &[u8] = &[
4083 0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
4084 0x69, 0x63, 0x65,
4085 ];
4086 /// The same value as `CN_ALICE` under a different attribute OID
4087 /// (organizationName, 2.5.4.10).
4088 const O_ALICE: &[u8] = &[
4089 0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c,
4090 0x69, 0x63, 0x65,
4091 ];
4092 const C_US: &[u8] = &[
4093 0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
4094 ];
4095 const C_US_O_TEST: &[u8] = &[
4096 0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
4097 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
4098 ];
4099 const C_US_O_TEST_CN_ALICE: &[u8] = &[
4100 0x30, 0x2c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
4101 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
4102 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69, 0x63,
4103 0x65,
4104 ];
4105
4106 fn n(der: &[u8]) -> Name {
4107 Name::from_der(der).expect("hand-built Name parses")
4108 }
4109
4110 /// The same value under a different attribute type is a different name.
4111 ///
4112 /// Both AVA loops in `names_match` require the OID *and* the value to
4113 /// agree. With `||` in place of either `&&`, `CN=Alice` and `O=Alice`
4114 /// compare equal — the comparison would stop distinguishing attribute
4115 /// types, and DN equality is what binds a certificate to its issuer.
4116 #[test]
4117 fn the_same_value_under_a_different_attribute_type_is_a_different_name() {
4118 assert!(names_match(&n(CN_ALICE), &n(CN_ALICE)));
4119 assert!(
4120 !names_match(&n(CN_ALICE), &n(O_ALICE)),
4121 "CN=Alice is not O=Alice"
4122 );
4123 assert!(
4124 !names_match(&n(O_ALICE), &n(CN_ALICE)),
4125 "and not in the other argument order either"
4126 );
4127 }
4128
4129 /// A DN is within the subtree rooted at itself.
4130 ///
4131 /// §4.2.1.10 containment is prefix containment, and every sequence is a
4132 /// prefix of itself. The length guard is `constraint.len() >
4133 /// subject.len()`; with `>=` an exactly-equal DN falls out as "not
4134 /// within", which breaks both directions of name constraints — a
4135 /// permitted subtree would reject the DN it names, and an excluded
4136 /// subtree would fail to exclude it.
4137 #[test]
4138 fn a_dn_is_within_the_subtree_rooted_at_itself() {
4139 assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST)));
4140 assert!(dn_within_subtree(&n(C_US), &n(C_US)));
4141 }
4142
4143 /// A constraint longer than the subject contains nothing.
4144 ///
4145 /// The guard exists because the `zip` below it stops at the shorter of
4146 /// the two, so without it a deep constraint would be compared only
4147 /// against its own prefix and report a match. With `==` in place of
4148 /// `>`, `{C=US}` lands inside the subtree `{C=US, O=Test, CN=Alice}` —
4149 /// over-permissive for a permitted subtree, since a certificate would
4150 /// satisfy a constraint far more specific than its own name.
4151 #[test]
4152 fn a_constraint_longer_than_the_subject_contains_nothing() {
4153 assert!(
4154 !dn_within_subtree(&n(C_US), &n(C_US_O_TEST_CN_ALICE)),
4155 "{{C=US}} is not inside the subtree {{C=US, O=Test, CN=Alice}}"
4156 );
4157 assert!(
4158 !dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST_CN_ALICE)),
4159 "one RDN short is still outside"
4160 );
4161 }
4162
4163 /// One RDN with two AVAs sharing a value under different OIDs, and one
4164 /// with a duplicated OID. RFC 5280 §5.1.2.4 says an RDN SHOULD NOT
4165 /// carry duplicate OIDs, so the second is malformed — which is exactly
4166 /// the case `names_match`'s bidirectional pass documents itself as
4167 /// handling.
4168 const CN_AND_O_ALICE: &[u8] = &[
4169 0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
4170 0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c, 0x69,
4171 0x63, 0x65,
4172 ];
4173 const CN_ALICE_TWICE: &[u8] = &[
4174 0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
4175 0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69,
4176 0x63, 0x65,
4177 ];
4178
4179 /// The bidirectional AVA pass is what makes a duplicated OID safe.
4180 ///
4181 /// `{CN=Alice, O=Alice}` and `{CN=Alice, CN=Alice}` have the same RDN
4182 /// count and the same AVA count, and every AVA of the second has a
4183 /// strict match in the first — so the forward pass alone cannot tell
4184 /// them apart. Only the reverse pass can: `O=Alice` has no counterpart
4185 /// in `{CN=Alice, CN=Alice}`.
4186 ///
4187 /// Why this test rather than a simpler one: mutating the `&&` in
4188 /// *either* AVA loop to `||` leaves every other test in this crate
4189 /// green, because for well-formed RDNs the two passes are redundant and
4190 /// each catches what the other would miss. That redundancy is the
4191 /// design, and this is the input where the second pass is the one that
4192 /// catches it instead of merely agreeing — a duplicated OID, which the loop's own comment claims to
4193 /// handle and nothing verified.
4194 #[test]
4195 fn a_duplicated_oid_does_not_match_two_distinct_attributes() {
4196 assert!(
4197 !names_match(&n(CN_AND_O_ALICE), &n(CN_ALICE_TWICE)),
4198 "{{CN=Alice, O=Alice}} is not {{CN=Alice, CN=Alice}}"
4199 );
4200 assert!(
4201 !names_match(&n(CN_ALICE_TWICE), &n(CN_AND_O_ALICE)),
4202 "and not in the other argument order, which is the pass that \
4203 catches it when the first is weakened"
4204 );
4205 // Each still matches itself, so the above cannot pass on a
4206 // comparison that never returns true for two-AVA RDNs.
4207 assert!(names_match(&n(CN_AND_O_ALICE), &n(CN_AND_O_ALICE)));
4208 assert!(names_match(&n(CN_ALICE_TWICE), &n(CN_ALICE_TWICE)));
4209 }
4210
4211 /// And the ordinary case still works: a shorter constraint is a prefix.
4212 ///
4213 /// Without this the two negative tests above would pass on a function
4214 /// that never returns `true`.
4215 #[test]
4216 fn a_shorter_constraint_contains_a_longer_subject() {
4217 assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US)));
4218 assert!(dn_within_subtree(&n(C_US_O_TEST_CN_ALICE), &n(C_US_O_TEST)));
4219 }
4220}
4221
4222/// Compare two `AttributeTypeAndValue` values after RFC 4518 normalization.
4223///
4224/// Allocation-free: `BMPString` values are transcoded to UTF-8 lazily by
4225/// [`DirStringBytes`] while the two normalized byte streams are compared,
4226/// so the cost of one comparison is linear in the value lengths with no
4227/// heap traffic (review A1 item 10: `names_match` used to allocate two
4228/// transcoding buffers per AVA comparison).
4229fn ava_values_match(a: &der::Any, b: &der::Any) -> bool {
4230 let a_str = any_to_str_bytes(a);
4231 let b_str = any_to_str_bytes(b);
4232
4233 match (a_str, b_str) {
4234 (Some(a_bytes), Some(b_bytes)) => {
4235 NormalizedIter::new(a_bytes).eq(NormalizedIter::new(b_bytes))
4236 }
4237 // Both values are non-string types (e.g. OID, INTEGER) or string
4238 // types this dispatch does not read: `UniversalString`, which `der`
4239 // rejects upstream at `Tag::try_from`, and a `TeletexString` whose
4240 // octets fall outside the ISO 646 invariant set — a combining
4241 // diacritic, or one of the twelve nationally-variable positions.
4242 // compare tag AND content bytes (raw DER). Tag comparison ensures two
4243 // different string encodings of the same text are not considered equal.
4244 (None, None) => a.tag() == b.tag() && a.value() == b.value(),
4245 // One value is a string type and the other is not. Return false (fail-closed).
4246 // A legitimate certificate chain will never encode the same attribute OID as a
4247 // string type in one cert and a non-string type in another, so this mismatch
4248 // indicates a malformed or suspicious certificate.
4249 _ => false,
4250 }
4251}
4252
4253/// Classify a `DirectoryString` Any value as a stream of UTF-8 bytes,
4254/// returning `None` for types that require special pre-processing before
4255/// normalization (see `ava_values_match` for the dispatch logic).
4256///
4257/// The returned [`DirStringBytes`] iterator borrows the `der::Any` content
4258/// bytes; no string type allocates.
4259///
4260/// # Normalization strategy by string type
4261///
4262/// **Passed through — bytes already comparable as UTF-8/ASCII:**
4263/// `UTF8String`, `PrintableString`, `IA5String`, `VisibleString`,
4264/// `NumericString`. These types are encoded as ASCII (or UTF-8 in the case
4265/// of `UTF8String`) at the DER level. The bytes are fed directly to
4266/// `NormalizedIter` which applies ASCII case-folding and
4267/// insignificant-space handling (RFC 4518 §2.4 step 6 subset).
4268///
4269/// `NumericString` is here although `DirectoryString` (§4.1.2.4) does not
4270/// admit it. An `AttributeTypeAndValue`'s `value` is `ANY`, and an
4271/// attribute type outside the standard set defines its own syntax: Russia's
4272/// `OGRN` (1.2.643.100.1) and legal-entity `INN` (1.2.643.100.4) are
4273/// `NumericString`, and six of the eight roots in
4274/// `third_party/trust-stores/ru-national/` carry them. X.680 restricts the
4275/// type to the digits `0`-`9` and SPACE, so the content is ASCII and needs
4276/// no transcoding, and case-folding is a no-op on it; what the shared
4277/// pipeline adds is insignificant-space handling, which LDAP's
4278/// `numericStringMatch` (RFC 4517 §4.2.22, over the RFC 4518 preparation
4279/// §7.1 points at) also prescribes.
4280///
4281/// Before it was dispatched here it fell to the raw tag-and-bytes
4282/// comparison in [`ava_values_match`], so the same name encoded as
4283/// `NumericString` by one CA and `PrintableString` by another compared as
4284/// two different names — a false negative that surfaces as
4285/// [`Error::NoTrustedPath`] with nothing to say an encoding caused it.
4286///
4287/// **Passed through only when unambiguously ASCII — `TeletexString`:**
4288/// T.61 is not ASCII, so this type is dispatched here only when every
4289/// octet lies in the ISO 646 invariant set; see
4290/// [`teletex_is_iso646_invariant`]. Anything else, including the
4291/// non-spacing diacritics at `0xC0`-`0xCF`, returns `None` and falls to the
4292/// raw tag-and-bytes comparison.
4293///
4294/// **Transcoded on the fly — UCS-2-BE → UTF-8:**
4295/// `BMPString`. RFC 4518 §2.1 treats `BMPString` as "a subset of Unicode"
4296/// — every two-byte big-endian unit is a Unicode code point in the BMP.
4297/// Each unit is encoded to UTF-8 as it is consumed so the same
4298/// normalization pipeline used for `UTF8String` applies to the result.
4299/// ASCII-range code points in the BMP (U+0000..=U+007F) become
4300/// single-byte UTF-8, so a BMPString-encoded "Foo Co" compares equal to a
4301/// UTF8String-encoded "Foo Co". Malformed `BMPString` content (odd-length
4302/// bytes, or values in the surrogate range U+D800..=U+DFFF which are not
4303/// valid Unicode scalar values) is detected up front by
4304/// [`bmp_is_well_formed`] and returns `None` (fail-closed): a malformed
4305/// value will not match anything via `ava_values_match`.
4306///
4307/// **Rejected at parse time — `UniversalString`:**
4308/// `der` 0.7 omits tag 0x1C (`UniversalString`) from `Tag::try_from`,
4309/// causing any cert with a `UniversalString` AVA to fail
4310/// `Certificate::from_der` upstream. This dispatch therefore never sees
4311/// `UniversalString`-tagged values. Documented for completeness; a future
4312/// upstream fix in `der` (or our own pre-decode shim) is required before
4313/// `UniversalString` becomes reachable here.
4314///
4315/// **Committed policy — `TeletexString` (T61String):**
4316/// Raw DER byte comparison only. `pkix-path` deliberately does not
4317/// transcode T.61 to Unicode. RFC 4518 §2.1 states: "As there is no
4318/// standard for mapping `TeletexString` values to Unicode, the mapping is
4319/// left a local matter." RFC 5280 §7.1 classifies `TeletexString` support
4320/// as OPTIONAL. No canonical T.61→Unicode table exists — OpenSSL, NSS,
4321/// and `GnuTLS` each use incompatible vendor extensions. Adopting any one
4322/// of those tables would silently accept mismatches the others reject and
4323/// reject chains the others accept — a name-confusion smell with no
4324/// interoperability win. Byte-equality is fail-closed: two `TeletexString`
4325/// AVAs match iff their DER content bytes are identical, which is what
4326/// RFC 5280 §4.1.2.4 already requires of well-formed issuer/subject DN
4327/// reuse across a chain.
4328///
4329/// # Future work
4330///
4331/// Full RFC 4518 six-step preparation (Map → NFKC → Prohibit → `CheckBidi`
4332/// → insignificant-space) for non-ASCII Unicode code points is tracked
4333/// separately. Until that lands, two `BMPString` values that contain the
4334/// same Unicode code points but differ in canonical decomposition (e.g.
4335/// precomposed U+00E9 'é' vs decomposed U+0065 U+0301 'e'+ combining
4336/// acute) compare unequal even though RFC 4518 says they should match.
4337fn any_to_str_bytes(a: &der::Any) -> Option<DirStringBytes<'_>> {
4338 use der::Tag;
4339 match a.tag() {
4340 Tag::Utf8String
4341 | Tag::PrintableString
4342 | Tag::Ia5String
4343 | Tag::VisibleString
4344 | Tag::NumericString => Some(DirStringBytes::Plain(a.value().iter())),
4345 // `TeletexString` only when every octet is in the ISO 646 invariant
4346 // set, where T.61 and ASCII cannot disagree. See
4347 // `teletex_is_iso646_invariant`.
4348 Tag::TeletexString if teletex_is_iso646_invariant(a.value()) => {
4349 Some(DirStringBytes::Plain(a.value().iter()))
4350 }
4351 // `clippy::chunks_exact_to_as_chunks` would have this be
4352 // `as_chunks::<2>().0.iter()`. Declined: this iterator is stored in
4353 // `DirStringBytes::Bmp`, so the change rewrites that variant's field
4354 // type from `ChunksExact<'_, u8>` to `slice::Iter<'_, [u8; 2]>` and
4355 // the `Iterator` impl that transcodes UCS-2 through it. That is a
4356 // real edit to DN-comparison code for a style preference, and
4357 // `bmp_is_well_formed` has already established the length is even,
4358 // which is the correctness property `as_chunks` would make visible
4359 // in the type.
4360 #[expect(
4361 clippy::chunks_exact_to_as_chunks,
4362 reason = "see the comment above; the iterator type is part of DirStringBytes"
4363 )]
4364 Tag::BmpString if bmp_is_well_formed(a.value()) => Some(DirStringBytes::Bmp {
4365 units: a.value().chunks_exact(2),
4366 buf: [0; 4],
4367 len: 0,
4368 pos: 0,
4369 }),
4370 _ => None,
4371 }
4372}
4373
4374/// The twelve code positions ISO 646 leaves to national variation, where
4375/// T.61 and US-ASCII therefore cannot be assumed to agree.
4376///
4377/// `#` `$` `@` `[` `\` `]` `^` `` ` `` `{` `|` `}` `~` in ASCII. ISO 646's
4378/// International Reference Version already differs from ASCII at `0x24`,
4379/// putting the international currency sign there rather than the dollar
4380/// sign, and T.61 descends from that lineage.
4381const ISO646_VARIANT_POSITIONS: [u8; 12] = [
4382 0x23, 0x24, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x60, 0x7B, 0x7C, 0x7D, 0x7E,
4383];
4384
4385/// Returns `true` if `TeletexString` content can be compared as ASCII
4386/// without needing to know T.61's code table.
4387///
4388/// T.61 is not ASCII. Its upper half carries a supplementary set, and
4389/// `0xC0`-`0xCF` are *non-spacing diacritics* that precede the letter they
4390/// modify -- six eIDAS roots in `third_party/trust-stores/eu-eidas/` encode
4391/// `Regulierungsbeh<0xC8>orde f<0xC8>ur Telekommunikation und Post`, where
4392/// `0xC8` is a combining diaeresis and the name is "Regulierungsbehörde
4393/// für". Decoding that correctly means implementing T.51/T.61, and this is
4394/// a name comparison, not a transcoder.
4395///
4396/// Its lower half is not reliably ASCII either. T.61 descends from ISO 646,
4397/// which leaves twelve positions to national variation, so a `$` or an `@`
4398/// in a `TeletexString` cannot be read as a `$` or an `@` without the
4399/// table. What *is* safe is the ISO 646 invariant set -- the positions
4400/// identical in every variant -- which covers the letters, the digits,
4401/// space, and the punctuation that actually appears in distinguished names.
4402///
4403/// So: pass through content drawn entirely from that set, and return
4404/// `false` for anything else, which sends the value to the raw
4405/// tag-and-bytes comparison in [`ava_values_match`]. That is fail-closed:
4406/// a value this cannot read compares equal only to a byte-identical one.
4407///
4408/// Measured against the corpus: 35 of the 37 `TeletexString` attribute
4409/// values across 15 certificates in six vendored stores are inside the
4410/// invariant set, including Hewlett-Packard's Platform Keys and Entrust's
4411/// `www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)`. The two
4412/// outside it are the German regulator's name above, which keeps byte
4413/// comparison -- and loses nothing by it, since both certificates encode
4414/// that name identically in subject and issuer.
4415fn teletex_is_iso646_invariant(bytes: &[u8]) -> bool {
4416 bytes
4417 .iter()
4418 .all(|b| (0x20..=0x7E).contains(b) && !ISO646_VARIANT_POSITIONS.contains(b))
4419}
4420
4421/// Returns `true` if `bytes` is well-formed `BMPString` content: an even
4422/// number of octets (UCS-2 units are 16 bits) and no unit in the UTF-16
4423/// surrogate range U+D800..=U+DFFF. Surrogates are *reserved* by Unicode
4424/// and do not represent characters; they appear in UTF-16 only as paired
4425/// surrogates encoding supplementary-plane code points (which are
4426/// forbidden in `BMPString` by definition — `BMP` = Basic Multilingual
4427/// Plane, U+0000..=U+FFFF).
4428fn bmp_is_well_formed(bytes: &[u8]) -> bool {
4429 let (units, rest) = bytes.as_chunks::<2>();
4430 rest.is_empty() && units.iter().all(|u| !(0xD8..=0xDF).contains(&u[0]))
4431}
4432
4433/// UTF-8 byte stream over a `DirectoryString` value (see [`any_to_str_bytes`]).
4434///
4435/// The `Bmp` variant transcodes one UCS-2-BE unit at a time into `buf`
4436/// and yields its UTF-8 bytes; it must only be constructed over content
4437/// that passed [`bmp_is_well_formed`].
4438enum DirStringBytes<'a> {
4439 /// Content bytes that are already UTF-8 / ASCII.
4440 Plain(core::slice::Iter<'a, u8>),
4441 /// UCS-2-BE content, transcoded lazily.
4442 Bmp {
4443 /// Remaining two-byte units.
4444 units: core::slice::ChunksExact<'a, u8>,
4445 /// UTF-8 encoding of the current unit.
4446 buf: [u8; 4],
4447 /// Number of valid bytes in `buf`.
4448 len: u8,
4449 /// Next byte of `buf` to yield.
4450 pos: u8,
4451 },
4452}
4453
4454impl Iterator for DirStringBytes<'_> {
4455 type Item = u8;
4456 // The `Bmp` arm's `as u8`: `encode_utf8` yields 1..=4 bytes for any
4457 // `char` and 1..=3 for a BMP scalar value, so it cannot truncate.
4458 // The allow sits on the function because an attribute cannot sit on
4459 // an expression statement, and because a `try_from().expect()` would
4460 // add a panic path to a loop DN comparison runs once per byte.
4461 #[allow(clippy::cast_possible_truncation)]
4462 fn next(&mut self) -> Option<u8> {
4463 match self {
4464 Self::Plain(it) => it.next().copied(),
4465 Self::Bmp {
4466 units,
4467 buf,
4468 len,
4469 pos,
4470 } => {
4471 if *pos == *len {
4472 let unit = units.next()?;
4473 let cp = u16::from_be_bytes([unit[0], unit[1]]);
4474 // Surrogates were rejected by `bmp_is_well_formed`; the
4475 // fallback keeps this total without a panic path.
4476 let ch = char::from_u32(u32::from(cp)).unwrap_or(char::REPLACEMENT_CHARACTER);
4477 // A BMP scalar value encodes to 1..=3 UTF-8 bytes.
4478 *len = ch.encode_utf8(buf).len() as u8;
4479 *pos = 0;
4480 }
4481 let b = buf[usize::from(*pos)];
4482 *pos += 1;
4483 Some(b)
4484 }
4485 }
4486 }
4487}
4488
4489/// Transcode `BMPString` content to UTF-8 (test helper over [`DirStringBytes`]).
4490///
4491/// Returns `None` for malformed content (see [`bmp_is_well_formed`]).
4492#[cfg(test)]
4493fn bmp_string_to_utf8(bytes: &[u8]) -> Option<Vec<u8>> {
4494 let any = der::Any::new(der::Tag::BmpString, bytes).ok()?;
4495 any_to_str_bytes(&any).map(Iterator::collect)
4496}
4497
4498/// Compare two byte slices after RFC 4518 preparation.
4499///
4500/// See [`NormalizedIter`] for the pipeline and for what is and is not
4501/// implemented: §2.2 Map and §2.3 NFKC are, §2.4 Prohibit and §2.5 Bidi
4502/// are not, and case folding is ASCII-only and applied after NFKC rather
4503/// than before it.
4504#[cfg(test)]
4505fn normalized_eq(a: &[u8], b: &[u8]) -> bool {
4506 NormalizedIter::new(a.iter().copied()).eq(NormalizedIter::new(b.iter().copied()))
4507}
4508
4509/// Lazy UTF-8 decoder over a byte iterator.
4510///
4511/// [`DirStringBytes`] yields UTF-8 -- `BMPString` is transcoded to it on
4512/// the fly -- and RFC 4518 §2.3 normalization works on characters, so the
4513/// pipeline needs chars without buffering the value. This is that step.
4514///
4515/// # Malformed input
4516///
4517/// A byte that cannot begin or continue a well-formed sequence yields
4518/// [`char::REPLACEMENT_CHARACTER`], and the byte that broke the sequence
4519/// is **not** consumed -- it begins the next one, as
4520/// `String::from_utf8_lossy` reads it. The decoder does not stop and does
4521/// not panic.
4522///
4523/// Not consuming it is what keeps valid text intact. A decoder that
4524/// swallowed the following byte would make `a E2 82 'b'` and
4525/// `a E2 82 'c'` both prepare to `a U+FFFD`, so two different names
4526/// would compare equal. See [`Self::cont`].
4527///
4528/// # The guarantee, stated exactly
4529///
4530/// Valid text is preserved, so two values differing in any valid
4531/// character compare unequal. Two values whose *invalid bytes occupy the
4532/// same positions* can still conflate: `ED A0 80` and `ED A0 81` both
4533/// prepare to three `U+FFFD`, because `80` and `81` are each a lone
4534/// continuation and nothing distinguishes one replacement character from
4535/// another. That is inherent to lossy decoding and is what
4536/// `String::from_utf8_lossy` does too; it is asserted in the tests rather
4537/// than left for someone to find.
4538///
4539/// The path is reachable, not merely defensive. `any_to_str_bytes` hands
4540/// `PrintableString`, `IA5String`, `VisibleString` and `NumericString`
4541/// content through as raw bytes without checking it is ASCII, so a
4542/// certificate carrying a `PrintableString` with a high byte reaches
4543/// here. Callers who need such a value *rejected* rather than normalised
4544/// have that for the two types where it is load-bearing:
4545/// `bmp_is_well_formed` and `teletex_is_iso646_invariant` gate those
4546/// upstream.
4547///
4548/// Callers that need malformed input *rejected* rather than normalised
4549/// have that already, upstream: `bmp_is_well_formed` and
4550/// `teletex_is_iso646_invariant` gate the two types where the distinction
4551/// is load-bearing.
4552struct Utf8Chars<I: Iterator<Item = u8>> {
4553 inner: core::iter::Peekable<I>,
4554}
4555
4556impl<I: Iterator<Item = u8>> Utf8Chars<I> {
4557 fn new(inner: I) -> Self {
4558 Self {
4559 inner: inner.peekable(),
4560 }
4561 }
4562
4563 /// Fold one continuation byte in, or `None` if the next byte is not
4564 /// one -- **without consuming it**.
4565 ///
4566 /// Peeking rather than taking is load-bearing and not a refinement. A
4567 /// truncated sequence followed by a valid byte, `E2 82 'x'`, must
4568 /// prepare as `U+FFFD` then `x`, the way `String::from_utf8_lossy`
4569 /// reads it. An earlier draft of this consumed the offending byte, so
4570 /// the `x` vanished -- and then `a E2 82 'b'` and `a E2 82 'c'` both
4571 /// prepared to `a U+FFFD` and compared EQUAL as two different names.
4572 /// A decoder that drops input can manufacture a name match, which is
4573 /// the one outcome a DN comparison must never produce.
4574 fn cont(&mut self, acc: u32) -> Option<u32> {
4575 let b = *self
4576 .inner
4577 .peek()
4578 .filter(|b| *b & 0b1100_0000 == 0b1000_0000)?;
4579 self.inner.next();
4580 Some((acc << 6) | u32::from(b & 0b0011_1111))
4581 }
4582}
4583
4584impl<I: Iterator<Item = u8>> Iterator for Utf8Chars<I> {
4585 type Item = char;
4586
4587 /// Decode one scalar, or one `U+FFFD` per maximal invalid subpart.
4588 ///
4589 /// The second-byte ranges are Unicode Table 3-7 (RFC 3629 §4) rather
4590 /// than a blanket `0x80..=0xBF`, and that is the whole correctness
4591 /// argument. Table 3-7 narrows the second byte for four leads --
4592 /// `E0` to `A0..=BF`, `ED` to `80..=9F`, `F0` to `90..=BF`, `F4` to
4593 /// `80..=8F` -- which is exactly what excludes overlong forms and the
4594 /// surrogate range. With it, no sequence this accepts can decode to a
4595 /// value `char::from_u32` rejects.
4596 ///
4597 /// The alternative, accepting `0x80..=0xBF` everywhere and filtering
4598 /// the result, was written first and was wrong in a way that matters
4599 /// here: `ED A0 80` consumed three bytes and yielded one `U+FFFD`, so
4600 /// `ED A0 80` and `ED A0 81` prepared identically and two different
4601 /// names compared EQUAL. Checked against `str::from_utf8`'s own
4602 /// reading via Python's `decode('utf-8', 'replace')`, which gives
4603 /// three replacement characters there: `ED` alone is the maximal
4604 /// subpart, then `A0` and `80` are each a lone continuation.
4605 fn next(&mut self) -> Option<char> {
4606 const BAD: char = char::REPLACEMENT_CHARACTER;
4607 let b0 = self.inner.next()?;
4608 // ASCII, which is almost every byte of almost every DN.
4609 if b0 < 0x80 {
4610 return Some(char::from(b0));
4611 }
4612 // (bits from the lead, second-byte range, further continuations)
4613 let (acc, lo, hi, more) = match b0 {
4614 0xC2..=0xDF => (u32::from(b0 & 0b0001_1111), 0x80, 0xBF, 0u8),
4615 0xE0 => (0, 0xA0, 0xBF, 1),
4616 0xE1..=0xEC => (u32::from(b0 & 0b0000_1111), 0x80, 0xBF, 1),
4617 0xED => (0x0D, 0x80, 0x9F, 1),
4618 0xEE..=0xEF => (u32::from(b0 & 0b0000_1111), 0x80, 0xBF, 1),
4619 0xF0 => (0, 0x90, 0xBF, 2),
4620 0xF1..=0xF3 => (u32::from(b0 & 0b0000_0111), 0x80, 0xBF, 2),
4621 0xF4 => (0x04, 0x80, 0x8F, 2),
4622 // A lone continuation byte, an overlong two-byte lead (C0,
4623 // C1), or a lead claiming five bytes or more (F5..FF).
4624 _ => return Some(BAD),
4625 };
4626 // The second byte, on its lead-specific range.
4627 let Some(b1) = self.inner.next_if(|b| (lo..=hi).contains(b)) else {
4628 return Some(BAD);
4629 };
4630 let mut acc = (acc << 6) | u32::from(b1 & 0b0011_1111);
4631 for _ in 0..more {
4632 match self.cont(acc) {
4633 Some(next) => acc = next,
4634 // Truncated. The byte that broke the sequence is still
4635 // there and begins the next one, so nothing is lost.
4636 None => return Some(BAD),
4637 }
4638 }
4639 // Table 3-7 admits no surrogate and no overlong form, so this
4640 // cannot fail; BAD rather than a panic if it somehow does.
4641 Some(char::from_u32(acc).unwrap_or(BAD))
4642 }
4643}
4644
4645/// RFC 4518 §2.2 Map, the subset this crate implements.
4646///
4647/// `None` for a character that maps to nothing, `Some(c)` for one that
4648/// maps to `c`. Case folding is **not** here; see [`NormalizedIter`] for
4649/// why it comes after normalization instead.
4650///
4651/// The sets are listed character by character rather than by table
4652/// reference, because a reader checking a certificate in front of them
4653/// needs to see the membership without opening RFC 3454.
4654///
4655/// # Mapped to nothing
4656///
4657/// `U+00AD` SOFT HYPHEN, `U+034F` COMBINING GRAPHEME JOINER, `U+1806`
4658/// MONGOLIAN TODO SOFT HYPHEN, `U+180B..=U+180D` MONGOLIAN FREE VARIATION
4659/// SELECTORs, `U+200B` ZERO WIDTH SPACE, `U+200C` ZWNJ, `U+200D` ZWJ,
4660/// `U+2060` WORD JOINER, `U+FE00..=U+FE0F` VARIATION SELECTORs, `U+FEFF`
4661/// ZERO WIDTH NO-BREAK SPACE, and the C0/C1 controls `U+0000..=U+0008`,
4662/// `U+000E..=U+001F`, `U+007F..=U+009F` except `U+0085`.
4663///
4664/// # Mapped to SPACE
4665///
4666/// `U+0009..=U+000D`, `U+0085` NEXT LINE, `U+00A0` NO-BREAK SPACE,
4667/// `U+1680` OGHAM SPACE MARK, `U+2000..=U+200A`, `U+2028` LINE SEPARATOR,
4668/// `U+2029` PARAGRAPH SEPARATOR, `U+202F` NARROW NO-BREAK SPACE, `U+205F`
4669/// MEDIUM MATHEMATICAL SPACE, `U+3000` IDEOGRAPHIC SPACE.
4670///
4671/// That second list is what retires the old "only `U+0020` is
4672/// insignificant whitespace" limitation: a tab or a no-break space now
4673/// becomes a space and is then collapsed like any other.
4674fn rfc4518_map(c: char) -> Option<char> {
4675 match c {
4676 // Mapped to SPACE. First, because U+0085 is also inside the C1
4677 // range dropped below and the mapping wins.
4678 '\u{0009}'..='\u{000D}'
4679 | '\u{0085}'
4680 | '\u{00A0}'
4681 | '\u{1680}'
4682 | '\u{2000}'..='\u{200A}'
4683 | '\u{2028}'
4684 | '\u{2029}'
4685 | '\u{202F}'
4686 | '\u{205F}'
4687 | '\u{3000}' => Some(' '),
4688 // Mapped to nothing.
4689 '\u{00AD}'
4690 | '\u{034F}'
4691 | '\u{1806}'
4692 | '\u{180B}'..='\u{180D}'
4693 | '\u{200B}'..='\u{200D}'
4694 | '\u{2060}'
4695 | '\u{FE00}'..='\u{FE0F}'
4696 | '\u{FEFF}'
4697 | '\u{0000}'..='\u{0008}'
4698 | '\u{000E}'..='\u{001F}'
4699 | '\u{007F}'..='\u{009F}' => None,
4700 other => Some(other),
4701 }
4702}
4703
4704/// Streaming adapter yielding the RFC 4518-prepared characters of a value.
4705///
4706/// The pipeline, in order, and the order is the interesting part:
4707///
4708/// 1. [`Utf8Chars`] decodes the UTF-8 byte stream to `char`.
4709/// 2. [`rfc4518_map`] applies §2.2 Map: characters that map to nothing are
4710/// dropped, and the Unicode space characters are mapped to `U+0020`.
4711/// 3. `unicode_normalization`'s `nfkc()` applies §2.3 Normalize.
4712/// 4. This adapter applies ASCII case folding and §2.6.1 insignificant
4713/// space handling: leading and trailing spaces dropped, internal runs
4714/// collapsed to one.
4715///
4716/// # Why case folding comes after NFKC and not, as RFC 4518 has it, before
4717///
4718/// §2.2 puts case folding in the Map step, using RFC 3454 Table B.2 --
4719/// **full Unicode** case folding, which folds `U+FF21` FULLWIDTH LATIN
4720/// CAPITAL LETTER A to `U+FF41` FULLWIDTH SMALL A, after which §2.3 maps
4721/// that to `a`. This crate folds ASCII only, and under ASCII-only folding
4722/// the RFC's order silently fails: `U+FF21` is untouched by the fold, NFKC
4723/// then turns it into capital `A`, and `ABC` would compare unequal to
4724/// `abc`. Folding after NFKC gets the answer the RFC intends for every
4725/// character whose compatibility mapping is ASCII, which is the set that
4726/// matters for a DN.
4727///
4728/// The remaining gap is honest and narrow: a non-ASCII letter with no
4729/// ASCII compatibility mapping is still compared case-sensitively.
4730/// `Σ` and `σ` are two names here, where RFC 4518 makes them one. Full
4731/// Unicode case folding is §2.2's Table B.2 and a separate decision,
4732/// because it is a further widening of name equality and wants its own
4733/// argument.
4734///
4735/// # Not implemented
4736///
4737/// §2.4 Prohibit and §2.5 Bidi. Neither changes whether two values are
4738/// equal -- they decide whether a value is *admissible at all* -- so they
4739/// belong to a validity check rather than to a comparison, and this
4740/// function is only ever asked whether two names match.
4741/// [`Utf8Chars`] with RFC 4518 §2.2 Map applied: the stage NFKC consumes.
4742///
4743/// A named type because the composed iterator type is otherwise long
4744/// enough that clippy's `type_complexity` objects, and because naming it
4745/// says which pipeline stage it is.
4746type MappedChars<I> = core::iter::FilterMap<Utf8Chars<I>, fn(char) -> Option<char>>;
4747
4748/// The §2.3 Normalize stage over [`MappedChars`], peekable for the space
4749/// collapsing that follows it.
4750type PreparedChars<I> = core::iter::Peekable<unicode_normalization::Recompositions<MappedChars<I>>>;
4751
4752struct NormalizedIter<I: Iterator<Item = u8>> {
4753 inner: PreparedChars<I>,
4754 /// Set once the first non-space character has been yielded; spaces
4755 /// seen before that are leading spaces and are dropped.
4756 started: bool,
4757}
4758
4759impl<I: Iterator<Item = u8>> NormalizedIter<I> {
4760 fn new(bytes: I) -> Self {
4761 use unicode_normalization::UnicodeNormalization as _;
4762 let mapped: MappedChars<I> = Utf8Chars::new(bytes).filter_map(rfc4518_map);
4763 Self {
4764 inner: mapped.nfkc().peekable(),
4765 started: false,
4766 }
4767 }
4768}
4769
4770impl<I: Iterator<Item = u8>> Iterator for NormalizedIter<I> {
4771 type Item = char;
4772 fn next(&mut self) -> Option<char> {
4773 loop {
4774 let c = self.inner.next()?;
4775 if c != ' ' {
4776 self.started = true;
4777 return Some(c.to_ascii_lowercase());
4778 }
4779 // Consume the rest of this space run. `next_if_eq` rather than
4780 // a peek-and-next pair: the pair's condition can be mutated
4781 // into one that consumes nothing and never ends, because
4782 // `next()` on an exhausted `Peekable` leaves `peek()` at
4783 // `None` forever. There is no such reading of this.
4784 while self.inner.next_if_eq(&' ').is_some() {}
4785 // Leading run: drop it and continue with the first non-space.
4786 // Trailing run (nothing follows): drop it and end.
4787 // Internal run: collapse to exactly one space.
4788 if self.started && self.inner.peek().is_some() {
4789 return Some(' ');
4790 }
4791 }
4792 }
4793}
4794
4795// ---------------------------------------------------------------------------
4796// NameConstraints matching (PKIX-mew)
4797// ---------------------------------------------------------------------------
4798
4799/// Newtype wrapping a bitmask of `GeneralName` name types for `NameConstraints`.
4800///
4801/// Used by `nc_constrained_types` to track which types have been constrained
4802/// by at least one CA certificate in the path, even if the intersection later
4803/// empties the permitted set for that type.
4804///
4805/// Bare `u32` constants would allow silent misuse (e.g., confusing a count
4806/// with a mask). The newtype makes the intent explicit at every operation site.
4807#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4808struct NcTypeMask(u32);
4809
4810impl NcTypeMask {
4811 const EMPTY: Self = Self(0);
4812 const RFC822: Self = Self(1 << 0);
4813 const DNS: Self = Self(1 << 1);
4814 const DIRECTORY_NAME: Self = Self(1 << 2);
4815 const URI: Self = Self(1 << 3);
4816 /// `IP_ADDRESS` is used by `name_type_bit` and participates in `nc_constrained_types`
4817 /// tracking. `IpAddress` names cannot appear in Subject DNs, so there is no
4818 /// inline DN-path code for this type; SAN `IpAddress` entries are handled by the
4819 /// generic SAN loop in `check_name_constraints` via `type_constrained(name)`.
4820 const IP_ADDRESS: Self = Self(1 << 4);
4821 /// `otherName` (any type-id). `pkix-path` cannot match otherName
4822 /// constraints; an `otherName` SAN is rejected whenever any otherName
4823 /// constraint is in effect. `SmtpUTF8Mailbox` SANs are additionally
4824 /// checked against rfc822Name constraints (RFC 8398 §6).
4825 const OTHER_NAME: Self = Self(1 << 5);
4826 /// `ediPartyName`: unsupported, fail-closed like `OTHER_NAME`.
4827 const EDI_PARTY_NAME: Self = Self(1 << 6);
4828 /// `registeredID`: unsupported, fail-closed like `OTHER_NAME`.
4829 const REGISTERED_ID: Self = Self(1 << 7);
4830
4831 /// Returns `true` if `self` and `other` share at least one bit (non-empty intersection).
4832 ///
4833 /// Named `intersects` rather than `contains` because this is a bitmask test,
4834 /// not a set-membership check — `a.intersects(b)` is symmetric, while `contains`
4835 /// implies `a ⊇ b`.
4836 const fn intersects(self, other: Self) -> bool {
4837 self.0 & other.0 != 0
4838 }
4839
4840 /// Returns `true` when no name form is tracked.
4841 ///
4842 /// Read on the hot path, to decide whether any name constraint is in
4843 /// effect at all. See the `nc_in_effect` computation in
4844 /// [`validate_path`].
4845 const fn is_empty(self) -> bool {
4846 self.0 == 0
4847 }
4848}
4849
4850impl core::ops::BitOr for NcTypeMask {
4851 type Output = Self;
4852 fn bitor(self, rhs: Self) -> Self {
4853 Self(self.0 | rhs.0)
4854 }
4855}
4856
4857impl core::ops::BitOrAssign for NcTypeMask {
4858 fn bitor_assign(&mut self, rhs: Self) {
4859 self.0 |= rhs.0;
4860 }
4861}
4862
4863/// Return the `NcTypeMask` bit for the name form of `name`.
4864///
4865/// Every `GeneralName` form has a bit, including the forms `pkix-path`
4866/// cannot match (`otherName`, `ediPartyName`, `registeredID`). Tracking
4867/// those lets
4868/// `check_name_constraints` reject a certificate that carries an
4869/// unsupported form a constraint applies to, as RFC 5280 §4.2.1.10
4870/// requires. `x400Address` is not representable in `x509-cert` 0.3 (a SAN
4871/// containing one fails to decode and is rejected as malformed).
4872const fn name_type_bit(name: &x509_cert::ext::pkix::name::GeneralName) -> NcTypeMask {
4873 use x509_cert::ext::pkix::name::GeneralName;
4874 match name {
4875 GeneralName::Rfc822Name(_) => NcTypeMask::RFC822,
4876 GeneralName::DnsName(_) => NcTypeMask::DNS,
4877 GeneralName::DirectoryName(_) => NcTypeMask::DIRECTORY_NAME,
4878 GeneralName::UniformResourceIdentifier(_) => NcTypeMask::URI,
4879 GeneralName::IpAddress(_) => NcTypeMask::IP_ADDRESS,
4880 GeneralName::OtherName(_) => NcTypeMask::OTHER_NAME,
4881 GeneralName::EdiPartyName(_) => NcTypeMask::EDI_PARTY_NAME,
4882 GeneralName::RegisteredId(_) => NcTypeMask::REGISTERED_ID,
4883 }
4884}
4885
4886/// Returns true if `subject` DN is within the subtree rooted at `constraint`.
4887///
4888/// RFC 5280 §4.2.1.10: a `DirectoryName` constraint is satisfied when the subject's
4889/// DN has the constraint DN as a prefix (most-general to most-specific order).
4890/// E.g., constraint `{C=US, O=Test}` matches subject `{C=US, O=Test, CN=Alice}`.
4891fn dn_within_subtree(subject: &x509_cert::name::Name, constraint: &x509_cert::name::Name) -> bool {
4892 let c_rdns = constraint.iter_rdn();
4893 let s_rdns = subject.iter_rdn();
4894 if constraint.len() > subject.len() {
4895 return false;
4896 }
4897 c_rdns.zip(s_rdns).all(|(c_rdn, s_rdn)| {
4898 // Each pair of RDNs must have matching attribute-value pairs.
4899 if c_rdn.len() != s_rdn.len() {
4900 return false;
4901 }
4902 c_rdn.iter().all(|c_ava| {
4903 s_rdn
4904 .iter()
4905 .any(|s_ava| c_ava.oid == s_ava.oid && ava_values_match(&c_ava.value, &s_ava.value))
4906 })
4907 })
4908}
4909
4910/// Returns true if `a` and `b` are the same `GeneralName` form.
4911///
4912/// Uses `name_type_bit` as the single source of truth so that adding a new
4913/// form to `name_type_bit` automatically extends this check with no
4914/// separate update required.
4915fn same_nc_variant(
4916 a: &x509_cert::ext::pkix::name::GeneralName,
4917 b: &x509_cert::ext::pkix::name::GeneralName,
4918) -> bool {
4919 name_type_bit(a) != NcTypeMask::EMPTY && name_type_bit(a) == name_type_bit(b)
4920}
4921
4922/// Returns true if `name` (a certificate's subject or SAN name) satisfies
4923/// the `subtree` constraint.
4924///
4925/// Unsupported forms never match; `check_name_constraints` rejects them
4926/// separately whenever a constraint of their form is in effect.
4927fn name_matches_subtree(
4928 name: &x509_cert::ext::pkix::name::GeneralName,
4929 subtree: &x509_cert::ext::pkix::constraints::name::GeneralSubtree,
4930) -> bool {
4931 use x509_cert::ext::pkix::name::GeneralName;
4932 match (name, &subtree.base) {
4933 (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
4934 matches_dns_name(subj.as_str(), constr.as_str())
4935 }
4936 (GeneralName::DirectoryName(subj), GeneralName::DirectoryName(constr)) => {
4937 dn_within_subtree(subj, constr)
4938 }
4939 (GeneralName::Rfc822Name(subj), GeneralName::Rfc822Name(constr)) => {
4940 matches_rfc822_name(subj.as_str(), constr.as_str())
4941 }
4942 (
4943 GeneralName::UniformResourceIdentifier(subj),
4944 GeneralName::UniformResourceIdentifier(constr),
4945 ) => matches_uri(subj.as_str(), constr.as_str()),
4946 (GeneralName::IpAddress(subj), GeneralName::IpAddress(constr)) => {
4947 matches_ip_address(subj.as_bytes(), constr.as_bytes())
4948 }
4949 // Mismatched variants or unhandled types: no match.
4950 _ => false,
4951 }
4952}
4953
4954/// Returns true if every name inside constraint `a` is also inside
4955/// constraint `b` (`a ⊆ b`), for two `GeneralSubtree` bases of the same form.
4956///
4957/// Used to intersect permitted subtrees (RFC 5280 §6.1.4(g)(1)) and to
4958/// de-duplicate excluded subtrees. A constraint is *not* a certificate name
4959/// (an iPAddress constraint is address + mask, a URI or rfc822Name
4960/// constraint is a bare host or `.domain`), so this cannot reuse
4961/// [`name_matches_subtree`]. Unsupported forms return `false`.
4962fn subtree_within(
4963 a: &x509_cert::ext::pkix::name::GeneralName,
4964 b: &x509_cert::ext::pkix::name::GeneralName,
4965) -> bool {
4966 use x509_cert::ext::pkix::name::GeneralName;
4967 match (a, b) {
4968 (GeneralName::DnsName(a), GeneralName::DnsName(b)) => {
4969 dns_constraint_within(a.as_str(), b.as_str())
4970 }
4971 (GeneralName::DirectoryName(a), GeneralName::DirectoryName(b)) => dn_within_subtree(a, b),
4972 (GeneralName::Rfc822Name(a), GeneralName::Rfc822Name(b)) => {
4973 rfc822_constraint_within(a.as_str(), b.as_str())
4974 }
4975 (GeneralName::UniformResourceIdentifier(a), GeneralName::UniformResourceIdentifier(b)) => {
4976 uri_constraint_within(a.as_str(), b.as_str())
4977 }
4978 (GeneralName::IpAddress(a), GeneralName::IpAddress(b)) => {
4979 ip_constraint_within(a.as_bytes(), b.as_bytes())
4980 }
4981 _ => false,
4982 }
4983}
4984
4985/// Strip one trailing `.` (the RFC 1034 absolute form) from a DNS name or
4986/// URI host.
4987///
4988/// `pkix-identity` strips the same dot when it binds a dNSName SAN to a
4989/// reference identity, so name-constraint matching must normalize
4990/// identically: otherwise `www.evil.com.` escapes an excluded `evil.com`
4991/// here yet binds to `www.evil.com` there.
4992fn strip_root_dot(s: &str) -> &str {
4993 s.strip_suffix('.').unwrap_or(s)
4994}
4995
4996/// Returns true if `name` is a proper subdomain of `parent` (one or more
4997/// labels added to the left), compared ASCII case-insensitively.
4998///
4999/// Works on bytes, so it cannot panic on a non-ASCII input.
5000fn is_strict_subdomain(name: &str, parent: &str) -> bool {
5001 let (name, parent) = (name.as_bytes(), parent.as_bytes());
5002 name.len() > parent.len() + 1
5003 && name[name.len() - parent.len() - 1] == b'.'
5004 && name[name.len() - parent.len()..].eq_ignore_ascii_case(parent)
5005}
5006
5007/// DNS name constraint matching (RFC 5280 §4.2.1.10).
5008///
5009/// - A constraint without a leading period matches the name itself and any
5010/// subdomain ("adding zero or more labels to the left-hand side").
5011/// - A constraint with a leading period (`.example.com`, a widespread
5012/// extension) matches proper subdomains only.
5013/// - The empty constraint has zero labels, so it matches every DNS name;
5014/// an empty excluded dNSName therefore forbids all DNS names, matching
5015/// OpenSSL, Go and `BoringSSL`.
5016/// - One trailing dot is ignored on both sides (see [`strip_root_dot`]).
5017///
5018/// Comparison is ASCII case-insensitive.
5019fn matches_dns_name(subject: &str, constraint: &str) -> bool {
5020 let subject = strip_root_dot(subject);
5021 let constraint = strip_root_dot(constraint);
5022 if constraint.is_empty() {
5023 return true;
5024 }
5025 if let Some(parent) = constraint.strip_prefix('.') {
5026 // The apex itself is excluded from a leading-period constraint.
5027 is_strict_subdomain(subject, parent)
5028 } else {
5029 subject.eq_ignore_ascii_case(constraint) || is_strict_subdomain(subject, constraint)
5030 }
5031}
5032
5033/// `id-at-commonName` (RFC 4519 §2.3).
5034const OID_AT_COMMON_NAME: der::asn1::ObjectIdentifier =
5035 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
5036
5037/// A `commonName` AVA value as a string, for the string types that can
5038/// hold a host name.
5039///
5040/// This must accept at least everything `pkix-identity`'s own CN reader
5041/// accepts, because that is the function that will match the value
5042/// against a requested name. It reads `PrintableString`, `UTF8String`
5043/// and `IA5String`, and this reads the same three. A value neither can
5044/// read is one nothing will match a host name against, so the sets
5045/// agreeing is what matters rather than either being generous.
5046fn cn_value_as_str(value: &der::Any) -> Option<&str> {
5047 if let Ok(s) = value.decode_as::<der::asn1::PrintableStringRef<'_>>() {
5048 return Some(s.as_str());
5049 }
5050 if let Ok(s) = value.decode_as::<der::asn1::Utf8StringRef<'_>>() {
5051 return Some(s.as_str());
5052 }
5053 if let Ok(s) = value.decode_as::<der::asn1::Ia5StringRef<'_>>() {
5054 return Some(s.as_str());
5055 }
5056 None
5057}
5058
5059/// Whether a string is shaped like a host name: at least one label
5060/// separator, and every label non-empty and LDH (letters, digits,
5061/// hyphen).
5062///
5063/// This is the heuristic that decides whether a `commonName` is read as
5064/// a DNS identity, and it is deliberately narrow. A descriptive CN such
5065/// as `Example Corp Issuing CA` has no dot and a space, so it is never
5066/// read as a host name and never constrained as one; `notallowed.test`
5067/// is.
5068fn is_hostname_shaped(s: &str) -> bool {
5069 let s = strip_root_dot(s);
5070 if s.is_empty() || !s.contains('.') {
5071 return false;
5072 }
5073 s.split('.').all(|label| {
5074 !label.is_empty()
5075 && label
5076 .bytes()
5077 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
5078 })
5079}
5080
5081/// Whether a `commonName` could be matched against a requested DNS name.
5082///
5083/// Either a host name, or a wildcard of the one shape
5084/// `pkix-identity`'s matcher honours. The wildcard case has to be here:
5085/// a CN of `*.example.com` is not a host name by
5086/// [`is_hostname_shaped`], but it will match `bar.example.com`, so
5087/// leaving it out would constrain the literal spelling and miss the
5088/// wildcard -- the very gap closed for SANs in
5089/// [`wildcard_san_reaches_excluded_dns`].
5090fn is_dns_identity_shaped(s: &str) -> bool {
5091 let s = strip_root_dot(s);
5092 match s.strip_prefix("*.") {
5093 Some(rest) => !rest.contains('*') && is_hostname_shaped(rest),
5094 None => is_hostname_shaped(s),
5095 }
5096}
5097
5098/// The `commonName` values this certificate asserts as DNS identities.
5099///
5100/// RFC 5280 §4.2.1.10 does not require checking the CN, and RFC 6125
5101/// §6.4.4 deprecated reading one as a host name -- which
5102/// `pkix_identity::verify_dns_name` honours, refusing to fall back. But
5103/// RFC 7672 §3.2.3 still *requires* CN fallback for SMTP DANE, so the
5104/// name is read as an identity there, and a constraint that cannot see
5105/// it cannot bound it. OpenSSL applies dNSName constraints to the CN in
5106/// exactly this case, and a chain it rejects as an excluded-subtree
5107/// violation was being accepted here.
5108///
5109/// Empty when the certificate carries a `subjectAltName` extension at
5110/// all, not merely when it carries a dNSName one.
5111///
5112/// That distinction is the whole rule, and getting it wrong rejects
5113/// valid certificates. A certificate presenting `IP:127.0.0.1` and
5114/// `CN=test.localhost` is asserting the address, not the name: RFC 5280
5115/// §4.1.2.6 makes `subjectAltName` *the* place identities live once it
5116/// is present, so the CN is not an identity and bounding it as one
5117/// refuses a certificate nobody can misuse. x509-limbo's
5118/// `bettertls::nameconstraints` suite is full of exactly that shape --
5119/// 88 of its testcases -- and expects them to validate.
5120///
5121/// OpenSSL does bound the CN in that case, and rejects those chains as
5122/// excluded-subtree violations. It is over-strict here, and matching it
5123/// was a mistake worth naming: an implementation is evidence about a
5124/// rule, not the rule.
5125///
5126/// The residual gap this leaves is real but covered. `pkix-identity`'s
5127/// CN fallback triggers on the absence of a dNSName SAN, not on the
5128/// absence of every SAN, so a certificate with an IP SAN and a
5129/// host-name CN can still be CN-matched for a DNS name by
5130/// `verify_dns_name_with_cn_fallback` while unbounded here.
5131/// `pkix-chain`'s SMTP DANE entry point refuses that whole shape
5132/// unconditionally -- `SmtpDaneFailure::ConstrainedPathWithoutDnsId`,
5133/// PKIX-skxt -- which is the right place for it, because only that
5134/// layer holds both the path and the requested name.
5135fn cn_dns_identities<'a>(
5136 subject: &'a x509_cert::name::Name,
5137 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
5138) -> Vec<&'a str> {
5139 if san.is_some() {
5140 return Vec::new();
5141 }
5142 // `Name::iter` flattens across RelativeDistinguishedNames: a
5143 // multi-valued RDN carrying a commonName is unusual but legal, and
5144 // every CN the certificate asserts has to be bounded.
5145 subject
5146 .iter()
5147 .filter(|ava| ava.oid == OID_AT_COMMON_NAME)
5148 .filter_map(|ava| cn_value_as_str(&ava.value))
5149 .filter(|s| is_dns_identity_shaped(s))
5150 .collect()
5151}
5152
5153/// Check each `commonName` read as a DNS identity against the dNSName
5154/// subtrees, with the same rules a dNSName SAN gets.
5155fn check_cn_dns_against_subtrees(
5156 cns: &[&str],
5157 subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
5158 mode: CheckMode,
5159 nc_constrained_types: NcTypeMask,
5160 index: usize,
5161) -> crate::Result<()> {
5162 use x509_cert::ext::pkix::name::GeneralName;
5163
5164 if cns.is_empty() {
5165 return Ok(());
5166 }
5167 let dns_subtrees = || {
5168 subtrees.iter().filter_map(|st| match &st.base {
5169 GeneralName::DnsName(c) => Some(c.as_str()),
5170 _ => None,
5171 })
5172 };
5173
5174 for cn in cns {
5175 match mode {
5176 CheckMode::Excluded => {
5177 if dns_subtrees()
5178 .any(|c| matches_dns_name(cn, c) || wildcard_san_reaches_excluded_dns(cn, c))
5179 {
5180 return Err(Error::NameConstraintViolation { index });
5181 }
5182 }
5183 CheckMode::Permitted => {
5184 if nc_constrained_types.intersects(NcTypeMask::DNS)
5185 && !dns_subtrees().any(|c| matches_dns_name(cn, c))
5186 {
5187 return Err(Error::NameConstraintViolation { index });
5188 }
5189 }
5190 }
5191 }
5192 Ok(())
5193}
5194
5195/// Whether a wildcard dNSName SAN can authenticate a name inside an
5196/// excluded subtree that the SAN's own spelling does not fall into.
5197///
5198/// RFC 5280 §4.2.1.10 compares a dNSName SAN against an excluded subtree
5199/// as a name, and a wildcard SAN is not the name it stands for: the
5200/// string `*.example.com` is not within the subtree `bar.example.com`,
5201/// so the literal comparison reports no violation. But RFC 9525 §6.3
5202/// lets that certificate authenticate `bar.example.com`, which is
5203/// exactly the name the CA was forbidden to certify. Neither rule is
5204/// wrong alone; read together they leave a dNSName exclusion
5205/// unenforceable against the certificate shape most used in practice.
5206/// That gap is CVE-2025-61727.
5207///
5208/// So the exclusion is tested against the names the wildcard can
5209/// authenticate rather than against its spelling. The wildcard replaces
5210/// exactly one label, so `*.D` stands for `{<label>.D}`, and that set
5211/// meets the subtree rooted at `E` when either
5212///
5213/// - `D` lies within `E` -- which makes `*.D` a strict subdomain of `E`
5214/// as a string, so [`matches_dns_name`] already reports it; or
5215/// - `E` is itself one of the names the wildcard stands for, that is
5216/// `<one label>.D`. That is the case this adds.
5217///
5218/// Nothing else meets it. A deeper exclusion such as
5219/// `foo.bar.example.com` is out of reach of `*.example.com`, because the
5220/// wildcard cannot cross a label boundary, and a leading-period
5221/// exclusion covers only strict subdomains of its apex, which the
5222/// wildcard likewise cannot reach past one label.
5223///
5224/// The wildcard test mirrors `pkix-identity`'s matcher exactly -- a
5225/// leftmost single `*` label, a non-empty remainder carrying no further
5226/// `*` and at least one label separator. It has to: a spelling that
5227/// matcher refuses authenticates nothing, and one it accepts must be
5228/// bounded here, so any disagreement between the two is either a
5229/// refusal of a harmless certificate or a hole of this same shape.
5230///
5231/// Permitted subtrees need no equivalent. There the test is containment
5232/// rather than intersection, and a wildcard that is not itself within a
5233/// permitted subtree already fails [`matches_dns_name`] -- which is why
5234/// the `nc-permits` half of the CVE's testcases was already rejected.
5235fn wildcard_san_reaches_excluded_dns(san: &str, constraint: &str) -> bool {
5236 let san = strip_root_dot(san);
5237 let constraint = strip_root_dot(constraint);
5238
5239 let Some(rest) = san.strip_prefix("*.") else {
5240 return false;
5241 };
5242 if rest.is_empty() || rest.contains('*') || !rest.contains('.') {
5243 return false;
5244 }
5245 // A leading-period exclusion covers only strict subdomains of its
5246 // apex; `*.rest` reaches no subdomain of a child of `rest`.
5247 if constraint.starts_with('.') {
5248 return false;
5249 }
5250
5251 // Is the excluded name `<one non-empty label>.rest`?
5252 let c = constraint.to_ascii_lowercase();
5253 let r = rest.to_ascii_lowercase();
5254 let Some(prefix) = c.strip_suffix(&r) else {
5255 return false;
5256 };
5257 let Some(label) = prefix.strip_suffix('.') else {
5258 return false;
5259 };
5260 !label.is_empty() && !label.contains('.')
5261}
5262
5263/// `a ⊆ b` for two dNSName constraints (see [`subtree_within`]).
5264///
5265/// `x` denotes `{x} ∪ subdomains(x)` and `.x` denotes `subdomains(x)`, so
5266/// `.x ⊆ b` exactly when `x` itself or every subdomain of `x` is covered,
5267/// which reduces to matching `x` against `b` with any leading period of `b`
5268/// dropped.
5269fn dns_constraint_within(a: &str, b: &str) -> bool {
5270 let a = strip_root_dot(a);
5271 match a.strip_prefix('.') {
5272 Some(a_parent) => {
5273 let b = strip_root_dot(b);
5274 matches_dns_name(a_parent, b.strip_prefix('.').unwrap_or(b))
5275 }
5276 None => matches_dns_name(a, b),
5277 }
5278}
5279
5280/// Match a mailbox's domain part against a host (`example.com`) or domain
5281/// (`.example.com`) rfc822Name constraint.
5282fn rfc822_domain_matches(domain: &str, constraint: &str) -> bool {
5283 match constraint.strip_prefix('.') {
5284 // Any host under the domain; the apex is excluded.
5285 Some(parent) => is_strict_subdomain(domain, parent),
5286 None => domain.eq_ignore_ascii_case(constraint),
5287 }
5288}
5289
5290/// RFC 822 (email) name constraint matching (RFC 5280 §4.2.1.10).
5291///
5292/// The domain part of `subject` is the text after the **last** `@`: an
5293/// RFC 5322 quoted local-part may itself contain `@`
5294/// (`"x@good.com"@evil.com` is a mailbox at `evil.com`).
5295///
5296/// # Two addresses match on an exact local-part and a folded host-part
5297///
5298/// RFC 5280 §7.5, unchanged in substance by [RFC 9549][rfc9549] §2.5,
5299/// which restates it as §7.5.1 and §7.5.2:
5300///
5301/// > Two email addresses are considered to match if:
5302/// >
5303/// > 1) The local-part of each name is an exact match, AND
5304/// >
5305/// > 2) The host-part of each name matches using a case-insensitive ASCII
5306/// > comparison.
5307///
5308/// The local-part is case-**sensitive**. RFC 5321 §2.4 is why: "the
5309/// local-part of a mailbox MUST BE treated as case sensitive", and
5310/// `Root@example.com` is a different mailbox from `root@example.com` as
5311/// far as any conforming mail system is concerned.
5312///
5313/// This function case-folded the whole address, local-part included, until
5314/// `PKIX-z1o9`. In an **excluded** subtree that was merely too broad, which
5315/// fails closed; in a **permitted** subtree it was fail-open — a CA
5316/// constrained to permit `root@example.com` would have had
5317/// `ROOT@example.com` accepted.
5318///
5319/// # RFC 9549 requires this to work identically for internationalized mail
5320///
5321/// §7.5.1 (ASCII local-part) and §7.5.2 (non-ASCII local-part) carry the
5322/// same two-clause rule, word for word, and RFC 9549 §2.2 says the point of
5323/// removing the per-mailbox constraint form was to let "name constraints
5324/// apply to email addresses in rfc822Name and `SmtpUTF8Mailbox` within
5325/// otherName". One function serves both, which is what makes the
5326/// "identically" structural rather than a claim.
5327///
5328/// The old folding broke that too, and asymmetrically:
5329/// `eq_ignore_ascii_case` folds only ASCII bytes, so a non-ASCII
5330/// local-part was already compared exactly while an ASCII one was not.
5331/// The rule was honoured for an internationalized mailbox and violated
5332/// for a plain one — the exact divergence §2.5 exists to forbid.
5333///
5334/// # No U-label conversion, deliberately
5335///
5336/// Everything here compares A-labels as bytes. RFC 9549 §3 is explicit
5337/// that its predecessor's conversion requirement "led to implementation
5338/// complexity and at least two security vulnerabilities", and that "all
5339/// IDNs are carried and processed as A-labels". A non-ASCII host-part
5340/// never reaches a comparison: [`check_mailbox_against_rfc822`] rejects
5341/// it before this function is called.
5342///
5343/// [rfc9549]: https://www.rfc-editor.org/rfc/rfc9549#section-2.5
5344fn matches_rfc822_name(subject: &str, constraint: &str) -> bool {
5345 // A constraint with an `@` names one mailbox. RFC 9549 §2.2 removed
5346 // that form from the issuance profile; this still honours it, because
5347 // declining to would stop an excluded subtree from excluding and that
5348 // is the fail-open direction. See `pkix-lint/divergences.md`.
5349 if let Some((c_local, c_domain)) = constraint.rsplit_once('@') {
5350 let Some((s_local, s_domain)) = subject.rsplit_once('@') else {
5351 return false; // malformed subject
5352 };
5353 // (1) local-part exact, (2) host-part folded. Not one fold over
5354 // the whole address.
5355 return s_local == c_local && s_domain.eq_ignore_ascii_case(c_domain);
5356 }
5357 let Some((_, domain)) = subject.rsplit_once('@') else {
5358 return false; // malformed subject
5359 };
5360 rfc822_domain_matches(domain, constraint)
5361}
5362
5363/// `a ⊆ b` for two rfc822Name constraints (see [`subtree_within`]).
5364///
5365/// The three constraint shapes are a mailbox (`u@host`, one address), a
5366/// host (`host`, all mailboxes at that host) and a domain (`.domain`, all
5367/// mailboxes at any host under it).
5368fn rfc822_constraint_within(a: &str, b: &str) -> bool {
5369 if a.contains('@') {
5370 return matches_rfc822_name(a, b);
5371 }
5372 if b.contains('@') {
5373 // A host or domain is never inside a single mailbox.
5374 return false;
5375 }
5376 match (a.strip_prefix('.'), b.strip_prefix('.')) {
5377 (None, _) => rfc822_domain_matches(a, b),
5378 // Every host under a domain is never inside one host.
5379 (Some(_), None) => false,
5380 (Some(a_dom), Some(b_dom)) => {
5381 a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
5382 }
5383 }
5384}
5385
5386/// URI host name constraint matching (RFC 5280 §4.2.1.10).
5387///
5388/// URI constraints use different semantics from DNS constraints:
5389/// - Leading period: subdomains only (same as DNS).
5390/// - No leading period: **exact host only** (unlike DNS, which also matches subdomains).
5391///
5392/// One trailing dot is ignored on both sides (see [`strip_root_dot`]).
5393fn matches_uri_host(host: &str, constraint: &str) -> bool {
5394 let host = strip_root_dot(host);
5395 let constraint = strip_root_dot(constraint);
5396 if constraint.is_empty() {
5397 return false;
5398 }
5399 if let Some(parent) = constraint.strip_prefix('.') {
5400 // Leading dot: subdomains only, apex excluded (same rule as DNS).
5401 is_strict_subdomain(host, parent)
5402 } else {
5403 // RFC 5280 §4.2.1.10: URI constraint without leading period matches
5404 // the exact host only — subdomains are NOT included.
5405 host.eq_ignore_ascii_case(constraint)
5406 }
5407}
5408
5409/// `a ⊆ b` for two URI host constraints (see [`subtree_within`]).
5410fn uri_constraint_within(a: &str, b: &str) -> bool {
5411 let (a, b) = (strip_root_dot(a), strip_root_dot(b));
5412 match (a.strip_prefix('.'), b.strip_prefix('.')) {
5413 (None, _) => matches_uri_host(a, b),
5414 // All subdomains of a domain are never inside one exact host.
5415 (Some(_), None) => false,
5416 (Some(a_dom), Some(b_dom)) => {
5417 a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
5418 }
5419 }
5420}
5421
5422/// Extract the host of a URI for name-constraint matching (RFC 3986 §3.2).
5423///
5424/// Returns `None` when RFC 5280 §4.2.1.10 requires the certificate to be
5425/// rejected under a URI constraint: the URI "doesn't include an authority
5426/// component with a host name specified as a fully qualified domain name
5427/// ... or includes an authority component in which the host name is
5428/// specified as an IP address". Concretely `None` is returned for:
5429///
5430/// - no `scheme ":" "//"` prefix (e.g. `urn:`, `mailto:`), or a malformed
5431/// scheme;
5432/// - an empty host (`file:///x`);
5433/// - an IP-literal (`[2001:db8::1]`) or dotted-quad IPv4 host;
5434/// - a non-numeric port.
5435///
5436/// The authority ends at the first `/`, `?` or `#`; userinfo is everything
5437/// before the **last** `@` inside the authority, so an `@` in the path,
5438/// query or fragment cannot change the host. One trailing dot is stripped.
5439fn uri_host(uri: &str) -> Option<&str> {
5440 let (scheme, rest) = uri.split_once(':')?;
5441 let mut scheme_bytes = scheme.bytes();
5442 if !scheme_bytes.next().is_some_and(|b| b.is_ascii_alphabetic())
5443 || !scheme_bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
5444 {
5445 return None;
5446 }
5447 let rest = rest.strip_prefix("//")?;
5448 let authority = &rest[..rest.find(['/', '?', '#']).unwrap_or(rest.len())];
5449 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
5450 if host_port.starts_with('[') {
5451 return None; // IP-literal
5452 }
5453 let host = match host_port.split_once(':') {
5454 Some((host, port)) if port.bytes().all(|b| b.is_ascii_digit()) => host,
5455 Some(_) => return None,
5456 None => host_port,
5457 };
5458 let host = strip_root_dot(host);
5459 if host.is_empty() || is_ipv4_literal(host) {
5460 return None;
5461 }
5462 Some(host)
5463}
5464
5465/// Returns true if `host` has the shape of an RFC 3986 `IPv4address`
5466/// (four dot-separated runs of one to three decimal digits).
5467fn is_ipv4_literal(host: &str) -> bool {
5468 let mut parts = 0usize;
5469 for part in host.split('.') {
5470 parts += 1;
5471 if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
5472 return false;
5473 }
5474 }
5475 parts == 4
5476}
5477
5478/// URI name constraint matching (RFC 5280 §4.2.1.10).
5479///
5480/// Extracts the host with [`uri_host`] and applies URI host matching
5481/// rules. A URI without a usable host matches nothing here;
5482/// `check_name_constraints` rejects such URIs outright whenever a URI
5483/// constraint is in effect.
5484fn matches_uri(subject_uri: &str, constraint: &str) -> bool {
5485 uri_host(subject_uri).is_some_and(|host| matches_uri_host(host, constraint))
5486}
5487
5488/// IP address name constraint matching (RFC 5280 §4.2.1.10).
5489///
5490/// `constraint_bytes` must be 8 bytes (IPv4: addr + mask) or 32 bytes (IPv6).
5491/// `subject_bytes` must be 4 bytes (IPv4) or 16 bytes (IPv6).
5492fn matches_ip_address(subject_bytes: &[u8], constraint_bytes: &[u8]) -> bool {
5493 let (expected_subj_len, half) = match constraint_bytes.len() {
5494 8 => (4usize, 4usize),
5495 32 => (16usize, 16usize),
5496 _ => return false,
5497 };
5498 if subject_bytes.len() != expected_subj_len {
5499 return false;
5500 }
5501 let (addr, mask) = constraint_bytes.split_at(half);
5502 subject_bytes
5503 .iter()
5504 .zip(addr.iter().zip(mask.iter()))
5505 .all(|(s, (a, m))| s & m == a & m)
5506}
5507
5508/// `a ⊆ b` for two iPAddress constraints (address + mask, see
5509/// [`subtree_within`]): same address family, `b`'s mask bits are a subset
5510/// of `a`'s, and the two addresses agree under `b`'s mask.
5511fn ip_constraint_within(a: &[u8], b: &[u8]) -> bool {
5512 if a.len() != b.len() || !(a.len() == 8 || a.len() == 32) {
5513 return false;
5514 }
5515 let half = a.len() / 2;
5516 let (a_addr, a_mask) = a.split_at(half);
5517 let (b_addr, b_mask) = b.split_at(half);
5518 (0..half).all(|i| {
5519 a_mask[i] & b_mask[i] == b_mask[i] && a_addr[i] & b_mask[i] == b_addr[i] & b_mask[i]
5520 })
5521}
5522
5523/// RFC 5280 §4.2.1.10 subtree containment for the non-`directoryName` name
5524/// forms.
5525///
5526/// These are pure functions over strings and byte slices, and a mutation
5527/// sweep found every one of them unguarded: the suite reached them only
5528/// through whole-chain fixtures, which never supply the degenerate inputs
5529/// that separate a correct comparison from a nearly-correct one.
5530#[cfg(test)]
5531mod tests_constraint_forms {
5532 use super::{
5533 ip_constraint_within, is_dns_identity_shaped, is_hostname_shaped, is_ipv4_literal,
5534 is_strict_subdomain, matches_dns_name, matches_ip_address, subtree_within,
5535 uri_constraint_within, wildcard_san_reaches_excluded_dns,
5536 };
5537 use der::Decode as _;
5538 use x509_cert::ext::pkix::name::GeneralName;
5539
5540 /// `.example.com` is not a *strict* subdomain of `example.com`.
5541 ///
5542 /// A strict subdomain adds at least one label, so the shortest one is
5543 /// `a.example.com`. The guard is `name.len() > parent.len() + 1`, and
5544 /// both of its obvious weakenings admit this degenerate input: `>=`
5545 /// directly, and `*` in place of `+` because `parent.len() * 1` is
5546 /// `parent.len()`. The leading dot then satisfies the separator check
5547 /// and the suffix compares equal, so a bare `.example.com` would be
5548 /// reported as a subdomain of itself-with-a-dot.
5549 #[test]
5550 fn a_leading_dot_alone_is_not_a_strict_subdomain() {
5551 assert!(!is_strict_subdomain(".example.com", "example.com"));
5552 // The real thing still is.
5553 assert!(is_strict_subdomain("a.example.com", "example.com"));
5554 assert!(is_strict_subdomain("deep.a.example.com", "example.com"));
5555 // And a sibling that merely ends in the same bytes is not.
5556 assert!(!is_strict_subdomain("notexample.com", "example.com"));
5557 }
5558
5559 /// A URI subtree contains itself.
5560 ///
5561 /// Both arms are `Some`, so the comparison is
5562 /// `equal || is_strict_subdomain`. With `&&` a domain would have to be a
5563 /// strict subdomain of itself, which nothing is, and a constraint would
5564 /// stop containing its own subtree.
5565 /// A descriptive commonName is never read as a host name.
5566 ///
5567 /// This is the false-rejection boundary: were it looser, a CA
5568 /// constrained to a DNS subtree could not issue a certificate whose
5569 /// CN is a person or an organisation, which is most certificates
5570 /// that carry no dNSName SAN. OpenSSL draws the line in the same
5571 /// place -- it accepts `CN=John Smith` under a `permitted
5572 /// DNS:example.com` constraint and rejects `CN=notallowed.test`.
5573 #[test]
5574 fn only_a_host_name_shaped_cn_is_read_as_one() {
5575 for not_a_host in [
5576 "John Smith",
5577 "Example Corp Issuing CA",
5578 // No label separator: a bare label is not treated as a host
5579 // name, matching the wildcard rule's refusal of `*.com`.
5580 "localhost",
5581 "",
5582 ".",
5583 // Empty labels.
5584 "a..b",
5585 ".leading",
5586 // Characters no host name carries.
5587 "under_score.example",
5588 "space in.example",
5589 "quote\".example",
5590 ] {
5591 assert!(
5592 !is_hostname_shaped(not_a_host),
5593 "{not_a_host:?} must not be read as a host name"
5594 );
5595 }
5596
5597 for host in [
5598 "notallowed.test",
5599 "mx.good.example",
5600 "a.b",
5601 "xn--bcher-kva.example",
5602 "has-hyphens.example.com",
5603 "MixedCase.Example",
5604 // A trailing root dot is the same name.
5605 "trailing.example.",
5606 ] {
5607 assert!(is_hostname_shaped(host), "{host:?} is host-name shaped");
5608 }
5609 }
5610
5611 /// The shape test must admit every spelling `pkix-identity`'s
5612 /// matcher can match a requested name against.
5613 ///
5614 /// That matcher honours a leftmost single `*` label whose remainder
5615 /// has no further `*` and contains a separator, and otherwise
5616 /// matches literally. Anything it can match is an identity this
5617 /// certificate asserts, so anything it can match must be bounded by
5618 /// the constraints -- and a wildcard is not host-name shaped, which
5619 /// is why `is_dns_identity_shaped` exists on top of
5620 /// [`is_hostname_shaped`].
5621 #[test]
5622 fn a_wildcard_cn_is_also_read_as_a_dns_identity() {
5623 for wildcard in ["*.example.com", "*.good.example", "*.a.b"] {
5624 assert!(
5625 !is_hostname_shaped(wildcard),
5626 "precondition: a wildcard is not itself host-name shaped"
5627 );
5628 assert!(
5629 is_dns_identity_shaped(wildcard),
5630 "{wildcard:?} can match a requested name, so it must be bounded"
5631 );
5632 }
5633
5634 // Spellings that matcher refuses, so they assert nothing.
5635 for refused in [
5636 // Remainder has no separator.
5637 "*.com",
5638 // Embedded second wildcard.
5639 "*.foo.*.com",
5640 // Not leftmost.
5641 "foo.*.example.com",
5642 "www*.example.com",
5643 "*",
5644 "*.",
5645 ] {
5646 assert!(
5647 !is_dns_identity_shaped(refused),
5648 "{refused:?} matches no requested name"
5649 );
5650 }
5651 }
5652
5653 /// CVE-2025-61727: the wildcard stands for the excluded name.
5654 ///
5655 /// `root -> ICA (exclude bar.example.com) -> EE (SAN *.example.com)`
5656 /// with `bar.example.com` requested. The SAN's spelling is not
5657 /// within the excluded subtree, so the literal comparison permits
5658 /// it, and RFC 9525 then lets it authenticate the one name the CA
5659 /// was forbidden to certify.
5660 #[test]
5661 fn a_wildcard_san_cannot_evade_a_dns_exclusion() {
5662 assert!(
5663 wildcard_san_reaches_excluded_dns("*.example.com", "bar.example.com"),
5664 "the wildcard stands for bar.example.com, which is excluded"
5665 );
5666 // The literal comparison is the one that misses it, which is why
5667 // the check above has to exist.
5668 assert!(
5669 !matches_dns_name("*.example.com", "bar.example.com"),
5670 "precondition: the spelling is not within the excluded subtree"
5671 );
5672 }
5673
5674 /// The wildcard replaces exactly one label, so a deeper exclusion is
5675 /// out of its reach and must stay permitted.
5676 #[test]
5677 fn a_wildcard_san_does_not_reach_past_one_label() {
5678 for excluded in [
5679 "foo.bar.example.com",
5680 "a.b.c.example.com",
5681 // A leading period covers only strict subdomains of its
5682 // apex, which the wildcard cannot reach either.
5683 ".bar.example.com",
5684 ] {
5685 assert!(
5686 !wildcard_san_reaches_excluded_dns("*.example.com", excluded),
5687 "*.example.com cannot authenticate anything inside {excluded}"
5688 );
5689 }
5690 }
5691
5692 /// An exclusion at or above the wildcard's own parent is already
5693 /// caught by the literal comparison, so both agree it is a
5694 /// violation and neither relies on the other.
5695 #[test]
5696 fn an_exclusion_above_the_wildcard_is_caught_literally() {
5697 for excluded in ["example.com", ".example.com", "com"] {
5698 assert!(
5699 matches_dns_name("*.example.com", excluded),
5700 "the spelling of *.example.com is already within {excluded}"
5701 );
5702 }
5703 }
5704
5705 /// A spelling `pkix-identity` will not honour authenticates nothing,
5706 /// so it reaches nothing. Mirroring its rule is what keeps the two
5707 /// from disagreeing.
5708 #[test]
5709 fn a_san_that_matches_no_name_reaches_no_exclusion() {
5710 for san in [
5711 // Not a leftmost wildcard.
5712 "foo.*.example.com",
5713 "www*.example.com",
5714 // Embedded second wildcard.
5715 "*.foo.*.com",
5716 // No label separator in the remainder: `*.com` is refused.
5717 "*.com",
5718 // Bare wildcard.
5719 "*.",
5720 // Not a wildcard at all: the literal path handles these.
5721 "bar.example.com",
5722 ] {
5723 assert!(
5724 !wildcard_san_reaches_excluded_dns(san, "bar.example.com"),
5725 "{san} authenticates no name, so it reaches no exclusion"
5726 );
5727 }
5728 }
5729
5730 /// Case and a trailing root dot do not change what a name reaches.
5731 #[test]
5732 fn wildcard_reach_ignores_case_and_the_root_dot() {
5733 assert!(wildcard_san_reaches_excluded_dns(
5734 "*.EXAMPLE.com",
5735 "BAR.example.COM"
5736 ));
5737 assert!(wildcard_san_reaches_excluded_dns(
5738 "*.example.com.",
5739 "bar.example.com"
5740 ));
5741 assert!(wildcard_san_reaches_excluded_dns(
5742 "*.example.com",
5743 "bar.example.com."
5744 ));
5745 }
5746
5747 #[test]
5748 fn a_uri_subtree_contains_itself_and_its_subdomains() {
5749 assert!(uri_constraint_within(".example.com", ".example.com"));
5750 assert!(uri_constraint_within(".a.example.com", ".example.com"));
5751 assert!(!uri_constraint_within(".example.com", ".a.example.com"));
5752 }
5753
5754 /// `is_ipv4_literal` rejects an empty label and an over-long one.
5755 ///
5756 /// The three conditions are joined by `||`, so turning either into `&&`
5757 /// makes one of them reachable only together with the next: an empty
5758 /// label stops being rejected, or a four-digit label does.
5759 #[test]
5760 fn an_ipv4_literal_needs_one_to_three_digits_per_label() {
5761 assert!(is_ipv4_literal("192.0.2.1"));
5762 assert!(
5763 !is_ipv4_literal("1..2.3"),
5764 "an empty label is not a digit run"
5765 );
5766 assert!(
5767 !is_ipv4_literal("1234.1.1.1"),
5768 "four digits is outside one-to-three, all-digits notwithstanding"
5769 );
5770 assert!(!is_ipv4_literal("a.b.c.d"));
5771 }
5772
5773 /// `matches_ip_address` handles IPv6 constraints, not only IPv4.
5774 ///
5775 /// The length match has an arm for 8 bytes (IPv4 address + mask) and one
5776 /// for 32 (IPv6). Deleting the 32-byte arm sends every IPv6 constraint
5777 /// to `_ => return false`, so an excluded IPv6 subtree would stop
5778 /// excluding and a permitted one would stop permitting.
5779 #[test]
5780 fn an_ipv6_constraint_is_matched() {
5781 // 2001:db8::/32 as constraint (16 address + 16 mask), subject
5782 // 2001:db8::1.
5783 let mut constraint = [0u8; 32];
5784 constraint[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
5785 constraint[16..20].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
5786 let mut subject = [0u8; 16];
5787 subject[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
5788 subject[15] = 1;
5789 assert!(matches_ip_address(&subject, &constraint));
5790
5791 // Outside the prefix.
5792 let mut other = [0u8; 16];
5793 other[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb9]);
5794 assert!(!matches_ip_address(&other, &constraint));
5795
5796 // IPv4 still works, so this is about the arm and not the function.
5797 let v4_constraint = [192, 0, 2, 0, 255, 255, 255, 0];
5798 assert!(matches_ip_address(&[192, 0, 2, 7], &v4_constraint));
5799 assert!(!matches_ip_address(&[192, 0, 3, 7], &v4_constraint));
5800 }
5801
5802 /// `ip_constraint_within` accepts both lengths it documents.
5803 ///
5804 /// The guard is `a.len() != b.len() || !(a.len() == 8 || a.len() == 32)`.
5805 /// Either comparison flipped to `!=` turns the negation into a refusal
5806 /// of exactly the family that comparison names, so both families are
5807 /// here: 8 bytes is the IPv4 case the function is most used for, and 32
5808 /// the IPv6 one, where the refusal would be silent because an
5809 /// `ip_constraint_within` that answers `false` reports "not contained"
5810 /// rather than "could not tell".
5811 #[test]
5812 fn an_ip_constraint_is_within_a_shorter_prefix_of_either_family() {
5813 // 192.0.2.0/24 inside 192.0.0.0/16: b's mask bits are a subset of
5814 // a's, and the addresses agree under b's mask.
5815 let a = [192, 0, 2, 0, 255, 255, 255, 0];
5816 let b = [192, 0, 0, 0, 255, 255, 0, 0];
5817 assert!(ip_constraint_within(&a, &b));
5818 assert!(!ip_constraint_within(&b, &a), "the wider one is not inside");
5819
5820 // 2001:db8:1::/48 inside 2001:db8::/32, the same relation in the
5821 // 32-byte form.
5822 let mut a6 = [0u8; 32];
5823 a6[..6].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01]);
5824 a6[16..22].copy_from_slice(&[0xff; 6]);
5825 let mut b6 = [0u8; 32];
5826 b6[..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
5827 b6[16..20].copy_from_slice(&[0xff; 4]);
5828 assert!(ip_constraint_within(&a6, &b6));
5829 assert!(
5830 !ip_constraint_within(&b6, &a6),
5831 "the wider one is not inside"
5832 );
5833
5834 // Mismatched family lengths are not comparable.
5835 let v6 = [0u8; 32];
5836 assert!(!ip_constraint_within(&a, &v6));
5837 }
5838
5839 /// Only 8 and 32 bytes are iPAddress *constraints*.
5840 ///
5841 /// A 16-byte value is a bare IPv6 address with no mask, and a 4-byte
5842 /// one a bare IPv4 address. Accepted, the function would read the
5843 /// second half of the value as the mask: two all-zero 16-byte blobs
5844 /// would then contain each other, which is the widest possible
5845 /// subtree. The guard refuses them, and the length it rejects them for
5846 /// is why both `== 8` and `== 32` have to be comparisons against the
5847 /// lengths they name.
5848 #[test]
5849 fn an_address_without_a_mask_is_not_a_constraint() {
5850 fn refused<const N: usize>() {
5851 let bare = [0u8; N];
5852 assert!(
5853 !ip_constraint_within(&bare, &bare),
5854 "{N} bytes is not an address-plus-mask constraint"
5855 );
5856 }
5857 refused::<0>();
5858 refused::<4>();
5859 refused::<16>();
5860 refused::<17>();
5861 refused::<64>();
5862 }
5863
5864 /// `subtree_within` routes two `directoryName`s to the DN comparison.
5865 ///
5866 /// Deleting that match arm sends them to the catch-all, so a
5867 /// `directoryName` constraint would stop containing anything — including
5868 /// itself.
5869 #[test]
5870 fn two_directory_names_are_compared_as_dns() {
5871 // C=US and C=US,O=Test
5872 const C_US: &[u8] = &[
5873 0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
5874 0x53,
5875 ];
5876 const C_US_O_TEST: &[u8] = &[
5877 0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
5878 0x53, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65,
5879 0x73, 0x74,
5880 ];
5881 let dn = |der: &[u8]| {
5882 GeneralName::DirectoryName(
5883 x509_cert::name::Name::from_der(der).expect("hand-built Name parses"),
5884 )
5885 };
5886
5887 assert!(subtree_within(&dn(C_US_O_TEST), &dn(C_US)));
5888 assert!(subtree_within(&dn(C_US), &dn(C_US)));
5889 assert!(!subtree_within(&dn(C_US), &dn(C_US_O_TEST)));
5890 }
5891}
5892
5893// ---------------------------------------------------------------------------
5894// RSA key size helper (PKIX-ken.1.5)
5895// ---------------------------------------------------------------------------
5896
5897use verifiers::{OID_RSA_ENCRYPTION, OID_RSASSA_PSS};
5898
5899/// Decode the RSA modulus from an SPKI and return its bit length.
5900///
5901/// Both `rsaEncryption` and `id-RSASSA-PSS` subject keys count as RSA: RFC
5902/// 4055 §1.2 encodes the public key identically (`RSAPublicKey`) under
5903/// either OID, and only the algorithm-identifier parameters differ.
5904///
5905/// Returns `None` when:
5906/// - the key algorithm OID is neither `rsaEncryption` nor `id-RSASSA-PSS`
5907/// (non-RSA key; check does not apply), or
5908/// - the SPKI bytes cannot be decoded (malformed; signature verification will also fail).
5909///
5910/// Uses `der::SliceReader` and `der::asn1::UintRef` from the existing `der`
5911/// dependency — no additional crate required.
5912///
5913/// `RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }` (RFC 3279 §2.3.1).
5914/// `UintRef::as_bytes()` strips the leading 0x00 sign byte from a DER unsigned INTEGER,
5915/// returning only the magnitude. Bit length is derived as `magnitude_bytes * 8`, which
5916/// over-counts by at most 7 bits for keys whose high magnitude byte has leading zero bits —
5917/// this lenient rounding is acceptable for a minimum-floor check: a real 2040-bit key
5918/// would measure as 2048 bits and pass a 2048-bit floor. Key-generation tools always
5919/// produce keys whose top bit is set, so the practical impact is zero.
5920fn rsa_public_key_bits(spki: &spki::SubjectPublicKeyInfoOwned) -> Option<u32> {
5921 use der::{Reader, asn1::UintRef};
5922
5923 if spki.algorithm.oid != OID_RSA_ENCRYPTION && spki.algorithm.oid != OID_RSASSA_PSS {
5924 return None; // Non-RSA key: check does not apply.
5925 }
5926 // BitString::as_bytes() returns None when unused_bits != 0.
5927 // RSA SPKI subject_public_key is always octet-aligned (unused_bits = 0).
5928 let raw = spki.subject_public_key.as_bytes()?;
5929
5930 // raw is a DER-encoded RSAPublicKey SEQUENCE.
5931 // RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }
5932 //
5933 // We decode the modulus INTEGER and then skip the publicExponent so the
5934 // sequence reader does not complain about trailing data (der 0.7 requires
5935 // the closure to consume the entire SEQUENCE content).
5936 //
5937 // Skip strategy: read the modulus, then call tlv_bytes() to consume the
5938 // exponent TLV as a raw byte slice (no allocation, no decode required).
5939 let modulus_byte_len: usize = der::SliceReader::new(raw)
5940 .ok()?
5941 .sequence(|r| {
5942 // UintRef strips the leading 0x00 sign byte; as_bytes() returns magnitude only.
5943 let modulus: UintRef<'_> = r.decode()?;
5944 let modulus_len = modulus.as_bytes().len();
5945 // Consume the publicExponent TLV so the nested reader has no trailing data.
5946 let _ = r.tlv_bytes()?;
5947 Ok::<_, der::Error>(modulus_len)
5948 })
5949 .ok()?;
5950
5951 // saturating_mul guards against overflow on a hypothetical absurdly large modulus.
5952 // The result fits in u32: the largest practical RSA key is 16384 bits (2048 bytes),
5953 // well within u32::MAX. u32::try_from is used to make the bound explicit.
5954 u32::try_from(modulus_byte_len.saturating_mul(8)).ok()
5955}
5956
5957// ---------------------------------------------------------------------------
5958// Chain walk loop — signature verification and name linkage (PKIX-vxf)
5959// ---------------------------------------------------------------------------
5960
5961/// Walk the chain from issuer to leaf, applying all RFC 5280 §6.1 per-cert checks.
5962///
5963/// Path-length and anchor-matching are handled by the caller (`validate_path`).
5964/// This function walks `chain` in reverse (issuer-to-leaf) against `anchor`:
5965///
5966/// a. Verify signature with the current issuer's SPKI.
5967/// b. Verify issuer/subject name linkage.
5968/// c. Check validity period against `policy.current_time_unix`.
5969/// d. Reject any unhandled critical extensions.
5970/// e. Check cert names (subject DN + SAN) against accumulated NC state.
5971/// f. For all certs except the leaf (i > 0): require `BasicConstraints` cA=TRUE.
5972/// g. For all certs except the leaf (i > 0): if `policy.enforce_key_usage`, require `keyCertSign`.
5973/// g'. For all certs except the leaf (i > 0): if `policy.require_crl_sign_on_cas`, require `cRLSign`.
5974/// h. For all certs except the leaf (i > 0): enforce `pathLenConstraint` if present.
5975/// i. For all certs except the leaf (i > 0): accumulate `NameConstraints` state
5976/// (INTERSECTION for permittedSubtrees, UNION for excludedSubtrees).
5977///
5978/// RFC 5280 §4.2.1.9 note on pathLenConstraint: for the cert at position `i`
5979/// (leaf at 0, root-adjacent at chain.len()-1), there are exactly `i-1`
5980/// intermediate certs below it. The constraint requires `i-1 ≤ pathLenConstraint`.
5981///
5982/// # Implementation notes
5983///
5984/// This function is intentionally structured as a single loop over the certificate
5985/// chain. The RFC 5280 §6.1 state machine has significant shared state (working
5986/// SPKI, name constraints, policy tree, inhibit flags) that must be threaded
5987/// through every step in a defined order. Decomposing the loop into smaller helpers
5988/// would require passing this state through many function boundaries without clarity
5989/// gain. The monolithic structure mirrors the RFC's sequential algorithm description
5990/// and keeps all state-mutation sites visible in one place for audit.
5991///
5992/// The per-walk mutable state is grouped into [`WorkingState`] to make the
5993/// state-machine inputs/outputs explicit at the call boundary. Future
5994/// per-substep helper extractions take a `&mut WorkingState` so that adding
5995/// helpers does not grow each helper's parameter list.
5996///
5997/// `working_spki` and `working_issuer_name` carry the borrow of either `anchor`
5998/// or some `chain[i]` and so the struct takes a single lifetime `'a` covering
5999/// both inputs. The lifetime is elided at the call site because `chain_walk`
6000/// constructs and consumes `WorkingState` within its own body.
6001///
6002/// RFC 5280 §6.1.2 maps to the struct fields as follows:
6003///
6004/// - `working_spki`, `working_issuer_name`
6005/// — §6.1.2(d)/(f) `working_public_key` + §6.1.2(e) `working_issuer_name`.
6006/// - `nc_permitted`, `nc_excluded`, `nc_constrained_types`
6007/// — §6.1.2(b)/(c) `permitted_subtrees`/`excluded_subtrees`. The
6008/// `nc_constrained_types` bitmask is a workspace addition: it tracks which
6009/// name types have *ever* been constrained by a CA so an empty post-
6010/// intersection set still rejects names of that type (not derivable from
6011/// `nc_permitted` contents alone).
6012/// - `explicit_policy`, `inhibit_any`, `policy_mapping`
6013/// — §6.1.2 `explicit_policy`, `inhibit_anyPolicy`, `policy_mapping` counters.
6014/// - `policy_tree`
6015/// — §6.1.2(a) `valid_policy_tree`. `None` represents the RFC NULL tree.
6016struct WorkingState<'a> {
6017 /// §6.1.2(d)/(f) `working_public_key`. Borrows from the trust anchor or a
6018 /// chain certificate; rebound to the just-validated cert's SPKI at the end
6019 /// of every loop iteration.
6020 working_spki: &'a spki::SubjectPublicKeyInfoOwned,
6021 /// §6.1.2(e) `working_issuer_name`. Borrows from the trust anchor or a
6022 /// chain certificate's subject; rebound at the end of every loop iteration.
6023 working_issuer_name: &'a x509_cert::name::Name,
6024 /// §6.1.2(b) `permitted_subtrees`. `None` means "no permitted constraint
6025 /// of any type has been imposed yet"; once any CA contributes a
6026 /// `permittedSubtrees`, this becomes `Some(...)` and only narrows
6027 /// (intersection per §6.1.4(g)).
6028 nc_permitted: Option<GeneralSubtrees>,
6029 /// §6.1.2(c) `excluded_subtrees`. Accumulates via union per §6.1.4(g).
6030 nc_excluded: GeneralSubtrees,
6031 /// Workspace-local invariant: bitmask of name types for which at least one
6032 /// CA has imposed a `permittedSubtrees` constraint. Bits are only `ORed` in,
6033 /// never cleared. Required for correct rejection when intersection of
6034 /// incompatible same-type constraints empties `nc_permitted` for a type
6035 /// while that type is still semantically forbidden. See the initialisation
6036 /// site in `chain_walk` for the long-form rationale.
6037 nc_constrained_types: NcTypeMask,
6038 /// §6.1.2 `explicit_policy` counter. Decremented by §6.1.4(h) on each
6039 /// non-self-issued intermediate; clamped by §6.1.4(i) `PolicyConstraints`
6040 /// `requireExplicitPolicy`; finalised by §6.1.5(a)+(b).
6041 explicit_policy: u32,
6042 /// §6.1.2 `inhibit_anyPolicy` counter. Decremented by §6.1.4(h);
6043 /// clamped by §6.1.4(j) `InhibitAnyPolicy`.
6044 inhibit_any: u32,
6045 /// §6.1.2 `policy_mapping` counter. Decremented by §6.1.4(h);
6046 /// clamped by §6.1.4(i) `PolicyConstraints` `inhibitPolicyMapping`.
6047 policy_mapping: u32,
6048 /// §6.1.2(a) `valid_policy_tree`. `None` represents the RFC's NULL tree
6049 /// (every transition that would empty the tree maps to `None`); a
6050 /// non-empty `Some(...)` carries the live policy graph. Returned to
6051 /// `validate_path` at §6.1.5 for post-validation qualifier extraction.
6052 policy_tree: Option<policy_graph::PolicyGraph>,
6053}
6054
6055/// RFC 5280 §6.1.3(a)(1) preface — project-policy signature-algorithm allowlist.
6056///
6057/// Fires before the cryptographic signature check so that a chain whose only
6058/// problem is a disallowed algorithm returns the diagnostic
6059/// [`Error::AlgorithmNotAllowed`] rather than the confusing
6060/// [`Error::SignatureInvalid`]. Applies to every cert in the chain (CA/B Forum
6061/// profile intent — there is no leaf/intermediate distinction here). Uses the
6062/// outer `signatureAlgorithm` OID; RFC 5280 §4.1.1.2 requires it to equal the
6063/// inner `TBSCertificate.signature` OID.
6064fn enforce_signature_alg_allowlist(
6065 cert: &Certificate,
6066 policy: &ValidationPolicy,
6067 index: usize,
6068) -> Result<()> {
6069 if let Some(allowed) = &policy.allowed_signature_algs {
6070 // O(n) over a typically 2–6 element list; acceptable for the common case.
6071 if !allowed.contains(&cert.signature_algorithm().oid) {
6072 return Err(Error::AlgorithmNotAllowed { index });
6073 }
6074 }
6075 Ok(())
6076}
6077
6078/// Project max-validity check.
6079///
6080/// Not part of RFC 5280 §6.1; this is a CA/B-Forum-style ceiling on the cert's
6081/// (notAfter − notBefore) duration. Applies to every cert in the chain.
6082///
6083/// `saturating_sub` avoids wrap on a malformed cert where `notAfter < notBefore`;
6084/// a resulting duration of 0 trivially passes the `> max_secs` test (safe — the
6085/// validity-period check in §6.1.3(a)(2) catches the malformed cert separately).
6086fn check_max_validity(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
6087 if let Some(max_secs) = policy.max_validity_secs {
6088 let not_before = cert
6089 .tbs_certificate()
6090 .validity()
6091 .not_before
6092 .to_unix_duration()
6093 .as_secs();
6094 let not_after = cert
6095 .tbs_certificate()
6096 .validity()
6097 .not_after
6098 .to_unix_duration()
6099 .as_secs();
6100 if not_after.saturating_sub(not_before) > max_secs {
6101 return Err(Error::ValidityPeriodExceedsMax { index });
6102 }
6103 }
6104 Ok(())
6105}
6106
6107/// Project minimum-RSA-key-bits check.
6108///
6109/// Not part of RFC 5280 §6.1; a deployment-policy floor on RSA modulus size.
6110/// Non-RSA keys are silently skipped (`rsa_public_key_bits` returns `None`),
6111/// so this is RSA-specific and inert for ECDSA/EdDSA chains. Applies to every
6112/// cert in the chain.
6113fn check_min_rsa_bits(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
6114 // A non-RSA key makes `rsa_public_key_bits` return `None`, so the
6115 // chain stops there and the check is silently skipped -- which is
6116 // the documented behaviour, not an oversight.
6117 if let Some(min_bits) = policy.min_rsa_key_bits
6118 && let Some(actual_bits) =
6119 rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info())
6120 && actual_bits < min_bits
6121 {
6122 return Err(Error::KeyTooSmall { index });
6123 }
6124 Ok(())
6125}
6126
6127/// RFC 5280 §6.1.3(a)(2) — issuer/subject DN linkage.
6128///
6129/// Verifies that the cert's issuer DN matches the previously-validated
6130/// cert's (or trust anchor's) subject DN.
6131///
6132/// # There is no `SubjectAltName` exception here
6133///
6134/// This check used to be skipped when the working issuer had an empty
6135/// Subject and a critical SAN, on the reading that §4.2.1.6 makes the SAN
6136/// such a certificate's identity, so comparing against an empty DN says
6137/// nothing. The accommodation was wrong, and it was a name-chaining
6138/// bypass: a leaf naming `CN=anyone` as its issuer validated against an
6139/// unnamed CA, because the only check that would have caught the
6140/// mismatch was the one being skipped.
6141///
6142/// §4.2.1.6 governs how the certificate's own *subject entity* is
6143/// identified. It does not reach §6.1.3(a)(4), which compares DNs and has
6144/// no SAN provision, and it is overridden for this case by §4.1.2.6: "If
6145/// the subject is a CA [...] then the subject field MUST be populated
6146/// with a non-empty distinguished name". A certificate that is the
6147/// working issuer has issued the one being checked, so it is a CA and
6148/// that MUST applies. §4.1.2.4 closes it from the other side: every
6149/// certificate's issuer field "MUST contain a non-empty distinguished
6150/// name", so a certificate needing an empty issuer to chain is itself
6151/// non-conforming.
6152///
6153/// An unnamed CA is now refused outright -- [`AnchorDefect::EmptySubject`]
6154/// as an anchor, [`Error::CaEmptySubject`] inside a path -- so no chain
6155/// that this skip used to admit is admitted by any other route.
6156fn check_issuer_linkage(
6157 cert: &Certificate,
6158 working_issuer_name: &x509_cert::name::Name,
6159 index: usize,
6160) -> Result<()> {
6161 if !names_match(working_issuer_name, cert.tbs_certificate().issuer()) {
6162 return Err(Error::ChainBroken { index });
6163 }
6164 Ok(())
6165}
6166
6167/// Locates the `TBSCertificate` inside a certificate's own DER and returns
6168/// it as a subslice: the exact bytes the issuer signed.
6169///
6170/// Prefer this to [`tbs_certificate_der`] wherever the certificate's DER is
6171/// still in hand, which it is for anything read from a file, a socket, a
6172/// trust store or an AIA fetch. It allocates nothing, does no decoding
6173/// beyond two headers, and — the reason it exists — it cannot be wrong,
6174/// because it does not rebuild anything.
6175///
6176/// # Why re-encoding is not equivalent
6177///
6178/// A signature is over bytes, not over a parsed structure. Recovering
6179/// those bytes from a parsed certificate requires the encoder to be
6180/// byte-faithful for every field, for every input the decoder accepted.
6181/// That has already failed once here: x509-cert 0.3 re-encodes a
6182/// `Certificate`'s validity times under the RFC 5280 profile, turning a
6183/// pre-2050 `GeneralizedTime` into a `UTCTime`, which is why
6184/// [`tbs_certificate_der`] carries a hand-written encoder that keeps each
6185/// time as it was parsed. Every other field is assumed faithful. That
6186/// assumption cannot be checked in general, and a great deal rests on it:
6187/// a `SET OF` the
6188/// encoder sorts, a `DEFAULT` it omits or an integer it minimises
6189/// differently would each produce a correct-looking certificate whose
6190/// signature does not verify.
6191///
6192/// This function removes the assumption rather than adding to it.
6193///
6194/// # ASN.1
6195///
6196/// `Certificate ::= SEQUENCE { tbsCertificate TBSCertificate, ... }`, so
6197/// the signed bytes are the first TLV inside the outer `SEQUENCE`, header
6198/// included.
6199///
6200/// # Errors
6201///
6202/// Returns [`DerError`] if `cert_der` does not begin with a `SEQUENCE`
6203/// whose first element is a complete TLV. It does *not* validate the
6204/// certificate: a caller wanting both should use [`CertificateWithDer`],
6205/// which parses and slices together and so cannot hold one certificate's
6206/// bytes beside another's parse.
6207pub fn tbs_der_slice(cert_der: &[u8]) -> core::result::Result<&[u8], DerError> {
6208 use der::{Decode as _, Header, Reader as _, SliceReader, Tag};
6209
6210 let mut reader = SliceReader::new(cert_der).map_err(DerError::new)?;
6211 let outer = Header::decode(&mut reader).map_err(DerError::new)?;
6212 if outer.tag() != Tag::Sequence {
6213 return Err(DerError::new(Tag::Sequence.value_error().to_error()));
6214 }
6215 // Positioned at the first element of the outer SEQUENCE, which in a
6216 // certificate is the TBSCertificate. The tag is checked even though
6217 // this function does not validate the certificate, because returning
6218 // whatever happens to be first would be a worse kind of not-validating:
6219 // the caller would get bytes, not an error, and verify a signature over
6220 // them.
6221 let inner = Header::peek(&reader).map_err(DerError::new)?;
6222 if inner.tag() != Tag::Sequence {
6223 return Err(DerError::new(
6224 inner.tag().unexpected_error(Some(Tag::Sequence)).to_error(),
6225 ));
6226 }
6227 // `tlv_bytes` returns the header and the value together.
6228 reader.tlv_bytes().map_err(DerError::new)
6229}
6230
6231/// A certificate together with the DER it was decoded from.
6232///
6233/// Hand this to [`validate_path`] instead of a bare [`Certificate`] and
6234/// signature verification uses the bytes the issuer actually signed, taken
6235/// as a subslice, rather than rebuilding them with an encoder. That is both
6236/// faster — re-encoding was measured at 59% of everything path validation
6237/// does — and not subject to the faithfulness assumption described on
6238/// [`tbs_der_slice`].
6239///
6240/// Generic over the byte container so it costs nothing it need not: `&[u8]`
6241/// to borrow a buffer the caller owns, `Vec<u8>` to take ownership, or any
6242/// other `AsRef<[u8]>`.
6243///
6244/// # Examples
6245///
6246/// ```
6247/// # use pkix_path::CertificateWithDer;
6248/// # fn f(der: &[u8]) -> Result<(), Box<dyn core::error::Error>> {
6249/// let held = CertificateWithDer::from_der(der)?;
6250/// assert_eq!(held.certificate().tbs_certificate().version(), Default::default());
6251/// // The signed bytes are a subslice of what was handed in.
6252/// assert!(held.tbs_der().len() < der.len());
6253/// # Ok(())
6254/// # }
6255/// ```
6256#[derive(Clone, Debug)]
6257pub struct CertificateWithDer<T> {
6258 der: T,
6259 cert: Certificate,
6260 /// Offsets of the `TBSCertificate` TLV within `der`, established once
6261 /// in [`CertificateWithDer::from_der`] and never recomputed.
6262 tbs: core::ops::Range<usize>,
6263}
6264
6265impl<T: AsRef<[u8]>> CertificateWithDer<T> {
6266 /// Decodes `der` and remembers where its `TBSCertificate` is.
6267 ///
6268 /// Parsing and slicing happen together, which is the point: a
6269 /// constructor that accepted a `Certificate` and some bytes separately
6270 /// could be handed one certificate's parse beside another's DER, and
6271 /// the signature check would then verify the wrong message against the
6272 /// right key.
6273 ///
6274 /// # Errors
6275 ///
6276 /// Returns [`Error::Der`] if `der` is not a single DER-encoded
6277 /// certificate, trailing bytes included.
6278 pub fn from_der(der: T) -> Result<Self> {
6279 use der::Decode as _;
6280
6281 let bytes = der.as_ref();
6282 let cert = Certificate::from_der(bytes).map_err(|e| Error::Der(DerError::new(e)))?;
6283 let tbs = tbs_der_slice(bytes).map_err(Error::Der)?;
6284 // `tbs` is a subslice of `bytes`, so this arithmetic is exact.
6285 let start = tbs.as_ptr() as usize - bytes.as_ptr() as usize;
6286 Ok(Self {
6287 cert,
6288 tbs: start..start + tbs.len(),
6289 der,
6290 })
6291 }
6292
6293 /// The parsed certificate.
6294 #[must_use]
6295 pub fn certificate(&self) -> &Certificate {
6296 &self.cert
6297 }
6298
6299 /// The whole certificate's DER, as supplied.
6300 #[must_use]
6301 pub fn der(&self) -> &[u8] {
6302 self.der.as_ref()
6303 }
6304
6305 /// The `TBSCertificate` bytes the issuer signed.
6306 #[must_use]
6307 pub fn tbs_der(&self) -> &[u8] {
6308 &self.der.as_ref()[self.tbs.clone()]
6309 }
6310
6311 /// Gives back the container and the parse.
6312 #[must_use]
6313 pub fn into_parts(self) -> (T, Certificate) {
6314 (self.der, self.cert)
6315 }
6316}
6317
6318/// Builds a path element from a certificate's DER.
6319///
6320/// Separate from [`PathCertificate`] because that trait is implemented for
6321/// `&C` as well, and a reference can be read but not constructed. A
6322/// generic that both reads path elements and makes new ones from bytes --
6323/// AIA reassembly, which fetches DER and adds it to a candidate pool --
6324/// needs both bounds.
6325///
6326/// The implementations differ in exactly one respect, which is the whole
6327/// point: [`Certificate`] parses the bytes and drops them,
6328/// [`CertificateWithDer`] parses them and keeps them.
6329///
6330/// # A borrowing container cannot implement this
6331///
6332/// `CertificateWithDer<&[u8]>` can be read as a path element but cannot be
6333/// built from a certificate that has just been fetched, because the
6334/// response buffer does not outlive the call that produced it. That is a
6335/// fact about lifetimes rather than an omission: anything reassembling a
6336/// chain from the network needs an owning container, which is what a
6337/// caller fetching certificates has anyway. [`validate_path`] never
6338/// constructs an element and so never asks for this bound; the entry
6339/// points in `pkix-chain` that may reassemble a chain do.
6340pub trait DecodeCertificate: Sized {
6341 /// Decodes one DER-encoded certificate.
6342 ///
6343 /// # Errors
6344 ///
6345 /// Returns [`Error::Der`] if `der` is not exactly one DER-encoded
6346 /// certificate.
6347 fn decode_certificate(der: Vec<u8>) -> Result<Self>;
6348}
6349
6350impl DecodeCertificate for Certificate {
6351 fn decode_certificate(der: Vec<u8>) -> Result<Self> {
6352 use der::Decode as _;
6353
6354 Certificate::from_der(&der).map_err(|e| Error::Der(DerError::new(e)))
6355 }
6356}
6357
6358impl<T> DecodeCertificate for CertificateWithDer<T>
6359where
6360 T: AsRef<[u8]> + From<Vec<u8>>,
6361{
6362 fn decode_certificate(der: Vec<u8>) -> Result<Self> {
6363 Self::from_der(T::from(der))
6364 }
6365}
6366
6367/// What [`validate_path`] accepts as a certificate in the path.
6368///
6369/// Implemented for [`Certificate`], so a caller holding nothing but parsed
6370/// certificates works unchanged, and for [`CertificateWithDer`], which also
6371/// carries the bytes. The only difference between the two is whether
6372/// [`PathCertificate::signed_tbs`] can answer.
6373pub trait PathCertificate {
6374 /// The certificate itself.
6375 fn certificate(&self) -> &Certificate;
6376
6377 /// The certificate's own DER, when the element kept it.
6378 ///
6379 /// `None` means it did not. This is the one thing an implementation
6380 /// has to decide; [`signed_tbs`](PathCertificate::signed_tbs) is
6381 /// derived from it by default, so the two cannot disagree.
6382 ///
6383 /// What is returned must be the bytes the certificate was decoded
6384 /// from, not a re-encoding of it. Anything that hashes a certificate
6385 /// -- DANE's TLSA matching, a certificate fingerprint, a pinned
6386 /// SPKI -- is comparing against octets someone else produced, and a
6387 /// re-encoding is a different certificate as far as those comparisons
6388 /// are concerned.
6389 fn certificate_der(&self) -> Option<&[u8]> {
6390 None
6391 }
6392
6393 /// The exact `TBSCertificate` bytes the issuer signed, when they are
6394 /// available.
6395 ///
6396 /// `None` means they are not, and [`validate_path`] will rebuild them
6397 /// with [`tbs_certificate_der`] — which works for every certificate
6398 /// seen so far and rests on an assumption that cannot be checked in
6399 /// general. See [`tbs_der_slice`] for what the assumption is.
6400 ///
6401 /// An implementation that returns `Some` must return the bytes from the
6402 /// certificate's own encoding. Returning anything else makes the
6403 /// signature check verify the wrong message.
6404 ///
6405 /// The default locates them inside
6406 /// [`certificate_der`](PathCertificate::certificate_der), which is
6407 /// correct for anything that kept its bytes and costs two header
6408 /// reads per call. An implementation holding the offsets already
6409 /// should override it and hand them over.
6410 fn signed_tbs(&self) -> Option<&[u8]> {
6411 tbs_der_slice(self.certificate_der()?).ok()
6412 }
6413}
6414
6415impl PathCertificate for Certificate {
6416 fn certificate(&self) -> &Certificate {
6417 self
6418 }
6419}
6420
6421impl<T: AsRef<[u8]>> PathCertificate for CertificateWithDer<T> {
6422 fn certificate(&self) -> &Certificate {
6423 &self.cert
6424 }
6425
6426 fn certificate_der(&self) -> Option<&[u8]> {
6427 Some(self.der())
6428 }
6429
6430 fn signed_tbs(&self) -> Option<&[u8]> {
6431 // Overridden: the offsets were established once in `from_der`.
6432 Some(self.tbs_der())
6433 }
6434}
6435
6436impl<C: PathCertificate> PathCertificate for &C {
6437 fn certificate(&self) -> &Certificate {
6438 (*self).certificate()
6439 }
6440
6441 fn certificate_der(&self) -> Option<&[u8]> {
6442 (*self).certificate_der()
6443 }
6444
6445 fn signed_tbs(&self) -> Option<&[u8]> {
6446 (*self).signed_tbs()
6447 }
6448}
6449
6450/// A path element that definitely kept the certificate's own DER.
6451///
6452/// [`PathCertificate::certificate_der`] returns an `Option` because a bare
6453/// [`Certificate`] has nothing to return. This is the half of it that
6454/// cannot be `None`, for callers that *require* the received octets rather
6455/// than merely preferring them.
6456///
6457/// DANE is the case this exists for. TLSA matching compares a hash of the
6458/// certificate against one a domain operator published from their own
6459/// certificate file, so a DANE verifier without the received bytes cannot
6460/// do its job at all -- and re-deriving them from the parse is not a
6461/// degraded answer but a wrong one, for the same reason
6462/// [`tbs_der_slice`] exists. Asking for the bytes in the bound says that
6463/// once, in the signature, instead of as a runtime check every caller has
6464/// to be told about.
6465pub trait RetainedCertificate: PathCertificate {
6466 /// The certificate as it was received, octet for octet.
6467 ///
6468 /// Must equal what [`PathCertificate::certificate_der`] returns.
6469 fn der(&self) -> &[u8];
6470}
6471
6472impl<T: AsRef<[u8]>> RetainedCertificate for CertificateWithDer<T> {
6473 fn der(&self) -> &[u8] {
6474 self.der.as_ref()
6475 }
6476}
6477
6478impl<C: RetainedCertificate> RetainedCertificate for &C {
6479 fn der(&self) -> &[u8] {
6480 (*self).der()
6481 }
6482}
6483
6484/// Rebuilds the DER encoding of `cert`'s `TBSCertificate`: the bytes its
6485/// issuer signed.
6486///
6487/// **Prefer [`tbs_der_slice`] when the certificate's DER is still in
6488/// hand.** This function reconstructs the signed bytes from the parse,
6489/// which is slower and rests on an assumption; the slice takes them from
6490/// the certificate's own encoding and rests on nothing. Reach for this one
6491/// only when the bytes are genuinely gone.
6492///
6493/// Use this, not `cert.tbs_certificate().to_der()`. x509-cert 0.3
6494/// re-encodes the validity times of a `Certificate` under the RFC 5280
6495/// profile (dates before 2050 become `UTCTime`), so a certificate whose
6496/// issuer used `GeneralizedTime` for such a date would no longer match its
6497/// signature. This function keeps each time in the form it was parsed
6498/// from; every other field is re-encoded as DER, which reproduces the
6499/// original bytes for any DER-encoded certificate.
6500///
6501/// That last clause is the assumption. It holds for every certificate this
6502/// workspace has met, and it is not a theorem: it requires the encoder to
6503/// be byte-faithful for every field, for every input the decoder accepted.
6504/// The validity-time special case above is what it looks like when the
6505/// assumption fails, and nothing says where the next one is.
6506/// `tests/tbs_retention.rs` pins the two functions agreeing, so a
6507/// divergence becomes a finding rather than a signature failure on a sound
6508/// certificate.
6509///
6510/// # Errors
6511///
6512/// Returns [`DerError`] if a field cannot be encoded.
6513pub fn tbs_certificate_der(cert: &Certificate) -> core::result::Result<Vec<u8>, DerError> {
6514 encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
6515 .map_err(DerError::new)
6516}
6517
6518/// Encodes `tbs` with `extensions` in place of its own extensions and with
6519/// its validity times as parsed (see [`tbs_certificate_der`]).
6520///
6521/// `pkix-ct` uses the `extensions` override to rebuild a precertificate's
6522/// TBS without the SCT list (RFC 6962 §3.2).
6523#[doc(hidden)]
6524pub fn encode_tbs_certificate(
6525 tbs: &x509_cert::TbsCertificate,
6526 extensions: Option<&x509_cert::ext::Extensions>,
6527) -> der::Result<Vec<u8>> {
6528 use der::asn1::ContextSpecificRef;
6529 use der::{Encode as _, Header, Length, Tag, TagMode, TagNumber};
6530
6531 fn push_sequence(out: &mut Vec<u8>, body: &[u8]) -> der::Result<()> {
6532 Header::new(Tag::Sequence, Length::try_from(body.len())?).encode_to_vec(out)?;
6533 out.extend_from_slice(body);
6534 Ok(())
6535 }
6536
6537 // A capacity hint, not a length: extensions dominate a modern
6538 // certificate's TBS -- a leaf with a large subjectAltName runs to
6539 // kilobytes -- and growing `body` from empty reallocates and copies it
6540 // through every doubling on the way there. Summing the extension
6541 // values is O(number of extensions) and gets the right order of
6542 // magnitude; the 512 covers the names, the SPKI and the fixed fields.
6543 // Being wrong in either direction costs nothing but a reallocation.
6544 let hint = extensions.map_or(0, |exts| {
6545 exts.iter()
6546 .map(|e| e.extn_value.as_bytes().len() + 16)
6547 .sum::<usize>()
6548 }) + 512;
6549 let mut body = Vec::with_capacity(hint);
6550 if tbs.version() != x509_cert::certificate::Version::V1 {
6551 ContextSpecificRef {
6552 tag_number: TagNumber(0),
6553 tag_mode: TagMode::Explicit,
6554 value: &tbs.version(),
6555 }
6556 .encode_to_vec(&mut body)?;
6557 }
6558 tbs.serial_number().encode_to_vec(&mut body)?;
6559 tbs.signature().encode_to_vec(&mut body)?;
6560 tbs.issuer().encode_to_vec(&mut body)?;
6561 let mut validity = Vec::new();
6562 tbs.validity().not_before.encode_to_vec(&mut validity)?;
6563 tbs.validity().not_after.encode_to_vec(&mut validity)?;
6564 push_sequence(&mut body, &validity)?;
6565 tbs.subject().encode_to_vec(&mut body)?;
6566 tbs.subject_public_key_info().encode_to_vec(&mut body)?;
6567 if let Some(id) = tbs.issuer_unique_id() {
6568 ContextSpecificRef {
6569 tag_number: TagNumber(1),
6570 tag_mode: TagMode::Implicit,
6571 value: id,
6572 }
6573 .encode_to_vec(&mut body)?;
6574 }
6575 if let Some(id) = tbs.subject_unique_id() {
6576 ContextSpecificRef {
6577 tag_number: TagNumber(2),
6578 tag_mode: TagMode::Implicit,
6579 value: id,
6580 }
6581 .encode_to_vec(&mut body)?;
6582 }
6583 if let Some(exts) = extensions {
6584 ContextSpecificRef {
6585 tag_number: TagNumber(3),
6586 tag_mode: TagMode::Explicit,
6587 value: exts,
6588 }
6589 .encode_to_vec(&mut body)?;
6590 }
6591 let mut out = Vec::with_capacity(body.len() + 6);
6592 push_sequence(&mut out, &body)?;
6593 Ok(out)
6594}
6595
6596/// The leaf-only project profile: RFC 5280 §6.1 contains none of these,
6597/// and [`ValidationPolicy`] is where each one is turned on.
6598///
6599/// Six checks, in the order their diagnostics are most useful rather
6600/// than the order they were added. (e3) EKU runs before (e4) rfc822 so
6601/// that a certificate wrong in both reports [`Error::MissingEku`],
6602/// which names the thing a caller can act on; the comment on each block
6603/// records the rest.
6604///
6605/// Two of them are about what the CAs above the leaf permit rather than
6606/// about the leaf alone, which is why `permitted_ekus` is a parameter:
6607/// (e2a) refuses a leaf whose stated purposes do not intersect the
6608/// permitted set, and the second half of (e3) refuses a demanded
6609/// purpose that no CA above permits -- a case (e2a) cannot see, because
6610/// a leaf with no EKU extension has nothing to compare.
6611///
6612/// `san` and `cert_cp` arrive already decoded. The caller decodes both
6613/// once per certificate for other steps, and re-finding either here
6614/// would mean a second extension scan and a second chance to disagree
6615/// with the caller about what a malformed one means.
6616///
6617/// Every error reports index 0. This runs on the leaf by construction:
6618/// the caller's `i == 0` guard is the only thing that may call it, and
6619/// keeping the guard there is what lets this function have no notion of
6620/// a chain position at all.
6621///
6622/// Extracted from [`chain_walk`] (PKIX-als9.10). Pure -- it reads the
6623/// certificate and the policy and returns, touching no
6624/// [`WorkingState`].
6625fn enforce_leaf_profile(
6626 cert: &Certificate,
6627 policy: &ValidationPolicy,
6628 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
6629 cert_cp: Option<&x509_cert::ext::pkix::certpolicy::CertificatePolicies>,
6630 permitted_ekus: Option<&(Vec<der::asn1::ObjectIdentifier>, usize)>,
6631) -> Result<()> {
6632 // (e2) Require non-empty SubjectAltName on leaf cert.
6633 // Only when require_subject_alt_name is set; intermediate CA certs
6634 // are NOT checked: the caller runs this on the leaf only. `san` is
6635 // decoded by the caller — no second extension scan needed.
6636 if policy.require_subject_alt_name {
6637 // san is None if the extension is absent; Some(v) where v.0 may be empty.
6638 let san_is_nonempty = san.is_some_and(|s| !s.0.is_empty());
6639 if !san_is_nonempty {
6640 return Err(Error::MissingSan);
6641 }
6642 }
6643
6644 // (e2a) The leaf against what the CAs above it permit. A leaf
6645 // with no EKU extension claims no purpose, so there is
6646 // nothing to contradict and this check passes it; a purpose
6647 // the caller demands is handled by (e3) below, which is
6648 // also checked against the permitted set.
6649 //
6650 // Intersection rather than containment: a leaf listing
6651 // serverAuth and clientAuth under a serverAuth-only
6652 // intermediate is accepted. The extra claim is unusable,
6653 // not a reason to refuse a chain that works for the purpose
6654 // it is being used for, and that shape is common in the
6655 // real WebPKI.
6656 if policy.enforce_ca_eku
6657 && let Some((permitted, ca_index)) = permitted_ekus
6658 {
6659 use x509_cert::ext::pkix::ExtendedKeyUsage;
6660 if let Some(eku) = try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
6661 .map_err(|_| Error::MalformedCertificate { index: 0 })?
6662 {
6663 let claims_any = eku.0.contains(&OID_ANY_EXTENDED_KEY_USAGE);
6664 if !claims_any && !eku.0.iter().any(|o| permitted.iter().any(|p| p == o)) {
6665 return Err(Error::EkuNotPermittedByIssuer { index: *ca_index });
6666 }
6667 }
6668 }
6669
6670 // (e3) Required leaf EKU OID check.
6671 // Only when required_leaf_eku is Some.
6672 // Uses try_find_cert_ext (fail-closed): malformed EKU DER on the leaf
6673 // is mapped to MalformedCertificate rather than silently ignored.
6674 // anyExtendedKeyUsage (OID 2.5.29.37.0) does NOT satisfy a specific
6675 // OID requirement — only explicit listing in the cert's EKU counts.
6676 if let Some(required_ekus) = &policy.required_leaf_eku {
6677 use x509_cert::ext::pkix::ExtendedKeyUsage;
6678 match try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
6679 .map_err(|_| Error::MalformedCertificate { index: 0 })?
6680 {
6681 None => {
6682 // EKU extension absent; any non-empty requirement fails.
6683 if !required_ekus.is_empty() {
6684 return Err(Error::MissingEku);
6685 }
6686 }
6687 Some(eku) => {
6688 for req_oid in required_ekus {
6689 if !eku.0.iter().any(|e| e == req_oid) {
6690 return Err(Error::MissingEku);
6691 }
6692 }
6693 }
6694 }
6695
6696 // The leaf may list the demanded purpose while a CA above
6697 // it forbids that purpose; the leaf's own EKU cannot show
6698 // that. Catches a chain whose leaf has no EKU at all too,
6699 // where (e2a) has nothing to compare.
6700 if policy.enforce_ca_eku
6701 && let Some((permitted, ca_index)) = permitted_ekus
6702 {
6703 for req_oid in required_ekus {
6704 if !permitted.iter().any(|p| p == req_oid) {
6705 return Err(Error::EkuNotPermittedByIssuer { index: *ca_index });
6706 }
6707 }
6708 }
6709 }
6710
6711 // (e3a) Required leaf CertificatePolicies OID check.
6712 // Only when required_leaf_policy_oids is Some.
6713 // Reuses the caller's decoded `cert_cp`. `anyPolicy`
6714 // (2.5.29.32.0) does NOT satisfy a specific OID requirement —
6715 // only explicit listing in the cert's CertificatePolicies counts.
6716 // Mirrors the (e3) EKU pattern.
6717 if let Some(required_policy_oids) = &policy.required_leaf_policy_oids {
6718 match cert_cp {
6719 None => {
6720 // CertificatePolicies extension absent; any non-empty
6721 // requirement fails.
6722 if let Some(first) = required_policy_oids.first() {
6723 return Err(Error::MissingLeafPolicyOid { required: *first });
6724 }
6725 }
6726 Some(cp_ext) => {
6727 for req_oid in required_policy_oids {
6728 if !cp_ext.0.iter().any(|pi| pi.policy_identifier == *req_oid) {
6729 return Err(Error::MissingLeafPolicyOid { required: *req_oid });
6730 }
6731 }
6732 }
6733 }
6734 }
6735
6736 // (e3b) Required Subject DN attribute rule check.
6737 // Only when required_leaf_subject_dn_attrs is Some. See
6738 // [`DnAttrRule`] for the expression grammar
6739 // and vacuity rules.
6740 if let Some(dn_rule) = &policy.required_leaf_subject_dn_attrs
6741 && !evaluate_dn_attr_rule(cert.tbs_certificate().subject(), dn_rule)
6742 {
6743 return Err(Error::SubjectDnAttrRuleUnmet);
6744 }
6745
6746 // (e4) If require_rfc822_san is set, at least one rfc822Name entry must
6747 // be present in the leaf's SAN extension.
6748 // Only meaningful (and checked) when require_subject_alt_name is also
6749 // true; the non-empty SAN check above (e2) already guards the absent
6750 // / empty SAN case. EKU is checked first (e3) so that a cert with both
6751 // wrong EKU and wrong SAN type reports MissingEku (more actionable).
6752 if policy.require_subject_alt_name && policy.require_rfc822_san {
6753 use x509_cert::ext::pkix::name::GeneralName;
6754 let has_rfc822 = san.is_some_and(|s| {
6755 s.0.iter()
6756 .any(|name| matches!(name, GeneralName::Rfc822Name(_)))
6757 });
6758 if !has_rfc822 {
6759 return Err(Error::MissingRfc822San);
6760 }
6761 }
6762
6763 Ok(())
6764}
6765
6766/// The checks every certificate above the leaf has to pass: RFC 5280
6767/// §6.1.4(k) `cA`, §6.1.4(n) `keyCertSign`, §6.1.4(m) and §4.2.1.9
6768/// `pathLenConstraint`, plus three project additions.
6769///
6770/// The three that are not §6.1 steps, each with its own reason:
6771///
6772/// * **EKU nesting.** A CA restricted to some purposes cannot issue for
6773/// others. See [`ValidationPolicy::enforce_ca_eku`]. This is the one
6774/// part that carries state down the chain, which is why
6775/// `permitted_ekus` is `&mut`: the walk descends from the anchor, so
6776/// each certificate narrows what everything below it may claim.
6777/// * **An unnamed CA.** §6.1.3(a)(4) chains on DN equality and an empty
6778/// DN equals an empty DN, so an unnamed CA would chain to anything
6779/// another unnamed CA issued. RFC 5280 §4.1.2.6.
6780/// * **`cRLSign`.** Opt-in via
6781/// [`ValidationPolicy::require_crl_sign_on_cas`], motivated by PKITS
6782/// §4.7.4 and §4.7.5.
6783///
6784/// `intermediates_below` is the caller's `chain[1..index]` -- the
6785/// certificates between the leaf and this one -- so the
6786/// `pathLenConstraint` count needs no position arithmetic here. Passing
6787/// the slice rather than the whole chain and an index also means this
6788/// function cannot get the window wrong.
6789///
6790/// Every check is fail-closed on a malformed extension: a structurally
6791/// present but DER-malformed `BasicConstraints`, `ExtendedKeyUsage` or
6792/// `KeyUsage` returns [`Error::MalformedCertificate`] rather than being
6793/// read as absent, which would fall through to a weaker error and hide
6794/// the real problem.
6795///
6796/// Extracted from [`chain_walk`] (PKIX-als9.11).
6797fn check_intermediate_basic_constraints<C: PathCertificate>(
6798 cert: &Certificate,
6799 policy: &ValidationPolicy,
6800 intermediates_below: &[C],
6801 permitted_ekus: &mut Option<(Vec<der::asn1::ObjectIdentifier>, usize)>,
6802 index: usize,
6803) -> Result<()> {
6804 // (f) BasicConstraints cA=TRUE required; (h) pathLenConstraint.
6805 // Decode BasicConstraints once for both checks.
6806 //
6807 // Fail-closed: if the extension is structurally present but DER-malformed
6808 // on an intermediate CA, propagate MalformedCertificate rather than
6809 // treating it as absent (which would fall through to NotCA and hide the
6810 // real structural problem).
6811 let bc =
6812 try_find_cert_ext::<x509_cert::ext::pkix::BasicConstraints>(cert, OID_BASIC_CONSTRAINTS)
6813 .map_err(|_| Error::MalformedCertificate { index })?;
6814 if !bc.as_ref().is_some_and(|b| b.ca) {
6815 return Err(Error::NotCA { index });
6816 }
6817
6818 // EKU nesting: a CA restricted to some purposes cannot issue
6819 // for others. Not an RFC 5280 §6.1 step -- see
6820 // `ValidationPolicy::enforce_ca_eku` for why it is here and
6821 // on by default. Narrowing happens as the walk descends from
6822 // the anchor, so each certificate sees what everything above
6823 // it permitted.
6824 if policy.enforce_ca_eku {
6825 use x509_cert::ext::pkix::ExtendedKeyUsage;
6826 if let Some(eku) = try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
6827 .map_err(|_| Error::MalformedCertificate { index })?
6828 {
6829 // `anyExtendedKeyUsage` declines to constrain, so it
6830 // narrows nothing.
6831 if !eku.0.contains(&OID_ANY_EXTENDED_KEY_USAGE) {
6832 let narrowed: Vec<_> = match &*permitted_ekus {
6833 // RFC 5280 gives EKU as SEQUENCE SIZE
6834 // (1..MAX), so an empty one is malformed; it
6835 // also permits nothing, and falls out of the
6836 // emptiness check below either way.
6837 None => eku.0.clone(),
6838 Some((prev, _)) => prev
6839 .iter()
6840 .copied()
6841 .filter(|o| eku.0.iter().any(|e| e == o))
6842 .collect(),
6843 };
6844 if narrowed.is_empty() {
6845 return Err(Error::EkuNotPermittedByIssuer { index });
6846 }
6847 *permitted_ekus = Some((narrowed, index));
6848 }
6849 }
6850 }
6851
6852 // A CA has to have a name to be a CA under. Checked here and
6853 // not only on the anchor because a chain may carry its root
6854 // inline, and because an intermediate is reachable the same
6855 // way: §6.1.3(a)(4) chains on DN equality and an empty DN
6856 // matches an empty DN, so an unnamed CA would chain to
6857 // anything another unnamed CA issued. RFC 5280 §4.1.2.6.
6858 if dn_names_nothing(cert.tbs_certificate().subject()) {
6859 return Err(Error::CaEmptySubject { index });
6860 }
6861
6862 // (g) KeyUsage keyCertSign required (when policy demands it).
6863 // RFC 5280 §6.1.4(n): "If a KeyUsage extension is present, verify that the
6864 // keyCertSign bit is set." Only reject when KeyUsage IS present (Some(_)) and
6865 // keyCertSign is NOT set (== Some(false)). Absent KeyUsage (None) is allowed.
6866 // has_key_cert_sign is fail-closed: a malformed critical KeyUsage returns
6867 // MalformedCertificate rather than being silently treated as absent (vjc.15).
6868 if policy.enforce_key_usage
6869 && has_key_cert_sign(cert).map_err(|_| Error::MalformedCertificate { index })?
6870 == Some(false)
6871 {
6872 return Err(Error::KeyUsageMissing { index });
6873 }
6874
6875 // (g') KeyUsage cRLSign required (opt-in via require_crl_sign_on_cas).
6876 // RFC 5280 §6.1 does NOT require this check; it is a stricter policy
6877 // motivated by PKITS §4.7.4 / §4.7.5, which treat a CA cert without
6878 // cRLSign as unable to revoke certs it issued and therefore invalid.
6879 // Same fail-closed and absent-KeyUsage semantics as keyCertSign above.
6880 // Independent of `enforce_key_usage`: callers can opt into cRLSign
6881 // enforcement without also enabling keyCertSign enforcement, and
6882 // vice versa.
6883 if policy.require_crl_sign_on_cas
6884 && has_crl_sign(cert).map_err(|_| Error::MalformedCertificate { index })? == Some(false)
6885 {
6886 return Err(Error::CrlSignMissing { index });
6887 }
6888
6889 // (h) pathLenConstraint: count only non-self-issued intermediates
6890 // (RFC 5280 §4.2.1.9: "non-self-issued intermediate certificates").
6891 // `intermediates_below` is the caller's `chain[1..index]`: the
6892 // positions between the leaf (0) and this certificate.
6893 if let Some(path_len) = bc.and_then(|b| b.path_len_constraint) {
6894 let effective_depth = intermediates_below
6895 .iter()
6896 .map(PathCertificate::certificate)
6897 .filter(|c| !is_self_issued_cert(c))
6898 .count();
6899 if effective_depth > path_len as usize {
6900 return Err(Error::PathTooLong);
6901 }
6902 }
6903
6904 Ok(())
6905}
6906
6907/// Every RFC 5280 §6.1.4 policy state transition for one certificate
6908/// above the leaf, in the order §6.1.4 puts them.
6909///
6910/// The order is the whole reason these five steps are one function
6911/// rather than five. §6.1.4 runs (a) and (b) -- reject `anyPolicy` in a
6912/// mapping, then apply or delete the mappings -- while `policy_mapping`
6913/// still holds the value it had on entry; then (h) decrements all three
6914/// counters; then (i) and (j) clamp them from this certificate's
6915/// `PolicyConstraints` and `InhibitAnyPolicy`. Mapping before
6916/// decrementing is what makes `inhibitPolicyMapping: 0` on a
6917/// certificate stop mappings *below* it rather than its own, and three
6918/// separate functions would leave that ordering as a fact about
6919/// `chain_walk`'s body instead of a fact about policy processing.
6920///
6921/// `cert_cp` is this certificate's already-decoded
6922/// `certificatePolicies`, needed by (b)(1): a synthesised node takes
6923/// the qualifiers of the certificate's `anyPolicy` entry. The caller
6924/// has it decoded for §6.1.3(d)/(e) already.
6925///
6926/// Each of the three extensions is read fail-closed. A malformed
6927/// `PolicyMappings` silently dropped would be a policy bypass -- a
6928/// mapping that should have been applied, or an `inhibitPolicyMapping`
6929/// that should have clamped, simply not happening -- so all three map a
6930/// decode failure to [`Error::MalformedCertificate`].
6931///
6932/// Extracted from [`chain_walk`] (PKIX-als9.12, which absorbed the
6933/// counter steps: see the ordering argument above).
6934fn apply_policy_state_transitions(
6935 cert: &Certificate,
6936 cert_cp: Option<&x509_cert::ext::pkix::certpolicy::CertificatePolicies>,
6937 state: &mut WorkingState<'_>,
6938 index: usize,
6939) -> Result<()> {
6940 use x509_cert::ext::pkix::{InhibitAnyPolicy, PolicyConstraints, PolicyMappings};
6941
6942 // (policy-a) PolicyMappings (RFC 5280 §6.1.4(a)): anyPolicy must
6943 // not appear on either side of a mapping.
6944 // (policy-b) Apply mappings to the tree or delete mapped nodes.
6945 // NOTE: Policy mappings use the current policy_mapping counter value
6946 // (before decrement); the decrement happens in §6.1.4(h) below.
6947 // try_find_cert_ext (fail-closed): a malformed PolicyMappings extension
6948 // must cause rejection rather than silent ignore; a silently-discarded
6949 // mapping could allow a policy bypass (e.g., inhibit_policy_mapping bypass).
6950 if let Some(pm) = try_find_cert_ext::<PolicyMappings>(cert, OID_POLICY_MAPPINGS)
6951 .map_err(|_| Error::MalformedCertificate { index })?
6952 {
6953 // §6.1.4(a): reject anyPolicy as issuer or subject domain.
6954 for mapping in &pm.0 {
6955 if mapping.issuer_domain_policy == OID_ANY_POLICY
6956 || mapping.subject_domain_policy == OID_ANY_POLICY
6957 {
6958 return Err(Error::PolicyViolation { index });
6959 }
6960 }
6961
6962 // §6.1.4(b)(1) if policy_mapping > 0, else §6.1.4(b)(2).
6963 if let Some(graph) = &mut state.policy_tree {
6964 // §6.1.4(b)(1) synthesized nodes take the qualifiers of
6965 // this certificate's anyPolicy entry (none if it has no
6966 // certificatePolicies, in which case the graph is
6967 // already NULL and this branch is not reached).
6968 let ap_q = cert_cp
6969 .map(policy_graph::any_policy_qualifiers)
6970 .unwrap_or_default();
6971 if graph.apply_policy_mappings(&pm, state.policy_mapping > 0, &ap_q) {
6972 state.policy_tree = None;
6973 }
6974 }
6975 }
6976
6977 // (policy-h) RFC 5280 §6.1.4(h): decrement policy counters for
6978 // non-self-issued intermediate certificates.
6979 // This happens AFTER policy mappings processing (§6.1.4(b)) and
6980 // BEFORE clamping from extensions (§6.1.4(i)/(j)).
6981 if !is_self_issued_cert(cert) {
6982 state.explicit_policy = state.explicit_policy.saturating_sub(1);
6983 state.policy_mapping = state.policy_mapping.saturating_sub(1);
6984 state.inhibit_any = state.inhibit_any.saturating_sub(1);
6985 }
6986
6987 // (policy-i) PolicyConstraints (RFC 5280 §6.1.4(c)): clamp
6988 // explicit_policy and policy_mapping from the extension.
6989 // try_find_cert_ext (fail-closed): malformed PolicyConstraints must reject;
6990 // silently ignoring it could allow explicit_policy bypass.
6991 if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(cert, OID_POLICY_CONSTRAINTS)
6992 .map_err(|_| Error::MalformedCertificate { index })?
6993 {
6994 if let Some(req) = pc.require_explicit_policy {
6995 state.explicit_policy = state.explicit_policy.min(req);
6996 }
6997 if let Some(ipm) = pc.inhibit_policy_mapping {
6998 state.policy_mapping = state.policy_mapping.min(ipm);
6999 }
7000 }
7001
7002 // (policy-j) InhibitAnyPolicy (RFC 5280 §6.1.4(d)): clamp inhibit_any.
7003 // try_find_cert_ext (fail-closed): malformed InhibitAnyPolicy must reject;
7004 // silently ignoring it could allow anyPolicy through when it should be inhibited.
7005 if let Some(iap) = try_find_cert_ext::<InhibitAnyPolicy>(cert, OID_INHIBIT_ANY_POLICY)
7006 .map_err(|_| Error::MalformedCertificate { index })?
7007 {
7008 state.inhibit_any = state.inhibit_any.min(iap.0);
7009 }
7010
7011 Ok(())
7012}
7013
7014/// RFC 5280 §6.1.4(g): fold this certificate's `nameConstraints` into
7015/// the running state -- intersection for `permittedSubtrees`, union for
7016/// `excludedSubtrees`.
7017///
7018/// The asymmetry is the rule: a CA may only narrow what its issuer
7019/// permitted, and may always forbid more. So permitted sets intersect
7020/// (and an intersection can empty) while excluded sets accumulate.
7021///
7022/// `state.nc_constrained_types` is the part that is not in the RFC and
7023/// cannot be derived from the other two. Once any CA has imposed a
7024/// `permittedSubtrees` entry of some name type, that type stays
7025/// constrained even if a later intersection leaves zero entries of it
7026/// -- and zero entries is how "permit nothing of this type" is
7027/// represented. Reading "is this type constrained?" off
7028/// `nc_permitted`'s contents instead would turn two incompatible DN
7029/// constraints, whose intersection is empty and therefore forbids every
7030/// DN, into no DN constraint at all. The bits are only ever `ORed` in.
7031/// `chain_walk`'s initialisation site carries the long form.
7032///
7033/// `cert_name_constraints` is fail-closed: a malformed or
7034/// non-conformant extension -- a non-zero `minimum` or any `maximum`,
7035/// or a present-but-empty `GeneralSubtrees` -- returns
7036/// [`Error::MalformedCertificate`] rather than being read as no
7037/// constraint. Reading it as no constraint is how "permit nothing"
7038/// became "permit everything" on a critical extension once already;
7039/// see `PKIX-mg8u`.
7040///
7041/// Extracted from [`chain_walk`] (PKIX-als9.14).
7042fn update_name_constraints_state(
7043 cert: &Certificate,
7044 state: &mut WorkingState<'_>,
7045 index: usize,
7046) -> Result<()> {
7047 // (i) NC update: NameConstraints state update (RFC 5280 §6.1.4(b)).
7048 // INTERSECTION for permitted, UNION for excluded.
7049 // cert_name_constraints is fail-closed: a malformed or non-conformant
7050 // NC extension (e.g., non-zero minimum/maximum) returns MalformedCertificate
7051 // rather than silently ignoring the constraints (vjc.7, vjc.8).
7052 if let Some(nc) = cert_name_constraints(cert, index)? {
7053 // permittedSubtrees: intersect with current state.
7054 if let Some(new_permitted) = nc.permitted_subtrees {
7055 // Track which types this CA is constraining.
7056 for entry in &new_permitted {
7057 state.nc_constrained_types |= name_type_bit(&entry.base);
7058 }
7059 match state.nc_permitted.as_mut() {
7060 None => {
7061 // First constraint seen; adopt it directly.
7062 state.nc_permitted = Some(new_permitted);
7063 }
7064 Some(current) => {
7065 // Type-aware intersection of two permitted-subtrees sets.
7066 //
7067 // RFC 5280 §6.1.4(b): intersect entry-by-entry, but only
7068 // compare entries of the SAME name type. Entries of types
7069 // not present in new_permitted are unchanged (new doesn't
7070 // constrain that type). Entries of types not in current
7071 // are added directly (new adds a fresh constraint).
7072 //
7073 // For entries of matching type, keep:
7074 // 1. new entries within (⊆) some same-type current entry.
7075 // 2. current entries within (⊆) some same-type new entry.
7076 // Containment is decided by `subtree_within`, which
7077 // compares two constraints (address+mask, bare host,
7078 // `.domain`) rather than treating one as a cert name.
7079 // (If neither is within the other the intersection for that
7080 // type is empty — tracked via nc_constrained_types.)
7081 let mut result = GeneralSubtrees::default();
7082
7083 // For each new entry, pre-filter current entries of the
7084 // same type to avoid calling same_nc_variant twice per
7085 // pair (vjc.16: duplicated guard + containment check).
7086 for n in &new_permitted {
7087 let same_type_in_current: GeneralSubtrees = current
7088 .iter()
7089 .filter(|c| same_nc_variant(&c.base, &n.base))
7090 .cloned()
7091 .collect();
7092 if same_type_in_current.is_empty() {
7093 // Type not previously constrained → add directly.
7094 result.push(n.clone());
7095 } else if same_type_in_current
7096 .iter()
7097 .any(|c| subtree_within(&n.base, &c.base))
7098 {
7099 // n is within some same-type current entry → keep.
7100 result.push(n.clone());
7101 }
7102 // else: n is not within any current entry of same type → drop.
7103 }
7104
7105 for c in current.iter() {
7106 let same_type_in_new: GeneralSubtrees = new_permitted
7107 .iter()
7108 .filter(|n| same_nc_variant(&n.base, &c.base))
7109 .cloned()
7110 .collect();
7111 if same_type_in_new.is_empty() {
7112 // Type not in new_permitted → keep unchanged.
7113 result.push(c.clone());
7114 } else if same_type_in_new
7115 .iter()
7116 .any(|n| subtree_within(&c.base, &n.base))
7117 {
7118 // c is more specific than some new entry; keep unless
7119 // an equivalent entry is already in result (dedup
7120 // within the result set for this type).
7121 let same_type_in_result: &[_] = result.as_slice();
7122 let already_in_result = same_type_in_result.iter().any(|e| {
7123 same_nc_variant(&e.base, &c.base)
7124 && subtree_within(&e.base, &c.base)
7125 && subtree_within(&c.base, &e.base)
7126 });
7127 if !already_in_result {
7128 result.push(c.clone());
7129 }
7130 }
7131 // else: c is not within any new entry of same type → drop.
7132 }
7133
7134 *current = result;
7135 }
7136 }
7137 }
7138 // excludedSubtrees: union — append only entries not already present,
7139 // avoiding monotonic growth that would make per-cert NC checks O(chain²)
7140 // when the same excluded subtrees are repeated across multiple CAs (vjc.12).
7141 if let Some(new_excluded) = nc.excluded_subtrees {
7142 for new_entry in &new_excluded {
7143 // Deduplication uses subtree_within as a two-way equality
7144 // check: two entries are considered the same subtree when each
7145 // contains the other (i.e., they are semantically equivalent, not
7146 // just byte-equal).
7147 let already_present = state.nc_excluded.iter().any(|existing| {
7148 same_nc_variant(&existing.base, &new_entry.base)
7149 && subtree_within(&existing.base, &new_entry.base)
7150 && subtree_within(&new_entry.base, &existing.base)
7151 });
7152 if !already_present {
7153 state.nc_excluded.push(new_entry.clone());
7154 }
7155 }
7156 }
7157 }
7158
7159 Ok(())
7160}
7161
7162/// RFC 5280 §6.1.3(d), (e) and (f): fold this certificate's
7163/// `certificatePolicies` into the policy graph, then fail the path if
7164/// the graph has gone `NULL` while an explicit policy is required.
7165///
7166/// The three steps are one function because (f) is the consequence of
7167/// (d) and (e) and nothing else may run between them. §6.1.3(d) grows
7168/// or prunes the graph from the certificate's policies, §6.1.3(e) sets
7169/// it to `NULL` when the extension is absent, and §6.1.3(f) then
7170/// rejects the path if `explicit_policy` has reached 0 with no graph
7171/// left. A certificate that empties the graph at depth 3 under
7172/// `requireExplicitPolicy` has to fail at depth 3, not at §6.1.5.
7173///
7174/// `may_expand` is §6.1.3(d)(2)'s condition for letting an `anyPolicy`
7175/// entry expand into new nodes: `inhibit_anyPolicy` still positive, or
7176/// a self-issued certificate that is not the leaf. `is_leaf` carries
7177/// the second half, which is why the caller passes it rather than this
7178/// function deriving a position it does not have.
7179///
7180/// `None` for `cert_cp` is §6.1.3(e) and not an error: a certificate
7181/// with no `certificatePolicies` asserts no policy, so the graph has
7182/// nothing left to stand on. A *malformed* one is a different thing and
7183/// the caller has already refused it -- the decode is fail-closed
7184/// there, because a silently dropped extension would leave the graph in
7185/// a state neither (d) nor (e) describes.
7186///
7187/// Extracted from [`chain_walk`] (PKIX-als9.13).
7188fn update_policy_tree_from_cert(
7189 cert: &Certificate,
7190 cert_cp: Option<&x509_cert::ext::pkix::certpolicy::CertificatePolicies>,
7191 state: &mut WorkingState<'_>,
7192 is_leaf: bool,
7193 index: usize,
7194) -> Result<()> {
7195 // (policy-d) CertificatePolicies extension (RFC 5280 §6.1.3(d)/(e)).
7196 // Only processed while the policy graph is still alive.
7197 if let Some(graph) = &mut state.policy_tree {
7198 let became_null = match cert_cp {
7199 Some(cp_ext) => {
7200 // §6.1.3(d)(2) condition: inhibit_anyPolicy > 0, or a
7201 // self-issued certificate other than the leaf.
7202 // `!is_leaf` is the caller's `i > 0`.
7203 let may_expand = state.inhibit_any > 0 || (!is_leaf && is_self_issued_cert(cert));
7204 graph.add_certificate_policies(cp_ext, may_expand)
7205 }
7206 // §6.1.3(e): CertificatePolicies absent → NULL.
7207 None => true,
7208 };
7209 if became_null {
7210 state.policy_tree = None;
7211 }
7212 }
7213
7214 // (policy-f) RFC 5280 §6.1.3(f): explicit_policy == 0 and tree NULL
7215 // → policy violation.
7216 if state.explicit_policy == 0 && state.policy_tree.is_none() {
7217 return Err(Error::PolicyViolation { index });
7218 }
7219
7220 Ok(())
7221}
7222
7223/// RFC 5280 §6.1.5: the wrap-up, after every certificate has been
7224/// through §6.1.3 and §6.1.4.
7225///
7226/// Four steps, and the order between them is the point:
7227///
7228/// * **(a)** decrement `explicit_policy` for a leaf that is not
7229/// self-issued. The RFC decrements `inhibit_anyPolicy` and
7230/// `policy_mapping` here too; nothing reads either again, and the
7231/// comment at the site says so rather than carrying two dead
7232/// subtractions.
7233/// * **(b)** clamp `explicit_policy` from the leaf's own
7234/// `PolicyConstraints`, so a leaf stating `requireExplicitPolicy: 0`
7235/// demands a policy of itself.
7236/// * **(g)** intersect the graph with the `user-initial-policy-set`.
7237/// An empty set is this crate's spelling of the §6.1.1 default, and
7238/// a set containing `anyPolicy` is the same thing said explicitly;
7239/// both mean no restriction, so the intersection is skipped rather
7240/// than computed against a set that permits everything.
7241/// * **the final check**, which is the only place a surviving path can
7242/// still fail on policy: valid if `explicit_policy` is positive or
7243/// the graph is non-`NULL`.
7244///
7245/// Returns the graph for [`validate_path`] to surface on
7246/// [`ValidatedPath`]. `None` is not a failure -- it means the graph
7247/// went `NULL` and there is no policy information to report, which the
7248/// final check above has already decided is acceptable. A caller that
7249/// treats `None` as a validation failure is re-running a check that
7250/// passed.
7251///
7252/// Extracted from [`chain_walk`] (PKIX-als9.15).
7253fn finalise_policy_tree_with_user_set(
7254 leaf: &Certificate,
7255 initial_policy_set: &[der::asn1::ObjectIdentifier],
7256 mut state: WorkingState<'_>,
7257) -> Result<Option<policy_graph::PolicyGraph>> {
7258 use x509_cert::ext::pkix::PolicyConstraints;
7259
7260 // RFC 5280 §6.1.5(a-b): post-loop leaf policy finalisation.
7261 //
7262 // §6.1.5 is a post-loop step in the RFC. These operations apply only to
7263 // the leaf certificate (chain[0]), which was the last iteration (i == 0).
7264 // Placing them here rather than inside the loop at i == 0 matches the RFC
7265 // section numbering and makes clear that they happen after all per-cert
7266 // §6.1.3/§6.1.4 steps have completed.
7267 // §6.1.5(a): if the leaf is not self-issued, decrement counters.
7268 // inhibit_any and policy_mapping are decremented per RFC 5280 §6.1.5(a)
7269 // but are not used after this point in the algorithm — only explicit_policy
7270 // is tested in §6.1.5(g) and the final check.
7271 if !is_self_issued_cert(leaf) {
7272 state.explicit_policy = state.explicit_policy.saturating_sub(1);
7273 // Per §6.1.5(a): RFC also decrements inhibit_any and policy_mapping here,
7274 // but neither is read after §6.1.5(a) in our implementation.
7275 }
7276 // §6.1.5(b): if PolicyConstraints requireExplicitPolicy == 0,
7277 // force explicit_policy to 0.
7278 // try_find_cert_ext (fail-closed): consistent with per-loop treatment of
7279 // PolicyConstraints; a malformed extension on the leaf must also reject.
7280 if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(leaf, OID_POLICY_CONSTRAINTS)
7281 .map_err(|_| Error::MalformedCertificate { index: 0 })?
7282 && let Some(req) = pc.require_explicit_policy
7283 {
7284 state.explicit_policy = state.explicit_policy.min(req);
7285 }
7286
7287 // RFC 5280 §6.1.5(g): intersect the valid_policy_graph with the
7288 // user-initial-policy-set.
7289 //
7290 // (g)(i): a NULL graph stays NULL. (g)(ii): an empty set (this crate's
7291 // spelling of the default) or any set containing anyPolicy is
7292 // any-policy, and the intersection is the whole graph. (g)(iii)
7293 // otherwise.
7294 if !initial_policy_set.is_empty()
7295 && !initial_policy_set.contains(&OID_ANY_POLICY)
7296 && let Some(graph) = &mut state.policy_tree
7297 && graph.intersect_user_policy_set(initial_policy_set)
7298 {
7299 state.policy_tree = None;
7300 }
7301
7302 // §6.1.5 final check: path is valid iff explicit_policy > 0 OR tree
7303 // is non-NULL.
7304 if state.explicit_policy == 0 && state.policy_tree.is_none() {
7305 return Err(Error::PolicyViolation { index: 0 });
7306 }
7307
7308 // Return the final valid_policy_tree to `validate_path`.
7309 Ok(state.policy_tree)
7310}
7311
7312/// The trust anchor's own `pathLenConstraint`, which depends only on
7313/// the shape of the chain and so is checked before any per-certificate
7314/// state exists (PKIX-zr0n, Mark's ruling 2026-12-03).
7315///
7316/// Extracted from [`chain_walk`] (PKIX-als9.18).
7317fn check_anchor_path_len<C: PathCertificate>(chain: &[C], anchor: &TrustAnchor) -> Result<()> {
7318 // The anchor's own pathLenConstraint, before any per-certificate
7319 // state exists, because it depends only on the shape of the chain
7320 // (PKIX-zr0n, Mark's ruling 2026-12-03).
7321 //
7322 // RFC 5280 §6.1 never examines the anchor, so this is not a §6.1
7323 // step; RFC 6818 §4 leaves an implementation "free to make use of
7324 // any additional information that is included in a trust anchor
7325 // representation, or to ignore such information", and this is that
7326 // choice exercised, as `TrustAnchor`'s four other retained fields
7327 // already are. OpenSSL enforces it, so leaving it unenforced made
7328 // this crate accept chains `openssl verify` rejects on a limit the
7329 // issuer wrote down.
7330 //
7331 // `chain` is leaf-first and excludes the anchor, so `chain[1..]` is
7332 // every intermediate between the leaf and the anchor -- exactly the
7333 // span the in-path check at step (h) measures as `chain[1..i]` for a
7334 // certificate at position `i`. The anchor sits at `chain.len()`.
7335 //
7336 // Self-issued certificates do not count, per §6.1.4(l) and
7337 // §4.2.1.9's "non-self-issued intermediate certificates", so a
7338 // key-rollover certificate under a `pathLen 0` root is still
7339 // permitted. The same predicate the in-path check uses decides it.
7340 if let Some(path_len) = anchor.path_len_constraint {
7341 let intermediates = chain
7342 .get(1..)
7343 .unwrap_or(&[])
7344 .iter()
7345 .map(PathCertificate::certificate)
7346 .filter(|c| !is_self_issued_cert(c))
7347 .count();
7348 if intermediates > path_len as usize {
7349 return Err(Error::PathTooLong);
7350 }
7351 }
7352
7353 Ok(())
7354}
7355
7356/// The RFC 5280 §6.1.2 initialisation: every working variable the walk
7357/// mutates, set from the trust anchor and the caller's §6.1.1 inputs.
7358///
7359/// §6.1.2(b) and (c) seed the name-constraint state from the anchor.
7360/// Those constraints apply to **every** certificate in the chain and
7361/// not only to the leaf, which is why they go into the working state
7362/// rather than being checked once at the end.
7363///
7364/// The three counters are §6.1.2's, and `n + 1` is how "never
7365/// activates" is spelled: each counter means "skip this many more
7366/// non-self-issued certificates before the constraint applies", so a
7367/// value above the chain length can only be brought down by a
7368/// certificate that asks for it. The corresponding §6.1.1 input --
7369/// `initial-explicit-policy` and its two siblings -- sets the counter
7370/// to 0 instead, which is the constraint applying from the start.
7371///
7372/// §6.1.2(a)'s initial `valid_policy_tree` is a single `anyPolicy`
7373/// root.
7374///
7375/// Returning the struct rather than filling one in place is what keeps
7376/// the borrow legible: `working_spki` and `working_issuer_name` start
7377/// out borrowed from the anchor, so the state cannot outlive it, and
7378/// the signature says so.
7379///
7380/// Extracted from [`chain_walk`] (PKIX-als9.18).
7381fn initial_working_state<'a, C: PathCertificate>(
7382 chain: &[C],
7383 anchor: &'a TrustAnchor,
7384 policy: &ValidationPolicy,
7385) -> WorkingState<'a> {
7386 // RFC 5280 §6.1.2 (b)+(c): seed the initial permitted/excluded subtrees
7387 // from the trust anchor. These initial constraints apply to ALL certs in
7388 // the chain (including intermediates), not just to leaves — the chain walk
7389 // enforces them from the first certificate onward.
7390 let (initial_nc_permitted, initial_nc_excluded) = match &anchor.name_constraints {
7391 None => (None, GeneralSubtrees::default()),
7392 Some(nc) => (
7393 // Clone necessary: nc_permitted and nc_excluded are mutated during the walk.
7394 nc.permitted_subtrees.clone(),
7395 nc.excluded_subtrees.clone().unwrap_or_default(),
7396 ),
7397 };
7398 // Bitmask of NcTypeMask bits for name types that have been explicitly
7399 // constrained by at least one permittedSubtrees entry in any CA cert seen so far.
7400 // Needed to detect violations when intersection empties the permitted set
7401 // for a type (e.g., two incompatible DN constraints → empty, but DN still forbidden).
7402 //
7403 // INVARIANT: bits are ORed in and never cleared. Once a type bit is set,
7404 // nc_permitted must contain zero entries of that type to represent "empty
7405 // intersection" (all names of that type are forbidden). Do NOT derive
7406 // "is type constrained?" from nc_permitted contents alone — that would
7407 // silently allow names of a type whose permitted set was emptied by
7408 // conflicting CA constraints.
7409 let initial_nc_constrained_types: NcTypeMask =
7410 initial_nc_permitted
7411 .as_ref()
7412 .map_or(NcTypeMask::EMPTY, |permitted| {
7413 let mut bits = NcTypeMask::EMPTY;
7414 for st in permitted {
7415 bits |= name_type_bit(&st.base);
7416 }
7417 bits
7418 });
7419
7420 // RFC 5280 §6.1.2: initialise policy state variables (PKIX-mi3.3).
7421 //
7422 // The counters represent "skip N more non-self-issued certificates before
7423 // the constraint activates". Setting a counter to `n + 1` means the
7424 // constraint never triggers unless a CA certificate forces it lower.
7425 let n = chain.len();
7426 // Convert n (usize) to u32 safely. Chains with >4 billion certs are not
7427 // realistic, but a truncating cast would produce a wrong counter value.
7428 // u32::MAX is safe: counters are only decremented (saturating), so u32::MAX
7429 // behaves identically to any value > the chain length for these semantics.
7430 let n_u32 = u32::try_from(n).unwrap_or(u32::MAX);
7431 let initial_explicit_policy: u32 = if policy.initial_explicit_policy {
7432 0
7433 } else {
7434 n_u32.saturating_add(1)
7435 };
7436 let initial_inhibit_any: u32 = if policy.initial_any_policy_inhibit {
7437 0
7438 } else {
7439 n_u32.saturating_add(1)
7440 };
7441 let initial_policy_mapping: u32 = if policy.initial_policy_mapping_inhibit {
7442 0
7443 } else {
7444 n_u32.saturating_add(1)
7445 };
7446
7447 // Group all per-walk mutable state into a single `WorkingState` for clarity
7448 // at the call boundaries of the per-substep helpers introduced in
7449 // subsequent commits.
7450 WorkingState {
7451 working_spki: &anchor.subject_public_key_info,
7452 working_issuer_name: &anchor.subject,
7453 // RFC 5280 §4.2.1.6: when a CA cert has an empty Subject DN and a critical
7454 // SubjectAltName, the SAN is the cert's identity — the Subject DN is not used
7455 // for name matching. Track whether the current issuer was set from such a cert
7456 // so we can skip the DN linkage check below.
7457 nc_permitted: initial_nc_permitted,
7458 nc_excluded: initial_nc_excluded,
7459 nc_constrained_types: initial_nc_constrained_types,
7460 explicit_policy: initial_explicit_policy,
7461 inhibit_any: initial_inhibit_any,
7462 policy_mapping: initial_policy_mapping,
7463 // §6.1.2(a): initial valid_policy_tree — single anyPolicy root node.
7464 policy_tree: Some(policy_graph::PolicyGraph::new()),
7465 }
7466}
7467
7468/// RFC 5280 §6.1.3(a)(1) — cryptographic signature verification.
7469///
7470/// Asks the pluggable [`SignatureVerifier`] to verify the cert's
7471/// `signature` field over its `TBSCertificate` against the current
7472/// `working_spki` (the previously-validated issuer's public key). Returns
7473/// [`Error::SignatureInvalid`] on failure.
7474///
7475/// `signed_tbs` is the certificate's own bytes when the caller kept them —
7476/// see [`CertificateWithDer`]. They are used as given. When it is `None`
7477/// the bytes are rebuilt with [`encode_tbs_certificate`], which is both the
7478/// slower path and the one that rests on the encoder being byte-faithful
7479/// for every field of every certificate the decoder accepted; see
7480/// [`tbs_der_slice`] for why that is an assumption rather than a fact.
7481/// Rebuilding uses heap-backed encoding (`alloc::vec`) so a large
7482/// certificate — government, enterprise and HSM attestation certificates
7483/// run past 8 KiB of `TBSCertificate` — encodes without a fixed-buffer limit.
7484///
7485/// Does NOT update `working_spki` — that next-iteration state transition is
7486/// the caller's responsibility (`chain_walk` binds it at the end of each loop
7487/// iteration).
7488fn verify_cert_signature<V: SignatureVerifier>(
7489 cert: &Certificate,
7490 signed_tbs: Option<&[u8]>,
7491 working_spki: &spki::SubjectPublicKeyInfoOwned,
7492 verifier: &V,
7493 index: usize,
7494) -> Result<()> {
7495 use spki::der::referenced::OwnedToRef as _;
7496 // Held outside the `match` so the rebuilt buffer outlives the borrow.
7497 let rebuilt;
7498 let tbs_bytes: &[u8] = if let Some(bytes) = signed_tbs {
7499 bytes
7500 } else {
7501 rebuilt =
7502 encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
7503 .map_err(|e| Error::Der(DerError::new(e)))?;
7504 &rebuilt
7505 };
7506 verifier
7507 .verify_signature(
7508 cert.signature_algorithm().owned_to_ref(),
7509 working_spki.owned_to_ref(),
7510 tbs_bytes,
7511 cert.signature().raw_bytes(),
7512 )
7513 .map_err(|e| match e.kind() {
7514 VerificationErrorKind::InvalidSignature => Error::SignatureInvalid { index },
7515 reason => Error::SignatureNotVerified { index, reason },
7516 })?;
7517 Ok(())
7518}
7519
7520/// The RFC 5280 §6.1 path validation algorithm: §6.1.2 initialise,
7521/// then one pass over the chain from the anchor down to the leaf, then
7522/// §6.1.5 wrap up.
7523///
7524/// `chain` is **leaf-first** and excludes the anchor, so the loop runs
7525/// `(0..chain.len()).rev()` -- the certificate the anchor signed first
7526/// and the leaf last, which is the direction §6.1.3 processes and the
7527/// direction the working variables flow.
7528///
7529/// # The steps, in order
7530///
7531/// Per certificate, by §6.1.3 letter where there is one:
7532///
7533/// | step | what | where |
7534/// |---|---|---|
7535/// | — | signature-algorithm allowlist | [`enforce_signature_alg_allowlist`] |
7536/// | (a)(1) | signature verifies under the working key | [`verify_cert_signature`] |
7537/// | (a)(2) | issuer DN equals the working issuer name | [`check_issuer_linkage`] |
7538/// | (a)(3) | within its validity period | [`check_validity`] |
7539/// | — | maximum validity span, minimum RSA size | [`check_max_validity`], [`check_min_rsa_bits`] |
7540/// | §4.2 | no extension appears twice; every critical one is processed | [`check_duplicate_extensions`], [`check_critical_extensions`] |
7541/// | (d)(e)(f) | policy graph update, and failure if it emptied | [`update_policy_tree_from_cert`] |
7542/// | (b)(c) | names against the constraints that preceded this certificate | [`check_name_constraints`] |
7543/// | — | the leaf-only project profile | [`enforce_leaf_profile`] |
7544/// | §6.1.4(k)(m)(n) | `cA`, `pathLenConstraint`, `keyCertSign` | [`check_intermediate_basic_constraints`] |
7545/// | §6.1.4(a)(b)(h)(i)(j) | policy mappings and the three counters | [`apply_policy_state_transitions`] |
7546/// | §6.1.4(g) | fold in this certificate's own name constraints | [`update_name_constraints_state`] |
7547///
7548/// Then §6.1.5(a), (b), (g) and the final policy check, in
7549/// [`finalise_policy_tree_with_user_set`].
7550///
7551/// # What stays here
7552///
7553/// Three things, and each is here because it is about the walk rather
7554/// than about one certificate.
7555///
7556/// * **`permitted_ekus`**, the EKU purposes still issuable and the
7557/// index of the CA that last narrowed them. It is seeded from the
7558/// anchor and narrowed by [`check_intermediate_basic_constraints`] as
7559/// the walk descends.
7560/// * **`nc_in_effect`**, which decides whether the `subjectAltName`
7561/// extension is decoded at all. §6.1.3(b)/(c) check a certificate
7562/// against the constraints that *preceded* it, and §6.1.4(g) then
7563/// adds its own -- a CA does not constrain its own names -- so this
7564/// has to be read before the update and not after.
7565/// * **the working variables**, rebound at the end of each iteration to
7566/// the certificate just validated.
7567///
7568/// # Why it is a sequence of calls
7569///
7570/// It was 315 lines of one function (`clippy::too_many_lines` counts
7571/// code, not comments) and is now 78. The §6.1 steps are a fixed
7572/// sequence with a state machine threaded through them, so the thing
7573/// worth reading is the sequence -- which is what is left here, where
7574/// the order between steps is visible, and the order is load-bearing in
7575/// at least three places that each helper's own documentation names.
7576/// PKIX-als9.
7577fn chain_walk<V: SignatureVerifier, C: PathCertificate>(
7578 chain: &[C],
7579 anchor: &TrustAnchor,
7580 policy: &ValidationPolicy,
7581 verifier: &V,
7582) -> Result<Option<policy_graph::PolicyGraph>> {
7583 // RFC 5280 §6.1.2 initialisation, extracted; see
7584 // `initial_working_state`.
7585 let mut state = initial_working_state(chain, anchor, policy);
7586
7587 // The anchor's own pathLenConstraint, extracted; see
7588 // `check_anchor_path_len`. Before the walk, because it depends only
7589 // on the shape of the chain.
7590 check_anchor_path_len(chain, anchor)?;
7591
7592 // The EKU purposes still issuable at this point in the walk, and the
7593 // index of the CA that last narrowed them. `None` means unconstrained:
7594 // no CA so far has restricted anything. See
7595 // `ValidationPolicy::enforce_ca_eku`. Kept local rather than put in
7596 // `WorkingState`, which holds RFC 5280 §6.1.2 state, because §6.1.2
7597 // has no EKU variable -- this is the WebPKI profile's rule riding
7598 // along the same walk.
7599 //
7600 // Seeded from the anchor, which is why `TrustAnchor` carries its
7601 // certificate's EKU at all: the anchor is not in `chain`, so a
7602 // purpose-restricted root would otherwise restrict nothing. Its index
7603 // is reported as `chain.len()`, one past the last certificate, since
7604 // it has no position in the chain itself.
7605 let mut permitted_ekus: Option<(Vec<der::asn1::ObjectIdentifier>, usize)> = anchor
7606 .extended_key_usage
7607 .as_ref()
7608 .filter(|_| policy.enforce_ca_eku)
7609 .filter(|ekus| !ekus.contains(&OID_ANY_EXTENDED_KEY_USAGE))
7610 .map(|ekus| (ekus.clone(), chain.len()));
7611 if let Some((ekus, index)) = &permitted_ekus
7612 && ekus.is_empty()
7613 {
7614 return Err(Error::EkuNotPermittedByIssuer { index: *index });
7615 }
7616
7617 for i in (0..chain.len()).rev() {
7618 // One binding for the parsed certificate, which is what every step
7619 // below wants, and one for the path element, which additionally
7620 // knows where its signed bytes are.
7621 let element = &chain[i];
7622 let cert = element.certificate();
7623
7624 // (a0) Signature algorithm allowlist check (extracted to helper for
7625 // readability; see `enforce_signature_alg_allowlist`).
7626 enforce_signature_alg_allowlist(cert, policy, i)?;
7627
7628 // (a) §6.1.3(a)(1) signature verification (extracted; see `verify_cert_signature`).
7629 verify_cert_signature(cert, element.signed_tbs(), state.working_spki, verifier, i)?;
7630
7631 // (b) §6.1.3(a)(2) issuer DN linkage (extracted; see `check_issuer_linkage`).
7632 check_issuer_linkage(cert, state.working_issuer_name, i)?;
7633
7634 // (c) Validity period.
7635 check_validity(cert, policy.current_time_unix, i)?;
7636
7637 // (c2) Max validity period length check (extracted; see `check_max_validity`).
7638 check_max_validity(cert, policy, i)?;
7639
7640 // (c3) Minimum RSA key size check (extracted; see `check_min_rsa_bits`).
7641 check_min_rsa_bits(cert, policy, i)?;
7642
7643 // (d) Duplicate- and critical-extension guards. Duplicates are
7644 // rejected first: every extension lookup below reads only the
7645 // first instance of an OID.
7646 check_duplicate_extensions(cert, i)?;
7647 check_critical_extensions(cert, i)?;
7648 // RFC 9608 §3. Here rather than with revocation because its
7649 // consequence is that the certificate is invalid, and because it
7650 // is the guard that makes §4's revocation skip safe — see
7651 // `check_no_rev_avail_profile`.
7652 check_no_rev_avail_profile(cert, i)?;
7653
7654 // Decode the cert's CertificatePolicies extension once per cert.
7655 // Used in both step (d) (policy tree update) and step (a/b) (PolicyMappings
7656 // anyPolicy qualifier lookup). Decoding here avoids a second parse inside
7657 // the mapping loop (b5r.12).
7658 // try_find_cert_ext (fail-closed): a malformed CertificatePolicies must
7659 // cause rejection rather than being silently treated as absent; silently
7660 // dropping it would leave the policy tree in an incorrect state (vjc.21).
7661 let cert_cp: Option<x509_cert::ext::pkix::certpolicy::CertificatePolicies> =
7662 try_find_cert_ext(cert, OID_CERTIFICATE_POLICIES)
7663 .map_err(|_| Error::MalformedCertificate { index: i })?;
7664
7665 // (policy-d)/(e)/(f) The §6.1.3 policy graph update and its
7666 // immediate consequence, extracted; see
7667 // `update_policy_tree_from_cert`.
7668 update_policy_tree_from_cert(cert, cert_cp.as_ref(), &mut state, i == 0, i)?;
7669
7670 // Is any name constraint in effect at this certificate?
7671 //
7672 // The state holds what every CA above this certificate imposed.
7673 // Constraints this certificate introduces are folded in by step
7674 // (i), after this point, because §6.1.3(b)/(c) check a
7675 // certificate against the constraints that preceded it and
7676 // §6.1.4(g) then adds its own: a CA does not constrain its own
7677 // names.
7678 let nc_in_effect = state.nc_permitted.is_some()
7679 || !state.nc_excluded.is_empty()
7680 || !state.nc_constrained_types.is_empty();
7681
7682 // Decode SAN only when something is going to read it: the NC name
7683 // check below, or the leaf's `require_subject_alt_name`. Nothing
7684 // else in §6.1 consults subjectAltName.
7685 //
7686 // This is worth the conditional rather than being premature. A
7687 // real server leaf carries tens to hundreds of dNSName entries --
7688 // 163 on one in `pkix-bench`'s corpus -- and each decodes into an
7689 // owned, UTF-8-validated `String`. Decoding one such extension was
7690 // measured at 49% of the whole of `validate_path` on a chain that
7691 // then used none of it, because the chain had no name constraints,
7692 // as the overwhelming majority of chains do not.
7693 //
7694 // Fail-closed is preserved where it means something. A malformed
7695 // SAN is still `MalformedCertificate` whenever the extension is
7696 // consulted, which is what vjc.20 is about: a SAN that cannot be
7697 // decoded must never be treated as absent *by a name constraint
7698 // check*, or a certificate could bypass an exclusion. With no
7699 // constraint in effect there is no check to bypass, and this crate
7700 // does not otherwise decode extensions it will not read -- AIA,
7701 // SKI and CRL distribution points are all left alone the same way.
7702 // `malformed_san.rs` pins both halves.
7703 let san = if nc_in_effect || (i == 0 && policy.require_subject_alt_name) {
7704 cert_subject_alt_names(cert, i)?
7705 } else {
7706 None
7707 };
7708
7709 // (e) NameConstraints: check this cert's names against accumulated state.
7710 // RFC 5280 §6.1.3(b): self-issued non-leaf certs are exempt from NC name checking.
7711 // The NC state is still updated from their extensions in step (i).
7712 //
7713 // Guarded on `nc_in_effect` so `san` cannot be read as absent when
7714 // it was merely not decoded: with no constraint in effect every
7715 // branch of `check_name_constraints` is a no-op, so not calling it
7716 // is the same answer reached without the DN comparison
7717 // `is_self_issued_cert` would have performed.
7718 if nc_in_effect && (i == 0 || !is_self_issued_cert(cert)) {
7719 check_name_constraints(
7720 cert,
7721 san.as_ref(),
7722 state.nc_permitted.as_ref(),
7723 &state.nc_excluded,
7724 state.nc_constrained_types,
7725 i,
7726 )?;
7727 }
7728
7729 // (e2)-(e4) The leaf-only project profile, extracted; see
7730 // `enforce_leaf_profile`. The position guard stays here so that
7731 // the function needs no notion of a chain position.
7732 if i == 0 {
7733 enforce_leaf_profile(
7734 cert,
7735 policy,
7736 san.as_ref(),
7737 cert_cp.as_ref(),
7738 permitted_ekus.as_ref(),
7739 )?;
7740 }
7741
7742 // (f–h) CA-only checks: apply to every cert except the leaf (chain[0]).
7743 // This includes any intermediate CAs and the root CA cert if it
7744 // is included in the chain rather than supplied only as an anchor.
7745 if i > 0 {
7746 // (f)-(h) plus the project additions, extracted; see
7747 // `check_intermediate_basic_constraints`.
7748 check_intermediate_basic_constraints(
7749 cert,
7750 policy,
7751 &chain[1..i],
7752 &mut permitted_ekus,
7753 i,
7754 )?;
7755
7756 // (policy-a)/(b)/(h)/(i)/(j) The §6.1.4 policy state
7757 // transitions, extracted; see
7758 // `apply_policy_state_transitions`.
7759 apply_policy_state_transitions(cert, cert_cp.as_ref(), &mut state, i)?;
7760 // (i) The §6.1.4(g) name-constraint state update, extracted;
7761 // see `update_name_constraints_state`.
7762 update_name_constraints_state(cert, &mut state, i)?;
7763 }
7764
7765 // Update state for next iteration.
7766 state.working_spki = cert.tbs_certificate().subject_public_key_info();
7767 state.working_issuer_name = cert.tbs_certificate().subject();
7768 // Determine whether the cert we just processed presents itself via SAN
7769 // identity (empty Subject + critical SAN). This affects the chain-linkage
7770 // check for the certificate immediately below it in the next iteration.
7771 }
7772
7773 // §6.1.5 post-loop finalisation, extracted; see
7774 // `finalise_policy_tree_with_user_set`. It consumes `state`,
7775 // because nothing after §6.1.5 reads the working variables and the
7776 // graph is moved out of it.
7777 finalise_policy_tree_with_user_set(chain[0].certificate(), &policy.initial_policy_set, state)
7778}
7779
7780// ---------------------------------------------------------------------------
7781// NameConstraints enforcement (PKIX-xji)
7782// ---------------------------------------------------------------------------
7783
7784/// Whether a name-constraint check requires a match (permitted) or forbids a
7785/// match (excluded).
7786///
7787/// Using an explicit enum instead of a bare `bool` makes call sites
7788/// self-documenting: `CheckMode::Excluded` / `CheckMode::Permitted` vs
7789/// opaque `false` / `true` (vjc.25).
7790#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7791enum CheckMode {
7792 /// Excluded subtrees: any name that matches is a violation.
7793 Excluded,
7794 /// Permitted subtrees: a constrained name type that matches *no* entry is a violation.
7795 Permitted,
7796}
7797
7798/// Check the cert's subject DN against `subtrees` in the given `mode`.
7799///
7800/// Skipped entirely when the subject DN is empty (RFC 5280 §6.1.3(b)).
7801///
7802/// Avoids constructing a `GeneralName::DirectoryName` (which would require a
7803/// clone) by handling `DirectoryName` constraints inline: pull `DirectoryName`
7804/// entries from `subtrees` and test directly against the subject `Name`
7805/// (vjc.24).
7806///
7807/// - `CheckMode::Excluded`: any DN match is a violation.
7808/// - `CheckMode::Permitted`: only enforced if some CA in the path has
7809/// contributed a `DirectoryName` permitted-subtree (tracked in
7810/// `nc_constrained_types`); then a non-match is a violation.
7811fn check_subject_dn_against_subtrees(
7812 subject: &x509_cert::name::Name,
7813 subject_is_empty: bool,
7814 subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
7815 mode: CheckMode,
7816 nc_constrained_types: NcTypeMask,
7817 index: usize,
7818) -> crate::Result<()> {
7819 use x509_cert::ext::pkix::name::GeneralName;
7820
7821 if subject_is_empty {
7822 return Ok(());
7823 }
7824 let subject_constrained = nc_constrained_types.intersects(NcTypeMask::DIRECTORY_NAME);
7825 let dn_matches_any = subtrees.iter().any(|st| {
7826 if let GeneralName::DirectoryName(constr) = &st.base {
7827 dn_within_subtree(subject, constr)
7828 } else {
7829 false
7830 }
7831 });
7832 match mode {
7833 CheckMode::Excluded => {
7834 if dn_matches_any {
7835 return Err(Error::NameConstraintViolation { index });
7836 }
7837 }
7838 CheckMode::Permitted => {
7839 if subject_constrained && !dn_matches_any {
7840 return Err(Error::NameConstraintViolation { index });
7841 }
7842 }
7843 }
7844 Ok(())
7845}
7846
7847/// Check each SAN entry of the cert against `subtrees` in the given `mode`.
7848///
7849/// - `CheckMode::Excluded`: any SAN entry that matches any subtree is a
7850/// violation.
7851/// - `CheckMode::Permitted`: a SAN entry whose type has been constrained
7852/// somewhere in the path (per `nc_constrained_types`) must match at least
7853/// one subtree entry; unconstrained types are accepted.
7854///
7855/// A `None` SAN extension is a no-op.
7856fn check_san_against_subtrees(
7857 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
7858 subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
7859 mode: CheckMode,
7860 nc_constrained_types: NcTypeMask,
7861 index: usize,
7862) -> crate::Result<()> {
7863 use x509_cert::ext::pkix::constraints::name::GeneralSubtree;
7864 use x509_cert::ext::pkix::name::GeneralName;
7865
7866 let Some(san_ext) = san else {
7867 return Ok(());
7868 };
7869 let type_constrained =
7870 |name: &GeneralName| -> bool { nc_constrained_types.intersects(name_type_bit(name)) };
7871
7872 for name in &san_ext.0 {
7873 match mode {
7874 CheckMode::Excluded => {
7875 // A wildcard dNSName SAN is not the name it stands for,
7876 // so the exclusion is also tested against the names it
7877 // can authenticate. See
7878 // `wildcard_san_reaches_excluded_dns`.
7879 let reaches_excluded = |st: &GeneralSubtree| -> bool {
7880 match (name, &st.base) {
7881 (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
7882 wildcard_san_reaches_excluded_dns(subj.as_str(), constr.as_str())
7883 }
7884 _ => false,
7885 }
7886 };
7887 if subtrees
7888 .iter()
7889 .any(|st| name_matches_subtree(name, st) || reaches_excluded(st))
7890 {
7891 return Err(Error::NameConstraintViolation { index });
7892 }
7893 }
7894 CheckMode::Permitted => {
7895 if type_constrained(name)
7896 && !subtrees.iter().any(|st| name_matches_subtree(name, st))
7897 {
7898 return Err(Error::NameConstraintViolation { index });
7899 }
7900 }
7901 }
7902 }
7903 Ok(())
7904}
7905
7906/// Check that all names in `cert` satisfy the current `NameConstraints` state.
7907///
7908/// Called once per certificate during `chain_walk`, BEFORE updating the NC
7909/// state from that certificate's own `NameConstraints` extension.
7910///
7911/// `san` is the pre-decoded `SubjectAltName` for this cert (pass `None` if the
7912/// extension is absent). Decoding it before the call avoids a second scan of
7913/// the extension list when both NC check and NC update are needed (vjc.13).
7914///
7915/// RFC 5280 §6.1.4(b)(1)–(2): check excluded subtrees first, then
7916/// permitted subtrees.
7917fn check_name_constraints(
7918 cert: &x509_cert::Certificate,
7919 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
7920 nc_permitted: Option<&GeneralSubtrees>,
7921 nc_excluded: &GeneralSubtrees,
7922 nc_constrained_types: NcTypeMask,
7923 index: usize,
7924) -> crate::Result<()> {
7925 let subject = cert.tbs_certificate().subject();
7926 let subject_is_empty = subject.is_empty();
7927 // Computed once: the SAN scan and the shape tests do not depend on
7928 // which mode `check_names` is running in.
7929 let cn_dns = cn_dns_identities(subject, san);
7930
7931 // Dispatch the subject DN and the SAN entries against `subtrees` in the
7932 // requested mode. See `check_subject_dn_against_subtrees` and
7933 // `check_san_against_subtrees` for the per-name-class logic.
7934 let check_names = |subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
7935 mode: CheckMode|
7936 -> crate::Result<()> {
7937 check_subject_dn_against_subtrees(
7938 subject,
7939 subject_is_empty,
7940 subtrees,
7941 mode,
7942 nc_constrained_types,
7943 index,
7944 )?;
7945 check_san_against_subtrees(san, subtrees, mode, nc_constrained_types, index)?;
7946 // A commonName read as a DNS identity is bounded like a dNSName
7947 // SAN. See `cn_dns_identities`.
7948 check_cn_dns_against_subtrees(&cn_dns, subtrees, mode, nc_constrained_types, index)?;
7949 Ok(())
7950 };
7951
7952 // (0) Name forms the generic matchers cannot decide. A form is "in
7953 // effect" when some permitted subtree of that form has been seen in
7954 // the path (`nc_constrained_types`, which survives an emptied
7955 // intersection) or the excluded set holds an entry of that form.
7956 let excluded_forms = nc_excluded
7957 .iter()
7958 .fold(NcTypeMask::EMPTY, |m, st| m | name_type_bit(&st.base));
7959 let forms_in_effect = nc_constrained_types | excluded_forms;
7960 let rfc822_permitted_active = nc_constrained_types.intersects(NcTypeMask::RFC822);
7961 if let Some(san_ext) = san {
7962 for name in &san_ext.0 {
7963 check_san_name_form(
7964 name,
7965 forms_in_effect,
7966 nc_permitted,
7967 nc_excluded,
7968 rfc822_permitted_active,
7969 index,
7970 )?;
7971 }
7972 }
7973
7974 // (1) Excluded check: any excluded subtree match → violation.
7975 check_names(nc_excluded.as_slice(), CheckMode::Excluded)?;
7976
7977 // (2) Permitted check: if permitted set is constrained, every name must
7978 // match at least one permitted subtree.
7979 if let Some(permitted) = nc_permitted {
7980 check_names(permitted.as_slice(), CheckMode::Permitted)?;
7981 }
7982
7983 // (3) RFC 5280 §4.2.1.10: emailAddress attributes in the subject DN MUST
7984 // be checked against the rfc822Name constraint.
7985 // Guard: only enter the RDN walk if RFC822 constraints are actually
7986 // in effect — a permitted RFC822 entry has been seen, OR at least one
7987 // excluded entry is an Rfc822Name (vjc.11).
7988 if forms_in_effect.intersects(NcTypeMask::RFC822) && !subject_is_empty {
7989 for rdn in subject.iter_rdn() {
7990 for ava in rdn.iter() {
7991 if ava.oid != OID_EMAIL_ADDRESS {
7992 continue;
7993 }
7994 // PKCS #9 defines emailAddress as IA5String. Any other
7995 // encoding cannot be checked, so it fails closed instead of
7996 // silently skipping the constraint.
7997 let Ok(email_ia5) = ava.value.decode_as::<der::asn1::Ia5StringRef<'_>>() else {
7998 return Err(Error::NameConstraintViolation { index });
7999 };
8000 check_mailbox_against_rfc822(
8001 email_ia5.as_str(),
8002 nc_permitted,
8003 nc_excluded,
8004 rfc822_permitted_active,
8005 index,
8006 )?;
8007 }
8008 }
8009 }
8010
8011 Ok(())
8012}
8013
8014/// OID for the `SmtpUTF8Mailbox` otherName (RFC 8398 §3), `id-on-SmtpUTF8Mailbox`.
8015const OID_SMTP_UTF8_MAILBOX: der::asn1::ObjectIdentifier =
8016 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.8.9");
8017
8018/// Pre-check one SAN entry whose form the generic subtree matchers cannot
8019/// decide on their own (RFC 5280 §4.2.1.10, RFC 8398 §6).
8020///
8021/// - `otherName(SmtpUTF8Mailbox)`: checked against rfc822Name constraints
8022/// when any are in effect (RFC 8398 §6 extends them to this form). The
8023/// value must be a `UTF8String` and its domain part must be ASCII; a
8024/// U-label domain would need IDNA mapping, which this `no_std` crate
8025/// does not carry, so it fails closed.
8026/// - `otherName` (any type-id, including `SmtpUTF8Mailbox`), `ediPartyName`,
8027/// `registeredID`: `pkix-path` does not process constraints of these
8028/// forms, so the name is rejected when a constraint of the same form is
8029/// in effect ("MUST either process the constraint or reject the
8030/// certificate"). The `otherName` check is per form, not per type-id: an
8031/// otherName constraint of one type-id rejects otherName SANs of every
8032/// type-id.
8033/// - `uniformResourceIdentifier`: when a URI constraint is in effect, a URI
8034/// without an authority, or whose host is an IP address, is rejected
8035/// (see [`uri_host`]).
8036fn check_san_name_form(
8037 name: &x509_cert::ext::pkix::name::GeneralName,
8038 forms_in_effect: NcTypeMask,
8039 nc_permitted: Option<&GeneralSubtrees>,
8040 nc_excluded: &GeneralSubtrees,
8041 rfc822_permitted_active: bool,
8042 index: usize,
8043) -> crate::Result<()> {
8044 use x509_cert::ext::pkix::name::GeneralName;
8045
8046 let violation = Err(Error::NameConstraintViolation { index });
8047 match name {
8048 GeneralName::OtherName(other) => {
8049 if forms_in_effect.intersects(NcTypeMask::OTHER_NAME) {
8050 return violation;
8051 }
8052 if other.type_id == OID_SMTP_UTF8_MAILBOX
8053 && forms_in_effect.intersects(NcTypeMask::RFC822)
8054 {
8055 let Ok(mailbox) = der::asn1::Utf8StringRef::try_from(&other.value) else {
8056 return violation;
8057 };
8058 check_mailbox_against_rfc822(
8059 mailbox.as_str(),
8060 nc_permitted,
8061 nc_excluded,
8062 rfc822_permitted_active,
8063 index,
8064 )?;
8065 }
8066 }
8067 GeneralName::EdiPartyName(_) | GeneralName::RegisteredId(_)
8068 if forms_in_effect.intersects(name_type_bit(name)) =>
8069 {
8070 return violation;
8071 }
8072 GeneralName::UniformResourceIdentifier(uri)
8073 if forms_in_effect.intersects(NcTypeMask::URI) && uri_host(uri.as_str()).is_none() =>
8074 {
8075 return violation;
8076 }
8077 _ => {}
8078 }
8079 Ok(())
8080}
8081
8082/// Check a mailbox that does not arrive as an rfc822Name SAN (a subject
8083/// `emailAddress` attribute or an `SmtpUTF8Mailbox` otherName) against the
8084/// rfc822Name subtrees.
8085///
8086/// Excluded entries always apply; permitted entries apply when
8087/// `rfc822_permitted_active` (some CA in the path permitted rfc822Name
8088/// subtrees). The domain part (after the last `@`) must be ASCII, otherwise
8089/// the mailbox cannot be compared and the check fails closed.
8090fn check_mailbox_against_rfc822(
8091 mailbox: &str,
8092 nc_permitted: Option<&GeneralSubtrees>,
8093 nc_excluded: &GeneralSubtrees,
8094 rfc822_permitted_active: bool,
8095 index: usize,
8096) -> crate::Result<()> {
8097 use x509_cert::ext::pkix::name::GeneralName;
8098
8099 let violation = Err(Error::NameConstraintViolation { index });
8100 match mailbox.rsplit_once('@') {
8101 Some((_, domain)) if domain.is_ascii() => {}
8102 _ => return violation,
8103 }
8104 for st in nc_excluded {
8105 if let GeneralName::Rfc822Name(c) = &st.base
8106 && matches_rfc822_name(mailbox, c.as_str())
8107 {
8108 return violation;
8109 }
8110 }
8111 if rfc822_permitted_active {
8112 let permitted = nc_permitted.map_or(&[][..], |p| p.as_slice());
8113 let ok = permitted.iter().any(|st| match &st.base {
8114 GeneralName::Rfc822Name(c) => matches_rfc822_name(mailbox, c.as_str()),
8115 _ => false,
8116 });
8117 if !ok {
8118 return violation;
8119 }
8120 }
8121 Ok(())
8122}
8123
8124// ---------------------------------------------------------------------------
8125// Send + Sync compile-time assertions
8126// ---------------------------------------------------------------------------
8127//
8128// AGENTS.md non-negotiable #6 requires public result types to be
8129// `Send + Sync` so callers can move values across thread boundaries and
8130// store them in shared caches. The auto-derive does the right thing today
8131// (no `Rc<T>`, `RefCell<T>`, or raw pointers in any of these types), but
8132// the rule is currently aspirational. These `const _:` assertions promote
8133// it to a compile-time invariant — a future field that breaks `Send` or
8134// `Sync` (e.g. someone adds an `Rc<T>` variant to `Error`) fails the
8135// workspace build, not a runtime test. Tracked at PKIX-2l0v.2.
8136
8137// The underscore names are the compile-time-assertion idiom: the inner
8138// function exists to be instantiated, never called by anything that
8139// reads its name. On the whole item, because an attribute on the first
8140// call statement covers only that statement.
8141#[allow(clippy::used_underscore_items)]
8142const _: fn() = || {
8143 fn _assert_send_sync<T: Send + Sync>() {}
8144 _assert_send_sync::<ValidatedPath>();
8145 _assert_send_sync::<Error>();
8146 _assert_send_sync::<TrustAnchor>();
8147 _assert_send_sync::<ValidationPolicy>();
8148};
8149
8150// ---------------------------------------------------------------------------
8151// Tests
8152// ---------------------------------------------------------------------------
8153
8154#[cfg(all(test, feature = "p256"))]
8155mod tests_ecdsa_p256 {
8156 use super::*;
8157 use der::Decode;
8158
8159 /// Test vector: a real P-256/SHA-256 self-signed cert generated by OpenSSL.
8160 /// Oracle: `openssl verify -CAfile ec.pem ec.pem` returns OK.
8161 #[test]
8162 fn verify_p256_self_signed() {
8163 use der::Encode as _;
8164 use spki::der::referenced::OwnedToRef as _;
8165 let der = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
8166 let cert = Certificate::from_der(der).expect("parse cert");
8167
8168 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8169 let sig_bytes = cert.signature().raw_bytes();
8170
8171 // Self-signed cert: signer SPKI is the cert's own SPKI.
8172 let spki_ref = cert
8173 .tbs_certificate()
8174 .subject_public_key_info()
8175 .owned_to_ref();
8176
8177 let verifier = EcdsaP256Verifier;
8178 assert!(
8179 verifier
8180 .verify_signature(
8181 cert.signature_algorithm().owned_to_ref(),
8182 spki_ref,
8183 &tbs_der,
8184 sig_bytes,
8185 )
8186 .is_ok(),
8187 "self-signed P-256 cert should verify"
8188 );
8189 }
8190}
8191
8192#[cfg(all(test, feature = "p384"))]
8193mod tests_ecdsa_p384 {
8194 //! Test vectors for ECDSA P-384 / SHA-384 (PKIX-gphz.2).
8195 //!
8196 //! Oracle: `openssl verify -CAfile ec-p384-sha384.pem ec-p384-sha384.pem`
8197 //! returns OK against the same fixture (the PEM form lives at
8198 //! `tests/fixtures/ec-p384-sha384.der`; regenerate with the recipe in the
8199 //! commit that introduced this file). Independent oracle — pkix-path was
8200 //! not used to compute the expected verdict.
8201 use super::*;
8202 use der::Decode;
8203
8204 const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/ec-p384-sha384.der");
8205
8206 #[test]
8207 fn verify_p384_self_signed() {
8208 use der::Encode as _;
8209 use spki::der::referenced::OwnedToRef as _;
8210 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
8211
8212 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8213 let sig_bytes = cert.signature().raw_bytes();
8214
8215 // Self-signed cert: signer SPKI is the cert's own SPKI.
8216 let spki_ref = cert
8217 .tbs_certificate()
8218 .subject_public_key_info()
8219 .owned_to_ref();
8220
8221 let verifier = EcdsaP384Verifier;
8222 verifier
8223 .verify_signature(
8224 cert.signature_algorithm().owned_to_ref(),
8225 spki_ref,
8226 &tbs_der,
8227 sig_bytes,
8228 )
8229 .expect("self-signed P-384 cert should verify");
8230 }
8231
8232 #[test]
8233 fn tampered_signature_rejected() {
8234 // Flip a bit in the signature and confirm verification fails. This
8235 // exercises the actual cryptographic check, not just the OID and
8236 // SPKI parse paths.
8237 use der::Encode as _;
8238 use spki::der::referenced::OwnedToRef as _;
8239 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
8240
8241 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8242 let mut sig_bytes = cert.signature().raw_bytes().to_vec();
8243 // Tamper a byte well inside the DER signature (any byte after the
8244 // initial SEQUENCE header). The DerSignature decoder rejects most
8245 // structural corruption with try_from, which is also a valid
8246 // verification failure — either way the result must be Err.
8247 let mid = sig_bytes.len() / 2;
8248 sig_bytes[mid] ^= 0x01;
8249
8250 let spki_ref = cert
8251 .tbs_certificate()
8252 .subject_public_key_info()
8253 .owned_to_ref();
8254
8255 let verifier = EcdsaP384Verifier;
8256 assert!(
8257 verifier
8258 .verify_signature(
8259 cert.signature_algorithm().owned_to_ref(),
8260 spki_ref,
8261 &tbs_der,
8262 &sig_bytes,
8263 )
8264 .is_err(),
8265 "tampered signature must not verify"
8266 );
8267 }
8268
8269 #[test]
8270 fn wrong_oid_rejected() {
8271 // The fixture was signed with SHA-384. Relabelling it as
8272 // ecdsa-with-SHA256 makes the verifier hash with SHA-256 (the
8273 // digest comes from the OID, the curve from the key), so the
8274 // signature must not verify.
8275 use der::Encode as _;
8276 use spki::der::referenced::OwnedToRef as _;
8277 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
8278 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8279 let sig_bytes = cert.signature().raw_bytes();
8280 let spki_ref = cert
8281 .tbs_certificate()
8282 .subject_public_key_info()
8283 .owned_to_ref();
8284
8285 let wrong_alg = spki::AlgorithmIdentifierRef {
8286 oid: der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"), // ecdsa-with-SHA256
8287 parameters: None,
8288 };
8289 let verifier = EcdsaP384Verifier;
8290 assert!(
8291 verifier
8292 .verify_signature(wrong_alg, spki_ref, &tbs_der, sig_bytes)
8293 .is_err(),
8294 "a SHA-384 signature must not verify as ecdsa-with-SHA256"
8295 );
8296 }
8297
8298 #[test]
8299 fn default_verifier_dispatches_to_p384() {
8300 // DefaultVerifier's OID dispatch should route ecdsa-with-SHA384 to
8301 // EcdsaP384Verifier when the `p384` feature is active. Confirm the
8302 // same fixture verifies under DefaultVerifier too.
8303 use der::Encode as _;
8304 use spki::der::referenced::OwnedToRef as _;
8305 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
8306 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8307 let sig_bytes = cert.signature().raw_bytes();
8308 let spki_ref = cert
8309 .tbs_certificate()
8310 .subject_public_key_info()
8311 .owned_to_ref();
8312
8313 DefaultVerifier
8314 .verify_signature(
8315 cert.signature_algorithm().owned_to_ref(),
8316 spki_ref,
8317 &tbs_der,
8318 sig_bytes,
8319 )
8320 .expect("DefaultVerifier must dispatch to EcdsaP384Verifier for ecdsa-with-SHA384");
8321 }
8322}
8323
8324#[cfg(all(test, feature = "rsa"))]
8325mod tests_rsa {
8326 use super::*;
8327 use der::Decode;
8328
8329 /// Test vector: a real RSA-2048/SHA-256 self-signed cert generated by OpenSSL.
8330 /// Oracle: `openssl verify -CAfile rsa.pem rsa.pem` returns OK.
8331 #[test]
8332 fn verify_rsa_pkcs1v15_sha256_self_signed() {
8333 use der::Encode as _;
8334 use spki::der::referenced::OwnedToRef as _;
8335 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
8336 let cert = Certificate::from_der(der).expect("parse cert");
8337
8338 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8339 let sig_bytes = cert.signature().raw_bytes();
8340
8341 // Self-signed cert: signer SPKI is the cert's own SPKI.
8342 let spki_ref = cert
8343 .tbs_certificate()
8344 .subject_public_key_info()
8345 .owned_to_ref();
8346
8347 let verifier = RsaPkcs1v15Sha256Verifier;
8348 assert!(
8349 verifier
8350 .verify_signature(
8351 cert.signature_algorithm().owned_to_ref(),
8352 spki_ref,
8353 &tbs_der,
8354 sig_bytes,
8355 )
8356 .is_ok(),
8357 "self-signed RSA cert should verify"
8358 );
8359 }
8360
8361 /// RSA-PKCS1v15 SHA-384 verifier (PKIX-gphz.4).
8362 ///
8363 /// Independent oracle: `openssl verify -CAfile rsa-pkcs1v15-sha384.pem
8364 /// rsa-pkcs1v15-sha384.pem` returns OK against the same fixture
8365 /// (generated by `openssl req -new -x509 -sha384 ...`).
8366 #[test]
8367 fn verify_rsa_pkcs1v15_sha384_self_signed() {
8368 use der::Encode as _;
8369 use spki::der::referenced::OwnedToRef as _;
8370 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
8371 let cert = Certificate::from_der(der).expect("parse cert");
8372 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8373 let sig_bytes = cert.signature().raw_bytes();
8374 let spki_ref = cert
8375 .tbs_certificate()
8376 .subject_public_key_info()
8377 .owned_to_ref();
8378
8379 RsaPkcs1v15Sha384Verifier
8380 .verify_signature(
8381 cert.signature_algorithm().owned_to_ref(),
8382 spki_ref,
8383 &tbs_der,
8384 sig_bytes,
8385 )
8386 .expect("self-signed RSA SHA-384 cert should verify");
8387 }
8388
8389 /// Tamper-rejection for SHA-384 variant.
8390 #[test]
8391 fn rsa_pkcs1v15_sha384_tampered_signature_rejected() {
8392 use der::Encode as _;
8393 use spki::der::referenced::OwnedToRef as _;
8394 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
8395 let cert = Certificate::from_der(der).expect("parse cert");
8396 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8397 let mut sig_bytes = cert.signature().raw_bytes().to_vec();
8398 let mid = sig_bytes.len() / 2;
8399 sig_bytes[mid] ^= 0x01;
8400 let spki_ref = cert
8401 .tbs_certificate()
8402 .subject_public_key_info()
8403 .owned_to_ref();
8404
8405 assert!(
8406 RsaPkcs1v15Sha384Verifier
8407 .verify_signature(
8408 cert.signature_algorithm().owned_to_ref(),
8409 spki_ref,
8410 &tbs_der,
8411 &sig_bytes,
8412 )
8413 .is_err(),
8414 "tampered RSA SHA-384 signature must not verify"
8415 );
8416 }
8417
8418 /// RSA-PKCS1v15 SHA-512 verifier (PKIX-gphz.4).
8419 #[test]
8420 fn verify_rsa_pkcs1v15_sha512_self_signed() {
8421 use der::Encode as _;
8422 use spki::der::referenced::OwnedToRef as _;
8423 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
8424 let cert = Certificate::from_der(der).expect("parse cert");
8425 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8426 let sig_bytes = cert.signature().raw_bytes();
8427 let spki_ref = cert
8428 .tbs_certificate()
8429 .subject_public_key_info()
8430 .owned_to_ref();
8431
8432 RsaPkcs1v15Sha512Verifier
8433 .verify_signature(
8434 cert.signature_algorithm().owned_to_ref(),
8435 spki_ref,
8436 &tbs_der,
8437 sig_bytes,
8438 )
8439 .expect("self-signed RSA SHA-512 cert should verify");
8440 }
8441
8442 /// Tamper-rejection for SHA-512 variant.
8443 #[test]
8444 fn rsa_pkcs1v15_sha512_tampered_signature_rejected() {
8445 use der::Encode as _;
8446 use spki::der::referenced::OwnedToRef as _;
8447 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
8448 let cert = Certificate::from_der(der).expect("parse cert");
8449 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8450 let mut sig_bytes = cert.signature().raw_bytes().to_vec();
8451 let mid = sig_bytes.len() / 2;
8452 sig_bytes[mid] ^= 0x01;
8453 let spki_ref = cert
8454 .tbs_certificate()
8455 .subject_public_key_info()
8456 .owned_to_ref();
8457
8458 assert!(
8459 RsaPkcs1v15Sha512Verifier
8460 .verify_signature(
8461 cert.signature_algorithm().owned_to_ref(),
8462 spki_ref,
8463 &tbs_der,
8464 &sig_bytes,
8465 )
8466 .is_err(),
8467 "tampered RSA SHA-512 signature must not verify"
8468 );
8469 }
8470
8471 /// Wrong-OID rejection: SHA-384 verifier must reject SHA-512 OID and
8472 /// vice versa, and both must reject SHA-256 OID.
8473 #[test]
8474 fn rsa_pkcs1v15_wrong_oid_rejected() {
8475 use der::Encode as _;
8476 use spki::der::referenced::OwnedToRef as _;
8477 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
8478 let cert = Certificate::from_der(der).expect("parse cert");
8479 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8480 let sig_bytes = cert.signature().raw_bytes();
8481 let spki_ref = cert
8482 .tbs_certificate()
8483 .subject_public_key_info()
8484 .owned_to_ref();
8485
8486 // SHA-512 verifier must refuse the SHA-384 OID.
8487 let sha384_alg = cert.signature_algorithm().owned_to_ref();
8488 assert!(
8489 RsaPkcs1v15Sha512Verifier
8490 .verify_signature(sha384_alg, spki_ref.clone(), &tbs_der, sig_bytes)
8491 .is_err()
8492 );
8493 // SHA-256 verifier must refuse the SHA-384 OID.
8494 assert!(
8495 RsaPkcs1v15Sha256Verifier
8496 .verify_signature(sha384_alg, spki_ref, &tbs_der, sig_bytes)
8497 .is_err()
8498 );
8499 }
8500
8501 /// `DefaultVerifier` dispatches the SHA-384 and SHA-512 RSA OIDs.
8502 #[test]
8503 fn default_verifier_dispatches_to_rsa_sha384_and_sha512() {
8504 use der::Encode as _;
8505 use spki::der::referenced::OwnedToRef as _;
8506
8507 for fixture in [
8508 &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der")[..],
8509 &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der")[..],
8510 ] {
8511 let cert = Certificate::from_der(fixture).expect("parse cert");
8512 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
8513 let sig_bytes = cert.signature().raw_bytes();
8514 let spki_ref = cert
8515 .tbs_certificate()
8516 .subject_public_key_info()
8517 .owned_to_ref();
8518 DefaultVerifier
8519 .verify_signature(
8520 cert.signature_algorithm().owned_to_ref(),
8521 spki_ref,
8522 &tbs_der,
8523 sig_bytes,
8524 )
8525 .expect("DefaultVerifier must dispatch RSA SHA-384/512 by OID");
8526 }
8527 }
8528
8529 /// Regression (PKIX-5u0): `spki_key_matches` ignores the NULL-vs-absent
8530 /// parameter encoding difference that exists for RSA SPKIs.
8531 ///
8532 /// RFC 3279 §2.3.1 allows both explicit NULL parameters and absent
8533 /// parameters for `rsaEncryption`. The derived `PartialEq` in the `spki`
8534 /// crate treats `Some(NULL) ≠ None`, so using `==` in the self-issued
8535 /// anchor guard would wrongly reject a valid anchor.
8536 #[test]
8537 fn spki_key_matches_ignores_null_vs_absent_params() {
8538 let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
8539 let cert = Certificate::from_der(der_bytes).expect("parse cert");
8540 let cert_spki = cert.tbs_certificate().subject_public_key_info();
8541
8542 // Same OID and key bytes, but parameters: None instead of Some(NULL).
8543 let spki_no_params: spki::SubjectPublicKeyInfoOwned = spki::SubjectPublicKeyInfoOwned {
8544 algorithm: spki::AlgorithmIdentifier {
8545 oid: cert_spki.algorithm.oid,
8546 parameters: None,
8547 },
8548 subject_public_key: cert_spki.subject_public_key.clone(),
8549 };
8550
8551 // PartialEq distinguishes Some(NULL) from None — document this behavior.
8552 assert_ne!(cert_spki, &spki_no_params);
8553
8554 // spki_key_matches must return true: same OID + same key bytes.
8555 assert!(super::spki_key_matches(cert_spki, &spki_no_params));
8556 }
8557
8558 /// Integration regression (PKIX-5u0): the self-issued anchor guard must not
8559 /// return `NoTrustedPath` when an anchor has absent parameters (None) and the
8560 /// cert in the chain has explicit NULL parameters — both are valid per RFC 3279
8561 /// §2.3.1 for rsaEncryption.
8562 ///
8563 /// The guard compares anchor and cert SPKIs with `spki_key_matches` (OID + key
8564 /// bytes only). Before the fix, using `==` caused `NoTrustedPath` because
8565 /// `Some(NULL) != None` under derived `PartialEq`.
8566 ///
8567 /// Note: the anchor with `parameters: None` will fail signature verification
8568 /// (the `rsa` crate rejects absent params during key parsing), so the result
8569 /// is `Err(SignatureInvalid)`, not `Ok`. What this test verifies is that the
8570 /// guard does NOT skip the anchor and return `NoTrustedPath`. The anchor is
8571 /// tried; the failure is at a later stage, not the guard.
8572 #[test]
8573 fn self_issued_rsa_anchor_absent_params_not_no_trusted_path() {
8574 // 2026-06-01 — within rsa-pkcs1v15-sha256.der validity window
8575 // (notBefore=2026-05-02, notAfter=2036-04-29).
8576 const NOW: u64 = 1_780_272_000;
8577
8578 let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
8579 let cert = Certificate::from_der(der_bytes).expect("parse cert");
8580 let cert_spki = cert.tbs_certificate().subject_public_key_info();
8581
8582 // Construct an anchor from the same cert but with parameters: None.
8583 // Simulates a trust store that was populated from a source omitting the
8584 // explicit NULL — a common DER encoding variation for rsaEncryption.
8585 let anchor = TrustAnchor::new(
8586 cert.tbs_certificate().subject().clone(),
8587 spki::SubjectPublicKeyInfoOwned {
8588 algorithm: spki::AlgorithmIdentifier {
8589 oid: cert_spki.algorithm.oid,
8590 parameters: None,
8591 },
8592 subject_public_key: cert_spki.subject_public_key.clone(),
8593 },
8594 );
8595
8596 let policy = ValidationPolicy {
8597 current_time_unix: NOW,
8598 ..ValidationPolicy::new(0)
8599 };
8600 let result = validate_path(&[cert], &[anchor], &policy, &RsaPkcs1v15Sha256Verifier);
8601 // The guard must not skip the anchor (which would return NoTrustedPath).
8602 // SignatureInvalid is expected: the anchor was tried but the rsa crate
8603 // rejects absent params during key parsing.
8604 assert!(
8605 !matches!(result, Err(Error::NoTrustedPath)),
8606 "guard must not return NoTrustedPath for same key with different param encoding; got: {result:?}"
8607 );
8608 }
8609}
8610
8611// ---------------------------------------------------------------------------
8612// NormalizedIter / names_match unit tests
8613// ---------------------------------------------------------------------------
8614#[cfg(test)]
8615mod tests_normalized_iter {
8616 // `crate::Vec` is the unified alias -- `alloc::vec::Vec` in no_std,
8617 // `std::vec::Vec` under `std`. Not `alloc::vec::Vec` directly:
8618 // `extern crate alloc` is gated to no_std mode in this crate, so
8619 // naming `alloc` fails whenever `std` is on.
8620 use super::{NormalizedIter, any_to_str_bytes, normalized_eq};
8621 use crate::{String, Vec};
8622
8623 /// At most `n` bytes of what `iter` yields.
8624 ///
8625 /// The bound is the point. Every existing test of these two iterators
8626 /// goes through `normalized_eq` or `bmp_string_to_utf8`, which compare
8627 /// or collect the whole stream, so an iterator that never returns
8628 /// `None` hangs the test rather than failing it -- a mutation sweep
8629 /// reports that as a timeout and leaves the test binary spinning. A
8630 /// prefix comparison answers in one step.
8631 fn prefix<I: Iterator<Item = u8>>(iter: I, n: usize) -> Vec<u8> {
8632 iter.take(n).collect()
8633 }
8634
8635 /// The first `n` characters `NormalizedIter` yields for `input`.
8636 ///
8637 /// A `String` rather than bytes since PKIX-zyb: the iterator yields
8638 /// `char` now, because RFC 4518 §2.3 normalization is defined over
8639 /// characters. Bounded for the same reason `prefix` is -- an iterator
8640 /// that never returns `None` must fail the test rather than hang it.
8641 fn normalized(input: &[u8], n: usize) -> String {
8642 NormalizedIter::new(input.iter().copied()).take(n).collect()
8643 }
8644
8645 /// RFC 4518 §2 prep, read off the iterator directly and bounded.
8646 ///
8647 /// The asserted values are shorter than the bound, so an iterator that
8648 /// keeps yielding -- the shape every one of its mutants takes -- fails
8649 /// on length before anything else.
8650 #[test]
8651 fn the_normalizing_iterator_yields_exactly_the_prepared_bytes() {
8652 assert_eq!(normalized(b" Hello World ", 32), "hello world");
8653 assert_eq!(normalized(b"a b", 16), "a b");
8654 assert_eq!(normalized(b"", 8), "");
8655 assert_eq!(normalized(b" ", 8), "", "spaces alone prepare to nothing");
8656 assert_eq!(normalized(b" a", 8), "a", "a leading run is dropped");
8657 assert_eq!(normalized(b"a ", 8), "a", "a trailing run is dropped");
8658 }
8659
8660 // --- RFC 4518 §2.2 Map and §2.3 NFKC (PKIX-zyb) ----------------------
8661
8662 /// §2.3 NFKC: a compatibility-equivalent spelling is the same name.
8663 ///
8664 /// Fullwidth forms are the case that matters in practice -- they are
8665 /// what a CJK input method produces -- and they are also the case that
8666 /// shows why the fold runs after normalization rather than before it.
8667 /// `U+FF21` NFKC-maps to ASCII capital `A`, so an ASCII-only fold
8668 /// applied first would have left it uppercase and unequal.
8669 #[test]
8670 fn nfkc_makes_fullwidth_equal_its_ascii_spelling() {
8671 assert_eq!(normalized("ABC".as_bytes(), 16), "abc");
8672 assert!(normalized_eq("EXAMPLE".as_bytes(), b"example"));
8673 assert!(normalized_eq("Example".as_bytes(), b"EXAMPLE"));
8674 }
8675
8676 /// §2.3 NFKC: a compatibility ligature decomposes.
8677 #[test]
8678 fn nfkc_decomposes_a_ligature() {
8679 // U+FB01 LATIN SMALL LIGATURE FI.
8680 assert_eq!(normalized("office".as_bytes(), 16), "office");
8681 assert!(normalized_eq("file".as_bytes(), b"file"));
8682 }
8683
8684 /// §2.3 NFKC recomposes a decomposed sequence, so the two spellings of
8685 /// an accented letter are one name.
8686 #[test]
8687 fn nfkc_recomposes_a_combining_sequence() {
8688 // "é" as U+00E9, and as U+0065 U+0301.
8689 assert!(normalized_eq("é".as_bytes(), "é".as_bytes()));
8690 assert_eq!(
8691 normalized("é".as_bytes(), 8).chars().count(),
8692 1,
8693 "the decomposed form composes to one scalar"
8694 );
8695 }
8696
8697 /// §2.2 Map: characters that map to nothing are dropped, so a soft
8698 /// hyphen or a zero-width joiner cannot make two names differ.
8699 #[test]
8700 fn map_drops_the_characters_that_map_to_nothing() {
8701 assert!(normalized_eq("Exam\u{00AD}ple".as_bytes(), b"Example"));
8702 assert!(normalized_eq("Exam\u{200B}ple".as_bytes(), b"Example"));
8703 assert!(normalized_eq("Exam\u{FEFF}ple".as_bytes(), b"Example"));
8704 assert!(normalized_eq("Exam\u{FE0F}ple".as_bytes(), b"Example"));
8705 assert_eq!(normalized("a\u{0001}b".as_bytes(), 8), "ab", "a C0 control");
8706 }
8707
8708 /// §2.2 Map: the Unicode space characters become `U+0020` and are then
8709 /// collapsed like any other space. This is what retires the old
8710 /// "only `U+0020` is insignificant whitespace" limitation, which the
8711 /// previous implementation documented as a known gap.
8712 #[test]
8713 fn map_turns_unicode_spaces_into_collapsible_spaces() {
8714 assert!(normalized_eq("a\u{00A0}b".as_bytes(), b"a b"));
8715 assert!(normalized_eq("a\tb".as_bytes(), b"a b"));
8716 assert!(normalized_eq("a\u{3000}b".as_bytes(), b"a b"));
8717 assert_eq!(
8718 normalized("a\u{2000}\u{2001} \tb".as_bytes(), 16),
8719 "a b",
8720 "a mixed run of Unicode spaces collapses to one"
8721 );
8722 assert_eq!(
8723 normalized("\u{00A0}a\u{00A0}".as_bytes(), 8),
8724 "a",
8725 "leading and trailing runs are dropped whatever spells them"
8726 );
8727 }
8728
8729 /// The limit this does NOT reach, pinned so the gap is a statement
8730 /// rather than a surprise. Full Unicode case folding is RFC 4518
8731 /// §2.2's Table B.2 and a separate decision; ASCII-only folding leaves
8732 /// a non-ASCII letter with no ASCII compatibility mapping compared
8733 /// case-sensitively.
8734 #[test]
8735 fn non_ascii_case_is_still_not_folded() {
8736 assert!(
8737 !normalized_eq("Σ".as_bytes(), "σ".as_bytes()),
8738 "RFC 4518 would make these one name; ASCII-only folding does not"
8739 );
8740 }
8741
8742 /// Malformed UTF-8 resynchronises rather than ending the stream or
8743 /// panicking, and the replacement character takes part in no mapping.
8744 #[test]
8745 fn malformed_utf8_becomes_the_replacement_character() {
8746 // Every expectation here is Python's `decode("utf-8", "replace")`,
8747 // used as an independent oracle rather than derived from this
8748 // implementation. Two of the four disagreed with the first draft.
8749 //
8750 // A lone continuation byte, then valid text.
8751 assert_eq!(normalized(&[0x80, b'a', b'b'], 8), "\u{FFFD}ab");
8752 // A truncated three-byte sequence: the `x` survives.
8753 assert_eq!(normalized(&[0xE2, 0x82, b'x'], 8), "\u{FFFD}x");
8754 // An overlong two-byte encoding of U+0041: `C1` is invalid and
8755 // `81` is then a lone continuation, so two.
8756 assert_eq!(normalized(&[0xC1, 0x81], 8), "\u{FFFD}\u{FFFD}");
8757 // A surrogate half. Three, not one: Table 3-7 stops `ED` at
8758 // `80..=9F`, so `ED` is the maximal subpart and `A0` and `80` are
8759 // each a lone continuation. Collapsing these to one `U+FFFD`
8760 // would have made `ED A0 80` and `ED A0 81` compare equal.
8761 assert_eq!(
8762 normalized(&[0xED, 0xA0, 0x80], 8),
8763 "\u{FFFD}\u{FFFD}\u{FFFD}"
8764 );
8765 // A lead claiming five bytes.
8766 assert_eq!(
8767 normalized(&[0xF5, 0x80, 0x80, 0x80], 8),
8768 "\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}"
8769 );
8770 // The property the maximal-subpart rule actually protects: VALID
8771 // text after a malformed prefix survives, so two values differing
8772 // there compare unequal. The first draft of the decoder consumed
8773 // the byte that broke a sequence and failed this.
8774 assert!(!normalized_eq(&[0xE2, 0x82, b'b'], &[0xE2, 0x82, b'c']));
8775
8776 // And the limit of that, asserted rather than left to be
8777 // discovered: two values whose invalid bytes sit in the same
8778 // positions DO conflate, because each becomes U+FFFD and nothing
8779 // distinguishes them. 0x80 and 0x81 are both lone continuations.
8780 // This is inherent to lossy decoding -- Python's
8781 // decode("utf-8", "replace") gives three replacement characters
8782 // for both -- and is the reason the comment on `Utf8Chars` claims
8783 // only that valid text is preserved.
8784 assert!(normalized_eq(&[0xED, 0xA0, 0x80], &[0xED, 0xA0, 0x81]));
8785 // Two values malformed the same way still compare equal.
8786 assert!(normalized_eq(&[0x80, b'a'], &[0x80, b'a']));
8787 }
8788
8789 /// A `BMPString` and a `UTF8String` spelling the same name compare
8790 /// equal through the whole pipeline, which is the path that made the
8791 /// allocation-free property worth keeping: the transcode is lazy and
8792 /// now feeds a lazy decoder and a lazy normalizer.
8793 #[test]
8794 fn a_bmpstring_and_a_utf8string_of_one_name_match() {
8795 // "Ac" with a fullwidth A: U+FF21 U+0063.
8796 let ucs2 = [0xFF, 0x21, 0x00, 0x63];
8797 let bmp = der::Any::new(der::Tag::BmpString, &ucs2[..]).expect("bmp value");
8798 let utf8 = der::Any::new(der::Tag::Utf8String, &b"ac"[..]).expect("utf8 value");
8799 assert!(super::ava_values_match(&bmp, &utf8));
8800 }
8801
8802 /// `DirectoryString` content reaches the comparison as UTF-8 bytes.
8803 ///
8804 /// The `BmpString` case transcodes one UCS-2 unit at a time through a
8805 /// four-byte buffer, so the bytes of a multi-byte character come out on
8806 /// successive calls and the position has to advance between them. The
8807 /// three units below encode to one, two and three UTF-8 bytes, which
8808 /// is every width a BMP scalar value takes.
8809 #[test]
8810 fn a_directory_string_yields_its_utf8_bytes_and_then_stops() {
8811 let utf8 = der::Any::new(der::Tag::Utf8String, &b"ab"[..]).expect("utf8 value");
8812 assert_eq!(
8813 prefix(any_to_str_bytes(&utf8).expect("a UTF8String is text"), 8),
8814 b"ab".to_vec()
8815 );
8816
8817 // U+0041 A, U+00E9 e-acute, U+20AC euro sign.
8818 let ucs2 = [0x00, 0x41, 0x00, 0xE9, 0x20, 0xAC];
8819 let bmp = der::Any::new(der::Tag::BmpString, &ucs2[..]).expect("bmp value");
8820 assert_eq!(
8821 prefix(any_to_str_bytes(&bmp).expect("a BMPString is text"), 16),
8822 [0x41, 0xC3, 0xA9, 0xE2, 0x82, 0xAC],
8823 "one, two and three UTF-8 bytes in that order"
8824 );
8825 }
8826
8827 /// Identical ASCII strings must compare equal.
8828 #[test]
8829 fn identical_strings_equal() {
8830 assert!(normalized_eq(b"hello", b"hello"));
8831 }
8832
8833 /// Case is folded to lowercase.
8834 #[test]
8835 fn case_folding() {
8836 assert!(normalized_eq(b"Hello", b"hello"));
8837 assert!(normalized_eq(b"HELLO WORLD", b"hello world"));
8838 }
8839
8840 /// Leading spaces are stripped.
8841 #[test]
8842 fn leading_spaces_stripped() {
8843 assert!(normalized_eq(b" hello", b"hello"));
8844 }
8845
8846 /// Trailing spaces are stripped.
8847 ///
8848 /// Regression test: `NormalizedIter` must not emit a trailing space for
8849 /// input that ends with a space sequence.
8850 #[test]
8851 fn trailing_spaces_stripped() {
8852 assert!(normalized_eq(b"hello ", b"hello"));
8853 assert!(normalized_eq(b"hello ", b"hello"));
8854 }
8855
8856 /// Multiple consecutive internal spaces are collapsed to a single space.
8857 ///
8858 /// Regression test for the double-space bug: `pending_space` must not
8859 /// cause two spaces to be emitted for a single space in the input.
8860 #[test]
8861 fn internal_spaces_collapsed() {
8862 assert!(normalized_eq(b"hello world", b"hello world"));
8863 assert!(normalized_eq(b"hello world", b"hello world"));
8864 }
8865
8866 /// Combined: leading + trailing + internal spaces, case folding.
8867 #[test]
8868 fn combined_normalization() {
8869 assert!(normalized_eq(b" Hello World ", b"hello world"));
8870 }
8871
8872 /// Empty string and all-spaces string must both yield zero bytes.
8873 #[test]
8874 fn empty_and_whitespace_only() {
8875 assert!(normalized_eq(b"", b""));
8876 assert!(normalized_eq(b" ", b""));
8877 assert!(normalized_eq(b" ", b" "));
8878 }
8879
8880 /// Different strings must NOT compare equal after normalization.
8881 #[test]
8882 fn different_strings_not_equal() {
8883 assert!(!normalized_eq(b"hello", b"world"));
8884 assert!(!normalized_eq(b"ab", b"abc"));
8885 }
8886
8887 /// `NormalizedIter`: input ending with an internal space sequence followed by
8888 /// trailing spaces must emit the space and then stop (no double space, no
8889 /// trailing space).
8890 #[test]
8891 fn internal_then_trailing_space_no_trailing_emit() {
8892 assert!(
8893 normalized_eq(b"ab ", b"ab"),
8894 "trailing spaces must not be emitted"
8895 );
8896 assert!(
8897 normalized_eq(b"ab cd ", b"ab cd"),
8898 "internal double-space collapses; trailing spaces stripped"
8899 );
8900 }
8901}
8902
8903// ---------------------------------------------------------------------------
8904// PKIX-l63j.1: BMPString transcoding tests
8905// ---------------------------------------------------------------------------
8906#[cfg(test)]
8907mod tests_bmp_string {
8908 use super::Vec;
8909 use super::{ava_values_match, bmp_string_to_utf8};
8910 use der::Tag;
8911 use der::asn1::Any;
8912
8913 /// Construct UCS-2-BE bytes for an ASCII-only string.
8914 ///
8915 /// Each ASCII byte `b` becomes the two-byte sequence `[0x00, b]` since
8916 /// ASCII code points are in the range U+0000..=U+007F and the
8917 /// big-endian UCS-2 encoding of U+00XX is `0x00, 0xXX`.
8918 ///
8919 /// Independent oracle: this construction matches the literal
8920 /// description in X.680 Annex B and ITU-T X.690 §8.6 ("`BMPString`
8921 /// is encoded as a sequence of two-octet code units in big-endian
8922 /// order, with each unit representing one Unicode code point").
8923 fn ucs2_be_ascii(s: &str) -> Vec<u8> {
8924 let mut v = Vec::with_capacity(s.len() * 2);
8925 for b in s.bytes() {
8926 assert!(
8927 b.is_ascii(),
8928 "ucs2_be_ascii test helper only supports ASCII input"
8929 );
8930 v.push(0x00);
8931 v.push(b);
8932 }
8933 v
8934 }
8935
8936 /// `bmp_string_to_utf8` round-trip for ASCII-only input.
8937 ///
8938 /// Independent oracle: ASCII Unicode code points (U+0000..=U+007F)
8939 /// are encoded identically as a single byte in UTF-8 and as a
8940 /// two-byte big-endian unit `[0x00, X]` in UCS-2. Decoding the
8941 /// UCS-2 form must yield bytes byte-equal to the original ASCII.
8942 #[test]
8943 fn ascii_round_trip() {
8944 let src = "Foo Co";
8945 let ucs2 = ucs2_be_ascii(src);
8946 let utf8 = bmp_string_to_utf8(&ucs2).expect("well-formed UCS-2 ASCII");
8947 assert_eq!(utf8, src.as_bytes());
8948 }
8949
8950 /// `bmp_string_to_utf8` for a non-ASCII BMP code point.
8951 ///
8952 /// Independent oracle: the Hiragana letter A (U+3042) has well-known
8953 /// encodings — UTF-8: `0xE3 0x81 0x82`; UCS-2-BE: `0x30 0x42`. Both
8954 /// are tabulated in the Unicode Character Database. Citing the
8955 /// Unicode codepoint is the external oracle here, not our own code.
8956 #[test]
8957 fn non_ascii_bmp_code_point() {
8958 // U+3042 (HIRAGANA LETTER A): UCS-2-BE bytes 0x30 0x42.
8959 let ucs2 = vec![0x30, 0x42];
8960 let utf8 = bmp_string_to_utf8(&ucs2).expect("U+3042 is a valid BMP code point");
8961 // U+3042 in UTF-8 is the well-known three-byte sequence E3 81 82.
8962 assert_eq!(utf8, vec![0xE3, 0x81, 0x82]);
8963 }
8964
8965 /// Odd-length UCS-2 input is malformed (each unit must be 2 bytes).
8966 /// Fail-closed: return None.
8967 #[test]
8968 fn odd_length_returns_none() {
8969 let malformed = vec![0x00, 0x46, 0x00]; // 3 bytes, not a multiple of 2
8970 assert_eq!(bmp_string_to_utf8(&malformed), None);
8971 }
8972
8973 /// UTF-16 surrogate values (U+D800..=U+DFFF) are not valid Unicode
8974 /// scalar values and must not appear in `BMPString`. Fail-closed:
8975 /// return None.
8976 ///
8977 /// Independent oracle: Unicode Standard §3.8 explicitly defines
8978 /// surrogates as non-scalar; `core::char::from_u32(0xD800..=0xDFFF)`
8979 /// returns None.
8980 #[test]
8981 fn surrogate_returns_none() {
8982 // U+D800 (high surrogate, first surrogate code point).
8983 assert_eq!(bmp_string_to_utf8(&[0xD8, 0x00]), None);
8984 // U+DC00 (low surrogate).
8985 assert_eq!(bmp_string_to_utf8(&[0xDC, 0x00]), None);
8986 // U+DFFF (last surrogate code point).
8987 assert_eq!(bmp_string_to_utf8(&[0xDF, 0xFF]), None);
8988 }
8989
8990 /// Empty `BMPString` content is well-formed (zero code points) and
8991 /// transcodes to an empty UTF-8 byte vector.
8992 #[test]
8993 fn empty_input_round_trip() {
8994 let utf8 = bmp_string_to_utf8(&[]).expect("empty UCS-2 is well-formed (zero units)");
8995 assert_eq!(utf8, [] as [u8; 0]);
8996 }
8997
8998 /// `ava_values_match`: a BMPString-encoded "Foo Co" must compare
8999 /// equal to a UTF8String-encoded "Foo Co".
9000 ///
9001 /// This is the core PKIX-l63j.1 invariant: same Unicode code points
9002 /// in different DER string types compare equal under DN matching.
9003 #[test]
9004 fn bmp_matches_utf8_same_text() {
9005 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
9006 let utf8 = Any::new(Tag::Utf8String, b"Foo Co".to_vec()).unwrap();
9007 assert!(super::ava_values_match(&bmp, &utf8));
9008 // Symmetry: order of arguments must not matter.
9009 assert!(ava_values_match(&utf8, &bmp));
9010 }
9011
9012 /// `ava_values_match`: `BMPString` and `PrintableString` comparisons
9013 /// must succeed for ASCII content with the same Unicode code points.
9014 #[test]
9015 fn bmp_matches_printable_same_text() {
9016 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Acme CA")).unwrap();
9017 let printable = Any::new(Tag::PrintableString, b"Acme CA".to_vec()).unwrap();
9018 assert!(ava_values_match(&bmp, &printable));
9019 assert!(ava_values_match(&printable, &bmp));
9020 }
9021
9022 /// `ava_values_match`: ASCII case-folding still applies to
9023 /// BMPString-derived UTF-8 bytes after transcoding (since BMP code
9024 /// points U+0041..=U+005A round-trip to ASCII bytes 0x41..=0x5A).
9025 #[test]
9026 fn bmp_matches_utf8_case_insensitive_ascii() {
9027 let bmp_upper = Any::new(Tag::BmpString, ucs2_be_ascii("FOO CO")).unwrap();
9028 let utf8_lower = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
9029 assert!(ava_values_match(&bmp_upper, &utf8_lower));
9030 }
9031
9032 /// `ava_values_match`: whitespace collapsing still applies to
9033 /// BMPString-derived UTF-8 bytes (BMP space U+0020 → byte 0x20).
9034 #[test]
9035 fn bmp_matches_utf8_whitespace_collapsed() {
9036 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii(" Foo Co ")).unwrap();
9037 let utf8 = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
9038 assert!(super::ava_values_match(&bmp, &utf8));
9039 }
9040
9041 /// `ava_values_match`: different Unicode content must NOT match
9042 /// across encodings.
9043 #[test]
9044 fn bmp_does_not_match_utf8_different_text() {
9045 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
9046 let utf8 = Any::new(Tag::Utf8String, b"Bar Co".to_vec()).unwrap();
9047 assert!(!ava_values_match(&bmp, &utf8));
9048 }
9049
9050 /// `ava_values_match`: malformed `BMPString` (odd length) is treated
9051 /// as a non-string type by the dispatcher (`any_to_str_bytes` returns
9052 /// None). It must therefore NOT match a well-formed `UTF8String` of
9053 /// any content. Fail-closed.
9054 #[test]
9055 fn malformed_bmp_does_not_match_well_formed_utf8() {
9056 // 3-byte content: malformed UCS-2.
9057 let malformed_bmp = Any::new(Tag::BmpString, vec![0x00, 0x46, 0x00]).unwrap();
9058 let utf8 = Any::new(Tag::Utf8String, b"F".to_vec()).unwrap();
9059 assert!(!ava_values_match(&malformed_bmp, &utf8));
9060 assert!(!ava_values_match(&utf8, &malformed_bmp));
9061 }
9062
9063 /// `ava_values_match`: non-ASCII Unicode code points compare equal
9064 /// when both AVAs encode the same code points (`BMPString` vs
9065 /// `UTF8String`).
9066 ///
9067 /// Independent oracle: the UCS-2-BE bytes for U+3042 are 0x30 0x42
9068 /// and the UTF-8 bytes are 0xE3 0x81 0x82, both per the Unicode
9069 /// Standard.
9070 #[test]
9071 fn bmp_matches_utf8_non_ascii() {
9072 // U+3042 HIRAGANA LETTER A.
9073 let bmp = Any::new(Tag::BmpString, vec![0x30, 0x42]).unwrap();
9074 let utf8 = Any::new(Tag::Utf8String, vec![0xE3, 0x81, 0x82]).unwrap();
9075 assert!(super::ava_values_match(&bmp, &utf8));
9076 }
9077
9078 /// Sanity: two BMPString-encoded values with the same Unicode code
9079 /// points compare equal (this exercises the BMPString-on-both-sides
9080 /// path through `any_to_str_bytes`, where both sides allocate).
9081 #[test]
9082 fn bmp_matches_bmp_same_text() {
9083 let a = Any::new(Tag::BmpString, ucs2_be_ascii("Acme")).unwrap();
9084 let b = Any::new(Tag::BmpString, ucs2_be_ascii("acme")).unwrap();
9085 assert!(ava_values_match(&a, &b));
9086 }
9087}
9088
9089// Review A1: NameConstraints helper unit tests (URI host extraction,
9090// constraint containment, streaming DN normalization).
9091#[cfg(test)]
9092mod tests_nc_review_a1 {
9093 use super::{
9094 dns_constraint_within, ip_constraint_within, matches_dns_name, matches_rfc822_name,
9095 normalized_eq, rfc822_constraint_within, uri_constraint_within, uri_host,
9096 };
9097
9098 #[test]
9099 fn uri_host_extraction() {
9100 assert_eq!(uri_host("https://good.com/x"), Some("good.com"));
9101 assert_eq!(
9102 uri_host("HTTPS://u:p@Good.com:443/a@b?c@d#e@f"),
9103 Some("Good.com")
9104 );
9105 assert_eq!(uri_host("https://evil.com/@good.com"), Some("evil.com"));
9106 assert_eq!(uri_host("https://evil.com#@good.com"), Some("evil.com"));
9107 assert_eq!(uri_host("https://evil.com./"), Some("evil.com"));
9108 // RFC 5280 §4.2.1.10 "MUST reject" shapes.
9109 assert_eq!(uri_host("urn:example:x"), None);
9110 assert_eq!(uri_host("mailto:a@b.example"), None);
9111 assert_eq!(uri_host("file:///etc/passwd"), None);
9112 assert_eq!(uri_host("https://192.0.2.1/"), None);
9113 assert_eq!(uri_host("https://[2001:db8::1]:8443/"), None);
9114 assert_eq!(uri_host("https://good.com:x/"), None);
9115 assert_eq!(uri_host("1http://good.com/"), None);
9116 assert_eq!(uri_host("://good.com/"), None);
9117 }
9118
9119 #[test]
9120 fn dns_matching_edges() {
9121 assert!(matches_dns_name("anything.example", ""));
9122 assert!(matches_dns_name("www.evil.com.", "evil.com"));
9123 assert!(matches_dns_name("www.evil.com", "evil.com."));
9124 assert!(!matches_dns_name("evil.com", ".evil.com"));
9125 assert!(!matches_dns_name("notevil.com", "evil.com"));
9126 }
9127
9128 #[test]
9129 fn rfc822_uses_last_at() {
9130 assert!(matches_rfc822_name("\"x@good.com\"@evil.com", "evil.com"));
9131 assert!(!matches_rfc822_name("\"x@good.com\"@evil.com", "good.com"));
9132 }
9133
9134 /// RFC 5280 §7.5(1), restated by RFC 9549 §7.5.1(1) and §7.5.2(1): the
9135 /// local-part of each name is an **exact** match. RFC 5321 §2.4 is the
9136 /// reason — a local-part is case-sensitive, so `Root@` and `root@` are
9137 /// different mailboxes.
9138 ///
9139 /// Before `PKIX-z1o9` this folded the whole address. In a permitted
9140 /// subtree that was fail-open: a CA constrained to `root@example.com`
9141 /// would have had `ROOT@example.com` accepted.
9142 #[test]
9143 fn rfc822_mailbox_constraint_matches_the_local_part_exactly() {
9144 assert!(matches_rfc822_name("root@example.com", "root@example.com"));
9145 assert!(
9146 !matches_rfc822_name("ROOT@example.com", "root@example.com"),
9147 "a case-folded local-part is a different mailbox (RFC 5321 §2.4)"
9148 );
9149 assert!(!matches_rfc822_name("Root@example.com", "root@example.com"));
9150 assert!(!matches_rfc822_name("root@example.com", "ROOT@example.com"));
9151 }
9152
9153 /// RFC 5280 §7.5(2): the host-part matches using a case-insensitive
9154 /// ASCII comparison. Folding the host while not folding the local-part
9155 /// is the whole point of the two-clause rule.
9156 #[test]
9157 fn rfc822_mailbox_constraint_folds_the_host_part() {
9158 assert!(matches_rfc822_name("root@EXAMPLE.COM", "root@example.com"));
9159 assert!(matches_rfc822_name("root@example.com", "root@EXAMPLE.COM"));
9160 assert!(!matches_rfc822_name("root@other.com", "root@example.com"));
9161 }
9162
9163 /// RFC 9549 §2.5 requires §7.5.1 (ASCII local-part) and §7.5.2
9164 /// (non-ASCII local-part) to be handled the same way, and §2.2 says
9165 /// removing the per-mailbox form was what let name constraints reach
9166 /// `SmtpUTF8Mailbox` as well as `rfc822Name`.
9167 ///
9168 /// The old single `eq_ignore_ascii_case` broke that asymmetrically,
9169 /// which is the subtle half of the bug: that function folds only ASCII
9170 /// bytes, so a non-ASCII local-part was *already* compared exactly
9171 /// while an ASCII one was not. The rule was honoured for an
9172 /// internationalized mailbox and violated for a plain one.
9173 ///
9174 /// This test asserts the two now behave alike: exact local-part,
9175 /// folded host, in both scripts.
9176 #[test]
9177 fn rfc822_ascii_and_internationalized_local_parts_are_handled_alike() {
9178 // Non-ASCII local-part: exact, and the host still folds.
9179 assert!(matches_rfc822_name(
9180 "ユーザ@example.com",
9181 "ユーザ@example.com"
9182 ));
9183 assert!(matches_rfc822_name(
9184 "ユーザ@EXAMPLE.COM",
9185 "ユーザ@example.com"
9186 ));
9187 assert!(!matches_rfc822_name(
9188 "ユーザ2@example.com",
9189 "ユーザ@example.com"
9190 ));
9191
9192 // The ASCII case, which is the one that used to differ. Both
9193 // scripts now reject a local-part that differs only by case --
9194 // the non-ASCII one trivially, the ASCII one because the fold is
9195 // gone.
9196 let ascii_rejects_case = !matches_rfc822_name("ROOT@example.com", "root@example.com");
9197 let idn_rejects_case = !matches_rfc822_name("ROOT@example.com", "root@example.com");
9198 assert_eq!(
9199 ascii_rejects_case, idn_rejects_case,
9200 "RFC 9549 §2.5: an ASCII and an internationalized local-part must be \
9201 handled in the same manner"
9202 );
9203 assert!(ascii_rejects_case);
9204 }
9205
9206 /// Host- and domain-form constraints ignore the local-part entirely,
9207 /// whatever script it is in, so the fix does not narrow them.
9208 #[test]
9209 fn rfc822_host_and_domain_constraints_are_unaffected_by_local_part_case() {
9210 for subject in ["root@example.com", "ROOT@example.com", "ユーザ@example.com"] {
9211 assert!(
9212 matches_rfc822_name(subject, "example.com"),
9213 "{subject} is at the constrained host"
9214 );
9215 assert!(
9216 matches_rfc822_name(subject, ".com"),
9217 "{subject} is under the constrained domain"
9218 );
9219 assert!(
9220 !matches_rfc822_name(subject, ".example.com"),
9221 "{subject}: a leading-period constraint excludes the apex"
9222 );
9223 }
9224 }
9225
9226 #[test]
9227 fn constraint_containment() {
9228 // DNS: x = {x} ∪ subdomains(x); .x = subdomains(x).
9229 assert!(dns_constraint_within(".example.com", "example.com"));
9230 assert!(!dns_constraint_within("example.com", ".example.com"));
9231 assert!(dns_constraint_within("a.example.com", ".example.com"));
9232 assert!(dns_constraint_within("example.com", ""));
9233 assert!(!dns_constraint_within("", "example.com"));
9234 // rfc822
9235 assert!(rfc822_constraint_within("host.example.com", ".example.com"));
9236 assert!(rfc822_constraint_within(
9237 "a@host.example.com",
9238 "host.example.com"
9239 ));
9240 assert!(!rfc822_constraint_within(
9241 ".example.com",
9242 "host.example.com"
9243 ));
9244 assert!(!rfc822_constraint_within(
9245 "host.example.com",
9246 "a@host.example.com"
9247 ));
9248 assert!(rfc822_constraint_within(".a.example.com", ".example.com"));
9249 // URI: no-dot = exact host only.
9250 assert!(uri_constraint_within("example.com", "example.com"));
9251 assert!(!uri_constraint_within("a.example.com", "example.com"));
9252 assert!(uri_constraint_within("a.example.com", ".example.com"));
9253 assert!(!uri_constraint_within(".example.com", "example.com"));
9254 // IP
9255 let v4 = |a: [u8; 4], m: [u8; 4]| [a, m].concat();
9256 assert!(ip_constraint_within(
9257 &v4([10, 1, 0, 0], [255, 255, 0, 0]),
9258 &v4([10, 0, 0, 0], [255, 0, 0, 0])
9259 ));
9260 assert!(!ip_constraint_within(
9261 &v4([10, 0, 0, 0], [255, 0, 0, 0]),
9262 &v4([10, 1, 0, 0], [255, 255, 0, 0])
9263 ));
9264 assert!(!ip_constraint_within(
9265 &v4([11, 1, 0, 0], [255, 255, 0, 0]),
9266 &v4([10, 0, 0, 0], [255, 0, 0, 0])
9267 ));
9268 assert!(!ip_constraint_within(
9269 &v4([10, 0, 0, 0], [255, 0, 0, 0]),
9270 &[0u8; 32]
9271 ));
9272 }
9273
9274 #[test]
9275 fn streaming_normalization_matches_slice_semantics() {
9276 assert!(normalized_eq(b" a B c ", b"a b c"));
9277 assert!(normalized_eq(b" ", b""));
9278 assert!(!normalized_eq(b"a b", b"ab"));
9279 }
9280}
9281
9282// PKIX-h6z: validate_path public API tests.
9283#[cfg(all(test, feature = "p256"))]
9284mod tests_validate_path {
9285 use super::*;
9286 use der::Decode;
9287
9288 // Fixtures and time constants reused from tests_chain_walk.
9289 const GRY_NOW: u64 = 1_780_272_000; // 2026-06-01
9290
9291 fn load(bytes: &[u8]) -> Certificate {
9292 Certificate::from_der(bytes).expect("parse cert")
9293 }
9294
9295 fn policy_at(t: u64) -> ValidationPolicy {
9296 ValidationPolicy::new(t)
9297 }
9298
9299 /// Happy-path 1-cert chain: self-signed cert is both chain and anchor.
9300 ///
9301 /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 0 })
9302 #[test]
9303 fn one_cert_chain_ok() {
9304 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
9305 let anchors =
9306 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
9307 let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
9308 .expect("1-cert chain must validate");
9309 assert_eq!(result.anchor_index, 0);
9310 assert_eq!(result.depth, 0);
9311 }
9312
9313 /// Happy-path 2-cert chain: leaf + intermediate, with root anchor.
9314 ///
9315 /// Oracle: openssl verify -`CAfile` gry-root.pem -untrusted gry-int.pem gry-leaf.pem → OK
9316 /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 1 })
9317 #[test]
9318 fn two_cert_chain_ok() {
9319 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
9320 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
9321 let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
9322 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9323 let result = validate_path(
9324 &[leaf, int_cert],
9325 &anchors,
9326 &policy_at(GRY_NOW),
9327 &EcdsaP256Verifier,
9328 )
9329 .expect("2-cert chain must validate");
9330 assert_eq!(result.anchor_index, 0);
9331 assert_eq!(result.depth, 1);
9332 }
9333
9334 /// §6.1.5 leaf-intrinsic outputs are populated correctly from `chain[0]`.
9335 ///
9336 /// Independent oracle: parse the leaf fixture a second time via
9337 /// `Certificate::from_der` (a different code path from `validate_path`'s
9338 /// chain[0] access). Compare each `ValidatedPath` accessor field against
9339 /// the independently-parsed leaf's `tbs_certificate` field. Catches:
9340 /// - Field swaps (e.g. `leaf_subject` accidentally populated from `issuer`).
9341 /// - Wrong cert in chain (e.g. `chain[1].subject` instead of `chain[0]`).
9342 /// - Forgotten field assignments.
9343 ///
9344 /// Does NOT validate x509-cert's parser correctness (that's tested
9345 /// upstream); it validates the wiring between `validate_path` and
9346 /// `ValidatedPath`.
9347 #[test]
9348 fn validated_path_exposes_leaf_subject_issuer_serial_spki() {
9349 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
9350 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
9351 let leaf_bytes = include_bytes!("../tests/fixtures/gry-leaf.der");
9352 let leaf = load(leaf_bytes);
9353
9354 // Independent oracle: re-parse the leaf via Certificate::from_der.
9355 // x509-cert's parser is the upstream oracle for the field values.
9356 let oracle_leaf =
9357 Certificate::from_der(leaf_bytes).expect("oracle: leaf fixture must parse");
9358
9359 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9360 let result = validate_path(
9361 &[leaf, int_cert],
9362 &anchors,
9363 &policy_at(GRY_NOW),
9364 &EcdsaP256Verifier,
9365 )
9366 .expect("2-cert chain must validate");
9367
9368 // The four §6.1.5 leaf-intrinsic outputs must match the
9369 // independently-parsed leaf's corresponding tbs_certificate fields.
9370 assert_eq!(
9371 &result.leaf_subject,
9372 oracle_leaf.tbs_certificate().subject(),
9373 "ValidatedPath.leaf_subject must equal chain[0].tbs_certificate().subject()"
9374 );
9375 assert_eq!(
9376 &result.leaf_issuer,
9377 oracle_leaf.tbs_certificate().issuer(),
9378 "ValidatedPath.leaf_issuer must equal chain[0].tbs_certificate().issuer()"
9379 );
9380 assert_eq!(
9381 &result.leaf_serial,
9382 oracle_leaf.tbs_certificate().serial_number(),
9383 "ValidatedPath.leaf_serial must equal chain[0].tbs_certificate().serial_number()"
9384 );
9385 assert_eq!(
9386 &result.leaf_spki,
9387 oracle_leaf.tbs_certificate().subject_public_key_info(),
9388 "ValidatedPath.leaf_spki must equal chain[0].tbs_certificate().subject_public_key_info()"
9389 );
9390
9391 // Sanity: leaf_subject != leaf_issuer for a real (non-self-signed)
9392 // leaf. This catches the swap-subject-with-issuer regression: a
9393 // subject-issuer copy bug would leave both fields equal to whichever
9394 // one was used.
9395 assert_ne!(
9396 result.leaf_subject, result.leaf_issuer,
9397 "non-self-signed leaf must have distinct subject and issuer DNs (regression: swap)"
9398 );
9399 }
9400
9401 /// §6.1.5 outputs for a 1-cert (self-signed) chain.
9402 ///
9403 /// Self-signed certs have `subject == issuer`. This documents that
9404 /// `leaf_subject` and `leaf_issuer` ARE expected to be equal in this
9405 /// case — the previous test's `assert_ne!` is for non-self-signed
9406 /// chains only.
9407 #[test]
9408 fn validated_path_outputs_for_self_signed_chain() {
9409 let cert_bytes = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
9410 let cert = load(cert_bytes);
9411 let oracle = Certificate::from_der(cert_bytes).expect("oracle: cert must parse");
9412 let anchors =
9413 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
9414
9415 let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
9416 .expect("1-cert self-signed chain must validate");
9417
9418 assert_eq!(&result.leaf_subject, oracle.tbs_certificate().subject());
9419 assert_eq!(&result.leaf_issuer, oracle.tbs_certificate().issuer());
9420 assert_eq!(
9421 &result.leaf_serial,
9422 oracle.tbs_certificate().serial_number()
9423 );
9424 assert_eq!(
9425 &result.leaf_spki,
9426 oracle.tbs_certificate().subject_public_key_info()
9427 );
9428 // Self-signed: subject == issuer by definition.
9429 assert_eq!(
9430 result.leaf_subject, result.leaf_issuer,
9431 "self-signed cert must have equal subject and issuer DNs"
9432 );
9433 }
9434
9435 /// Multiple anchors: correct anchor is second in the slice.
9436 ///
9437 /// Expected: Ok(ValidatedPath { `anchor_index`: 1, depth: 0 })
9438 #[test]
9439 fn correct_anchor_index_when_multiple_anchors() {
9440 let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
9441 let rsa = load(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"));
9442 // First anchor is the RSA cert (wrong name and SPKI for the P-256 chain).
9443 // Second anchor matches.
9444 let anchors = [
9445 TrustAnchor::from_cert(rsa).expect("fixture CA is a usable trust anchor"),
9446 TrustAnchor::from_cert(p256.clone()).expect("fixture CA is a usable trust anchor"),
9447 ];
9448 let result = validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
9449 .expect("must find second anchor");
9450 assert_eq!(result.anchor_index, 1);
9451 assert_eq!(result.depth, 0);
9452 }
9453
9454 /// Empty chain returns `NoTrustedPath`.
9455 #[test]
9456 fn empty_chain_returns_error() {
9457 let anchors =
9458 [
9459 TrustAnchor::from_cert(load(include_bytes!(
9460 "../tests/fixtures/ec-p256-sha256.der"
9461 )))
9462 .expect("fixture CA is a usable trust anchor"),
9463 ];
9464 assert!(
9465 matches!(
9466 // An empty slice literal cannot tell the compiler what a
9467 // path element is; the chain type has to be named.
9468 validate_path::<_, Certificate>(
9469 &[],
9470 &anchors,
9471 &policy_at(GRY_NOW),
9472 &EcdsaP256Verifier
9473 ),
9474 Err(Error::NoTrustedPath)
9475 ),
9476 "empty chain must fail"
9477 );
9478 }
9479
9480 /// Duplicate certificate in chain returns `DuplicateCertificate` error.
9481 ///
9482 /// Oracle: RFC 5280 does not define behavior for duplicate certs; we reject
9483 /// early with a diagnostic error rather than failing later with a confusing
9484 /// `SignatureInvalid` or `ChainBroken`.
9485 ///
9486 /// Duplicate is detected by (issuer DN, serial number) identity per RFC 5280
9487 /// §4.1.2.2 — the same cert appearing twice has the same issuer+serial.
9488 /// SPKI equality is intentionally NOT used (cross-signed CAs share a key but
9489 /// have distinct issuer+serial and must not be rejected).
9490 #[test]
9491 fn duplicate_cert_in_chain_returns_error() {
9492 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
9493 let anchors =
9494 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
9495 // Chain [cert, cert]: same cert at index 0 and index 1 — same issuer+serial.
9496 let result = validate_path(
9497 &[cert.clone(), cert],
9498 &anchors,
9499 &policy_at(GRY_NOW),
9500 &EcdsaP256Verifier,
9501 );
9502 assert!(
9503 matches!(
9504 result,
9505 Err(Error::DuplicateCertificate {
9506 first: 0,
9507 second: 1
9508 })
9509 ),
9510 "duplicate cert must return DuplicateCertificate{{first:0, second:1}}, got {result:?}"
9511 );
9512 }
9513
9514 /// `path_too_long`: vxf chain [leaf, int] with `max_path_len` = 0.
9515 ///
9516 /// chain.len()=2 → 1 intermediate. 1 > `max_path_len(0)` → `PathTooLong`.
9517 #[test]
9518 fn path_too_long_returns_error() {
9519 let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
9520 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
9521 let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
9522 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9523 let policy = ValidationPolicy {
9524 current_time_unix: GRY_NOW,
9525 max_path_len: 0,
9526 ..ValidationPolicy::new(0)
9527 };
9528 assert!(
9529 matches!(
9530 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
9531 Err(Error::PathTooLong)
9532 ),
9533 "1 intermediate with max_path_len=0 must return PathTooLong"
9534 );
9535 }
9536
9537 /// `no_trusted_path`: vxf chain presented to an unrelated anchor (gry-root).
9538 ///
9539 /// vxf's last cert issuer name does not match gry-root's subject name.
9540 #[test]
9541 fn no_trusted_path_unrelated_anchor_returns_error() {
9542 let gry_root = load(include_bytes!("../tests/fixtures/gry-root.der"));
9543 let vxf_int = load(include_bytes!("../tests/fixtures/vxf-int.der"));
9544 let vxf_leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
9545 let anchors =
9546 [TrustAnchor::from_cert(gry_root).expect("fixture CA is a usable trust anchor")];
9547 assert!(
9548 matches!(
9549 validate_path(
9550 &[vxf_leaf, vxf_int],
9551 &anchors,
9552 &policy_at(GRY_NOW),
9553 &EcdsaP256Verifier
9554 ),
9555 Err(Error::NoTrustedPath)
9556 ),
9557 "vxf chain with gry anchor must return NoTrustedPath"
9558 );
9559 }
9560
9561 /// `oid_mismatch`: outer signatureAlgorithm OID differs from inner TBS signature OID.
9562 ///
9563 /// Patch the SECOND occurrence of the ECDSA-with-SHA256 OID bytes in vxf-leaf.der
9564 /// to ECDSA-with-SHA384. The inner TBS.signature remains SHA256.
9565 /// `check_oid_consistency` detects this → `MalformedCertificate` { index: 0 }.
9566 ///
9567 /// Oracle: RFC 5280 §4.1.1.2 requires outer and inner `AlgorithmIdentifiers` to be identical.
9568 #[test]
9569 fn oid_mismatch_outer_returns_malformed_certificate() {
9570 let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
9571 // ECDSA-with-SHA256 OID content bytes: 1.2.840.10045.4.3.2
9572 let oid_sha256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
9573 // ECDSA-with-SHA384 OID content bytes: 1.2.840.10045.4.3.3 (same length, last byte differs)
9574 let oid_sha384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
9575 // In Certificate DER the inner TBS.signature OID appears FIRST (inside TBSCertificate)
9576 // and the outer signatureAlgorithm OID appears SECOND (after TBSCertificate). Patching
9577 // only the second occurrence changes the outer OID while leaving the inner intact.
9578 let first = leaf_der
9579 .windows(8)
9580 .position(|w| w == oid_sha256)
9581 .expect("inner SHA256 OID must be present in vxf-leaf.der");
9582 let second = leaf_der[first + 8..]
9583 .windows(8)
9584 .position(|w| w == oid_sha256)
9585 .map(|p| first + 8 + p)
9586 .expect("outer SHA256 OID must be present in vxf-leaf.der");
9587 leaf_der[second..second + 8].copy_from_slice(oid_sha384);
9588 let leaf = Certificate::from_der(&leaf_der).expect("patched DER must parse");
9589 assert_ne!(
9590 leaf.signature_algorithm(),
9591 leaf.tbs_certificate().signature(),
9592 "outer/inner OIDs must differ after patch"
9593 );
9594 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
9595 let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
9596 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9597 assert!(
9598 matches!(
9599 validate_path(
9600 &[leaf, int_cert],
9601 &anchors,
9602 &policy_at(GRY_NOW),
9603 &EcdsaP256Verifier
9604 ),
9605 Err(Error::MalformedCertificate { index: 0 })
9606 ),
9607 "outer/inner OID mismatch must return MalformedCertificate {{ index: 0 }}"
9608 );
9609 }
9610
9611 /// `intermediate_not_ca`: nca-int has no `BasicConstraints` extension.
9612 ///
9613 /// Oracle: pyca/cryptography — nca-int built without any extensions.
9614 /// cert_is_ca(nca-int) returns None → `NotCA` { index: 1 }.
9615 #[test]
9616 fn intermediate_not_ca_returns_not_ca() {
9617 let root = load(include_bytes!("../tests/fixtures/nca-root.der"));
9618 let int_cert = load(include_bytes!("../tests/fixtures/nca-int.der"));
9619 let leaf = load(include_bytes!("../tests/fixtures/nca-leaf.der"));
9620 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9621 assert!(
9622 matches!(
9623 validate_path(
9624 &[leaf, int_cert],
9625 &anchors,
9626 &policy_at(GRY_NOW),
9627 &EcdsaP256Verifier
9628 ),
9629 Err(Error::NotCA { index: 1 })
9630 ),
9631 "intermediate without BasicConstraints CA flag must return NotCA {{ index: 1 }}"
9632 );
9633 }
9634
9635 /// `key_usage_missing_cert_sign`: kuf-int has `KeyUsage` with digitalSignature only.
9636 ///
9637 /// Oracle: pyca/cryptography — kuf-int KeyUsage.keyCertSign = False.
9638 /// Default policy has `enforce_key_usage` = true; `chain_walk` checks at i=1.
9639 #[test]
9640 fn key_usage_missing_cert_sign_returns_error() {
9641 let root = load(include_bytes!("../tests/fixtures/kuf-root.der"));
9642 let int_cert = load(include_bytes!("../tests/fixtures/kuf-int.der"));
9643 let leaf = load(include_bytes!("../tests/fixtures/kuf-leaf.der"));
9644 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9645 assert!(
9646 matches!(
9647 validate_path(
9648 &[leaf, int_cert],
9649 &anchors,
9650 &policy_at(GRY_NOW),
9651 &EcdsaP256Verifier
9652 ),
9653 Err(Error::KeyUsageMissing { index: 1 })
9654 ),
9655 "intermediate with KeyUsage but no keyCertSign must return KeyUsageMissing {{ index: 1 }}"
9656 );
9657 }
9658
9659 /// `absent_key_usage_intermediate_accepted`: nku-int has NO `KeyUsage` extension at all.
9660 ///
9661 /// RFC 5280 §6.1.4(n): "If a `KeyUsage` extension is **present**, verify that the
9662 /// keyCertSign bit is set." Absent `KeyUsage` must not be rejected by `enforce_key_usage`.
9663 ///
9664 /// Oracle: pyca/cryptography — nku-int has only `BasicConstraints` (OID 2.5.29.19),
9665 /// no `KeyUsage` extension.
9666 #[test]
9667 fn absent_key_usage_intermediate_accepted() {
9668 let root = load(include_bytes!("../tests/fixtures/nku-root.der"));
9669 let int_cert = load(include_bytes!("../tests/fixtures/nku-int.der"));
9670 let leaf = load(include_bytes!("../tests/fixtures/nku-leaf.der"));
9671 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
9672 // Default policy has enforce_key_usage = true.
9673 // nku-int has no KeyUsage — must NOT trigger KeyUsageMissing per RFC 5280 §6.1.4(n).
9674 let now: u64 = 1_720_000_000; // 2024-07-03, within nku-int validity (2024-2030)
9675 let policy = ValidationPolicy {
9676 current_time_unix: now,
9677 ..ValidationPolicy::new(0)
9678 };
9679 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier).expect(
9680 "intermediate with absent KeyUsage must be accepted when enforce_key_usage=true",
9681 );
9682 }
9683
9684 /// Leaf with critical `ExtendedKeyUsage` → `validate_path` must accept it.
9685 ///
9686 /// EKU is in `HANDLED_CRITICAL_OIDS`; its value is not inspected.
9687 /// Oracle: pyca/cryptography — eku-critical-self-signed.der, critical=True, serverAuth.
9688 #[test]
9689 fn critical_eku_accepted() {
9690 let cert = load(include_bytes!(
9691 "../tests/fixtures/eku-critical-self-signed.der"
9692 ));
9693 let anchors =
9694 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
9695 validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
9696 .expect("cert with critical EKU must be accepted");
9697 }
9698
9699 /// Security test: anchor with matching name but wrong SPKI must be rejected.
9700 ///
9701 /// Guards against a name-collision attack: an attacker who creates a root cert
9702 /// with the same DN as a trusted anchor but a different key must not be accepted.
9703 /// The self-issued SPKI guard in `validate_path` catches this.
9704 #[test]
9705 fn forged_anchor_name_match_spki_mismatch_rejected() {
9706 use der::Decode as _;
9707 let p256 = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
9708 .expect("parse P-256 cert");
9709 let rsa =
9710 Certificate::from_der(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"))
9711 .expect("parse RSA cert");
9712 // Forged anchor: P-256 cert's subject name + RSA cert's SPKI.
9713 let forged = TrustAnchor::new(
9714 p256.tbs_certificate().subject().clone(),
9715 rsa.tbs_certificate().subject_public_key_info().clone(),
9716 );
9717 let anchors = [forged];
9718 assert!(
9719 matches!(
9720 validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
9721 Err(Error::NoTrustedPath)
9722 ),
9723 "anchor with matching name but wrong SPKI must return NoTrustedPath"
9724 );
9725 }
9726
9727 /// Verify that `validate_path` handles large certs without `Error::Der`.
9728 ///
9729 /// The previous fixed 8 KiB stack buffer returned `Error::Der` for any cert
9730 /// whose `TBSCertificate` DER exceeded 8 KiB. The heap-backed encoding path
9731 /// introduced in v0.2 removes that limit. This test verifies that a normally-
9732 /// sized cert (well under 8 KiB) still validates correctly, confirming the
9733 /// heap path is wired up correctly and not just a dead code path.
9734 ///
9735 /// Oracle: the gry-leaf fixture validates correctly via openssl verify.
9736 #[test]
9737 fn large_cert_encoding_does_not_fail_with_der_error() {
9738 // We don't have an actual > 8 KiB TBSCertificate fixture in the test suite,
9739 // but we can verify the heap path is taken by confirming normal certs still pass.
9740 // The regression test for the bug is: this path no longer returns Error::Der
9741 // for legitimately-sized certs.
9742 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
9743 let anchors =
9744 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
9745 // Must not return Err(Error::Der(...)) — the heap encoding path must succeed.
9746 let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier);
9747 assert!(
9748 !matches!(result, Err(Error::Der(_))),
9749 "heap-backed encoding must not return Error::Der for a normal cert"
9750 );
9751 }
9752}
9753
9754// PKIX-vxf + PKIX-gry: chain_walk tests require the p256 feature.
9755#[cfg(all(test, feature = "p256"))]
9756mod tests_chain_walk {
9757 use super::*;
9758 use der::Decode;
9759
9760 // Fixtures (PKIX-vxf):
9761 // vxf-root.der — self-signed root CA, CN=PKIX-vxf-root (P-256)
9762 // vxf-int.der — intermediate CA, CN=PKIX-vxf-int, signed by vxf-root
9763 // vxf-leaf.der — leaf cert, CN=PKIX-vxf-leaf, signed by vxf-int
9764 // chk-root.der / chk-int.der / chk-leaf-wrong-issuer.der — ChainBroken test chain
9765 //
9766 // Fixtures (PKIX-gry):
9767 // gry-root.der — root CA, CN=PKIX-gry-root (P-256)
9768 // gry-int.der — intermediate CA, CN=PKIX-gry-int, valid 2026-2036
9769 // gry-leaf.der — leaf, CN=PKIX-gry-leaf, valid 2026-2027 (short-lived)
9770 // gry-leaf-unknown-crit.der — leaf with unknown critical extension
9771 //
9772 // Unix timestamp constants for gry validity tests:
9773 // GRY_NOW = 1780272000 (2026-06-01, all gry certs valid)
9774 // GRY_EXPIRED = 1830384000 (2028-01-02, gry-leaf expired; gry-int still valid)
9775 // GRY_NOTYET = 0 (1970-01-01, all gry certs not-yet-valid)
9776 //
9777 // Oracle:
9778 // vxf chain: openssl verify -CAfile vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
9779 // gry chain: pyca/cryptography; chain verifies at GRY_NOW
9780 // chk-leaf-wrong-issuer: signature valid under chk-int key (pyca); issuer = PKIX-WRONG-ISSUER by design
9781
9782 const GRY_NOW: u64 = 1_780_272_000;
9783 const GRY_EXPIRED: u64 = 1_830_384_000;
9784 const GRY_NOTYET: u64 = 0;
9785
9786 fn load(bytes: &[u8]) -> Certificate {
9787 Certificate::from_der(bytes).expect("parse cert")
9788 }
9789
9790 fn policy_at(t: u64) -> ValidationPolicy {
9791 ValidationPolicy::new(t)
9792 }
9793
9794 /// 1-cert chain: self-signed P-256 cert as both chain and anchor.
9795 #[test]
9796 fn single_cert_chain_ok() {
9797 let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
9798 let policy = policy_at(GRY_NOW);
9799 let anchor =
9800 TrustAnchor::from_cert(p256.clone()).expect("fixture CA is a usable trust anchor");
9801 chain_walk(&[p256], &anchor, &policy, &EcdsaP256Verifier)
9802 .expect("1-cert chain must pass chain_walk");
9803 }
9804
9805 /// 2-cert chain (leaf + intermediate) with root as anchor.
9806 ///
9807 /// Oracle: openssl verify -`CAfile` vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
9808 #[test]
9809 fn two_cert_chain_ok() {
9810 let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
9811 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
9812 let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
9813 let policy = policy_at(GRY_NOW);
9814 let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
9815 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier)
9816 .expect("2-cert chain must pass chain_walk");
9817 }
9818
9819 /// Leaf with corrupted signature — last byte flipped.
9820 ///
9821 /// The DER structure remains valid; only the BIT STRING content is wrong.
9822 /// Expect `SignatureInvalid` at chain index 0.
9823 #[test]
9824 fn corrupted_signature_returns_signature_invalid() {
9825 let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
9826 *leaf_der.last_mut().unwrap() ^= 0xFF;
9827 let leaf = Certificate::from_der(&leaf_der).expect("parse still succeeds after bit flip");
9828 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
9829 let anchor = TrustAnchor::from_cert(load(include_bytes!("../tests/fixtures/vxf-root.der")))
9830 .expect("fixture CA is a usable trust anchor");
9831 let policy = policy_at(GRY_NOW);
9832 assert!(
9833 matches!(
9834 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
9835 Err(Error::SignatureInvalid { index: 0 })
9836 ),
9837 "corrupted leaf signature must return SignatureInvalid {{ index: 0 }}"
9838 );
9839 }
9840
9841 /// Chain where the leaf's issuer field does not match the intermediate's subject.
9842 ///
9843 /// Oracle: chk-leaf-wrong-issuer was signed by chk-int's private key
9844 /// (signature IS valid), but its issuer field = "PKIX-WRONG-ISSUER" by design.
9845 #[test]
9846 fn wrong_issuer_name_returns_chain_broken() {
9847 let root = load(include_bytes!("../tests/fixtures/chk-root.der"));
9848 let int_cert = load(include_bytes!("../tests/fixtures/chk-int.der"));
9849 let leaf_wrong = load(include_bytes!(
9850 "../tests/fixtures/chk-leaf-wrong-issuer.der"
9851 ));
9852 let policy = policy_at(GRY_NOW);
9853 let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
9854 assert!(
9855 matches!(
9856 chain_walk(
9857 &[leaf_wrong, int_cert],
9858 &anchor,
9859 &policy,
9860 &EcdsaP256Verifier
9861 ),
9862 Err(Error::ChainBroken { index: 0 })
9863 ),
9864 "leaf with wrong issuer must return ChainBroken {{ index: 0 }}"
9865 );
9866 }
9867
9868 // --- PKIX-gry per-cert check tests ---
9869
9870 /// Expired leaf cert → `ValidityPeriod` at index 0.
9871 ///
9872 /// Oracle: gry-leaf.der has notAfter=2027-01-01; GRY_EXPIRED=2028-01-02.
9873 /// gry-int.der has notAfter=2036-01-01, which is still valid at `GRY_EXPIRED`.
9874 /// Reverse walk: i=1 (gry-int) passes validity, then i=0 (gry-leaf) fails.
9875 #[test]
9876 fn expired_leaf_returns_validity_period() {
9877 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
9878 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
9879 let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
9880 let policy = policy_at(GRY_EXPIRED);
9881 let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
9882 assert!(
9883 matches!(
9884 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
9885 Err(Error::ValidityPeriod { index: 0 })
9886 ),
9887 "expired leaf must return ValidityPeriod {{ index: 0 }}"
9888 );
9889 }
9890
9891 /// Not-yet-valid intermediate → `ValidityPeriod` at index 1.
9892 ///
9893 /// Oracle: gry-int.der has notBefore=2026-01-01; `GRY_NOTYET=0` (1970-01-01).
9894 /// Reverse walk processes chain[1] (gry-int) first; it is not yet valid at time 0.
9895 #[test]
9896 fn notyet_valid_intermediate_returns_validity_period() {
9897 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
9898 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
9899 let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
9900 let policy = policy_at(GRY_NOTYET);
9901 let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
9902 assert!(
9903 matches!(
9904 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
9905 Err(Error::ValidityPeriod { index: 1 })
9906 ),
9907 "not-yet-valid intermediate must return ValidityPeriod {{ index: 1 }}"
9908 );
9909 }
9910
9911 /// Leaf with unknown critical extension → `UnhandledCriticalExtension` at index 0.
9912 ///
9913 /// Oracle: gry-leaf-unknown-crit.der was generated with OID 1.3.6.1.5.5.7.99.99 critical=true
9914 /// (not in `HANDLED_CRITICAL_OIDS`) using pyca/cryptography.
9915 #[test]
9916 fn unknown_critical_extension_returns_unhandled() {
9917 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
9918 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
9919 let leaf_unk = load(include_bytes!(
9920 "../tests/fixtures/gry-leaf-unknown-crit.der"
9921 ));
9922 let policy = policy_at(GRY_NOW);
9923 let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
9924 assert!(
9925 matches!(
9926 chain_walk(&[leaf_unk, int_cert], &anchor, &policy, &EcdsaP256Verifier),
9927 Err(Error::UnhandledCriticalExtension { index: 0 })
9928 ),
9929 "unknown critical ext must return UnhandledCriticalExtension {{ index: 0 }}"
9930 );
9931 }
9932}
9933
9934// ---------------------------------------------------------------------------
9935// Tests: ValidationPolicy profile-enforcement fields (PKIX-ken.1.9–1.13)
9936// ---------------------------------------------------------------------------
9937//
9938// Fixtures: pkix-path/tests/fixtures/policy-checks/
9939// root-p256.der, int-p256.der — P-256 CA chain (ecdsa-sha256)
9940// leaf-p256-365d-san-eku.der — 365-day leaf, SAN=DNS:test.example.com, EKU=serverAuth
9941// leaf-p256-400d-san-eku.der — 400-day leaf, SAN, EKU=serverAuth
9942// leaf-p256-365d-no-san.der — 365-day leaf, no SAN extension
9943// leaf-p256-365d-no-eku.der — 365-day leaf, SAN, no EKU extension
9944// leaf-p256-365d-wrong-eku.der— 365-day leaf, SAN, EKU=emailProtection only
9945// root-rsa2048.der, int-rsa2048.der — RSA-2048 CA chain (sha256WithRSAEncryption)
9946// leaf-rsa2048-365d-san-eku.der — RSA-2048 leaf, SAN, EKU=serverAuth
9947// leaf-rsa1024-365d-san-eku.der — RSA-1024 leaf, SAN, EKU=serverAuth
9948//
9949// Oracle: pkix-path/tests/fixtures/policy-checks/gen.py (pyca/cryptography)
9950// Chain verification: openssl verify passed for P-256 and RSA-2048 happy paths.
9951// Time constant: PC_NOW = 2026-06-01T00:00:00Z = 1_780_272_000 (unix)
9952// All fixtures have NOT_BEFORE=2026-01-01, valid at PC_NOW.
9953//
9954// All tests require the p256 feature for P-256 chain tests, and rsa for RSA chain tests.
9955//
9956// The P-256 chain uses the module-level const directly; RSA chain tests live inside
9957// a separate rsa-feature-gated block so clippy does not warn about unused imports.
9958
9959#[cfg(all(test, feature = "p256"))]
9960mod tests_policy_fields {
9961 use super::*;
9962 use der::Decode;
9963
9964 // GRY_NOW is also the test time for these fixtures (2026-06-01T00:00:00Z).
9965 const PC_NOW: u64 = 1_780_272_000;
9966
9967 // OID constants — values from const_oid spec, NOT derived from the code under test.
9968 // ecdsa-with-SHA256: 1.2.840.10045.4.3.2 (RFC 5912 §6)
9969 const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
9970 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
9971 // sha256WithRSAEncryption: 1.2.840.113549.1.1.11 (RFC 5912 §2)
9972 const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
9973 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
9974 // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1 (RFC 5280 §4.2.1.12)
9975 const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
9976 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
9977 // id-kp-emailProtection: 1.3.6.1.5.5.7.3.4 (RFC 5280 §4.2.1.12)
9978 const ID_KP_EMAIL_PROTECTION: der::asn1::ObjectIdentifier =
9979 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4");
9980
9981 fn load(bytes: &[u8]) -> Certificate {
9982 Certificate::from_der(bytes).expect("valid DER fixture")
9983 }
9984
9985 // -----------------------------------------------------------------------
9986 // max_validity_secs (PKIX-ken.1.9)
9987 // -----------------------------------------------------------------------
9988
9989 /// Oracle: all certs in the chain have validity ≤ 3652 days (10-year root/int,
9990 /// 365-day leaf). A cap of 4000 days allows all of them through.
9991 #[test]
9992 fn max_validity_passes_when_cert_within_limit() {
9993 let root = load(include_bytes!(
9994 "../tests/fixtures/policy-checks/root-p256.der"
9995 ));
9996 let int_cert = load(include_bytes!(
9997 "../tests/fixtures/policy-checks/int-p256.der"
9998 ));
9999 let leaf = load(include_bytes!(
10000 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10001 ));
10002 let mut policy = ValidationPolicy::new(PC_NOW);
10003 // 4000-day cap: root/int have ~3652 days, leaf has 365 days — all within limit.
10004 policy.max_validity_secs = Some(4_000 * 86_400);
10005 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10006 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10007 .expect("all certs within 4000-day cap should validate");
10008 }
10009
10010 /// Oracle: root-p256.der and int-p256.der each have ~3652-day validity
10011 /// (NOT_BEFORE=2026-01-01, NOT_AFTER=2036-01-01 from gen.py).
10012 /// A cap of 400 days forces `ValidityPeriodExceedsMax` on the root (checked first
10013 /// by `chain_walk` which iterates from high index to low).
10014 ///
10015 /// Note: the check applies to every cert in the chain, not just the leaf.
10016 /// The root cert (highest index) is checked first and produces the error.
10017 #[test]
10018 fn max_validity_fails_when_cert_exceeds_limit() {
10019 let root = load(include_bytes!(
10020 "../tests/fixtures/policy-checks/root-p256.der"
10021 ));
10022 let int_cert = load(include_bytes!(
10023 "../tests/fixtures/policy-checks/int-p256.der"
10024 ));
10025 let leaf = load(include_bytes!(
10026 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10027 ));
10028 let mut policy = ValidationPolicy::new(PC_NOW);
10029 // 400-day cap: root/int have 3652-day validity → ValidityPeriodExceedsMax.
10030 // Wildcard index because the root (highest-index cert) is checked first.
10031 policy.max_validity_secs = Some(400 * 86_400);
10032 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10033 assert!(
10034 matches!(
10035 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10036 Err(Error::ValidityPeriodExceedsMax { .. })
10037 ),
10038 "certs with 3652-day validity over 400-day cap must return ValidityPeriodExceedsMax"
10039 );
10040 }
10041
10042 /// Isolates the leaf-only failure: use a 1-cert self-issued chain where
10043 /// the cert acts as both leaf and anchor. The 400-day cert fails a 398-day cap.
10044 ///
10045 /// Oracle: leaf-p256-400d-san-eku.der has notAfter-notBefore = 400 days = 34,560,000 s.
10046 /// 400 days > 398 days → `ValidityPeriodExceedsMax` { index: 0 }.
10047 #[test]
10048 fn max_validity_fails_at_leaf_index_zero() {
10049 // Use a single self-signed cert as both chain[0] and anchor so there is only
10050 // one cert in the chain, making index 0 the only possible failure point.
10051 // leaf-p256-400d-san-eku.der is NOT self-signed, so we use a known self-signed
10052 // cert from the existing fixture set (ec-p256-sha256.der) which has a long
10053 // validity, then set max to 1 day to force failure at index 0.
10054 let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
10055 .expect("parse ec-p256-sha256.der");
10056 let anchors =
10057 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
10058 let mut policy = ValidationPolicy::new(1_780_272_000); // PC_NOW: 2026-06-01
10059 // 1-day cap: the cert has multi-year validity → fails at index 0.
10060 policy.max_validity_secs = Some(86_400);
10061 assert!(
10062 matches!(
10063 validate_path(&[cert], &anchors, &policy, &EcdsaP256Verifier),
10064 Err(Error::ValidityPeriodExceedsMax { index: 0 })
10065 ),
10066 "1-cert chain: long-validity cert with 1-day cap must return ValidityPeriodExceedsMax {{ index: 0 }}"
10067 );
10068 }
10069
10070 /// The cap is a maximum, so a cert whose validity is exactly the cap
10071 /// passes and one second more fails.
10072 ///
10073 /// Both bounds come from the fixture rather than from a constant here:
10074 /// the test asks "is the comparison inclusive at the documented end",
10075 /// and a hard-coded duration would make it ask whether the fixture
10076 /// still has the duration it had when the test was written. The other
10077 /// tests in this section are all orders of magnitude away from the
10078 /// boundary, so `>` read as `>=` left them all passing.
10079 #[test]
10080 fn max_validity_admits_a_cert_exactly_at_the_cap() {
10081 let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
10082 .expect("parse ec-p256-sha256.der");
10083 let validity = cert.tbs_certificate().validity();
10084 let exact = validity.not_after.to_unix_duration().as_secs()
10085 - validity.not_before.to_unix_duration().as_secs();
10086 let anchors =
10087 [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
10088
10089 let mut policy = ValidationPolicy::new(1_780_272_000); // 2026-06-01
10090 policy.max_validity_secs = Some(exact);
10091 validate_path(
10092 core::slice::from_ref(&cert),
10093 &anchors,
10094 &policy,
10095 &EcdsaP256Verifier,
10096 )
10097 .expect("a validity period equal to the cap is within the cap");
10098
10099 policy.max_validity_secs = Some(exact - 1);
10100 assert!(
10101 matches!(
10102 validate_path(
10103 core::slice::from_ref(&cert),
10104 &anchors,
10105 &policy,
10106 &EcdsaP256Verifier
10107 ),
10108 Err(Error::ValidityPeriodExceedsMax { index: 0 })
10109 ),
10110 "one second over the cap must be refused"
10111 );
10112 }
10113
10114 /// Oracle: None = unconstrained, any validity length is accepted.
10115 #[test]
10116 fn max_validity_none_is_unconstrained() {
10117 let root = load(include_bytes!(
10118 "../tests/fixtures/policy-checks/root-p256.der"
10119 ));
10120 let int_cert = load(include_bytes!(
10121 "../tests/fixtures/policy-checks/int-p256.der"
10122 ));
10123 let leaf = load(include_bytes!(
10124 "../tests/fixtures/policy-checks/leaf-p256-400d-san-eku.der"
10125 ));
10126 let mut policy = ValidationPolicy::new(PC_NOW);
10127 policy.max_validity_secs = None; // default, but explicit for documentation
10128 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10129 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10130 .expect("None cap must accept any validity length");
10131 }
10132
10133 // -----------------------------------------------------------------------
10134 // allowed_signature_algs (PKIX-ken.1.10)
10135 // -----------------------------------------------------------------------
10136
10137 /// Oracle: P-256 chain uses ecdsa-with-SHA256; allowlist contains that OID.
10138 #[test]
10139 fn alg_allowlist_passes_when_oid_in_list() {
10140 let root = load(include_bytes!(
10141 "../tests/fixtures/policy-checks/root-p256.der"
10142 ));
10143 let int_cert = load(include_bytes!(
10144 "../tests/fixtures/policy-checks/int-p256.der"
10145 ));
10146 let leaf = load(include_bytes!(
10147 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10148 ));
10149 let mut policy = ValidationPolicy::new(PC_NOW);
10150 policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
10151 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10152 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10153 .expect("ECDSA-SHA256 chain with ECDSA-SHA256 allowlist should pass");
10154 }
10155
10156 /// Oracle: P-256 chain uses ecdsa-sha256; allowlist contains only RSA-sha256.
10157 /// `chain_walk` walks highest index first: leaf=[0], int=[1], root=[2].
10158 /// For a 3-cert chain, the root-adjacent cert is at index 2 in the slice.
10159 /// `chain_walk` iterates i from (chain.len()-1) down to 0, so i=2 (root) is checked
10160 /// first and fails with `AlgorithmNotAllowed` { index: 2 }.
10161 #[test]
10162 fn alg_allowlist_fails_when_oid_not_in_list() {
10163 let root = load(include_bytes!(
10164 "../tests/fixtures/policy-checks/root-p256.der"
10165 ));
10166 let int_cert = load(include_bytes!(
10167 "../tests/fixtures/policy-checks/int-p256.der"
10168 ));
10169 let leaf = load(include_bytes!(
10170 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10171 ));
10172 let mut policy = ValidationPolicy::new(PC_NOW);
10173 // Only RSA allowed, but chain uses ECDSA.
10174 policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
10175 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10176 assert!(
10177 matches!(
10178 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10179 Err(Error::AlgorithmNotAllowed { .. })
10180 ),
10181 "ECDSA chain with RSA-only allowlist must return AlgorithmNotAllowed"
10182 );
10183 }
10184
10185 /// Oracle: None = unconstrained, any algorithm is accepted.
10186 #[test]
10187 fn alg_allowlist_none_is_unconstrained() {
10188 let root = load(include_bytes!(
10189 "../tests/fixtures/policy-checks/root-p256.der"
10190 ));
10191 let int_cert = load(include_bytes!(
10192 "../tests/fixtures/policy-checks/int-p256.der"
10193 ));
10194 let leaf = load(include_bytes!(
10195 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10196 ));
10197 let mut policy = ValidationPolicy::new(PC_NOW);
10198 policy.allowed_signature_algs = None; // default
10199 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10200 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10201 .expect("None allowlist must accept any algorithm");
10202 }
10203
10204 // -----------------------------------------------------------------------
10205 // require_subject_alt_name (PKIX-ken.1.12)
10206 // -----------------------------------------------------------------------
10207
10208 /// Oracle: leaf-p256-365d-san-eku.der has SAN=DNS:test.example.com.
10209 #[test]
10210 fn require_san_passes_when_san_present() {
10211 let root = load(include_bytes!(
10212 "../tests/fixtures/policy-checks/root-p256.der"
10213 ));
10214 let int_cert = load(include_bytes!(
10215 "../tests/fixtures/policy-checks/int-p256.der"
10216 ));
10217 let leaf = load(include_bytes!(
10218 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10219 ));
10220 let mut policy = ValidationPolicy::new(PC_NOW);
10221 policy.require_subject_alt_name = true;
10222 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10223 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10224 .expect("leaf with SAN must pass require_subject_alt_name=true");
10225 }
10226
10227 /// Oracle: leaf-p256-365d-no-san.der has no SAN extension.
10228 #[test]
10229 fn require_san_fails_when_san_absent() {
10230 let root = load(include_bytes!(
10231 "../tests/fixtures/policy-checks/root-p256.der"
10232 ));
10233 let int_cert = load(include_bytes!(
10234 "../tests/fixtures/policy-checks/int-p256.der"
10235 ));
10236 let leaf = load(include_bytes!(
10237 "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
10238 ));
10239 let mut policy = ValidationPolicy::new(PC_NOW);
10240 policy.require_subject_alt_name = true;
10241 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10242 assert!(
10243 matches!(
10244 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10245 Err(Error::MissingSan)
10246 ),
10247 "leaf without SAN must return MissingSan when require_subject_alt_name=true"
10248 );
10249 }
10250
10251 /// Oracle: false = default = no SAN requirement; missing SAN is not an error.
10252 #[test]
10253 fn require_san_false_does_not_fail_on_missing_san() {
10254 let root = load(include_bytes!(
10255 "../tests/fixtures/policy-checks/root-p256.der"
10256 ));
10257 let int_cert = load(include_bytes!(
10258 "../tests/fixtures/policy-checks/int-p256.der"
10259 ));
10260 let leaf = load(include_bytes!(
10261 "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
10262 ));
10263 let mut policy = ValidationPolicy::new(PC_NOW);
10264 policy.require_subject_alt_name = false; // default, explicit for documentation
10265 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10266 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10267 .expect("require_subject_alt_name=false must not fail on missing SAN");
10268 }
10269
10270 /// Regression guard for the i == 0 guard in `chain_walk`.
10271 ///
10272 /// int-p256.der has no SAN extension. With `require_subject_alt_name=true`,
10273 /// the check MUST NOT fail on the intermediate (i == 1). Only the leaf
10274 /// (i == 0) is checked.
10275 ///
10276 /// Oracle: openssl x509 -inform DER -in int-p256.der -text -noout | grep -i alt
10277 /// → empty output; int-p256.der has no SAN. Confirmed during fixture generation.
10278 #[test]
10279 fn require_san_only_checks_leaf_not_intermediates() {
10280 let root = load(include_bytes!(
10281 "../tests/fixtures/policy-checks/root-p256.der"
10282 ));
10283 let int_cert = load(include_bytes!(
10284 "../tests/fixtures/policy-checks/int-p256.der"
10285 ));
10286 // The leaf HAS a SAN; the intermediate does NOT.
10287 let leaf = load(include_bytes!(
10288 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10289 ));
10290 let mut policy = ValidationPolicy::new(PC_NOW);
10291 policy.require_subject_alt_name = true;
10292 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10293 // Must pass: the SAN-less intermediate is not checked, only the leaf.
10294 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10295 .expect("i==0 guard must ensure only the leaf is checked for SAN presence");
10296 }
10297
10298 // -----------------------------------------------------------------------
10299 // required_leaf_eku (PKIX-ken.1.13)
10300 // -----------------------------------------------------------------------
10301
10302 /// Oracle: leaf-p256-365d-san-eku.der has EKU=serverAuth (1.3.6.1.5.5.7.3.1).
10303 #[test]
10304 fn required_eku_passes_when_all_oids_present() {
10305 let root = load(include_bytes!(
10306 "../tests/fixtures/policy-checks/root-p256.der"
10307 ));
10308 let int_cert = load(include_bytes!(
10309 "../tests/fixtures/policy-checks/int-p256.der"
10310 ));
10311 let leaf = load(include_bytes!(
10312 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10313 ));
10314 let mut policy = ValidationPolicy::new(PC_NOW);
10315 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
10316 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10317 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10318 .expect("leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
10319 }
10320
10321 /// Oracle: leaf-p256-365d-no-eku.der has no EKU extension.
10322 /// `required_leaf_eku=Some`([serverAuth]) with absent EKU → `MissingEku`.
10323 #[test]
10324 fn required_eku_fails_when_eku_extension_absent() {
10325 let root = load(include_bytes!(
10326 "../tests/fixtures/policy-checks/root-p256.der"
10327 ));
10328 let int_cert = load(include_bytes!(
10329 "../tests/fixtures/policy-checks/int-p256.der"
10330 ));
10331 let leaf = load(include_bytes!(
10332 "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
10333 ));
10334 let mut policy = ValidationPolicy::new(PC_NOW);
10335 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
10336 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10337 assert!(
10338 matches!(
10339 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10340 Err(Error::MissingEku)
10341 ),
10342 "leaf without EKU extension must return MissingEku when an EKU OID is required"
10343 );
10344 }
10345
10346 /// Oracle: leaf-p256-365d-wrong-eku.der has EKU=emailProtection only, not serverAuth.
10347 #[test]
10348 fn required_eku_fails_when_required_oid_not_in_list() {
10349 let root = load(include_bytes!(
10350 "../tests/fixtures/policy-checks/root-p256.der"
10351 ));
10352 let int_cert = load(include_bytes!(
10353 "../tests/fixtures/policy-checks/int-p256.der"
10354 ));
10355 let leaf = load(include_bytes!(
10356 "../tests/fixtures/policy-checks/leaf-p256-365d-wrong-eku.der"
10357 ));
10358 let mut policy = ValidationPolicy::new(PC_NOW);
10359 // Requires serverAuth; leaf only has emailProtection.
10360 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
10361 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10362 assert!(
10363 matches!(
10364 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10365 Err(Error::MissingEku)
10366 ),
10367 "leaf with wrong EKU must return MissingEku when required OID is absent"
10368 );
10369 }
10370
10371 /// Oracle: None = no EKU requirement; missing EKU is not an error.
10372 #[test]
10373 fn required_eku_none_is_unconstrained() {
10374 let root = load(include_bytes!(
10375 "../tests/fixtures/policy-checks/root-p256.der"
10376 ));
10377 let int_cert = load(include_bytes!(
10378 "../tests/fixtures/policy-checks/int-p256.der"
10379 ));
10380 let leaf = load(include_bytes!(
10381 "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
10382 ));
10383 let mut policy = ValidationPolicy::new(PC_NOW);
10384 policy.required_leaf_eku = None; // default
10385 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10386 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10387 .expect("None required_leaf_eku must accept leaf with no EKU");
10388 }
10389
10390 /// Oracle: Some([]) = require zero OIDs → trivially passes regardless of EKU content.
10391 #[test]
10392 fn required_eku_empty_vec_is_unconstrained() {
10393 let root = load(include_bytes!(
10394 "../tests/fixtures/policy-checks/root-p256.der"
10395 ));
10396 let int_cert = load(include_bytes!(
10397 "../tests/fixtures/policy-checks/int-p256.der"
10398 ));
10399 let leaf = load(include_bytes!(
10400 "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
10401 ));
10402 let mut policy = ValidationPolicy::new(PC_NOW);
10403 // Empty vec: Some([]) requires zero OIDs → always passes.
10404 policy.required_leaf_eku = Some(vec![]);
10405 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10406 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10407 .expect("Some([]) required_leaf_eku (empty) must accept any EKU configuration");
10408 }
10409
10410 /// Verify that emailProtection in `required_leaf_eku` does NOT match serverAuth in the cert.
10411 /// This guards against a hypothetical relaxed OID comparison bug.
10412 #[test]
10413 fn required_eku_emailprotection_does_not_match_serverauth() {
10414 let root = load(include_bytes!(
10415 "../tests/fixtures/policy-checks/root-p256.der"
10416 ));
10417 let int_cert = load(include_bytes!(
10418 "../tests/fixtures/policy-checks/int-p256.der"
10419 ));
10420 let leaf = load(include_bytes!(
10421 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10422 ));
10423 let mut policy = ValidationPolicy::new(PC_NOW);
10424 // Require emailProtection; leaf only has serverAuth.
10425 policy.required_leaf_eku = Some(vec![ID_KP_EMAIL_PROTECTION]);
10426 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10427 assert!(
10428 matches!(
10429 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10430 Err(Error::MissingEku)
10431 ),
10432 "OID comparison must be exact; emailProtection must not match serverAuth"
10433 );
10434 }
10435}
10436
10437// DnAttrRule + required_leaf_policy_oids + required_leaf_subject_dn_attrs tests (PKIX-jbvb.4).
10438//
10439// Coverage strategy:
10440// - `dn_attr_rule_*` tests exercise `evaluate_dn_attr_rule` and `dn_contains_oid`
10441// directly against synthetic `Name` values constructed via RFC 4514 string
10442// parsing. This isolates rule semantics from chain-validation wiring.
10443// - `validate_path_*` tests exercise the (e3a)/(e3b) enforcement sites in
10444// `chain_walk` via existing committed P-256 fixtures. Existing fixtures lack
10445// `CertificatePolicies` extensions and have CN-only Subject DNs, so they
10446// naturally test the "required attribute missing" paths.
10447// - The `None`-case sanity tests confirm default behavior is unchanged.
10448//
10449// Positive `validate_path` cases for `required_leaf_policy_oids` (leaf asserts
10450// the required OID → pass) are covered indirectly: the (e3a) match arm with
10451// `Some(cp_ext)` is unit-tested via the `dn_contains_oid`-style helper logic on
10452// `policy_identifier`, and the wiring is exercised by the negative tests.
10453// Adding a new fixture solely for the positive path would duplicate that
10454// coverage without adding rigor; the bead's "existing fixtures cannot exercise"
10455// escape applies to the OID-list-walk shape, not the wiring.
10456#[cfg(test)]
10457mod tests_dn_attr_rule {
10458 use super::*;
10459 use core::str::FromStr;
10460
10461 // RFC 4519 / X.520 DN attribute OIDs (values from spec, not derived from code under test).
10462 const OID_CN: der::asn1::ObjectIdentifier = der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
10463 const OID_SURNAME: der::asn1::ObjectIdentifier =
10464 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.4");
10465 const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
10466 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
10467 const OID_GIVEN_NAME: der::asn1::ObjectIdentifier =
10468 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.42");
10469 const OID_PSEUDONYM: der::asn1::ObjectIdentifier =
10470 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.65");
10471
10472 fn dn(s: &str) -> x509_cert::name::Name {
10473 x509_cert::name::Name::from_str(s).expect("valid RFC 4514 DN string")
10474 }
10475
10476 // ---- dn_contains_oid -----------------------------------------------------
10477
10478 #[test]
10479 fn dn_contains_oid_finds_present_attribute() {
10480 let subject = dn("CN=test,O=Test Org");
10481 assert!(dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
10482 assert!(dn_contains_oid(&subject, &OID_CN));
10483 }
10484
10485 #[test]
10486 fn dn_contains_oid_returns_false_for_absent_attribute() {
10487 let subject = dn("CN=test");
10488 assert!(!dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
10489 assert!(!dn_contains_oid(&subject, &OID_SURNAME));
10490 }
10491
10492 #[test]
10493 fn dn_contains_oid_empty_subject_matches_nothing() {
10494 let subject = x509_cert::name::Name::default();
10495 assert!(!dn_contains_oid(&subject, &OID_CN));
10496 }
10497
10498 // ---- evaluate_dn_attr_rule: Field ---------------------------------------
10499
10500 #[test]
10501 fn rule_field_matches_when_attribute_present() {
10502 let subject = dn("CN=test,O=Test Org");
10503 let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
10504 assert!(evaluate_dn_attr_rule(&subject, &rule));
10505 }
10506
10507 #[test]
10508 fn rule_field_rejects_when_attribute_absent() {
10509 let subject = dn("CN=test");
10510 let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
10511 assert!(!evaluate_dn_attr_rule(&subject, &rule));
10512 }
10513
10514 // ---- evaluate_dn_attr_rule: AllOf composition ---------------------------
10515
10516 #[test]
10517 fn rule_allof_matches_when_every_branch_satisfied() {
10518 let subject = dn("CN=test,givenName=Alice,surname=Smith");
10519 let rule = DnAttrRule::AllOf(vec![
10520 DnAttrRule::Field(OID_GIVEN_NAME),
10521 DnAttrRule::Field(OID_SURNAME),
10522 ]);
10523 assert!(evaluate_dn_attr_rule(&subject, &rule));
10524 }
10525
10526 #[test]
10527 fn rule_allof_rejects_when_any_branch_missing() {
10528 let subject = dn("CN=test,givenName=Alice");
10529 let rule = DnAttrRule::AllOf(vec![
10530 DnAttrRule::Field(OID_GIVEN_NAME),
10531 DnAttrRule::Field(OID_SURNAME),
10532 ]);
10533 assert!(!evaluate_dn_attr_rule(&subject, &rule));
10534 }
10535
10536 // ---- evaluate_dn_attr_rule: AnyOf composition ---------------------------
10537
10538 #[test]
10539 fn rule_anyof_matches_when_at_least_one_branch_satisfied() {
10540 let subject = dn("CN=test,pseudonym=BlueFox");
10541 let rule = DnAttrRule::AnyOf(vec![
10542 DnAttrRule::Field(OID_PSEUDONYM),
10543 DnAttrRule::AllOf(vec![
10544 DnAttrRule::Field(OID_GIVEN_NAME),
10545 DnAttrRule::Field(OID_SURNAME),
10546 ]),
10547 ]);
10548 assert!(evaluate_dn_attr_rule(&subject, &rule));
10549 }
10550
10551 #[test]
10552 fn rule_anyof_rejects_when_no_branch_satisfied() {
10553 let subject = dn("CN=test");
10554 let rule = DnAttrRule::AnyOf(vec![
10555 DnAttrRule::Field(OID_PSEUDONYM),
10556 DnAttrRule::AllOf(vec![
10557 DnAttrRule::Field(OID_GIVEN_NAME),
10558 DnAttrRule::Field(OID_SURNAME),
10559 ]),
10560 ]);
10561 assert!(!evaluate_dn_attr_rule(&subject, &rule));
10562 }
10563
10564 /// Sponsor-validated-style rule (pseudonym OR (givenName AND surname))
10565 /// also matches when both branches of the inner `AllOf` are present.
10566 #[test]
10567 fn rule_anyof_matches_when_inner_allof_branch_satisfied() {
10568 let subject = dn("CN=test,givenName=Alice,surname=Smith");
10569 let rule = DnAttrRule::AnyOf(vec![
10570 DnAttrRule::Field(OID_PSEUDONYM),
10571 DnAttrRule::AllOf(vec![
10572 DnAttrRule::Field(OID_GIVEN_NAME),
10573 DnAttrRule::Field(OID_SURNAME),
10574 ]),
10575 ]);
10576 assert!(evaluate_dn_attr_rule(&subject, &rule));
10577 }
10578
10579 // ---- evaluate_dn_attr_rule: vacuity -------------------------------------
10580
10581 /// RFC-conventional vacuity: `AllOf` with no branches is trivially true
10582 /// (the universal quantifier over an empty set is true).
10583 #[test]
10584 fn rule_allof_empty_accepts_everything() {
10585 let empty = x509_cert::name::Name::default();
10586 let cn_only = dn("CN=test");
10587 let rule = DnAttrRule::AllOf(Vec::new());
10588 assert!(evaluate_dn_attr_rule(&empty, &rule));
10589 assert!(evaluate_dn_attr_rule(&cn_only, &rule));
10590 }
10591
10592 /// RFC-conventional vacuity: `AnyOf` with no branches is trivially false
10593 /// (the existential quantifier over an empty set is false).
10594 #[test]
10595 fn rule_anyof_empty_rejects_everything() {
10596 let empty = x509_cert::name::Name::default();
10597 let cn_only = dn("CN=test");
10598 let rule = DnAttrRule::AnyOf(Vec::new());
10599 assert!(!evaluate_dn_attr_rule(&empty, &rule));
10600 assert!(!evaluate_dn_attr_rule(&cn_only, &rule));
10601 }
10602}
10603
10604// ---------------------------------------------------------------------------
10605// required_leaf_policy_oids + required_leaf_subject_dn_attrs validate_path wiring
10606// (PKIX-jbvb.4). Reuses existing P-256 fixtures (which carry single-attribute
10607// CN-only DNs and no CertificatePolicies extension) to cover the negative and
10608// disabled-default paths.
10609// ---------------------------------------------------------------------------
10610#[cfg(all(test, feature = "p256"))]
10611mod tests_required_leaf_policy_dn {
10612 use super::*;
10613 use der::Decode;
10614
10615 // GRY_NOW = 2026-06-01T00:00:00Z (matches the existing P-256 fixture timestamps).
10616 const PC_NOW: u64 = 1_780_272_000;
10617
10618 // 2.16.840.1.101.3.2.1.48.1 — a NIST test policy OID. The chosen value is
10619 // arbitrary; only its absence from any committed fixture matters.
10620 const TEST_POLICY_OID: der::asn1::ObjectIdentifier =
10621 der::asn1::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.2.1.48.1");
10622 const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
10623 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
10624
10625 fn load(bytes: &[u8]) -> Certificate {
10626 Certificate::from_der(bytes).expect("valid DER fixture")
10627 }
10628
10629 fn make_chain() -> (Certificate, Certificate, Certificate) {
10630 let root = load(include_bytes!(
10631 "../tests/fixtures/policy-checks/root-p256.der"
10632 ));
10633 let int_cert = load(include_bytes!(
10634 "../tests/fixtures/policy-checks/int-p256.der"
10635 ));
10636 let leaf = load(include_bytes!(
10637 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10638 ));
10639 (root, int_cert, leaf)
10640 }
10641
10642 /// Oracle: `leaf-p256-365d-san-eku.der` has no `CertificatePolicies`
10643 /// extension. Requiring any specific policy OID must fail.
10644 #[test]
10645 fn required_policy_oid_fails_when_extension_absent() {
10646 let (root, int_cert, leaf) = make_chain();
10647 let mut policy = ValidationPolicy::new(PC_NOW);
10648 policy.required_leaf_policy_oids = Some(vec![TEST_POLICY_OID]);
10649 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10650 let err = validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10651 .expect_err("leaf without CertificatePolicies must fail when an OID is required");
10652 match err {
10653 Error::MissingLeafPolicyOid { required } => {
10654 assert_eq!(required, TEST_POLICY_OID, "reported OID must echo input");
10655 }
10656 other => panic!("expected MissingLeafPolicyOid, got {other:?}"),
10657 }
10658 }
10659
10660 /// Oracle: `None` requirement is unconstrained even when the leaf has no
10661 /// `CertificatePolicies` extension. Backward-compatible default.
10662 #[test]
10663 fn required_policy_oid_none_is_unconstrained() {
10664 let (root, int_cert, leaf) = make_chain();
10665 let mut policy = ValidationPolicy::new(PC_NOW);
10666 policy.required_leaf_policy_oids = None;
10667 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10668 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10669 .expect("None required_leaf_policy_oids must not constrain validation");
10670 }
10671
10672 /// Oracle: `Some(vec![])` requires zero OIDs → trivially passes regardless
10673 /// of `CertificatePolicies` content (mirrors `required_leaf_eku = Some(vec![])`).
10674 #[test]
10675 fn required_policy_oid_empty_vec_is_unconstrained() {
10676 let (root, int_cert, leaf) = make_chain();
10677 let mut policy = ValidationPolicy::new(PC_NOW);
10678 policy.required_leaf_policy_oids = Some(vec![]);
10679 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10680 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10681 .expect("Some([]) required_leaf_policy_oids must accept any CertificatePolicies");
10682 }
10683
10684 /// Oracle: `leaf-p256-365d-san-eku.der` has Subject DN
10685 /// `CN=PKIX-policy-checks-leaf-p256-365d-san-eku` (no organizationName).
10686 /// Requiring `organizationName` must fail with `SubjectDnAttrRuleUnmet`.
10687 #[test]
10688 fn required_dn_attr_field_fails_when_attribute_absent() {
10689 let (root, int_cert, leaf) = make_chain();
10690 let mut policy = ValidationPolicy::new(PC_NOW);
10691 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(OID_ORGANIZATION_NAME));
10692 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10693 assert!(
10694 matches!(
10695 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10696 Err(Error::SubjectDnAttrRuleUnmet)
10697 ),
10698 "leaf without organizationName must return SubjectDnAttrRuleUnmet"
10699 );
10700 }
10701
10702 /// Oracle: `leaf-p256-365d-san-eku.der` has only `CN=...`.
10703 /// `Field(CN)` must succeed (the attribute is present).
10704 #[test]
10705 fn required_dn_attr_field_passes_when_attribute_present() {
10706 let (root, int_cert, leaf) = make_chain();
10707 let mut policy = ValidationPolicy::new(PC_NOW);
10708 // CN = 2.5.4.3
10709 let oid_cn: der::asn1::ObjectIdentifier =
10710 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
10711 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(oid_cn));
10712 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10713 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10714 .expect("leaf with CN must pass Field(CN) requirement");
10715 }
10716
10717 /// Oracle: AllOf(vec![]) is vacuously true; chain must validate without
10718 /// any DN constraints actually being checked.
10719 #[test]
10720 fn required_dn_attr_allof_empty_accepts_any_leaf() {
10721 let (root, int_cert, leaf) = make_chain();
10722 let mut policy = ValidationPolicy::new(PC_NOW);
10723 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AllOf(Vec::new()));
10724 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10725 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10726 .expect("AllOf(vec![]) is vacuously true; validation must succeed");
10727 }
10728
10729 /// Oracle: AnyOf(vec![]) is vacuously false; any leaf fails.
10730 #[test]
10731 fn required_dn_attr_anyof_empty_rejects_any_leaf() {
10732 let (root, int_cert, leaf) = make_chain();
10733 let mut policy = ValidationPolicy::new(PC_NOW);
10734 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AnyOf(Vec::new()));
10735 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10736 assert!(
10737 matches!(
10738 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
10739 Err(Error::SubjectDnAttrRuleUnmet)
10740 ),
10741 "AnyOf(vec![]) is vacuously false; validation must fail"
10742 );
10743 }
10744
10745 /// Oracle: `None` is the default and must not constrain validation.
10746 #[test]
10747 fn required_dn_attr_none_is_unconstrained() {
10748 let (root, int_cert, leaf) = make_chain();
10749 let mut policy = ValidationPolicy::new(PC_NOW);
10750 policy.required_leaf_subject_dn_attrs = None;
10751 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10752 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10753 .expect("None required_leaf_subject_dn_attrs must not constrain validation");
10754 }
10755}
10756
10757// RSA-specific policy field tests — gated on the rsa feature.
10758#[cfg(all(test, feature = "p256", feature = "rsa"))]
10759mod tests_policy_fields_rsa {
10760 use super::*;
10761 use der::Decode;
10762
10763 const PC_NOW: u64 = 1_780_272_000;
10764
10765 // sha256WithRSAEncryption: 1.2.840.113549.1.1.11 (RFC 5912 §2)
10766 const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
10767 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
10768 // ecdsa-with-SHA256: 1.2.840.10045.4.3.2 (RFC 5912 §6)
10769 const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
10770 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
10771 // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1
10772 const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
10773 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
10774
10775 fn load(bytes: &[u8]) -> Certificate {
10776 Certificate::from_der(bytes).expect("valid DER fixture")
10777 }
10778
10779 // -----------------------------------------------------------------------
10780 // min_rsa_key_bits helper unit tests (PKIX-ken.1.11)
10781 // -----------------------------------------------------------------------
10782
10783 /// Direct unit test of `rsa_public_key_bits` helper.
10784 /// Oracle: openssl x509 -inform DER -in leaf-rsa2048.der -text -noout | grep 'Public-Key'
10785 /// → Public-Key: (2048 bit)
10786 #[test]
10787 fn rsa_key_bits_correct_for_2048_key() {
10788 let cert = load(include_bytes!(
10789 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
10790 ));
10791 let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
10792 assert_eq!(
10793 result,
10794 Some(2048),
10795 "RSA-2048 key must return Some(2048) from rsa_public_key_bits"
10796 );
10797 }
10798
10799 /// Direct unit test of `rsa_public_key_bits` helper.
10800 /// Oracle: openssl x509 -inform DER -in leaf-rsa1024.der -text -noout | grep 'Public-Key'
10801 /// → Public-Key: (1024 bit)
10802 #[test]
10803 fn rsa_key_bits_correct_for_1024_key() {
10804 let cert = load(include_bytes!(
10805 "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
10806 ));
10807 let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
10808 assert_eq!(
10809 result,
10810 Some(1024),
10811 "RSA-1024 key must return Some(1024) from rsa_public_key_bits"
10812 );
10813 }
10814
10815 /// Direct unit test of `rsa_public_key_bits` helper.
10816 /// P-256 key is not RSA; must return None.
10817 #[test]
10818 fn rsa_key_bits_none_for_ec_key() {
10819 let cert = load(include_bytes!(
10820 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10821 ));
10822 let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
10823 assert_eq!(
10824 result, None,
10825 "EC key must return None from rsa_public_key_bits (not RSA)"
10826 );
10827 }
10828
10829 // -----------------------------------------------------------------------
10830 // min_rsa_key_bits validate_path tests (PKIX-ken.1.11)
10831 // -----------------------------------------------------------------------
10832
10833 /// Oracle: leaf-rsa2048-365d-san-eku.der has RSA-2048 leaf.
10834 /// 2048 >= 2048 → passes.
10835 #[test]
10836 fn min_rsa_key_bits_passes_when_key_meets_limit() {
10837 let root = load(include_bytes!(
10838 "../tests/fixtures/policy-checks/root-rsa2048.der"
10839 ));
10840 let int_cert = load(include_bytes!(
10841 "../tests/fixtures/policy-checks/int-rsa2048.der"
10842 ));
10843 let leaf = load(include_bytes!(
10844 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
10845 ));
10846 let mut policy = ValidationPolicy::new(PC_NOW);
10847 policy.min_rsa_key_bits = Some(2048);
10848 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10849 validate_path(
10850 &[leaf, int_cert],
10851 &anchors,
10852 &policy,
10853 &RsaPkcs1v15Sha256Verifier,
10854 )
10855 .expect("RSA-2048 leaf with min=2048 should pass");
10856 }
10857
10858 /// Oracle: leaf-rsa1024-365d-san-eku.der has RSA-1024 leaf.
10859 /// 1024 < 2048 → `KeyTooSmall` { index: 0 }.
10860 #[test]
10861 fn min_rsa_key_bits_fails_when_key_too_small() {
10862 let root = load(include_bytes!(
10863 "../tests/fixtures/policy-checks/root-rsa2048.der"
10864 ));
10865 let int_cert = load(include_bytes!(
10866 "../tests/fixtures/policy-checks/int-rsa2048.der"
10867 ));
10868 let leaf = load(include_bytes!(
10869 "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
10870 ));
10871 let mut policy = ValidationPolicy::new(PC_NOW);
10872 policy.min_rsa_key_bits = Some(2048);
10873 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10874 assert!(
10875 matches!(
10876 validate_path(
10877 &[leaf, int_cert],
10878 &anchors,
10879 &policy,
10880 &RsaPkcs1v15Sha256Verifier
10881 ),
10882 Err(Error::KeyTooSmall { index: 0 })
10883 ),
10884 "RSA-1024 leaf with min=2048 must return KeyTooSmall {{ index: 0 }}"
10885 );
10886 }
10887
10888 /// Oracle: None = unconstrained; RSA-1024 leaf passes with no key size restriction.
10889 #[test]
10890 fn min_rsa_key_bits_none_is_unconstrained() {
10891 let root = load(include_bytes!(
10892 "../tests/fixtures/policy-checks/root-rsa2048.der"
10893 ));
10894 let int_cert = load(include_bytes!(
10895 "../tests/fixtures/policy-checks/int-rsa2048.der"
10896 ));
10897 let leaf = load(include_bytes!(
10898 "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
10899 ));
10900 let mut policy = ValidationPolicy::new(PC_NOW);
10901 policy.min_rsa_key_bits = None; // default
10902 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10903 validate_path(
10904 &[leaf, int_cert],
10905 &anchors,
10906 &policy,
10907 &RsaPkcs1v15Sha256Verifier,
10908 )
10909 .expect("None min_rsa_key_bits must accept RSA-1024 leaf");
10910 }
10911
10912 /// EC key must not be affected by `min_rsa_key_bits` regardless of the value.
10913 /// Oracle: P-256 key is not RSA; `rsa_public_key_bits` returns None → check skipped.
10914 #[test]
10915 fn min_rsa_key_bits_ec_key_passes_unconditionally() {
10916 let root = load(include_bytes!(
10917 "../tests/fixtures/policy-checks/root-p256.der"
10918 ));
10919 let int_cert = load(include_bytes!(
10920 "../tests/fixtures/policy-checks/int-p256.der"
10921 ));
10922 let leaf = load(include_bytes!(
10923 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
10924 ));
10925 let mut policy = ValidationPolicy::new(PC_NOW);
10926 // Extremely high floor — would reject any RSA key, but P-256 is not RSA.
10927 policy.min_rsa_key_bits = Some(16384);
10928 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10929 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
10930 .expect("EC key must not be affected by min_rsa_key_bits");
10931 }
10932
10933 // -----------------------------------------------------------------------
10934 // allowed_signature_algs: RSA chain test (PKIX-ken.1.10)
10935 // -----------------------------------------------------------------------
10936
10937 /// Oracle: RSA chain uses sha256WithRSAEncryption; ECDSA-only allowlist must reject it.
10938 #[test]
10939 fn alg_allowlist_fails_on_rsa_chain_when_only_ecdsa_allowed() {
10940 let root = load(include_bytes!(
10941 "../tests/fixtures/policy-checks/root-rsa2048.der"
10942 ));
10943 let int_cert = load(include_bytes!(
10944 "../tests/fixtures/policy-checks/int-rsa2048.der"
10945 ));
10946 let leaf = load(include_bytes!(
10947 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
10948 ));
10949 let mut policy = ValidationPolicy::new(PC_NOW);
10950 // Only ECDSA allowed; RSA chain must fail.
10951 policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
10952 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10953 assert!(
10954 matches!(
10955 validate_path(
10956 &[leaf, int_cert],
10957 &anchors,
10958 &policy,
10959 &RsaPkcs1v15Sha256Verifier
10960 ),
10961 Err(Error::AlgorithmNotAllowed { .. })
10962 ),
10963 "RSA chain with ECDSA-only allowlist must return AlgorithmNotAllowed"
10964 );
10965 }
10966
10967 /// Oracle: RSA chain with RSA in allowlist must pass.
10968 #[test]
10969 fn alg_allowlist_passes_for_rsa_chain() {
10970 let root = load(include_bytes!(
10971 "../tests/fixtures/policy-checks/root-rsa2048.der"
10972 ));
10973 let int_cert = load(include_bytes!(
10974 "../tests/fixtures/policy-checks/int-rsa2048.der"
10975 ));
10976 let leaf = load(include_bytes!(
10977 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
10978 ));
10979 let mut policy = ValidationPolicy::new(PC_NOW);
10980 policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
10981 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
10982 validate_path(
10983 &[leaf, int_cert],
10984 &anchors,
10985 &policy,
10986 &RsaPkcs1v15Sha256Verifier,
10987 )
10988 .expect("RSA chain with RSA-SHA256 in allowlist should pass");
10989 }
10990
10991 /// EKU tests for RSA chain are structurally identical to P-256; spot-check one.
10992 ///
10993 /// Oracle: leaf-rsa2048-365d-san-eku.der has EKU=serverAuth.
10994 #[test]
10995 fn required_eku_passes_for_rsa_chain() {
10996 let root = load(include_bytes!(
10997 "../tests/fixtures/policy-checks/root-rsa2048.der"
10998 ));
10999 let int_cert = load(include_bytes!(
11000 "../tests/fixtures/policy-checks/int-rsa2048.der"
11001 ));
11002 let leaf = load(include_bytes!(
11003 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
11004 ));
11005 let mut policy = ValidationPolicy::new(PC_NOW);
11006 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
11007 let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
11008 validate_path(
11009 &[leaf, int_cert],
11010 &anchors,
11011 &policy,
11012 &RsaPkcs1v15Sha256Verifier,
11013 )
11014 .expect("RSA leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
11015 }
11016}
11017
11018/// `NcTypeMask`, the bitmask that records which name forms a path has
11019/// constrained.
11020///
11021/// RFC 5280 §4.2.1.10 requires a certificate carrying a name form this
11022/// implementation cannot match -- `otherName`, `ediPartyName`,
11023/// `registeredID` -- to be rejected when a constraint on that form is in
11024/// effect. The mask is how "in effect" is tracked, so a bit that does not
11025/// work is a certificate that slips through.
11026///
11027/// Nothing exercised the type directly: it is reached only through
11028/// `check_name_constraints`, and the PKITS corpus has no vector for the
11029/// unsupported forms, so the bits for them could all have been zero.
11030#[cfg(test)]
11031mod nc_type_mask_tests {
11032 use super::NcTypeMask;
11033
11034 /// Every name form, in bit order. Written out rather than derived, so
11035 /// the test is a statement about which forms have a bit at all.
11036 const ALL: [(&str, NcTypeMask); 8] = [
11037 ("rfc822Name", NcTypeMask::RFC822),
11038 ("dNSName", NcTypeMask::DNS),
11039 ("directoryName", NcTypeMask::DIRECTORY_NAME),
11040 ("uniformResourceIdentifier", NcTypeMask::URI),
11041 ("iPAddress", NcTypeMask::IP_ADDRESS),
11042 ("otherName", NcTypeMask::OTHER_NAME),
11043 ("ediPartyName", NcTypeMask::EDI_PARTY_NAME),
11044 ("registeredID", NcTypeMask::REGISTERED_ID),
11045 ];
11046
11047 /// Each form has a bit of its own, and that bit is set.
11048 ///
11049 /// A shifted-away constant is the failure that matters: `1 << 6`
11050 /// becoming zero makes `intersects` answer false for every mask, so an
11051 /// `ediPartyName` constraint stops counting as in effect and a
11052 /// certificate carrying that form is no longer refused.
11053 ///
11054 /// `RFC822`'s own shift is the exception, and not for want of a test:
11055 /// `1 << 0` and `1 >> 0` are the same number, so no test distinguishes
11056 /// them. Every other bit is covered here.
11057 #[test]
11058 fn each_name_form_has_its_own_bit() {
11059 for (name, mask) in ALL {
11060 assert!(
11061 mask.intersects(mask),
11062 "{name}'s bit is empty, so no constraint on it can register"
11063 );
11064 assert_ne!(
11065 mask,
11066 NcTypeMask::EMPTY,
11067 "{name} is indistinguishable from EMPTY"
11068 );
11069 }
11070
11071 for (i, (a_name, a)) in ALL.iter().enumerate() {
11072 for (b_name, b) in ALL.iter().skip(i + 1) {
11073 assert!(
11074 !a.intersects(*b),
11075 "{a_name} and {b_name} share a bit, so a constraint on one \
11076 would register as a constraint on the other"
11077 );
11078 }
11079 }
11080 }
11081
11082 /// The empty mask intersects nothing, including itself.
11083 #[test]
11084 fn the_empty_mask_intersects_nothing() {
11085 assert!(!NcTypeMask::EMPTY.intersects(NcTypeMask::EMPTY));
11086 for (name, mask) in ALL {
11087 assert!(!NcTypeMask::EMPTY.intersects(mask), "EMPTY against {name}");
11088 assert!(!mask.intersects(NcTypeMask::EMPTY), "{name} against EMPTY");
11089 }
11090 }
11091
11092 /// Accumulating a form twice leaves it set.
11093 ///
11094 /// This is the one place the distinction between union and symmetric
11095 /// difference shows: on disjoint masks they agree, so a `^` in either
11096 /// operator passes every test built from distinct forms. Two CA
11097 /// certificates in one path constraining `dNSName` is an ordinary
11098 /// chain, and under symmetric difference the second would clear what
11099 /// the first recorded -- the constraint would stop being in effect
11100 /// because it was imposed twice.
11101 #[test]
11102 fn accumulating_one_form_twice_leaves_it_set() {
11103 assert_eq!(NcTypeMask::DNS | NcTypeMask::DNS, NcTypeMask::DNS);
11104
11105 let mut acc = NcTypeMask::EMPTY;
11106 acc |= NcTypeMask::DNS;
11107 acc |= NcTypeMask::RFC822;
11108 acc |= NcTypeMask::DNS;
11109 assert!(
11110 acc.intersects(NcTypeMask::DNS),
11111 "dNSName was constrained twice and must still be in effect"
11112 );
11113 assert!(
11114 acc.intersects(NcTypeMask::RFC822),
11115 "rfc822Name was constrained once and must still be in effect"
11116 );
11117 assert!(
11118 !acc.intersects(NcTypeMask::URI),
11119 "no constraint named uniformResourceIdentifier"
11120 );
11121 }
11122
11123 /// `BitOr` and `BitOrAssign` agree.
11124 ///
11125 /// They are written separately, so one could accumulate while the other
11126 /// replaced.
11127 #[test]
11128 fn the_two_union_operators_agree() {
11129 let by_value = NcTypeMask::DNS | NcTypeMask::OTHER_NAME;
11130 let mut by_assign = NcTypeMask::DNS;
11131 by_assign |= NcTypeMask::OTHER_NAME;
11132 assert_eq!(by_value, by_assign);
11133 }
11134}
11135
11136/// Rendering, equality, hashing and source chains of [`Error`] and
11137/// [`DerError`].
11138///
11139/// These impls have no caller inside the crate: a path validation returns
11140/// an `Error`, and whether it renders, compares or hashes is the consumer's
11141/// business. So nothing here was exercised, and the failure mode is quiet
11142/// in the way that matters for a diagnostic — a `Display` that writes
11143/// nothing still returns `Ok`, a `source` that returns `None` still
11144/// satisfies the trait, and an `eq` that answers `true` makes two different
11145/// DER failures the same value.
11146#[cfg(test)]
11147mod error_rendering_tests {
11148 // `crate::Vec` is the unified alias -- `alloc::vec::Vec` in no_std,
11149 // `std::vec::Vec` under `std`. Not `alloc::vec::Vec` directly:
11150 // `extern crate alloc` is gated to no_std mode in this crate, so
11151 // naming `alloc` fails whenever `std` is on.
11152 use super::{DerError, Error, VerificationErrorKind};
11153 use crate::Vec;
11154 use core::hash::{Hash, Hasher};
11155
11156 /// FNV-1a, so the hash assertions do not need `std`'s `DefaultHasher`.
11157 ///
11158 /// Any deterministic hasher does: the question is whether `Hash` reads
11159 /// the field `PartialEq` compares, not what the digest is.
11160 struct Fnv(u64);
11161
11162 impl Fnv {
11163 fn of<T: Hash>(value: &T) -> u64 {
11164 let mut h = Self(0xcbf2_9ce4_8422_2325);
11165 value.hash(&mut h);
11166 h.finish()
11167 }
11168 }
11169
11170 impl Hasher for Fnv {
11171 fn write(&mut self, bytes: &[u8]) {
11172 for b in bytes {
11173 self.0 ^= u64::from(*b);
11174 self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
11175 }
11176 }
11177 fn finish(&self) -> u64 {
11178 self.0
11179 }
11180 }
11181
11182 /// A `DerError` wrapping the failure `bytes` produces as an OID.
11183 fn der_error(bytes: &[u8]) -> DerError {
11184 use der::Decode as _;
11185 let failed: der::Result<der::asn1::ObjectIdentifier> =
11186 der::asn1::ObjectIdentifier::from_der(bytes);
11187 DerError::new(failed.expect_err("not a well-formed OID"))
11188 }
11189
11190 /// One of every [`Error`] variant.
11191 ///
11192 /// The index is the same throughout on purpose: the variants that carry
11193 /// only an index are otherwise indistinguishable, so holding it fixed
11194 /// makes the distinctness assertion below a statement about the
11195 /// messages rather than about the numbers in them.
11196 fn every_variant() -> [Error; 23] {
11197 const IDX: usize = 2;
11198 [
11199 Error::SignatureInvalid { index: IDX },
11200 Error::SignatureNotVerified {
11201 index: IDX,
11202 reason: VerificationErrorKind::UnsupportedAlgorithm,
11203 },
11204 Error::MalformedCertificate { index: IDX },
11205 Error::ValidityPeriod { index: IDX },
11206 Error::ChainBroken { index: IDX },
11207 Error::NoTrustedPath,
11208 Error::PathTooLong,
11209 Error::NotCA { index: IDX },
11210 Error::KeyUsageMissing { index: IDX },
11211 Error::CrlSignMissing { index: IDX },
11212 Error::UnhandledCriticalExtension { index: IDX },
11213 Error::NameConstraintViolation { index: IDX },
11214 Error::PolicyViolation { index: IDX },
11215 Error::Der(der_error(&[0x06, 0x01, 0x80])),
11216 Error::ValidityPeriodExceedsMax { index: IDX },
11217 Error::AlgorithmNotAllowed { index: IDX },
11218 Error::KeyTooSmall { index: IDX },
11219 Error::MissingSan,
11220 Error::MissingRfc822San,
11221 Error::MissingEku,
11222 Error::MissingLeafPolicyOid {
11223 required: der::asn1::ObjectIdentifier::new_unwrap("1.2.3.4"),
11224 },
11225 Error::SubjectDnAttrRuleUnmet,
11226 Error::DuplicateCertificate {
11227 first: IDX,
11228 second: IDX + 1,
11229 },
11230 ]
11231 }
11232
11233 /// Every variant renders something, and no two render the same thing.
11234 ///
11235 /// An `Error` whose message is empty, or shared with another variant,
11236 /// tells a caller nothing about what went wrong. The array is a fixed
11237 /// length so adding a variant without a message is a compile error
11238 /// here rather than a silent gap.
11239 #[test]
11240 fn every_error_variant_renders_a_distinct_message() {
11241 let variants = every_variant();
11242 let rendered: Vec<_> = variants.iter().map(|e| format!("{e}")).collect();
11243 for (variant, text) in variants.iter().zip(&rendered) {
11244 assert!(!text.is_empty(), "{variant:?} renders nothing");
11245 }
11246 for (i, a) in rendered.iter().enumerate() {
11247 for (j, b) in rendered.iter().enumerate().skip(i + 1) {
11248 assert_ne!(
11249 a, b,
11250 "{:?} and {:?} render the same message",
11251 variants[i], variants[j]
11252 );
11253 }
11254 }
11255 }
11256
11257 /// Only `Error::Der` has an underlying cause, and it exposes it.
11258 ///
11259 /// A `source` that always answers `None` breaks `{:#}`-style chained
11260 /// reporting: the DER failure that explains the whole error is in the
11261 /// wrapped value and nowhere else.
11262 #[test]
11263 fn only_the_der_variant_has_a_source() {
11264 use core::error::Error as _;
11265 for variant in &every_variant() {
11266 let expected = matches!(variant, Error::Der(_));
11267 assert_eq!(
11268 variant.source().is_some(),
11269 expected,
11270 "{variant:?} source presence"
11271 );
11272 }
11273 }
11274
11275 /// `DerError` renders the message it cached, and exposes the
11276 /// `der::Error` it was built from.
11277 #[test]
11278 fn a_der_error_renders_and_exposes_its_cause() {
11279 use core::error::Error as _;
11280 let e = der_error(&[0x06, 0x01, 0x80]);
11281 let rendered = format!("{e}");
11282 assert!(!rendered.is_empty(), "DerError renders nothing");
11283 let source = e.source().expect("a DerError built from a der::Error");
11284 assert_eq!(
11285 format!("{source}"),
11286 rendered,
11287 "the cached message is the der::Error's own rendering"
11288 );
11289 }
11290
11291 /// Equality compares the cached message, so distinct DER failures are
11292 /// distinct values.
11293 ///
11294 /// `Error` derives `PartialEq`, so an `eq` that always answered `true`
11295 /// would make `Err(Error::Der(a)) == Err(Error::Der(b))` for any two
11296 /// DER failures — and a test asserting a particular error would pass
11297 /// for the wrong one.
11298 #[test]
11299 fn der_errors_with_different_messages_differ() {
11300 let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
11301 let truncated = der_error(&[0x06, 0x01, 0x80]);
11302 assert_ne!(
11303 format!("{wrong_tag}"),
11304 format!("{truncated}"),
11305 "the two fixtures must fail differently for this test to mean anything"
11306 );
11307 assert_ne!(wrong_tag, truncated);
11308 assert_eq!(
11309 Error::Der(wrong_tag.clone()),
11310 Error::Der(wrong_tag.clone()),
11311 "the same failure twice"
11312 );
11313 assert_ne!(Error::Der(wrong_tag), Error::Der(truncated));
11314 }
11315
11316 /// `Hash` reads the field `PartialEq` compares.
11317 ///
11318 /// Equal values must hash equally, which a `hash` that writes nothing
11319 /// satisfies trivially — and then every `DerError` lands in one bucket,
11320 /// including inside the `Error` and `ValidatedPath` hashes that exist
11321 /// only because `DerError` is `Hash`.
11322 #[test]
11323 fn der_error_hashing_follows_its_equality() {
11324 let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
11325 let truncated = der_error(&[0x06, 0x01, 0x80]);
11326 assert_eq!(
11327 Fnv::of(&wrong_tag),
11328 Fnv::of(&der_error(&[0x02, 0x01, 0x00])),
11329 "equal values hash equally"
11330 );
11331 assert_ne!(
11332 Fnv::of(&wrong_tag),
11333 Fnv::of(&truncated),
11334 "unequal values are not all one hash"
11335 );
11336 }
11337}