Skip to main content

pkix_path/
verifiers.rs

1//! `RustCrypto` [`SignatureVerifier`] backends.
2//!
3//! Every verifier here takes the algorithm from two places, as RFC 5280
4//! §4.1.1.2 and RFC 5480 §2.1.1 require:
5//!
6//! - the **key type and curve** come from the issuer's
7//!   `SubjectPublicKeyInfo` -- for ECDSA from its `parameters` field, in
8//!   either form RFC 5480 §2.1.1 defines: a `namedCurve` OID, or an
9//!   X9.62 `SpecifiedECDomain` resolved by
10//!   [`crate::specified_curve`] -- and
11//! - the **signature scheme and digest** come from the subject's
12//!   `signatureAlgorithm`.
13//!
14//! So a P-384 issuer key that signs with `ecdsa-with-SHA256` (OpenSSL's
15//! default digest for EC keys) verifies, and an ECDSA signature whose
16//! algorithm OID names one digest cannot be checked against a curve chosen
17//! from that OID.
18
19// With only some backend features enabled, the OIDs and helpers of the
20// others are unused; gating each item separately would obscure the code.
21#![cfg_attr(
22    not(all(
23        feature = "p256",
24        feature = "p384",
25        feature = "p521",
26        feature = "rsa",
27        feature = "ed25519"
28    )),
29    allow(dead_code, unused_imports, unused_variables)
30)]
31
32use crate::SignatureVerifier;
33// The same list as `sha2_digest` below, for the same reason: every
34// brainpool feature reaches a `Vec`-returning digest helper too, and a
35// `use` whose cfg is narrower than its users' is invisible until some
36// combination turns the users on without it.
37#[cfg(any(
38    feature = "p256",
39    feature = "p384",
40    feature = "p521",
41    feature = "rsa",
42    feature = "bp224",
43    feature = "bp256",
44    feature = "bp384",
45    feature = "bp512"
46))]
47use crate::Vec;
48use crate::{VerificationError, VerificationErrorKind};
49use der::asn1::ObjectIdentifier;
50use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
51
52type VerifyResult = core::result::Result<(), VerificationError>;
53
54// ---------------------------------------------------------------------------
55// OIDs
56// ---------------------------------------------------------------------------
57
58/// `ecdsa-with-SHA256` (RFC 5758 §3.2): 1.2.840.10045.4.3.2.
59pub(crate) const OID_ECDSA_WITH_SHA256: ObjectIdentifier =
60    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
61/// `ecdsa-with-SHA384` (RFC 5758 §3.2): 1.2.840.10045.4.3.3.
62pub(crate) const OID_ECDSA_WITH_SHA384: ObjectIdentifier =
63    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3");
64/// `ecdsa-with-SHA512` (RFC 5758 §3.2): 1.2.840.10045.4.3.4.
65pub(crate) const OID_ECDSA_WITH_SHA512: ObjectIdentifier =
66    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.4");
67
68/// `id-ecPublicKey` (RFC 5480 §2.1.1): 1.2.840.10045.2.1.
69const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
70/// `secp256r1` / `prime256v1` (RFC 5480 §2.1.1.1).
71const OID_SECP256R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
72/// `secp384r1` (RFC 5480 §2.1.1.1).
73const OID_SECP384R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
74/// `secp521r1` (RFC 5480 §2.1.1.1).
75const OID_SECP521R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
76/// `sm2p256v1` (GB/T 32918.5): 1.2.156.10197.1.301.
77///
78/// The curve SM2 is defined over. Named here rather than in the
79/// brainpool block because it is not an RFC 5639 curve and is not
80/// reachable through the ECDSA dispatch -- see [`Sm2WithSm3Verifier`].
81#[cfg(feature = "sm2")]
82const OID_SM2P256V1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.156.10197.1.301");
83
84/// `brainpoolP224r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.5.
85pub(crate) const OID_BRAINPOOL_P224R1: ObjectIdentifier =
86    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.5");
87/// `brainpoolP256r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.7.
88pub(crate) const OID_BRAINPOOL_P256R1: ObjectIdentifier =
89    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.7");
90/// `brainpoolP384r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.11.
91pub(crate) const OID_BRAINPOOL_P384R1: ObjectIdentifier =
92    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.11");
93/// `brainpoolP512r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.13.
94///
95/// Implemented by [`crate::brainpool_p512r1`] rather than by an upstream
96/// crate, because none provides this curve. Every German CSCA
97/// certificate uses it.
98pub(crate) const OID_BRAINPOOL_P512R1: ObjectIdentifier =
99    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.13");
100
101/// `rsaEncryption` (RFC 3279 §2.3.1).
102pub(crate) const OID_RSA_ENCRYPTION: ObjectIdentifier =
103    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
104/// `sha256WithRSAEncryption` (RFC 4055 §5).
105pub(crate) const OID_SHA256_WITH_RSA: ObjectIdentifier =
106    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
107/// `sha384WithRSAEncryption` (RFC 4055 §5).
108pub(crate) const OID_SHA384_WITH_RSA: ObjectIdentifier =
109    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.12");
110/// `sha512WithRSAEncryption` (RFC 4055 §5).
111pub(crate) const OID_SHA512_WITH_RSA: ObjectIdentifier =
112    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
113/// `id-RSASSA-PSS` (RFC 4055 §3.1).
114pub(crate) const OID_RSASSA_PSS: ObjectIdentifier =
115    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
116/// `id-mgf1` (RFC 4055 §2.2).
117#[cfg(feature = "rsa")]
118const OID_MGF1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.8");
119/// `id-sha256` (RFC 4055 §2.1).
120#[cfg(feature = "rsa")]
121const OID_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
122/// `id-sha384` (RFC 4055 §2.1).
123#[cfg(feature = "rsa")]
124const OID_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2");
125/// `id-sha512` (RFC 4055 §2.1).
126#[cfg(feature = "rsa")]
127const OID_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3");
128
129/// `id-Ed25519` (RFC 8410 §3): 1.3.101.112.
130pub(crate) const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
131
132// An intra-doc link only resolves when its target is compiled in, and
133// CI documents each feature on its own (`cargo hack doc --each-feature`).
134// So a doc comment behind feature A may not link an item behind feature
135// B: the three legacy verifiers cross-reference each other, and each
136// pair is a configuration where one exists and the other does not. Where
137// the doc and the target share a gate, as here, the link is fine; where
138// they do not, the name goes in backticks.
139
140/// `sha1WithRSAEncryption` — RFC 3279 §2.2.1.
141///
142/// Only reachable with the `rsa-sha1` feature. See
143/// [`RsaPkcs1v15Sha1Verifier`] for why it is not on by default.
144#[cfg(feature = "rsa-sha1")]
145const OID_SHA1_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.5");
146
147/// `ripemd160WithRSA` — 1.3.36.3.3.1.2, on the Teletrust arc.
148///
149/// Not an RFC 3279 algorithm. It comes from the German Teletrust/BSI
150/// arc, and nine self-issued roots in
151/// `third_party/trust-stores/eu-eidas/` are signed with it: the German
152/// qualified-signature CAs, `3R-CA 1:PN` through `11R-CA 1:PN`, issued
153/// by the Regulierungsbehörde für Telekommunikation und Post and later
154/// the Bundesnetzagentur.
155#[cfg(feature = "rsa-ripemd160")]
156const OID_RIPEMD160_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.36.3.3.1.2");
157
158/// `sha1WithRSA` — the OIW spelling of the same algorithm,
159/// 1.3.14.3.2.29.
160///
161/// RFC 3279 §2.2.1 names PKCS#1's `sha-1WithRSAEncryption`
162/// (1.2.840.113549.1.1.5) and that is what everything modern emits, but
163/// the OIW Security Special Interest Group arc carries an equivalent
164/// OID for the identical construction, and real certificates use it.
165///
166/// Measured: six self-issued roots in
167/// `third_party/trust-stores/uefi-oem-pk/` are signed this way,
168/// VeriSign-era certificates inside OEM Secure Boot key databases. They
169/// reported `UnsupportedAlgorithm` for an algorithm this crate
170/// implements, which made an OID alias look like a missing primitive.
171///
172/// The two are the same signature over the same digest, so they share
173/// one verifier.
174#[cfg(feature = "rsa-sha1")]
175const OID_SHA1_WITH_RSA_OIW: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.29");
176
177/// `ecdsa-with-SHA1` — RFC 3279 §2.2.3.
178///
179/// Only reachable with the `ecdsa-sha1` feature. See
180/// [`EcdsaSha1Verifier`].
181#[cfg(feature = "ecdsa-sha1")]
182const OID_ECDSA_WITH_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.1");
183
184// ---------------------------------------------------------------------------
185// Digest selection
186// ---------------------------------------------------------------------------
187
188/// A SHA-2 digest named by a signature or hash algorithm OID.
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190enum Sha2 {
191    Sha256,
192    Sha384,
193    Sha512,
194}
195
196/// Digest named by an `ecdsa-with-SHA*` signature OID, or `None`.
197fn ecdsa_digest(oid: ObjectIdentifier) -> Option<Sha2> {
198    match oid {
199        OID_ECDSA_WITH_SHA256 => Some(Sha2::Sha256),
200        OID_ECDSA_WITH_SHA384 => Some(Sha2::Sha384),
201        OID_ECDSA_WITH_SHA512 => Some(Sha2::Sha512),
202        _ => None,
203    }
204}
205
206// SHA-1 is kept off the `Sha2` path on purpose. Adding a variant to that
207// enum would put SHA-1 into every digest match in this file, including the
208// ones reached by default, and would make "is this build willing to use
209// SHA-1?" a question about runtime values rather than about compilation.
210// Separate functions behind separate features mean the answer is: only if
211// you asked for it, and otherwise the code is not here.
212// Gated on `ecdsa-sha1` alone, not on both. ECDSA verifies over a
213// pre-computed digest so it needs this; the RSA path hands SHA-1 to
214// `VerifyingKey<sha1::Sha1>` and never digests separately. With only
215// `rsa-sha1` enabled a broader gate leaves this dead, which is an error
216// under -D warnings and was caught by the feature powerset.
217#[cfg(feature = "ecdsa-sha1")]
218fn sha1_digest(message: &[u8]) -> Vec<u8> {
219    use sha1::Digest as _;
220    sha1::Sha1::digest(message).to_vec()
221}
222
223// Every ECDSA and RSA verifier prehashes through here, the brainpool
224// curves included: `ecdsa_generic_curve_verify!` and
225// `ecdsa_curve_verify!` both call it. The list used to name only the
226// NIST curves and RSA, so `bp224` or `bp512` on its own left the
227// function cfg'd out while its callers remained -- invisible to any
228// build where some other feature happened to be on too.
229#[cfg(any(
230    feature = "p256",
231    feature = "p384",
232    feature = "p521",
233    feature = "rsa",
234    feature = "bp224",
235    feature = "bp256",
236    feature = "bp384",
237    feature = "bp512"
238))]
239fn sha2_digest(alg: Sha2, message: &[u8]) -> Vec<u8> {
240    use sha2::Digest as _;
241    match alg {
242        Sha2::Sha256 => sha2::Sha256::digest(message).to_vec(),
243        Sha2::Sha384 => sha2::Sha384::digest(message).to_vec(),
244        Sha2::Sha512 => sha2::Sha512::digest(message).to_vec(),
245    }
246}
247
248// ---------------------------------------------------------------------------
249// ECDSA
250// ---------------------------------------------------------------------------
251
252/// Named curve of an `id-ecPublicKey` SPKI, or `None` for any other key.
253/// The curve of an EC key, from either form RFC 5480 §2.1.1 allows.
254///
255/// A `namedCurve` OID is read directly. A `specifiedCurve`
256/// (X9.62 `SpecifiedECDomain`) is matched against the curves this crate
257/// implements by
258/// [`named_curve_from_specified`](crate::specified_curve::named_curve_from_specified),
259/// which returns the equivalent OID so the dispatch below is unchanged.
260///
261/// The second form matters because ICAO Doc 9303 Part 12 §4.1.6.3
262/// requires it for every machine-readable travel document CSCA, against
263/// RFC 5480's "specifiedCurve MUST NOT be used". Reading only the OID
264/// made 79 certificates in `third_party/trust-stores/icao-csca/`
265/// unverifiable on curves whose arithmetic is right here -- see
266/// `pkix-path/tests/explicit_ec_parameters.rs`.
267fn ec_named_curve(spki: &SubjectPublicKeyInfoRef<'_>) -> Option<ObjectIdentifier> {
268    if spki.algorithm.oid != OID_EC_PUBLIC_KEY {
269        return None;
270    }
271    let params = spki.algorithm.parameters?;
272    if let Ok(oid) = params.decode_as::<ObjectIdentifier>() {
273        return Some(oid);
274    }
275    crate::specified_curve::named_curve_from_specified(params)
276}
277
278macro_rules! ecdsa_curve_verify {
279    ($fn_name:ident, $feature:literal, $krate:ident) => {
280        #[cfg(feature = $feature)]
281        fn $fn_name(
282            spki: SubjectPublicKeyInfoRef<'_>,
283            digest: Sha2,
284            message: &[u8],
285            signature: &[u8],
286        ) -> VerifyResult {
287            use signature::hazmat::PrehashVerifier as _;
288            use $krate::ecdsa::{DerSignature, VerifyingKey};
289
290            // From the SEC 1 point, not from the SPKI.
291            //
292            // `VerifyingKey::try_from(spki)` re-reads
293            // `algorithm.parameters` and requires the `namedCurve` OID
294            // for this curve, so a key carrying an X9.62
295            // `SpecifiedECDomain` -- mandatory for every ICAO Doc 9303
296            // CSCA, see `crate::specified_curve` -- was rejected as a
297            // malformed key even once the curve had been recognized.
298            //
299            // Nothing is checked less. `ec_named_curve` resolved the
300            // curve and the caller matched it against this function's
301            // own curve before dispatching here, which is the check
302            // `try_from` would repeat. `from_sec1_bytes` still validates
303            // the encoding and that the point is on the curve, and it
304            // rejects the identity.
305            let point = spki
306                .subject_public_key
307                .as_bytes()
308                .ok_or_else(VerificationError::malformed_key)?;
309            let vk = VerifyingKey::from_sec1_bytes(point)
310                .map_err(|_| VerificationError::malformed_key())?;
311            let sig = DerSignature::try_from(signature)
312                .map_err(|_| VerificationError::invalid_signature())?;
313            // No padding to the field width. SEC 1 v2 §4.1.4 step 5 reads
314            // the digest as an integer, taking the leftmost min(N, outlen)
315            // bits, and `ecdsa`'s `bytes2scalar` does exactly that: it
316            // truncates a digest wider than the curve order and reduces a
317            // narrower one unchanged. A shorter digest is therefore the
318            // same scalar as the same digest left-padded with zeros, so
319            // P-521 with `ecdsa-with-SHA256` needs nothing done to it.
320            let prehash = sha2_digest(digest, message);
321            vk.verify_prehash(&prehash, &sig).map_err(|e| {
322                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
323            })
324        }
325    };
326}
327
328/// ECDSA verification for a curve whose crate does not re-export
329/// `VerifyingKey`.
330///
331/// `p256` and friends re-export `ecdsa::VerifyingKey<Self>` under
332/// `<krate>::ecdsa`; the brainpool crates carry two curves each and
333/// re-export only the signature types, so the key type is named
334/// generically here instead. Otherwise identical to
335/// [`ecdsa_curve_verify!`], including building the key from the SEC 1
336/// point rather than the SPKI, for the reason given there.
337macro_rules! ecdsa_generic_curve_verify {
338    ($fn_name:ident, $feature:literal, $curve:ty) => {
339        #[cfg(feature = $feature)]
340        fn $fn_name(
341            spki: SubjectPublicKeyInfoRef<'_>,
342            digest: Sha2,
343            message: &[u8],
344            signature: &[u8],
345        ) -> VerifyResult {
346            use signature::hazmat::PrehashVerifier as _;
347
348            let point = spki
349                .subject_public_key
350                .as_bytes()
351                .ok_or_else(VerificationError::malformed_key)?;
352            let vk = ecdsa::VerifyingKey::<$curve>::from_sec1_bytes(point)
353                .map_err(|_| VerificationError::malformed_key())?;
354            let sig = ecdsa::der::Signature::<$curve>::try_from(signature)
355                .map_err(|_| VerificationError::invalid_signature())?;
356            let prehash = sha2_digest(digest, message);
357            vk.verify_prehash(&prehash, &sig).map_err(|e| {
358                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
359            })
360        }
361    };
362}
363
364ecdsa_generic_curve_verify!(
365    verify_ecdsa_bp224,
366    "bp224",
367    crate::brainpool_p224r1::BrainpoolP224r1
368);
369ecdsa_generic_curve_verify!(verify_ecdsa_bp256, "bp256", bp256::BrainpoolP256r1);
370ecdsa_generic_curve_verify!(verify_ecdsa_bp384, "bp384", bp384::BrainpoolP384r1);
371ecdsa_generic_curve_verify!(
372    verify_ecdsa_bp512,
373    "bp512",
374    crate::brainpool_p512r1::BrainpoolP512r1
375);
376ecdsa_curve_verify!(verify_ecdsa_p256, "p256", p256);
377ecdsa_curve_verify!(verify_ecdsa_p384, "p384", p384);
378ecdsa_curve_verify!(verify_ecdsa_p521, "p521", p521);
379
380/// Which curves an ECDSA verifier accepts.
381#[derive(Clone, Copy)]
382// Independent feature flags rather than a state machine: each bool says
383// whether one curve's backend is compiled in, and no combination of
384// them is invalid.
385#[allow(clippy::struct_excessive_bools)]
386struct Curves {
387    p256: bool,
388    p384: bool,
389    p521: bool,
390    bp224: bool,
391    bp256: bool,
392    bp384: bool,
393    bp512: bool,
394}
395
396/// ECDSA dispatch: digest from `algorithm`, curve from `issuer_spki`.
397fn verify_ecdsa(
398    curves: Curves,
399    algorithm: AlgorithmIdentifierRef<'_>,
400    issuer_spki: SubjectPublicKeyInfoRef<'_>,
401    message: &[u8],
402    signature: &[u8],
403) -> VerifyResult {
404    let digest =
405        ecdsa_digest(algorithm.oid).ok_or_else(VerificationError::unsupported_algorithm)?;
406    // RFC 5758 §3.2 says the parameters field MUST be omitted for every
407    // ECDSA OID, and this accepts it anyway when it is present and NULL.
408    //
409    // WHY. A bare `05 00` carries nothing. The scheme and digest come
410    // from the OID, which is what `ecdsa_digest` just read, so an
411    // attacker who adds or strips a NULL changes two bytes that feed
412    // into no decision. The security intent of the field -- that the
413    // same algorithm be named consistently -- is enforced by
414    // `check_oid_consistency`, which compares OIDs across the inner and
415    // outer `AlgorithmIdentifier`.
416    //
417    // That function reached this conclusion first, and said so: "RFC
418    // 5280 says the two AlgorithmIdentifiers MUST be identical, but many
419    // production CAs generate certs where one field has explicit NULL
420    // parameters and the other omits them -- a mismatch that OpenSSL and
421    // other validators accept in practice." Refusing the whole
422    // certificate here, for the field that function deliberately
423    // ignores, was this file contradicting the path validator rather
424    // than making a judgement.
425    //
426    // The RSA path in this same file already takes the NULL-or-absent
427    // reading (`is_none_or(|p| p.is_null())`), as RFC 4055 §5 requires
428    // of it.
429    //
430    // MEASURED: 17 certificates across the vendored corpora do this, 4
431    // of Germany's 23 among them, and two of those four are CSCA roots.
432    // `serialNumber=013` is `ecdsa-with-SHA256` on brainpoolP256r1 --
433    // a curve this crate implements -- and this refusal was the only
434    // thing standing between it and verifying.
435    //
436    // An IETF profile rule cannot make a national root unusable. BSI
437    // published it, an operator installed it, and the signature is
438    // cryptographically valid; OpenSSL verifies it. Same principle as
439    // `AnchorAdmission`, one layer down.
440    //
441    // Still refused: parameters present and NOT NULL. That is a
442    // structure making a claim this code does not understand, which is
443    // different from a two-byte encoding habit carried over from RSA.
444    if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
445        return Err(VerificationError::unsupported_algorithm());
446    }
447    let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
448    match curve {
449        #[cfg(feature = "p256")]
450        OID_SECP256R1 if curves.p256 => verify_ecdsa_p256(issuer_spki, digest, message, signature),
451        #[cfg(feature = "p384")]
452        OID_SECP384R1 if curves.p384 => verify_ecdsa_p384(issuer_spki, digest, message, signature),
453        #[cfg(feature = "p521")]
454        OID_SECP521R1 if curves.p521 => verify_ecdsa_p521(issuer_spki, digest, message, signature),
455        #[cfg(feature = "bp224")]
456        OID_BRAINPOOL_P224R1 if curves.bp224 => {
457            verify_ecdsa_bp224(issuer_spki, digest, message, signature)
458        }
459        #[cfg(feature = "bp256")]
460        OID_BRAINPOOL_P256R1 if curves.bp256 => {
461            verify_ecdsa_bp256(issuer_spki, digest, message, signature)
462        }
463        #[cfg(feature = "bp384")]
464        OID_BRAINPOOL_P384R1 if curves.bp384 => {
465            verify_ecdsa_bp384(issuer_spki, digest, message, signature)
466        }
467        #[cfg(feature = "bp512")]
468        OID_BRAINPOOL_P512R1 if curves.bp512 => {
469            verify_ecdsa_bp512(issuer_spki, digest, message, signature)
470        }
471        _ => Err(VerificationError::unsupported_key()),
472    }
473}
474
475macro_rules! ecdsa_verifier {
476    ($(#[$doc:meta])* $name:ident, $feature:literal, $field:ident) => {
477        $(#[$doc])*
478        #[cfg(feature = $feature)]
479        #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
480        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
481        pub struct $name;
482
483        #[cfg(feature = $feature)]
484        impl SignatureVerifier for $name {
485            fn verify_signature(
486                &self,
487                algorithm: AlgorithmIdentifierRef<'_>,
488                issuer_spki: SubjectPublicKeyInfoRef<'_>,
489                message: &[u8],
490                signature: &[u8],
491            ) -> VerifyResult {
492                let curves = Curves {
493                    p256: false,
494                    p384: false,
495                    p521: false,
496                    bp224: false,
497                    bp256: false,
498                    bp384: false,
499                    bp512: false,
500                };
501                let curves = Curves {
502                    $field: true,
503                    ..curves
504                };
505                verify_ecdsa(curves, algorithm, issuer_spki, message, signature)
506            }
507        }
508    };
509}
510
511ecdsa_verifier!(
512    /// ECDSA verifier for P-256 (`secp256r1`) issuer keys.
513    ///
514    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
515    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
516    /// absent). Rejects issuer keys on any other curve.
517    /// Feature-gated behind `p256`.
518    EcdsaP256Verifier,
519    "p256",
520    p256
521);
522
523ecdsa_verifier!(
524    /// ECDSA verifier for P-384 (`secp384r1`) issuer keys.
525    ///
526    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
527    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
528    /// absent). Rejects issuer keys on any other curve.
529    /// Feature-gated behind `p384`.
530    EcdsaP384Verifier,
531    "p384",
532    p384
533);
534
535ecdsa_verifier!(
536    /// ECDSA verifier for P-521 (`secp521r1`) issuer keys.
537    ///
538    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
539    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
540    /// absent). Rejects issuer keys on any other curve.
541    /// Feature-gated behind `p521`.
542    EcdsaP521Verifier,
543    "p521",
544    p521
545);
546
547// ---------------------------------------------------------------------------
548// RSA
549// ---------------------------------------------------------------------------
550
551/// Decodes an RSA public key from an SPKI whose algorithm is `rsaEncryption`
552/// (parameters NULL or absent, RFC 3279 §2.3.1) or, when `allow_pss_key` is
553/// set, `id-RSASSA-PSS` (RFC 4055 §1.2).
554///
555/// Moduli from 1024 to 8192 bits are accepted (the `rsa` crate's limits).
556/// What an RSA public key's DER had to be forgiven for.
557///
558/// Returned beside the key by [`rsa_public_key_lenient`], so a caller
559/// learns what was tolerated rather than only that it worked. Nothing in
560/// this crate acts on the value; it exists because silently accepting
561/// malformed input is how a lenient parser becomes a liability.
562#[cfg(feature = "rsa")]
563#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
564pub enum RsaKeyDeviation {
565    /// An INTEGER carried more leading zero octets than it needs.
566    ///
567    /// `02 04 00 00 00 03` for the exponent 3, where DER requires the
568    /// minimal `02 01 03`. Unambiguous: the extra octets change no
569    /// value, and X.690 §8.3.2 forbids them only so that one value has
570    /// one encoding.
571    ///
572    /// Austria's `a-sign Premium CA` and `a-sign uni`, in
573    /// `third_party/trust-stores/eu-eidas/`, both do this.
574    NonMinimalInteger,
575    /// An INTEGER's high bit was set without the leading zero octet that
576    /// DER requires, so as written it denotes a negative number.
577    ///
578    /// `02 04 C0 00 00 01` for the exponent 0xC0000001, where the
579    /// canonical form is `02 05 00 C0 00 00 01`. Reading it as positive
580    /// is a **reinterpretation**, not a relaxed length check -- see
581    /// [`rsa_public_key_lenient`] on why that is sound for this field
582    /// and would not be elsewhere.
583    ///
584    /// Germany's `3R-CA 1:PN` and `4R-CA 1:PN` of January 1999 do this;
585    /// `5R-CA` of March 2000 encodes the identical exponent correctly,
586    /// so it was an encoder bug they fixed within fourteen months.
587    NegativeInteger,
588}
589
590/// An RSA public key from an SPKI whose `RSAPublicKey` INTEGERs may not
591/// be canonical DER, with whatever had to be forgiven.
592///
593/// # Why this exists at all
594///
595/// `rsa::PublicKey::from_pkcs1_der` decodes through `der`'s typed
596/// `UintRef`, which enforces X.690 §8.3.2 minimal encoding -- correctly,
597/// and this function does not change that for anybody else. It drops to
598/// `der`'s untyped layer for this one structure instead, reading each
599/// INTEGER's value octets with `Header::decode` and `read_slice` and
600/// handing the magnitudes to `rsa::PublicKey::new`.
601///
602/// **No fork, and no patched dependency.** Everything here is public API
603/// of `der` and `rsa`, and `tbs_der_slice` in this crate's root already
604/// reads raw TLVs the same way.
605///
606/// # Why reading these as unsigned is sound
607///
608/// A modulus and a public exponent are definitionally non-negative, so
609/// there is no value a negative encoding could have been intended to
610/// mean. That is what makes [`NegativeInteger`](RsaKeyDeviation::NegativeInteger)
611/// recoverable here and would not make it recoverable in, say, a
612/// validity date or a path length: those have signed interpretations
613/// that differ from the unsigned one, and guessing between them would be
614/// inventing input.
615///
616/// The arithmetic is unchanged. `rsa::PublicKey::new` still applies
617/// every check it applies to a canonically encoded key -- `e` odd, `e`
618/// in `MIN_PUB_EXPONENT..=MAX_PUB_EXPONENT`, `e < n`, `n` odd and
619/// non-zero, modulus within `MIN_SIZE..=MAX_SIZE` -- so a key that is
620/// weak rather than merely mis-encoded is refused exactly as before.
621/// Only the parse is lenient; nothing downstream is.
622///
623/// # Errors
624///
625/// [`MalformedKey`](VerificationErrorKind::MalformedKey) when the
626/// structure is not two INTEGERs in a SEQUENCE, or when `rsa` rejects
627/// the resulting key. A deviation is reported, never an error.
628#[cfg(feature = "rsa")]
629pub fn rsa_public_key_lenient(
630    spki: &SubjectPublicKeyInfoRef<'_>,
631) -> core::result::Result<(rsa::PublicKey, Option<RsaKeyDeviation>), VerificationError> {
632    use der::{Decode as _, Header, SliceReader, Tag};
633
634    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
635        && spki.algorithm.parameters.is_none_or(der::AnyRef::is_null);
636    if !oid_ok {
637        return Err(VerificationError::unsupported_key());
638    }
639    let key_bytes = spki
640        .subject_public_key
641        .as_bytes()
642        .ok_or_else(VerificationError::malformed_key)?;
643
644    // Strict first, so a conformant key takes the ordinary path and this
645    // function is a fallback rather than a replacement.
646    if let Ok(key) = {
647        use rsa::pkcs1::DecodeRsaPublicKey as _;
648        rsa::PublicKey::from_pkcs1_der(key_bytes)
649    } {
650        return Ok((key, None));
651    }
652
653    let mut reader = SliceReader::new(key_bytes).map_err(|_| VerificationError::malformed_key())?;
654    let outer = Header::decode(&mut reader).map_err(|_| VerificationError::malformed_key())?;
655    if outer.tag() != Tag::Sequence {
656        return Err(VerificationError::malformed_key());
657    }
658
659    /// One INTEGER's value octets, plus what was wrong with them.
660    fn integer<'a>(
661        reader: &mut der::SliceReader<'a>,
662    ) -> core::result::Result<(&'a [u8], Option<RsaKeyDeviation>), VerificationError> {
663        use der::{Decode as _, Header, Reader as _, Tag};
664
665        let header = Header::decode(reader).map_err(|_| VerificationError::malformed_key())?;
666        if header.tag() != Tag::Integer {
667            return Err(VerificationError::malformed_key());
668        }
669        let raw = reader
670            .read_slice(header.length())
671            .map_err(|_| VerificationError::malformed_key())?;
672        let (first, rest) = raw
673            .split_first()
674            .ok_or_else(VerificationError::malformed_key)?;
675
676        // DER (X.690 §8.3.2): the first nine bits may not be all zero or
677        // all one. So exactly one leading 0x00 is correct when the next
678        // octet's high bit is set, and otherwise there must be none.
679        let deviation = if *first == 0x00 {
680            match rest.first() {
681                // `00 C0 ...` -- the one permitted leading zero.
682                Some(b) if b & 0x80 != 0 => None,
683                // `00 00 00 03` -- more zeros than needed. Also `00 03`,
684                // where the zero buys nothing because 0x03 is positive.
685                _ => Some(RsaKeyDeviation::NonMinimalInteger),
686            }
687        } else if *first & 0x80 != 0 {
688            // `C0 00 00 01` -- high bit set with no leading zero, so this
689            // denotes a negative number as written.
690            Some(RsaKeyDeviation::NegativeInteger)
691        } else {
692            None
693        };
694
695        // The magnitude: leading zero octets carry no value whichever
696        // deviation applied, and stripping them is what makes
697        // `BoxedUint::from_be_slice` see the number that was meant.
698        let magnitude = &raw[raw.iter().take_while(|&&b| b == 0).count()..];
699        Ok((magnitude, deviation))
700    }
701
702    let (n_bytes, n_dev) = integer(&mut reader)?;
703    let (e_bytes, e_dev) = integer(&mut reader)?;
704
705    // `NegativeInteger` is reported ahead of `NonMinimalInteger` when
706    // both appear: it is the stronger claim about the input, and a
707    // caller logging one line should see the worse of the two.
708    let deviation = match (n_dev, e_dev) {
709        (Some(RsaKeyDeviation::NegativeInteger), _)
710        | (_, Some(RsaKeyDeviation::NegativeInteger)) => Some(RsaKeyDeviation::NegativeInteger),
711        (Some(d), _) | (_, Some(d)) => Some(d),
712        (None, None) => None,
713    };
714
715    let n = rsa::BoxedUint::from_be_slice_vartime(n_bytes);
716    let e = rsa::BoxedUint::from_be_slice_vartime(e_bytes);
717    let key = rsa::PublicKey::new(n, e)
718        .map_err(|e| VerificationError::with_source(VerificationErrorKind::MalformedKey, e))?;
719    Ok((key, deviation))
720}
721
722#[cfg(feature = "rsa")]
723fn rsa_public_key(
724    spki: &SubjectPublicKeyInfoRef<'_>,
725    allow_pss_key: bool,
726) -> core::result::Result<rsa::PublicKey, VerificationError> {
727    use rsa::pkcs1::DecodeRsaPublicKey as _;
728
729    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
730        && spki.algorithm.parameters.is_none_or(der::AnyRef::is_null);
731    let pss_ok = allow_pss_key && spki.algorithm.oid == OID_RSASSA_PSS;
732    if !(oid_ok || pss_ok) {
733        return Err(VerificationError::unsupported_key());
734    }
735    let key_bytes = spki
736        .subject_public_key
737        .as_bytes()
738        .ok_or_else(VerificationError::malformed_key)?;
739    match rsa::PublicKey::from_pkcs1_der(key_bytes) {
740        Ok(key) => Ok(key),
741        // The lenient retry. In the `rustcrypto` umbrella, so this is
742        // the default path for the four certificates that need it.
743        //
744        // Deliberately NOT reported from here. `verify_signature`
745        // returns `Result<(), VerificationError>` and has no channel for
746        // "it worked, and here is what was odd about it" -- unlike
747        // anchor loading, where `LoadedAnchors::deviations` exists for
748        // exactly that. Rather than invent a side channel or log from a
749        // `no_std` crate, the deviation is made available to a caller
750        // who wants it through the public
751        // [`rsa_public_key_lenient`], which returns it beside the key.
752        // A caller auditing a bundle calls that; a caller validating a
753        // path gets the key.
754        //
755        // Turning `rsa-noncanonical-key` OFF restores the refusal, which
756        // is what an operator who would rather be told should do. The
757        // decision to make it the default was measured: four
758        // certificates of 2,409 self-issued in the vendored corpus
759        // change answer, and nothing else does.
760        #[cfg(feature = "rsa-noncanonical-key")]
761        Err(_) => rsa_public_key_lenient(spki).map(|(key, _deviation)| key),
762        #[cfg(not(feature = "rsa-noncanonical-key"))]
763        Err(e) => Err(VerificationError::with_source(
764            VerificationErrorKind::MalformedKey,
765            e,
766        )),
767    }
768}
769
770/// RSA PKCS#1 v1.5 verification with the given digest.
771#[cfg(feature = "rsa")]
772fn verify_rsa_pkcs1v15(
773    digest: Sha2,
774    algorithm: AlgorithmIdentifierRef<'_>,
775    issuer_spki: SubjectPublicKeyInfoRef<'_>,
776    message: &[u8],
777    signature: &[u8],
778) -> VerifyResult {
779    use rsa::pkcs1v15::{Signature, VerifyingKey};
780    use rsa::signature::Verifier as _;
781
782    // RFC 4055 §5: parameters MUST be NULL; absent is accepted for
783    // interoperability, matching the issuer-key decoding above.
784    if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
785        return Err(VerificationError::unsupported_algorithm());
786    }
787    let key = rsa_public_key(&issuer_spki, false)?;
788    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
789    let result = match digest {
790        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new(key).verify(message, &sig),
791        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new(key).verify(message, &sig),
792        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new(key).verify(message, &sig),
793    };
794    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
795}
796
797/// Hash named by an RFC 4055 `HashAlgorithm` identifier (parameters NULL or
798/// absent, RFC 4055 §2.1).
799#[cfg(feature = "rsa")]
800fn rfc4055_hash(alg: &spki::AlgorithmIdentifierOwned) -> Option<Sha2> {
801    if !alg.parameters.as_ref().is_none_or(der::Any::is_null) {
802        return None;
803    }
804    match alg.oid {
805        OID_SHA256 => Some(Sha2::Sha256),
806        OID_SHA384 => Some(Sha2::Sha384),
807        OID_SHA512 => Some(Sha2::Sha512),
808        _ => None,
809    }
810}
811
812/// RSASSA-PSS verification (RFC 4055 §3.1, RFC 8017 §8.1.2).
813///
814/// Supported parameters: `hashAlgorithm` SHA-256, SHA-384 or SHA-512;
815/// `maskGenAlgorithm` MGF1 over the same hash; any `saltLength`;
816/// `trailerField` 1. The default parameters (SHA-1) are rejected.
817#[cfg(feature = "rsa")]
818fn verify_rsa_pss(
819    algorithm: AlgorithmIdentifierRef<'_>,
820    issuer_spki: SubjectPublicKeyInfoRef<'_>,
821    message: &[u8],
822    signature: &[u8],
823) -> VerifyResult {
824    use der::{Decode as _, Encode as _};
825    use rsa::pkcs1::{RsaPssParamsOwned, TrailerField};
826    use rsa::pss::{Signature, VerifyingKey};
827    use rsa::signature::hazmat::PrehashVerifier as _;
828
829    let params_der = algorithm
830        .parameters
831        .ok_or_else(VerificationError::unsupported_algorithm)?
832        .to_der()
833        .map_err(|_| VerificationError::unsupported_algorithm())?;
834    let params = RsaPssParamsOwned::from_der(&params_der)
835        .map_err(|_| VerificationError::unsupported_algorithm())?;
836    let hash = rfc4055_hash(&params.hash).ok_or_else(VerificationError::unsupported_algorithm)?;
837    if params.mask_gen.oid != OID_MGF1 {
838        return Err(VerificationError::unsupported_algorithm());
839    }
840    let mgf_hash = params
841        .mask_gen
842        .parameters
843        .as_ref()
844        .and_then(rfc4055_hash)
845        .ok_or_else(VerificationError::unsupported_algorithm)?;
846    if mgf_hash != hash || params.trailer_field != TrailerField::BC {
847        return Err(VerificationError::unsupported_algorithm());
848    }
849    // RFC 4055 §3.1: when the issuer key is an id-RSASSA-PSS key with
850    // parameters, the signature must use the same hash and MGF and a salt
851    // at least as long. We check the hash and MGF; a key restricted that
852    // way still verifies only signatures that match its own parameters.
853    if issuer_spki.algorithm.oid == OID_RSASSA_PSS
854        && let Some(key_params) = issuer_spki.algorithm.parameters
855    {
856        let key_params_der = key_params
857            .to_der()
858            .map_err(|_| VerificationError::malformed_key())?;
859        let key_params = RsaPssParamsOwned::from_der(&key_params_der)
860            .map_err(|_| VerificationError::malformed_key())?;
861        let key_hash =
862            rfc4055_hash(&key_params.hash).ok_or_else(VerificationError::unsupported_key)?;
863        if key_hash != hash || params.salt_len < key_params.salt_len {
864            return Err(VerificationError::unsupported_key());
865        }
866    }
867    let key = rsa_public_key(&issuer_spki, true)?;
868    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
869    let salt_len = usize::from(params.salt_len);
870    let prehash = sha2_digest(hash, message);
871    let result = match hash {
872        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new_with_salt_len(key, salt_len)
873            .verify_prehash(&prehash, &sig),
874        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new_with_salt_len(key, salt_len)
875            .verify_prehash(&prehash, &sig),
876        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new_with_salt_len(key, salt_len)
877            .verify_prehash(&prehash, &sig),
878    };
879    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
880}
881
882macro_rules! rsa_pkcs1v15_verifier {
883    ($(#[$doc:meta])* $name:ident, $oid:ident, $digest:ident) => {
884        $(#[$doc])*
885        #[cfg(feature = "rsa")]
886        #[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
887        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
888        pub struct $name;
889
890        #[cfg(feature = "rsa")]
891        impl SignatureVerifier for $name {
892            fn verify_signature(
893                &self,
894                algorithm: AlgorithmIdentifierRef<'_>,
895                issuer_spki: SubjectPublicKeyInfoRef<'_>,
896                message: &[u8],
897                signature: &[u8],
898            ) -> VerifyResult {
899                if algorithm.oid != $oid {
900                    return Err(VerificationError::unsupported_algorithm());
901                }
902                verify_rsa_pkcs1v15(Sha2::$digest, algorithm, issuer_spki, message, signature)
903            }
904        }
905    };
906}
907
908rsa_pkcs1v15_verifier!(
909    /// RSA with PKCS#1 v1.5 padding and SHA-256 signature verifier.
910    ///
911    /// Handles OID `sha256WithRSAEncryption` (1.2.840.113549.1.1.11).
912    /// Feature-gated behind `rsa`.
913    RsaPkcs1v15Sha256Verifier,
914    OID_SHA256_WITH_RSA,
915    Sha256
916);
917
918rsa_pkcs1v15_verifier!(
919    /// RSA with PKCS#1 v1.5 padding and SHA-384 signature verifier.
920    ///
921    /// Handles OID `sha384WithRSAEncryption` (1.2.840.113549.1.1.12).
922    /// Feature-gated behind `rsa`.
923    RsaPkcs1v15Sha384Verifier,
924    OID_SHA384_WITH_RSA,
925    Sha384
926);
927
928rsa_pkcs1v15_verifier!(
929    /// RSA with PKCS#1 v1.5 padding and SHA-512 signature verifier.
930    ///
931    /// Handles OID `sha512WithRSAEncryption` (1.2.840.113549.1.1.13).
932    /// Feature-gated behind `rsa`.
933    RsaPkcs1v15Sha512Verifier,
934    OID_SHA512_WITH_RSA,
935    Sha512
936);
937
938/// Verifies RSA PKCS#1 v1.5 signatures over SHA-1. **Legacy interop only.**
939///
940/// # Security
941///
942/// SHA-1 collisions are practical. `SHAttered` (2017) produced a colliding
943/// pair for roughly 2^63 operations, and chosen-prefix collisions followed
944/// in 2020 at lower cost. An attacker able to mint a certificate that
945/// collides with one a CA signed can substitute it, and the signature will
946/// verify. Treat a SHA-1-signed chain as evidence of provenance, not as
947/// proof of identity.
948///
949/// It exists because messages outlive algorithms. S/MIME signed in 2015
950/// sits in a mailbox today, and a client that cannot check its chain can
951/// tell the user nothing useful — "verify, then warn" is what clients
952/// actually do. CA/Browser Forum rules forbid new SHA-1 issuance; they do
953/// not delete the archive.
954///
955/// Off by default, behind the `rsa-sha1` feature, and deliberately *not*
956/// in the `rustcrypto` umbrella — that umbrella means "algorithms we
957/// recommend". New deployments MUST NOT enable this.
958///
959/// Verification only. Nothing in this workspace signs with SHA-1 and
960/// nothing is intended to.
961#[cfg(feature = "rsa-sha1")]
962#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
963#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
964pub struct RsaPkcs1v15Sha1Verifier;
965
966#[cfg(feature = "rsa-sha1")]
967impl SignatureVerifier for RsaPkcs1v15Sha1Verifier {
968    fn verify_signature(
969        &self,
970        algorithm: AlgorithmIdentifierRef<'_>,
971        issuer_spki: SubjectPublicKeyInfoRef<'_>,
972        message: &[u8],
973        signature: &[u8],
974    ) -> VerifyResult {
975        use rsa::pkcs1v15::{Signature, VerifyingKey};
976        use rsa::signature::Verifier as _;
977
978        if algorithm.oid != OID_SHA1_WITH_RSA && algorithm.oid != OID_SHA1_WITH_RSA_OIW {
979            return Err(VerificationError::unsupported_algorithm());
980        }
981        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
982            return Err(VerificationError::unsupported_algorithm());
983        }
984        let key = rsa_public_key(&issuer_spki, false)?;
985        let sig =
986            Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
987        VerifyingKey::<sha1::Sha1>::new(key)
988            .verify(message, &sig)
989            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
990    }
991}
992
993/// ECDSA-over-SHA-1 for one curve.
994///
995/// Deliberately a separate macro from [`ecdsa_generic_curve_verify!`]
996/// rather than a `Sha2` variant. The comment on [`ecdsa_digest`] gives
997/// the reason: putting SHA-1 into that enum would put it into every
998/// digest match in this file, including the ones reached by default, and
999/// make "is this build willing to use SHA-1?" a question about runtime
1000/// values instead of about compilation. Each of these exists only when
1001/// both `ecdsa-sha1` and the curve's own feature are on.
1002macro_rules! ecdsa_sha1_curve_verify {
1003    ($fn_name:ident, $feature:literal, $curve:ty) => {
1004        #[cfg(all(feature = "ecdsa-sha1", feature = $feature))]
1005        fn $fn_name(
1006            spki: SubjectPublicKeyInfoRef<'_>,
1007            message: &[u8],
1008            signature: &[u8],
1009        ) -> VerifyResult {
1010            use signature::hazmat::PrehashVerifier as _;
1011
1012            let point = spki
1013                .subject_public_key
1014                .as_bytes()
1015                .ok_or_else(VerificationError::malformed_key)?;
1016            let vk = ecdsa::VerifyingKey::<$curve>::from_sec1_bytes(point)
1017                .map_err(|_| VerificationError::malformed_key())?;
1018            let sig = ecdsa::der::Signature::<$curve>::try_from(signature)
1019                .map_err(|_| VerificationError::invalid_signature())?;
1020            // FIPS 186-4 takes the leftmost min(N, outlen) bits of the
1021            // hash. For a 160-bit digest and any field here that is all
1022            // of it, and `ecdsa`'s `bytes2scalar` reduces a narrower
1023            // digest unchanged, so a 20-byte prehash needs no padding.
1024            let prehash = sha1_digest(message);
1025            vk.verify_prehash(&prehash, &sig).map_err(|e| {
1026                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
1027            })
1028        }
1029    };
1030}
1031
1032ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_p256, "p256", p256::NistP256);
1033ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_p384, "p384", p384::NistP384);
1034ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_p521, "p521", p521::NistP521);
1035ecdsa_sha1_curve_verify!(
1036    verify_ecdsa_sha1_bp224,
1037    "bp224",
1038    crate::brainpool_p224r1::BrainpoolP224r1
1039);
1040ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_bp256, "bp256", bp256::BrainpoolP256r1);
1041ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_bp384, "bp384", bp384::BrainpoolP384r1);
1042ecdsa_sha1_curve_verify!(
1043    verify_ecdsa_sha1_bp512,
1044    "bp512",
1045    crate::brainpool_p512r1::BrainpoolP512r1
1046);
1047
1048/// `id-Ed448` (RFC 8410 §3) — 1.3.101.113.
1049#[cfg(feature = "ed448")]
1050const OID_ED448: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.113");
1051
1052/// Verifies Ed448 signatures (RFC 8032 `EdDSA`, RFC 8410 encoding).
1053///
1054/// # Scope
1055///
1056/// Four certificates in `third_party/trust-stores/br-icpbrasil/` are
1057/// signed with it, ICP-Brasil's `AC Raiz Brasileira v6` among them. No
1058/// browser root program ships an Ed448 CA, which is why a validator
1059/// built only against the web PKI never meets one.
1060///
1061/// # Encoding
1062///
1063/// RFC 8410 §4: the key is the raw 57-octet encoding in the
1064/// `subjectPublicKey` BIT STRING with no encapsulating `OCTET STRING`,
1065/// and the signature is the raw 114 octets. Both follow from RFC 8032's
1066/// `b = 456` for Ed448.
1067///
1068/// # The context string
1069///
1070/// RFC 8032 Ed448 signs over a context, and RFC 8410 §6 requires it to
1071/// be **empty** for X.509. `signature::Verifier::verify` is the
1072/// empty-context path; `verify_ctx` would be wrong here.
1073///
1074/// Verification only.
1075#[cfg(feature = "ed448")]
1076#[cfg_attr(docsrs, doc(cfg(feature = "ed448")))]
1077#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1078pub struct Ed448Verifier;
1079
1080#[cfg(feature = "ed448")]
1081impl SignatureVerifier for Ed448Verifier {
1082    fn verify_signature(
1083        &self,
1084        algorithm: AlgorithmIdentifierRef<'_>,
1085        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1086        message: &[u8],
1087        signature: &[u8],
1088    ) -> VerifyResult {
1089        use ed448_goldilocks::{Signature, VerifyingKey};
1090        use signature::Verifier as _;
1091
1092        if algorithm.oid != OID_ED448 {
1093            return Err(VerificationError::unsupported_algorithm());
1094        }
1095        // RFC 8410 §3: "the parameters field MUST be absent". NULL is
1096        // tolerated as elsewhere in this file, for producers carrying
1097        // the RSA habit across.
1098        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
1099            return Err(VerificationError::unsupported_algorithm());
1100        }
1101        let key_bytes = issuer_spki
1102            .subject_public_key
1103            .as_bytes()
1104            .ok_or_else(VerificationError::malformed_key)?;
1105        let key: &[u8; 57] = key_bytes
1106            .try_into()
1107            .map_err(|_| VerificationError::malformed_key())?;
1108        let vk = VerifyingKey::from_bytes(key).map_err(|_| VerificationError::malformed_key())?;
1109        let sig: &[u8; 114] = signature
1110            .try_into()
1111            .map_err(|_| VerificationError::invalid_signature())?;
1112        let sig =
1113            Signature::try_from(&sig[..]).map_err(|_| VerificationError::invalid_signature())?;
1114        vk.verify(message, &sig)
1115            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
1116    }
1117}
1118
1119/// `id-Ed521` as ICP-Brasil assigns it — 1.3.6.1.4.1.44588.2.1.
1120///
1121/// DOC-ICP-01.01 names the algorithm symbolically and never gives this
1122/// number; the binding rests on the `AC Raiz Brasileira v7` certificate
1123/// declaring it and then verifying as Ed521. See
1124/// [`crate::ed521`].
1125#[cfg(feature = "ed521")]
1126const OID_ED521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.44588.2.1");
1127
1128/// Verifies Ed521 signatures (`EdDSA` over E-521, per ICP-Brasil).
1129///
1130/// # ⚠ One certificate, and not for general use
1131///
1132/// **Read [`crate::ed521`] before enabling the `ed521` feature.** That
1133/// module has no published test vectors, no second implementation to
1134/// compare against, and exactly one real signature exercising it. Its
1135/// edge cases are untested.
1136///
1137/// This verifier exists so that no certificate in
1138/// `third_party/trust-stores/` is refused for an algorithm nobody
1139/// looked at. The certificate in question is ICP-Brasil's `AC Raiz
1140/// Brasileira v7`, and it is the only place this will appear.
1141///
1142/// # Encoding
1143///
1144/// Both the key and the signature are raw in their BIT STRINGs, with no
1145/// encapsulating `OCTET STRING` -- like Ed25519 and Ed448 under RFC
1146/// 8410, and unlike GOST. The key is 66 octets and the signature 132,
1147/// which follows from `b = 528` in DOC-ICP-01.01.
1148///
1149/// Verification only.
1150#[cfg(feature = "ed521")]
1151#[cfg_attr(docsrs, doc(cfg(feature = "ed521")))]
1152#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1153pub struct Ed521Verifier;
1154
1155#[cfg(feature = "ed521")]
1156impl SignatureVerifier for Ed521Verifier {
1157    fn verify_signature(
1158        &self,
1159        algorithm: AlgorithmIdentifierRef<'_>,
1160        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1161        message: &[u8],
1162        signature: &[u8],
1163    ) -> VerifyResult {
1164        if algorithm.oid != OID_ED521 {
1165            return Err(VerificationError::unsupported_algorithm());
1166        }
1167        // The AC Raiz v7 certificate carries no parameters at all, which
1168        // matches RFC 8410's treatment of the EdDSA algorithms. NULL is
1169        // tolerated as elsewhere in this file.
1170        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
1171            return Err(VerificationError::unsupported_algorithm());
1172        }
1173        let key_bytes = issuer_spki
1174            .subject_public_key
1175            .as_bytes()
1176            .ok_or_else(VerificationError::malformed_key)?;
1177        let key: &[u8; 66] = key_bytes
1178            .try_into()
1179            .map_err(|_| VerificationError::malformed_key())?;
1180        let sig: &[u8; 132] = signature
1181            .try_into()
1182            .map_err(|_| VerificationError::invalid_signature())?;
1183        if crate::ed521::verify(key, sig, message) {
1184            Ok(())
1185        } else {
1186            Err(VerificationError::invalid_signature())
1187        }
1188    }
1189}
1190
1191/// `id-ml-dsa-87` (FIPS 204) — 2.16.840.1.101.3.4.3.19, on NIST's CSOR
1192/// signature arc.
1193///
1194/// Identified from the certificates rather than from the registry: the
1195/// Caliptra chain names the algorithm in its own subjects
1196/// (`CN=Caliptra 2.0 MlDsa87 FMC Alias`), and the sizes agree -- a
1197/// 2592-octet key and a 4627-octet signature are exactly
1198/// `VerifyingKeySize::<MlDsa87>` and `SignatureSize::<MlDsa87>`, which
1199/// the `ml-dsa` crate asserts for itself.
1200#[cfg(feature = "ml-dsa")]
1201const OID_ML_DSA_87: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.3.19");
1202
1203/// Verifies ML-DSA-87 signatures (FIPS 204).
1204///
1205/// # Scope
1206///
1207/// ML-DSA-87 only, which is what the Caliptra 2.x DICE chains in
1208/// `third_party/trust-stores/caliptra-dice/` use. ML-DSA-44 and -65 are
1209/// not wired up because nothing in any vendored corpus uses them; adding
1210/// either is a parameter-set constant and a dispatch arm.
1211///
1212/// # On by default
1213///
1214/// In the `rustcrypto` umbrella, for the same reason as
1215/// [`Sm2WithSm3Verifier`]: a current standard with a maintained
1216/// implementation is not a legacy primitive. Post-quantum signatures are
1217/// the newest thing here, not the oldest, and a silicon root of trust
1218/// shipping them is exactly the deployment a validator should not refuse
1219/// by default.
1220///
1221/// # The empty context string
1222///
1223/// FIPS 204 signs over a context string as well as the message, and
1224/// X.509 ML-DSA uses an **empty** one. `signature::Verifier::verify`
1225/// passes `&[]`, which is why it is used here rather than
1226/// `verify_with_context`: getting that wrong would fail every signature
1227/// while looking like a key or encoding problem.
1228///
1229/// Verification only.
1230#[cfg(feature = "ml-dsa")]
1231#[cfg_attr(docsrs, doc(cfg(feature = "ml-dsa")))]
1232#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1233pub struct MlDsa87Verifier;
1234
1235#[cfg(feature = "ml-dsa")]
1236impl SignatureVerifier for MlDsa87Verifier {
1237    fn verify_signature(
1238        &self,
1239        algorithm: AlgorithmIdentifierRef<'_>,
1240        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1241        message: &[u8],
1242        signature: &[u8],
1243    ) -> VerifyResult {
1244        use ml_dsa::signature::Verifier as _;
1245        use ml_dsa::{EncodedVerifyingKey, MlDsa87, Signature, VerifyingKey};
1246
1247        if algorithm.oid != OID_ML_DSA_87 {
1248            return Err(VerificationError::unsupported_algorithm());
1249        }
1250        // FIPS 204 and the LAMPS certificate profile give ML-DSA no
1251        // AlgorithmIdentifier parameters at all. NULL is accepted as
1252        // elsewhere in this file, for producers that carry the RSA habit
1253        // across.
1254        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
1255            return Err(VerificationError::unsupported_algorithm());
1256        }
1257        // The key is the raw FIPS 204 encoding in the BIT STRING, with no
1258        // encapsulating OCTET STRING -- unlike GOST, and like Ed25519.
1259        let key_bytes = issuer_spki
1260            .subject_public_key
1261            .as_bytes()
1262            .ok_or_else(VerificationError::malformed_key)?;
1263        let encoded = EncodedVerifyingKey::<MlDsa87>::try_from(key_bytes)
1264            .map_err(|_| VerificationError::malformed_key())?;
1265        let vk = VerifyingKey::<MlDsa87>::decode(&encoded);
1266        let sig = Signature::<MlDsa87>::try_from(signature)
1267            .map_err(|_| VerificationError::invalid_signature())?;
1268        vk.verify(message, &sig)
1269            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
1270    }
1271}
1272
1273/// `GOST R 34.10-2012 with GOST R 34.11-2012 (256-bit)` —
1274/// 1.2.643.7.1.1.3.2.
1275#[cfg(feature = "gost")]
1276const OID_GOST_2012_256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.643.7.1.1.3.2");
1277/// `GOST R 34.10-2001 with GOST R 34.11-94` — 1.2.643.2.2.3.
1278#[cfg(feature = "gost")]
1279const OID_GOST_2001: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.643.2.2.3");
1280/// `id-GostR3410-2001-CryptoPro-A-ParamSet` — 1.2.643.2.2.35.1.
1281///
1282/// The only GOST curve this crate implements, and the one all six
1283/// Russian national roots use. A key naming any other parameter set is
1284/// an unsupported key, not a malformed one.
1285#[cfg(feature = "gost")]
1286const OID_GOST_CRYPTOPRO_A: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.643.2.2.35.1");
1287
1288/// Verifies GOST R 34.10 signatures (RFC 4491, RFC 7091).
1289///
1290/// # Scope
1291///
1292/// The `id-GostR3410-2001-CryptoPro-A-ParamSet` curve only, which is
1293/// what all six self-issued roots in
1294/// `third_party/trust-stores/ru-national/` use. Both digest generations
1295/// are handled: GOST R 34.11-2012 (Streebog-256) for the five 2012
1296/// certificates and GOST R 34.11-94 for the one 2001 certificate.
1297///
1298/// # Off by default, and not because of the algorithm
1299///
1300/// Unlike [`Sm2WithSm3Verifier`], this is outside the `rustcrypto`
1301/// umbrella. The reason is provenance, not strength: the signature
1302/// scheme is implemented in [`crate::gost_r3410`] rather than by a
1303/// maintained upstream, because no crate provides it and our OpenSSL has
1304/// no GOST to cross-check against. What validates it instead is RFC
1305/// 7091 §7's own test example plus these six certificates; see that
1306/// module. A caller who wants it should ask.
1307///
1308/// # The encodings
1309///
1310/// RFC 4491 specifies two byte orders that disagree, and both are
1311/// handled here rather than in [`crate::gost_r3410`], which takes
1312/// big-endian throughout so that its arithmetic can be checked against
1313/// the RFC vector with no encoding in the way:
1314///
1315/// - the key (§2.3.2) is a DER `OCTET STRING` *inside* the BIT STRING,
1316///   64 octets, **little-endian** `x` then **little-endian** `y`;
1317/// - the signature (§2.2.2) is 64 raw octets, **big-endian** `s` then
1318///   **big-endian** `r` -- not a `SEQUENCE`, and reversed from ECDSA.
1319///
1320/// The digest is reversed before it becomes the integer `alpha`. RFC
1321/// 7091 §5.3 defines the integer-to-vector mapping but not how a hash's
1322/// octets map onto it, and the RFC's example gives `e` without `M`, so
1323/// the convention was settled by measurement: unreversed verifies 0 of
1324/// 6 and reversed verifies 6 of 6.
1325///
1326/// Verification only.
1327#[cfg(feature = "gost")]
1328#[cfg_attr(docsrs, doc(cfg(feature = "gost")))]
1329#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1330pub struct GostR3410Verifier;
1331
1332#[cfg(feature = "gost")]
1333impl SignatureVerifier for GostR3410Verifier {
1334    fn verify_signature(
1335        &self,
1336        algorithm: AlgorithmIdentifierRef<'_>,
1337        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1338        message: &[u8],
1339        signature: &[u8],
1340    ) -> VerifyResult {
1341        use der::{Decode as _, Reader as _};
1342        use streebog::digest::Digest as _;
1343
1344        let reversed_digest: [u8; 32] = if algorithm.oid == OID_GOST_2012_256 {
1345            streebog::Streebog256::digest(message).into()
1346        } else if algorithm.oid == OID_GOST_2001 {
1347            gost94::Gost94CryptoPro::digest(message).into()
1348        } else {
1349            return Err(VerificationError::unsupported_algorithm());
1350        };
1351        // Reversed to become `alpha`; see the type docs.
1352        let mut e = reversed_digest;
1353        e.reverse();
1354
1355        // The key's parameter set, from
1356        // `GostR3410-2001-PublicKeyParameters ::= SEQUENCE {
1357        //     publicKeyParamSet OBJECT IDENTIFIER,
1358        //     digestParamSet    OBJECT IDENTIFIER, ... }`
1359        // (RFC 4491 §2.3.1). Only the first field is read: it names the
1360        // curve, and using a curve the key did not name would be
1361        // verifying against parameters nobody specified.
1362        let params = algorithm
1363            .parameters
1364            .or(issuer_spki.algorithm.parameters)
1365            .ok_or_else(VerificationError::unsupported_key)?;
1366        // `value()` is the SEQUENCE content, so the first element is
1367        // read directly rather than through another SEQUENCE layer --
1368        // the same approach `specified_curve` takes.
1369        let mut reader = der::SliceReader::new(params.value())
1370            .map_err(|_| VerificationError::malformed_key())?;
1371        let param_set = reader
1372            .decode::<ObjectIdentifier>()
1373            .map_err(|_| VerificationError::malformed_key())?;
1374        if param_set != OID_GOST_CRYPTOPRO_A {
1375            return Err(VerificationError::unsupported_key());
1376        }
1377
1378        // The key: a DER OCTET STRING inside the BIT STRING, 64 octets,
1379        // each coordinate little-endian.
1380        let bits = issuer_spki
1381            .subject_public_key
1382            .as_bytes()
1383            .ok_or_else(VerificationError::malformed_key)?;
1384        let inner = <&der::asn1::OctetStringRef>::from_der(bits)
1385            .map_err(|_| VerificationError::malformed_key())?;
1386        let raw = inner.as_bytes();
1387        if raw.len() != 64 {
1388            return Err(VerificationError::malformed_key());
1389        }
1390        let mut qx = [0u8; 32];
1391        let mut qy = [0u8; 32];
1392        qx.copy_from_slice(&raw[..32]);
1393        qy.copy_from_slice(&raw[32..]);
1394        qx.reverse();
1395        qy.reverse();
1396
1397        // The signature: 64 raw octets, `s` first, both big-endian.
1398        if signature.len() != 64 {
1399            return Err(VerificationError::invalid_signature());
1400        }
1401        let mut s = [0u8; 32];
1402        let mut r = [0u8; 32];
1403        s.copy_from_slice(&signature[..32]);
1404        r.copy_from_slice(&signature[32..]);
1405
1406        if crate::gost_r3410::verify_cryptopro_a(&qx, &qy, &r, &s, &e) {
1407            Ok(())
1408        } else {
1409            Err(VerificationError::invalid_signature())
1410        }
1411    }
1412}
1413
1414/// `SM2-with-SM3` — 1.2.156.10197.1.501, the Chinese national arc.
1415#[cfg(feature = "sm2")]
1416const OID_SM2_WITH_SM3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.156.10197.1.501");
1417
1418/// The GB/T 32918.2 default distinguishing identifier.
1419///
1420/// SM2 is not ECDSA, and this constant is the sharpest expression of
1421/// why. Before hashing the message, SM2 computes
1422///
1423/// ```text
1424/// Z = SM3(ENTLA || ID || a || b || Gx || Gy || Px || Py)
1425/// ```
1426///
1427/// and signs `SM3(Z || M)`. `ID` is the signer's *distinguishing
1428/// identifier*, so the digest depends on the curve parameters and on the
1429/// signer's own public key as well as on the message. No amount of
1430/// adding the sm2p256v1 curve to the ECDSA dispatch in this file would
1431/// reach that; the hash input itself differs.
1432///
1433/// GB/T 32918.2 §10 specifies this sixteen-octet ASCII default for
1434/// applications that do not define an identifier of their own, and RFC
1435/// 8998 §3.2 names the same value for TLS 1.3. Certificate signatures
1436/// use it, which is what makes verifying them possible without
1437/// out-of-band knowledge of who signed.
1438#[cfg(feature = "sm2")]
1439const SM2_DEFAULT_DISTID: &str = "1234567812345678";
1440
1441/// Verifies SM2 signatures over SM3 (GB/T 32918).
1442///
1443/// # Scope
1444///
1445/// Nine self-issued roots in `third_party/trust-stores/cn-sm2/` are
1446/// signed this way: four from the China Financial Certification
1447/// Authority, two from `UniTrust`, two from GDCA and NRCAC's `ROOTCA`.
1448/// Before this verifier they reported
1449/// [`UnsupportedAlgorithm`](VerificationErrorKind::UnsupportedAlgorithm),
1450/// which was accurate and unhelpful.
1451///
1452/// The signer's distinguishing identifier is
1453/// `SM2_DEFAULT_DISTID`; see there for why SM2 needs one at all and
1454/// why a certificate's is not configurable.
1455///
1456/// # Not a legacy primitive
1457///
1458/// Unlike `RsaPkcs1v15Sha1Verifier` or
1459/// `RsaPkcs1v15Ripemd160Verifier`, this is in the `rustcrypto`
1460/// umbrella and on by default. Those two are named rather than linked
1461/// on purpose: they are gated on `rsa-sha1` and `rsa-ripemd160`, which
1462/// `rustcrypto` does not include, so under the default feature set the
1463/// links have no targets -- which is the whole point the sentence is
1464/// making. SM2 is a current national standard with
1465/// no published break, and the roots using it are in production.
1466///
1467/// Verification only.
1468#[cfg(feature = "sm2")]
1469#[cfg_attr(docsrs, doc(cfg(feature = "sm2")))]
1470#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1471pub struct Sm2WithSm3Verifier;
1472
1473#[cfg(feature = "sm2")]
1474impl SignatureVerifier for Sm2WithSm3Verifier {
1475    fn verify_signature(
1476        &self,
1477        algorithm: AlgorithmIdentifierRef<'_>,
1478        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1479        message: &[u8],
1480        signature: &[u8],
1481    ) -> VerifyResult {
1482        use sm2::dsa::signature::Verifier as _;
1483        use sm2::dsa::{DerSignature, Signature, VerifyingKey};
1484
1485        if algorithm.oid != OID_SM2_WITH_SM3 {
1486            return Err(VerificationError::unsupported_algorithm());
1487        }
1488        // NULL-or-absent, as elsewhere in this file.
1489        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
1490            return Err(VerificationError::unsupported_algorithm());
1491        }
1492        // The key must be an EC key on sm2p256v1. The curve is resolved
1493        // through `ec_named_curve`, so an SM2 key carrying explicit
1494        // domain parameters is read like any other -- which matters
1495        // because the Chinese arc predates nobody's habits in
1496        // particular and both forms occur.
1497        let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
1498        if curve != OID_SM2P256V1 {
1499            return Err(VerificationError::unsupported_key());
1500        }
1501        let point = issuer_spki
1502            .subject_public_key
1503            .as_bytes()
1504            .ok_or_else(VerificationError::malformed_key)?;
1505        let vk = VerifyingKey::from_sec1_bytes(SM2_DEFAULT_DISTID, point)
1506            .map_err(|_| VerificationError::malformed_key())?;
1507        // Certificate signatures carry the DER `SEQUENCE { r, s }`, so it
1508        // is decoded and then converted to the fixed-width form the
1509        // verifier takes. `sm2` exposes no single `from_der`, and this
1510        // is the two-step its own docs use.
1511        let der_sig = DerSignature::try_from(signature)
1512            .map_err(|_| VerificationError::invalid_signature())?;
1513        let sig =
1514            Signature::try_from(der_sig).map_err(|_| VerificationError::invalid_signature())?;
1515        // `verify` hashes `Z || message` with SM3 internally, so the
1516        // TBSCertificate goes in whole rather than pre-hashed.
1517        vk.verify(message, &sig)
1518            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
1519    }
1520}
1521
1522/// Verifies RSA PKCS#1 v1.5 signatures over RIPEMD-160.
1523/// **Legacy interop only.**
1524///
1525/// # Security
1526///
1527/// RIPEMD-160 is **not** in the same position as MD5 or SHA-1. No
1528/// practical collision attack against the full function has been
1529/// published; the best results are on reduced-round variants. Its
1530/// 160-bit output gives the same theoretical collision resistance as
1531/// SHA-1's, without SHA-1's realised break.
1532///
1533/// So this is off by default for a different reason than
1534/// `RsaPkcs1v15Sha1Verifier`: nothing modern emits it, not that the
1535/// primitive is broken. A caller enabling it is accepting an
1536/// unfashionable hash, not a forgeable one.
1537///
1538/// # Scope
1539///
1540/// Measured: nine self-issued roots in
1541/// `third_party/trust-stores/eu-eidas/` are signed `ripemd160WithRSA`,
1542/// the German qualified-signature CAs. They are roots in a bundle the EU
1543/// publishes and signs, and before this they could not be verified at
1544/// all -- which was this crate declining a primitive for being German
1545/// and obscure rather than for being weak.
1546///
1547/// The `DigestInfo` prefix comes from `ripemd`'s `AssociatedOid`
1548/// (1.3.36.3.2.1), so the PKCS#1 v1.5 encoding is built by the `rsa`
1549/// crate exactly as it is for SHA-1 and SHA-2.
1550///
1551/// Verification only.
1552#[cfg(feature = "rsa-ripemd160")]
1553#[cfg_attr(docsrs, doc(cfg(feature = "rsa-ripemd160")))]
1554#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1555pub struct RsaPkcs1v15Ripemd160Verifier;
1556
1557#[cfg(feature = "rsa-ripemd160")]
1558impl SignatureVerifier for RsaPkcs1v15Ripemd160Verifier {
1559    fn verify_signature(
1560        &self,
1561        algorithm: AlgorithmIdentifierRef<'_>,
1562        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1563        message: &[u8],
1564        signature: &[u8],
1565    ) -> VerifyResult {
1566        use rsa::pkcs1v15::{Signature, VerifyingKey};
1567        use rsa::signature::Verifier as _;
1568
1569        if algorithm.oid != OID_RIPEMD160_WITH_RSA {
1570            return Err(VerificationError::unsupported_algorithm());
1571        }
1572        // NULL-or-absent, as RFC 4055 §5 requires for RSA.
1573        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
1574            return Err(VerificationError::unsupported_algorithm());
1575        }
1576        let key = rsa_public_key(&issuer_spki, false)?;
1577        let sig =
1578            Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
1579        VerifyingKey::<ripemd::Ripemd160>::new(key)
1580            .verify(message, &sig)
1581            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
1582    }
1583}
1584
1585/// Verifies ECDSA signatures over SHA-1, on any curve this build has.
1586/// **Legacy interop only.**
1587///
1588/// # Security
1589///
1590/// See `RsaPkcs1v15Sha1Verifier`: the same practical collision attacks
1591/// apply and the same conclusion follows. A SHA-1-signed chain is
1592/// provenance, not proof.
1593///
1594/// Off by default, behind the `ecdsa-sha1` feature, outside the
1595/// `rustcrypto` umbrella. New deployments MUST NOT enable this.
1596///
1597/// # Scope
1598///
1599/// Every curve this build implements, which is the point of the rename:
1600/// this was `EcdsaP256Sha1Verifier`, P-256 only, on the reasoning that
1601/// "a deployment old enough to still sign with SHA-1 is overwhelmingly
1602/// on P-256 or RSA".
1603///
1604/// That reasoning was wrong about the one case anybody measured here.
1605/// `ecdsa-with-SHA1` names no curve, and Germany's oldest CSCA
1606/// generation -- `CN=csca-germany,serialNumber=001` in
1607/// `third_party/trust-stores/de-csca/` -- signs with SHA-1 over
1608/// **brainpoolP256r1**. A P-256-only verifier reported
1609/// [`UnsupportedKey`](VerificationErrorKind::UnsupportedKey) for it even
1610/// with the feature on, so the curve was "the problem" for a curve this
1611/// crate implements. A national root is not out of scope.
1612///
1613/// A curve the build does not implement still reports `UnsupportedKey`,
1614/// which remains the honest answer: it names this build's gap rather
1615/// than a defect in the certificate.
1616///
1617/// Verification only.
1618#[cfg(feature = "ecdsa-sha1")]
1619#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
1620#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1621pub struct EcdsaSha1Verifier;
1622
1623#[cfg(feature = "ecdsa-sha1")]
1624impl SignatureVerifier for EcdsaSha1Verifier {
1625    fn verify_signature(
1626        &self,
1627        algorithm: AlgorithmIdentifierRef<'_>,
1628        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1629        message: &[u8],
1630        signature: &[u8],
1631    ) -> VerifyResult {
1632        if algorithm.oid != OID_ECDSA_WITH_SHA1 {
1633            return Err(VerificationError::unsupported_algorithm());
1634        }
1635        // NULL-or-absent, for the reason given in `verify_ecdsa`.
1636        if !algorithm.parameters.is_none_or(der::AnyRef::is_null) {
1637            return Err(VerificationError::unsupported_algorithm());
1638        }
1639        // The curve from either parameter form, so an explicit-parameter
1640        // key -- which every ICAO Doc 9303 CSCA carries -- resolves the
1641        // same way a `namedCurve` one does.
1642        let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
1643        match curve {
1644            #[cfg(feature = "p256")]
1645            OID_SECP256R1 => verify_ecdsa_sha1_p256(issuer_spki, message, signature),
1646            #[cfg(feature = "p384")]
1647            OID_SECP384R1 => verify_ecdsa_sha1_p384(issuer_spki, message, signature),
1648            #[cfg(feature = "p521")]
1649            OID_SECP521R1 => verify_ecdsa_sha1_p521(issuer_spki, message, signature),
1650            #[cfg(feature = "bp224")]
1651            OID_BRAINPOOL_P224R1 => verify_ecdsa_sha1_bp224(issuer_spki, message, signature),
1652            #[cfg(feature = "bp256")]
1653            OID_BRAINPOOL_P256R1 => verify_ecdsa_sha1_bp256(issuer_spki, message, signature),
1654            #[cfg(feature = "bp384")]
1655            OID_BRAINPOOL_P384R1 => verify_ecdsa_sha1_bp384(issuer_spki, message, signature),
1656            #[cfg(feature = "bp512")]
1657            OID_BRAINPOOL_P512R1 => verify_ecdsa_sha1_bp512(issuer_spki, message, signature),
1658            _ => Err(VerificationError::unsupported_key()),
1659        }
1660    }
1661}
1662
1663/// RSASSA-PSS signature verifier (RFC 4055 §3.1).
1664///
1665/// Handles OID `id-RSASSA-PSS` (1.2.840.113549.1.1.10) with
1666/// `hashAlgorithm` SHA-256, SHA-384 or SHA-512, `maskGenAlgorithm` MGF1
1667/// over the same hash, any `saltLength`, and `trailerField` 1. The issuer
1668/// key may be `rsaEncryption` or `id-RSASSA-PSS`. Feature-gated behind
1669/// `rsa`.
1670#[cfg(feature = "rsa")]
1671#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
1672#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1673pub struct RsaPssVerifier;
1674
1675#[cfg(feature = "rsa")]
1676impl SignatureVerifier for RsaPssVerifier {
1677    fn verify_signature(
1678        &self,
1679        algorithm: AlgorithmIdentifierRef<'_>,
1680        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1681        message: &[u8],
1682        signature: &[u8],
1683    ) -> VerifyResult {
1684        if algorithm.oid != OID_RSASSA_PSS {
1685            return Err(VerificationError::unsupported_algorithm());
1686        }
1687        verify_rsa_pss(algorithm, issuer_spki, message, signature)
1688    }
1689}
1690
1691// ---------------------------------------------------------------------------
1692// Ed25519
1693// ---------------------------------------------------------------------------
1694
1695/// Ed25519 signature verifier (RFC 8410, RFC 8032 §5.1.7).
1696///
1697/// Handles OID `id-Ed25519` (1.3.101.112) for both the signature algorithm
1698/// and the issuer key; RFC 8410 §3 requires absent parameters in both.
1699/// Verification uses `ed25519-dalek`'s `verify_strict`, which also rejects
1700/// small-order public keys and non-canonical signatures.
1701/// Feature-gated behind `ed25519`.
1702#[cfg(feature = "ed25519")]
1703#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
1704#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1705pub struct Ed25519Verifier;
1706
1707#[cfg(feature = "ed25519")]
1708impl SignatureVerifier for Ed25519Verifier {
1709    fn verify_signature(
1710        &self,
1711        algorithm: AlgorithmIdentifierRef<'_>,
1712        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1713        message: &[u8],
1714        signature: &[u8],
1715    ) -> VerifyResult {
1716        if algorithm.oid != OID_ED25519 || algorithm.parameters.is_some() {
1717            return Err(VerificationError::unsupported_algorithm());
1718        }
1719        if issuer_spki.algorithm.oid != OID_ED25519 || issuer_spki.algorithm.parameters.is_some() {
1720            return Err(VerificationError::unsupported_key());
1721        }
1722        let key_bytes: &[u8; 32] = issuer_spki
1723            .subject_public_key
1724            .as_bytes()
1725            .and_then(|b| b.try_into().ok())
1726            .ok_or_else(VerificationError::malformed_key)?;
1727        let vk = ed25519_dalek::VerifyingKey::from_bytes(key_bytes)
1728            .map_err(|_| VerificationError::malformed_key())?;
1729        let sig = ed25519_dalek::Signature::from_slice(signature)
1730            .map_err(|_| VerificationError::invalid_signature())?;
1731        vk.verify_strict(message, &sig)
1732            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
1733    }
1734}
1735
1736// ---------------------------------------------------------------------------
1737// DefaultVerifier
1738// ---------------------------------------------------------------------------
1739
1740/// A [`SignatureVerifier`] covering every `RustCrypto` backend enabled at
1741/// build time.
1742///
1743/// This is the recommended out-of-the-box verifier. With all backend
1744/// features on (`rustcrypto`) it supports:
1745///
1746/// - ECDSA (`ecdsa-with-SHA256`, `-SHA384`, `-SHA512`) on P-256, P-384 and
1747///   P-521 issuer keys (features `p256`, `p384`, `p521`). The curve is taken
1748///   from the issuer's `SubjectPublicKeyInfo`, not from the signature OID.
1749/// - RSA PKCS#1 v1.5 with SHA-256, SHA-384 or SHA-512 (feature `rsa`).
1750/// - RSASSA-PSS as described on [`RsaPssVerifier`] (feature `rsa`).
1751/// - Ed25519 (feature `ed25519`).
1752///
1753/// Anything else returns an [`UnsupportedAlgorithm`] error, including
1754/// SHA-1 based algorithms.
1755///
1756/// [`UnsupportedAlgorithm`]: crate::VerificationErrorKind::UnsupportedAlgorithm
1757///
1758/// To support additional algorithms, implement [`SignatureVerifier`]
1759/// directly and fall back to `DefaultVerifier` for the rest.
1760#[cfg(any(
1761    feature = "p256",
1762    feature = "p384",
1763    feature = "p521",
1764    feature = "rsa",
1765    feature = "ed25519"
1766))]
1767#[cfg_attr(
1768    docsrs,
1769    doc(cfg(any(
1770        feature = "p256",
1771        feature = "p384",
1772        feature = "p521",
1773        feature = "rsa",
1774        feature = "ed25519"
1775    )))
1776)]
1777#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1778pub struct DefaultVerifier;
1779
1780#[cfg(any(
1781    feature = "p256",
1782    feature = "p384",
1783    feature = "p521",
1784    feature = "rsa",
1785    feature = "ed25519"
1786))]
1787impl SignatureVerifier for DefaultVerifier {
1788    fn verify_signature(
1789        &self,
1790        algorithm: AlgorithmIdentifierRef<'_>,
1791        issuer_spki: SubjectPublicKeyInfoRef<'_>,
1792        message: &[u8],
1793        signature: &[u8],
1794    ) -> VerifyResult {
1795        let oid = algorithm.oid;
1796        if ecdsa_digest(oid).is_some() {
1797            let curves = Curves {
1798                p256: cfg!(feature = "p256"),
1799                p384: cfg!(feature = "p384"),
1800                p521: cfg!(feature = "p521"),
1801                bp224: cfg!(feature = "bp224"),
1802                bp256: cfg!(feature = "bp256"),
1803                bp384: cfg!(feature = "bp384"),
1804                bp512: cfg!(feature = "bp512"),
1805            };
1806            return verify_ecdsa(curves, algorithm, issuer_spki, message, signature);
1807        }
1808        #[cfg(feature = "rsa")]
1809        {
1810            let digest = match oid {
1811                OID_SHA256_WITH_RSA => Some(Sha2::Sha256),
1812                OID_SHA384_WITH_RSA => Some(Sha2::Sha384),
1813                OID_SHA512_WITH_RSA => Some(Sha2::Sha512),
1814                _ => None,
1815            };
1816            if let Some(digest) = digest {
1817                return verify_rsa_pkcs1v15(digest, algorithm, issuer_spki, message, signature);
1818            }
1819            if oid == OID_RSASSA_PSS {
1820                return verify_rsa_pss(algorithm, issuer_spki, message, signature);
1821            }
1822        }
1823        #[cfg(feature = "ed25519")]
1824        if oid == OID_ED25519 {
1825            return Ed25519Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1826        }
1827        // Legacy SHA-1, last and only when asked for. Placed after every
1828        // modern algorithm so enabling it cannot change how anything else
1829        // is dispatched.
1830        #[cfg(feature = "rsa-sha1")]
1831        if oid == OID_SHA1_WITH_RSA || oid == OID_SHA1_WITH_RSA_OIW {
1832            return RsaPkcs1v15Sha1Verifier.verify_signature(
1833                algorithm,
1834                issuer_spki,
1835                message,
1836                signature,
1837            );
1838        }
1839        #[cfg(feature = "ed448")]
1840        if oid == OID_ED448 {
1841            return Ed448Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1842        }
1843        #[cfg(feature = "ed521")]
1844        if oid == OID_ED521 {
1845            return Ed521Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1846        }
1847        #[cfg(feature = "ml-dsa")]
1848        if oid == OID_ML_DSA_87 {
1849            return MlDsa87Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1850        }
1851        #[cfg(feature = "gost")]
1852        if oid == OID_GOST_2012_256 || oid == OID_GOST_2001 {
1853            return GostR3410Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1854        }
1855        #[cfg(feature = "sm2")]
1856        if oid == OID_SM2_WITH_SM3 {
1857            return Sm2WithSm3Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1858        }
1859        #[cfg(feature = "rsa-ripemd160")]
1860        if oid == OID_RIPEMD160_WITH_RSA {
1861            return RsaPkcs1v15Ripemd160Verifier.verify_signature(
1862                algorithm,
1863                issuer_spki,
1864                message,
1865                signature,
1866            );
1867        }
1868        #[cfg(feature = "ecdsa-sha1")]
1869        if oid == OID_ECDSA_WITH_SHA1 {
1870            return EcdsaSha1Verifier.verify_signature(algorithm, issuer_spki, message, signature);
1871        }
1872        Err(VerificationError::unsupported_algorithm())
1873    }
1874}