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, its `namedCurve` parameter), and
8//! - the **signature scheme and digest** come from the subject's
9//!   `signatureAlgorithm`.
10//!
11//! So a P-384 issuer key that signs with `ecdsa-with-SHA256` (OpenSSL's
12//! default digest for EC keys) verifies, and an ECDSA signature whose
13//! algorithm OID names one digest cannot be checked against a curve chosen
14//! from that OID.
15
16// With only some backend features enabled, the OIDs and helpers of the
17// others are unused; gating each item separately would obscure the code.
18#![cfg_attr(
19    not(all(
20        feature = "p256",
21        feature = "p384",
22        feature = "p521",
23        feature = "rsa",
24        feature = "ed25519"
25    )),
26    allow(dead_code, unused_imports, unused_variables)
27)]
28
29use crate::SignatureVerifier;
30#[cfg(any(feature = "p256", feature = "p384", feature = "p521", feature = "rsa"))]
31use crate::Vec;
32use crate::{VerificationError, VerificationErrorKind};
33use der::asn1::ObjectIdentifier;
34use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
35
36type VerifyResult = core::result::Result<(), VerificationError>;
37
38// ---------------------------------------------------------------------------
39// OIDs
40// ---------------------------------------------------------------------------
41
42/// `ecdsa-with-SHA256` (RFC 5758 §3.2): 1.2.840.10045.4.3.2.
43pub(crate) const OID_ECDSA_WITH_SHA256: ObjectIdentifier =
44    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
45/// `ecdsa-with-SHA384` (RFC 5758 §3.2): 1.2.840.10045.4.3.3.
46pub(crate) const OID_ECDSA_WITH_SHA384: ObjectIdentifier =
47    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3");
48/// `ecdsa-with-SHA512` (RFC 5758 §3.2): 1.2.840.10045.4.3.4.
49pub(crate) const OID_ECDSA_WITH_SHA512: ObjectIdentifier =
50    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.4");
51
52/// `id-ecPublicKey` (RFC 5480 §2.1.1): 1.2.840.10045.2.1.
53const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
54/// `secp256r1` / `prime256v1` (RFC 5480 §2.1.1.1).
55const OID_SECP256R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
56/// `secp384r1` (RFC 5480 §2.1.1.1).
57const OID_SECP384R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
58/// `secp521r1` (RFC 5480 §2.1.1.1).
59const OID_SECP521R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
60
61/// `rsaEncryption` (RFC 3279 §2.3.1).
62pub(crate) const OID_RSA_ENCRYPTION: ObjectIdentifier =
63    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
64/// `sha256WithRSAEncryption` (RFC 4055 §5).
65pub(crate) const OID_SHA256_WITH_RSA: ObjectIdentifier =
66    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
67/// `sha384WithRSAEncryption` (RFC 4055 §5).
68pub(crate) const OID_SHA384_WITH_RSA: ObjectIdentifier =
69    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.12");
70/// `sha512WithRSAEncryption` (RFC 4055 §5).
71pub(crate) const OID_SHA512_WITH_RSA: ObjectIdentifier =
72    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
73/// `id-RSASSA-PSS` (RFC 4055 §3.1).
74pub(crate) const OID_RSASSA_PSS: ObjectIdentifier =
75    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
76/// `id-mgf1` (RFC 4055 §2.2).
77#[cfg(feature = "rsa")]
78const OID_MGF1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.8");
79/// `id-sha256` (RFC 4055 §2.1).
80#[cfg(feature = "rsa")]
81const OID_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
82/// `id-sha384` (RFC 4055 §2.1).
83#[cfg(feature = "rsa")]
84const OID_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2");
85/// `id-sha512` (RFC 4055 §2.1).
86#[cfg(feature = "rsa")]
87const OID_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3");
88
89/// `id-Ed25519` (RFC 8410 §3): 1.3.101.112.
90pub(crate) const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
91
92/// `sha1WithRSAEncryption` — RFC 3279 §2.2.1.
93///
94/// Only reachable with the `rsa-sha1` feature. See
95/// [`RsaPkcs1v15Sha1Verifier`] for why it is not on by default.
96#[cfg(feature = "rsa-sha1")]
97const OID_SHA1_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.5");
98
99/// `ecdsa-with-SHA1` — RFC 3279 §2.2.3.
100///
101/// Only reachable with the `ecdsa-sha1` feature. See
102/// [`EcdsaP256Sha1Verifier`].
103#[cfg(feature = "ecdsa-sha1")]
104const OID_ECDSA_WITH_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.1");
105
106// ---------------------------------------------------------------------------
107// Digest selection
108// ---------------------------------------------------------------------------
109
110/// A SHA-2 digest named by a signature or hash algorithm OID.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112enum Sha2 {
113    Sha256,
114    Sha384,
115    Sha512,
116}
117
118/// Digest named by an `ecdsa-with-SHA*` signature OID, or `None`.
119fn ecdsa_digest(oid: ObjectIdentifier) -> Option<Sha2> {
120    match oid {
121        OID_ECDSA_WITH_SHA256 => Some(Sha2::Sha256),
122        OID_ECDSA_WITH_SHA384 => Some(Sha2::Sha384),
123        OID_ECDSA_WITH_SHA512 => Some(Sha2::Sha512),
124        _ => None,
125    }
126}
127
128// SHA-1 is kept off the `Sha2` path on purpose. Adding a variant to that
129// enum would put SHA-1 into every digest match in this file, including the
130// ones reached by default, and would make "is this build willing to use
131// SHA-1?" a question about runtime values rather than about compilation.
132// Separate functions behind separate features mean the answer is: only if
133// you asked for it, and otherwise the code is not here.
134// Gated on `ecdsa-sha1` alone, not on both. ECDSA verifies over a
135// pre-computed digest so it needs this; the RSA path hands SHA-1 to
136// `VerifyingKey<sha1::Sha1>` and never digests separately. With only
137// `rsa-sha1` enabled a broader gate leaves this dead, which is an error
138// under -D warnings and was caught by the feature powerset.
139#[cfg(feature = "ecdsa-sha1")]
140fn sha1_digest(message: &[u8]) -> Vec<u8> {
141    use sha1::Digest as _;
142    sha1::Sha1::digest(message).to_vec()
143}
144
145#[cfg(any(feature = "p256", feature = "p384", feature = "p521", feature = "rsa"))]
146fn sha2_digest(alg: Sha2, message: &[u8]) -> Vec<u8> {
147    use sha2::Digest as _;
148    match alg {
149        Sha2::Sha256 => sha2::Sha256::digest(message).to_vec(),
150        Sha2::Sha384 => sha2::Sha384::digest(message).to_vec(),
151        Sha2::Sha512 => sha2::Sha512::digest(message).to_vec(),
152    }
153}
154
155// ---------------------------------------------------------------------------
156// ECDSA
157// ---------------------------------------------------------------------------
158
159/// Named curve of an `id-ecPublicKey` SPKI, or `None` for any other key.
160fn ec_named_curve(spki: &SubjectPublicKeyInfoRef<'_>) -> Option<ObjectIdentifier> {
161    if spki.algorithm.oid != OID_EC_PUBLIC_KEY {
162        return None;
163    }
164    spki.algorithm
165        .parameters?
166        .decode_as::<ObjectIdentifier>()
167        .ok()
168}
169
170macro_rules! ecdsa_curve_verify {
171    ($fn_name:ident, $feature:literal, $krate:ident) => {
172        #[cfg(feature = $feature)]
173        fn $fn_name(
174            spki: SubjectPublicKeyInfoRef<'_>,
175            digest: Sha2,
176            message: &[u8],
177            signature: &[u8],
178        ) -> VerifyResult {
179            use signature::hazmat::PrehashVerifier as _;
180            use $krate::ecdsa::{DerSignature, VerifyingKey};
181
182            let vk =
183                VerifyingKey::try_from(spki).map_err(|_| VerificationError::malformed_key())?;
184            let sig = DerSignature::try_from(signature)
185                .map_err(|_| VerificationError::invalid_signature())?;
186            // No padding to the field width. SEC 1 v2 §4.1.4 step 5 reads
187            // the digest as an integer, taking the leftmost min(N, outlen)
188            // bits, and `ecdsa`'s `bytes2scalar` does exactly that: it
189            // truncates a digest wider than the curve order and reduces a
190            // narrower one unchanged. A shorter digest is therefore the
191            // same scalar as the same digest left-padded with zeros, so
192            // P-521 with `ecdsa-with-SHA256` needs nothing done to it.
193            let prehash = sha2_digest(digest, message);
194            vk.verify_prehash(&prehash, &sig).map_err(|e| {
195                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
196            })
197        }
198    };
199}
200
201ecdsa_curve_verify!(verify_ecdsa_p256, "p256", p256);
202ecdsa_curve_verify!(verify_ecdsa_p384, "p384", p384);
203ecdsa_curve_verify!(verify_ecdsa_p521, "p521", p521);
204
205/// Which curves an ECDSA verifier accepts.
206#[derive(Clone, Copy)]
207struct Curves {
208    p256: bool,
209    p384: bool,
210    p521: bool,
211}
212
213/// ECDSA dispatch: digest from `algorithm`, curve from `issuer_spki`.
214fn verify_ecdsa(
215    curves: Curves,
216    algorithm: AlgorithmIdentifierRef<'_>,
217    issuer_spki: SubjectPublicKeyInfoRef<'_>,
218    message: &[u8],
219    signature: &[u8],
220) -> VerifyResult {
221    let digest =
222        ecdsa_digest(algorithm.oid).ok_or_else(VerificationError::unsupported_algorithm)?;
223    // RFC 5758 §3.2: the parameters field MUST be absent.
224    if algorithm.parameters.is_some() {
225        return Err(VerificationError::unsupported_algorithm());
226    }
227    let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
228    match curve {
229        #[cfg(feature = "p256")]
230        OID_SECP256R1 if curves.p256 => verify_ecdsa_p256(issuer_spki, digest, message, signature),
231        #[cfg(feature = "p384")]
232        OID_SECP384R1 if curves.p384 => verify_ecdsa_p384(issuer_spki, digest, message, signature),
233        #[cfg(feature = "p521")]
234        OID_SECP521R1 if curves.p521 => verify_ecdsa_p521(issuer_spki, digest, message, signature),
235        _ => Err(VerificationError::unsupported_key()),
236    }
237}
238
239macro_rules! ecdsa_verifier {
240    ($(#[$doc:meta])* $name:ident, $feature:literal, $field:ident) => {
241        $(#[$doc])*
242        #[cfg(feature = $feature)]
243        #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
244        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
245        pub struct $name;
246
247        #[cfg(feature = $feature)]
248        impl SignatureVerifier for $name {
249            fn verify_signature(
250                &self,
251                algorithm: AlgorithmIdentifierRef<'_>,
252                issuer_spki: SubjectPublicKeyInfoRef<'_>,
253                message: &[u8],
254                signature: &[u8],
255            ) -> VerifyResult {
256                let curves = Curves {
257                    p256: false,
258                    p384: false,
259                    p521: false,
260                };
261                let curves = Curves {
262                    $field: true,
263                    ..curves
264                };
265                verify_ecdsa(curves, algorithm, issuer_spki, message, signature)
266            }
267        }
268    };
269}
270
271ecdsa_verifier!(
272    /// ECDSA verifier for P-256 (`secp256r1`) issuer keys.
273    ///
274    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
275    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
276    /// absent). Rejects issuer keys on any other curve.
277    /// Feature-gated behind `p256`.
278    EcdsaP256Verifier,
279    "p256",
280    p256
281);
282
283ecdsa_verifier!(
284    /// ECDSA verifier for P-384 (`secp384r1`) issuer keys.
285    ///
286    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
287    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
288    /// absent). Rejects issuer keys on any other curve.
289    /// Feature-gated behind `p384`.
290    EcdsaP384Verifier,
291    "p384",
292    p384
293);
294
295ecdsa_verifier!(
296    /// ECDSA verifier for P-521 (`secp521r1`) issuer keys.
297    ///
298    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
299    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
300    /// absent). Rejects issuer keys on any other curve.
301    /// Feature-gated behind `p521`.
302    EcdsaP521Verifier,
303    "p521",
304    p521
305);
306
307// ---------------------------------------------------------------------------
308// RSA
309// ---------------------------------------------------------------------------
310
311/// Decodes an RSA public key from an SPKI whose algorithm is `rsaEncryption`
312/// (parameters NULL or absent, RFC 3279 §2.3.1) or, when `allow_pss_key` is
313/// set, `id-RSASSA-PSS` (RFC 4055 §1.2).
314///
315/// Moduli from 1024 to 8192 bits are accepted (the `rsa` crate's limits).
316#[cfg(feature = "rsa")]
317fn rsa_public_key(
318    spki: &SubjectPublicKeyInfoRef<'_>,
319    allow_pss_key: bool,
320) -> core::result::Result<rsa::PublicKey, VerificationError> {
321    use rsa::pkcs1::DecodeRsaPublicKey as _;
322
323    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
324        && spki.algorithm.parameters.is_none_or(|p| p.is_null());
325    let pss_ok = allow_pss_key && spki.algorithm.oid == OID_RSASSA_PSS;
326    if !(oid_ok || pss_ok) {
327        return Err(VerificationError::unsupported_key());
328    }
329    let key_bytes = spki
330        .subject_public_key
331        .as_bytes()
332        .ok_or_else(VerificationError::malformed_key)?;
333    rsa::PublicKey::from_pkcs1_der(key_bytes)
334        .map_err(|e| VerificationError::with_source(VerificationErrorKind::MalformedKey, e))
335}
336
337/// RSA PKCS#1 v1.5 verification with the given digest.
338#[cfg(feature = "rsa")]
339fn verify_rsa_pkcs1v15(
340    digest: Sha2,
341    algorithm: AlgorithmIdentifierRef<'_>,
342    issuer_spki: SubjectPublicKeyInfoRef<'_>,
343    message: &[u8],
344    signature: &[u8],
345) -> VerifyResult {
346    use rsa::pkcs1v15::{Signature, VerifyingKey};
347    use rsa::signature::Verifier as _;
348
349    // RFC 4055 §5: parameters MUST be NULL; absent is accepted for
350    // interoperability, matching the issuer-key decoding above.
351    if !algorithm.parameters.is_none_or(|p| p.is_null()) {
352        return Err(VerificationError::unsupported_algorithm());
353    }
354    let key = rsa_public_key(&issuer_spki, false)?;
355    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
356    let result = match digest {
357        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new(key).verify(message, &sig),
358        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new(key).verify(message, &sig),
359        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new(key).verify(message, &sig),
360    };
361    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
362}
363
364/// Hash named by an RFC 4055 `HashAlgorithm` identifier (parameters NULL or
365/// absent, RFC 4055 §2.1).
366#[cfg(feature = "rsa")]
367fn rfc4055_hash(alg: &spki::AlgorithmIdentifierOwned) -> Option<Sha2> {
368    if !alg.parameters.as_ref().is_none_or(der::Any::is_null) {
369        return None;
370    }
371    match alg.oid {
372        OID_SHA256 => Some(Sha2::Sha256),
373        OID_SHA384 => Some(Sha2::Sha384),
374        OID_SHA512 => Some(Sha2::Sha512),
375        _ => None,
376    }
377}
378
379/// RSASSA-PSS verification (RFC 4055 §3.1, RFC 8017 §8.1.2).
380///
381/// Supported parameters: `hashAlgorithm` SHA-256, SHA-384 or SHA-512;
382/// `maskGenAlgorithm` MGF1 over the same hash; any `saltLength`;
383/// `trailerField` 1. The default parameters (SHA-1) are rejected.
384#[cfg(feature = "rsa")]
385fn verify_rsa_pss(
386    algorithm: AlgorithmIdentifierRef<'_>,
387    issuer_spki: SubjectPublicKeyInfoRef<'_>,
388    message: &[u8],
389    signature: &[u8],
390) -> VerifyResult {
391    use der::{Decode as _, Encode as _};
392    use rsa::pkcs1::{RsaPssParamsOwned, TrailerField};
393    use rsa::pss::{Signature, VerifyingKey};
394    use rsa::signature::hazmat::PrehashVerifier as _;
395
396    let params_der = algorithm
397        .parameters
398        .ok_or_else(VerificationError::unsupported_algorithm)?
399        .to_der()
400        .map_err(|_| VerificationError::unsupported_algorithm())?;
401    let params = RsaPssParamsOwned::from_der(&params_der)
402        .map_err(|_| VerificationError::unsupported_algorithm())?;
403    let hash = rfc4055_hash(&params.hash).ok_or_else(VerificationError::unsupported_algorithm)?;
404    if params.mask_gen.oid != OID_MGF1 {
405        return Err(VerificationError::unsupported_algorithm());
406    }
407    let mgf_hash = params
408        .mask_gen
409        .parameters
410        .as_ref()
411        .and_then(rfc4055_hash)
412        .ok_or_else(VerificationError::unsupported_algorithm)?;
413    if mgf_hash != hash || params.trailer_field != TrailerField::BC {
414        return Err(VerificationError::unsupported_algorithm());
415    }
416    // RFC 4055 §3.1: when the issuer key is an id-RSASSA-PSS key with
417    // parameters, the signature must use the same hash and MGF and a salt
418    // at least as long. We check the hash and MGF; a key restricted that
419    // way still verifies only signatures that match its own parameters.
420    if issuer_spki.algorithm.oid == OID_RSASSA_PSS {
421        if let Some(key_params) = issuer_spki.algorithm.parameters {
422            let key_params_der = key_params
423                .to_der()
424                .map_err(|_| VerificationError::malformed_key())?;
425            let key_params = RsaPssParamsOwned::from_der(&key_params_der)
426                .map_err(|_| VerificationError::malformed_key())?;
427            let key_hash =
428                rfc4055_hash(&key_params.hash).ok_or_else(VerificationError::unsupported_key)?;
429            if key_hash != hash || params.salt_len < key_params.salt_len {
430                return Err(VerificationError::unsupported_key());
431            }
432        }
433    }
434    let key = rsa_public_key(&issuer_spki, true)?;
435    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
436    let salt_len = usize::from(params.salt_len);
437    let prehash = sha2_digest(hash, message);
438    let result = match hash {
439        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new_with_salt_len(key, salt_len)
440            .verify_prehash(&prehash, &sig),
441        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new_with_salt_len(key, salt_len)
442            .verify_prehash(&prehash, &sig),
443        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new_with_salt_len(key, salt_len)
444            .verify_prehash(&prehash, &sig),
445    };
446    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
447}
448
449macro_rules! rsa_pkcs1v15_verifier {
450    ($(#[$doc:meta])* $name:ident, $oid:ident, $digest:ident) => {
451        $(#[$doc])*
452        #[cfg(feature = "rsa")]
453        #[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
454        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
455        pub struct $name;
456
457        #[cfg(feature = "rsa")]
458        impl SignatureVerifier for $name {
459            fn verify_signature(
460                &self,
461                algorithm: AlgorithmIdentifierRef<'_>,
462                issuer_spki: SubjectPublicKeyInfoRef<'_>,
463                message: &[u8],
464                signature: &[u8],
465            ) -> VerifyResult {
466                if algorithm.oid != $oid {
467                    return Err(VerificationError::unsupported_algorithm());
468                }
469                verify_rsa_pkcs1v15(Sha2::$digest, algorithm, issuer_spki, message, signature)
470            }
471        }
472    };
473}
474
475rsa_pkcs1v15_verifier!(
476    /// RSA with PKCS#1 v1.5 padding and SHA-256 signature verifier.
477    ///
478    /// Handles OID `sha256WithRSAEncryption` (1.2.840.113549.1.1.11).
479    /// Feature-gated behind `rsa`.
480    RsaPkcs1v15Sha256Verifier,
481    OID_SHA256_WITH_RSA,
482    Sha256
483);
484
485rsa_pkcs1v15_verifier!(
486    /// RSA with PKCS#1 v1.5 padding and SHA-384 signature verifier.
487    ///
488    /// Handles OID `sha384WithRSAEncryption` (1.2.840.113549.1.1.12).
489    /// Feature-gated behind `rsa`.
490    RsaPkcs1v15Sha384Verifier,
491    OID_SHA384_WITH_RSA,
492    Sha384
493);
494
495rsa_pkcs1v15_verifier!(
496    /// RSA with PKCS#1 v1.5 padding and SHA-512 signature verifier.
497    ///
498    /// Handles OID `sha512WithRSAEncryption` (1.2.840.113549.1.1.13).
499    /// Feature-gated behind `rsa`.
500    RsaPkcs1v15Sha512Verifier,
501    OID_SHA512_WITH_RSA,
502    Sha512
503);
504
505/// Verifies RSA PKCS#1 v1.5 signatures over SHA-1. **Legacy interop only.**
506///
507/// # Security
508///
509/// SHA-1 collisions are practical. SHAttered (2017) produced a colliding
510/// pair for roughly 2^63 operations, and chosen-prefix collisions followed
511/// in 2020 at lower cost. An attacker able to mint a certificate that
512/// collides with one a CA signed can substitute it, and the signature will
513/// verify. Treat a SHA-1-signed chain as evidence of provenance, not as
514/// proof of identity.
515///
516/// It exists because messages outlive algorithms. S/MIME signed in 2015
517/// sits in a mailbox today, and a client that cannot check its chain can
518/// tell the user nothing useful — "verify, then warn" is what clients
519/// actually do. CA/Browser Forum rules forbid new SHA-1 issuance; they do
520/// not delete the archive.
521///
522/// Off by default, behind the `rsa-sha1` feature, and deliberately *not*
523/// in the `rustcrypto` umbrella — that umbrella means "algorithms we
524/// recommend". New deployments MUST NOT enable this.
525///
526/// Verification only. Nothing in this workspace signs with SHA-1 and
527/// nothing is intended to.
528#[cfg(feature = "rsa-sha1")]
529#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
530#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
531pub struct RsaPkcs1v15Sha1Verifier;
532
533#[cfg(feature = "rsa-sha1")]
534impl SignatureVerifier for RsaPkcs1v15Sha1Verifier {
535    fn verify_signature(
536        &self,
537        algorithm: AlgorithmIdentifierRef<'_>,
538        issuer_spki: SubjectPublicKeyInfoRef<'_>,
539        message: &[u8],
540        signature: &[u8],
541    ) -> VerifyResult {
542        use rsa::pkcs1v15::{Signature, VerifyingKey};
543        use rsa::signature::Verifier as _;
544
545        if algorithm.oid != OID_SHA1_WITH_RSA {
546            return Err(VerificationError::unsupported_algorithm());
547        }
548        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
549            return Err(VerificationError::unsupported_algorithm());
550        }
551        let key = rsa_public_key(&issuer_spki, false)?;
552        let sig =
553            Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
554        VerifyingKey::<sha1::Sha1>::new(key)
555            .verify(message, &sig)
556            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
557    }
558}
559
560/// Verifies ECDSA P-256 signatures over SHA-1. **Legacy interop only.**
561///
562/// # Security
563///
564/// See [`RsaPkcs1v15Sha1Verifier`]: the same practical collision attacks
565/// apply and the same conclusion follows. A SHA-1-signed chain is
566/// provenance, not proof.
567///
568/// Off by default, behind the `ecdsa-sha1` feature, outside the
569/// `rustcrypto` umbrella. New deployments MUST NOT enable this.
570///
571/// # Scope
572///
573/// P-256 only. `ecdsa-with-SHA1` names no curve, so P-384 and P-521 with
574/// SHA-1 are expressible and do occur, but a deployment old enough to
575/// still sign with SHA-1 is overwhelmingly on P-256 or RSA. Those
576/// combinations are out of scope rather than overlooked, and surface as
577/// [`UnsupportedKey`](VerificationErrorKind::UnsupportedKey), which says
578/// the curve was the problem.
579///
580/// Verification only.
581#[cfg(feature = "ecdsa-sha1")]
582#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
583#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
584pub struct EcdsaP256Sha1Verifier;
585
586#[cfg(feature = "ecdsa-sha1")]
587impl SignatureVerifier for EcdsaP256Sha1Verifier {
588    fn verify_signature(
589        &self,
590        algorithm: AlgorithmIdentifierRef<'_>,
591        issuer_spki: SubjectPublicKeyInfoRef<'_>,
592        message: &[u8],
593        signature: &[u8],
594    ) -> VerifyResult {
595        use p256::ecdsa::{DerSignature, VerifyingKey};
596        use signature::hazmat::PrehashVerifier as _;
597
598        if algorithm.oid != OID_ECDSA_WITH_SHA1 {
599            return Err(VerificationError::unsupported_algorithm());
600        }
601        if algorithm.parameters.is_some() {
602            return Err(VerificationError::unsupported_algorithm());
603        }
604        // P-256 only, so a P-384 or P-521 key is reported as an
605        // unsupported key rather than checked against the wrong curve.
606        if ec_named_curve(&issuer_spki) != Some(OID_SECP256R1) {
607            return Err(VerificationError::unsupported_key());
608        }
609        let vk =
610            VerifyingKey::try_from(issuer_spki).map_err(|_| VerificationError::malformed_key())?;
611        let sig = DerSignature::try_from(signature)
612            .map_err(|_| VerificationError::invalid_signature())?;
613        // FIPS 186-4 uses the leftmost min(N, outlen) bits of the hash,
614        // which for a 160-bit digest and a 256-bit field is all of it;
615        // `ecdsa` reduces the 20 bytes to the same scalar the padded form
616        // would give.
617        let prehash = sha1_digest(message);
618        vk.verify_prehash(&prehash, &sig)
619            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
620    }
621}
622
623/// RSASSA-PSS signature verifier (RFC 4055 §3.1).
624///
625/// Handles OID `id-RSASSA-PSS` (1.2.840.113549.1.1.10) with
626/// `hashAlgorithm` SHA-256, SHA-384 or SHA-512, `maskGenAlgorithm` MGF1
627/// over the same hash, any `saltLength`, and `trailerField` 1. The issuer
628/// key may be `rsaEncryption` or `id-RSASSA-PSS`. Feature-gated behind
629/// `rsa`.
630#[cfg(feature = "rsa")]
631#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
632#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
633pub struct RsaPssVerifier;
634
635#[cfg(feature = "rsa")]
636impl SignatureVerifier for RsaPssVerifier {
637    fn verify_signature(
638        &self,
639        algorithm: AlgorithmIdentifierRef<'_>,
640        issuer_spki: SubjectPublicKeyInfoRef<'_>,
641        message: &[u8],
642        signature: &[u8],
643    ) -> VerifyResult {
644        if algorithm.oid != OID_RSASSA_PSS {
645            return Err(VerificationError::unsupported_algorithm());
646        }
647        verify_rsa_pss(algorithm, issuer_spki, message, signature)
648    }
649}
650
651// ---------------------------------------------------------------------------
652// Ed25519
653// ---------------------------------------------------------------------------
654
655/// Ed25519 signature verifier (RFC 8410, RFC 8032 §5.1.7).
656///
657/// Handles OID `id-Ed25519` (1.3.101.112) for both the signature algorithm
658/// and the issuer key; RFC 8410 §3 requires absent parameters in both.
659/// Verification uses `ed25519-dalek`'s `verify_strict`, which also rejects
660/// small-order public keys and non-canonical signatures.
661/// Feature-gated behind `ed25519`.
662#[cfg(feature = "ed25519")]
663#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
664#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
665pub struct Ed25519Verifier;
666
667#[cfg(feature = "ed25519")]
668impl SignatureVerifier for Ed25519Verifier {
669    fn verify_signature(
670        &self,
671        algorithm: AlgorithmIdentifierRef<'_>,
672        issuer_spki: SubjectPublicKeyInfoRef<'_>,
673        message: &[u8],
674        signature: &[u8],
675    ) -> VerifyResult {
676        if algorithm.oid != OID_ED25519 || algorithm.parameters.is_some() {
677            return Err(VerificationError::unsupported_algorithm());
678        }
679        if issuer_spki.algorithm.oid != OID_ED25519 || issuer_spki.algorithm.parameters.is_some() {
680            return Err(VerificationError::unsupported_key());
681        }
682        let key_bytes: &[u8; 32] = issuer_spki
683            .subject_public_key
684            .as_bytes()
685            .and_then(|b| b.try_into().ok())
686            .ok_or_else(VerificationError::malformed_key)?;
687        let vk = ed25519_dalek::VerifyingKey::from_bytes(key_bytes)
688            .map_err(|_| VerificationError::malformed_key())?;
689        let sig = ed25519_dalek::Signature::from_slice(signature)
690            .map_err(|_| VerificationError::invalid_signature())?;
691        vk.verify_strict(message, &sig)
692            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
693    }
694}
695
696// ---------------------------------------------------------------------------
697// DefaultVerifier
698// ---------------------------------------------------------------------------
699
700/// A [`SignatureVerifier`] covering every `RustCrypto` backend enabled at
701/// build time.
702///
703/// This is the recommended out-of-the-box verifier. With all backend
704/// features on (`rustcrypto`) it supports:
705///
706/// - ECDSA (`ecdsa-with-SHA256`, `-SHA384`, `-SHA512`) on P-256, P-384 and
707///   P-521 issuer keys (features `p256`, `p384`, `p521`). The curve is taken
708///   from the issuer's `SubjectPublicKeyInfo`, not from the signature OID.
709/// - RSA PKCS#1 v1.5 with SHA-256, SHA-384 or SHA-512 (feature `rsa`).
710/// - RSASSA-PSS as described on [`RsaPssVerifier`] (feature `rsa`).
711/// - Ed25519 (feature `ed25519`).
712///
713/// Anything else returns an [`UnsupportedAlgorithm`] error, including
714/// SHA-1 based algorithms.
715///
716/// [`UnsupportedAlgorithm`]: crate::VerificationErrorKind::UnsupportedAlgorithm
717///
718/// To support additional algorithms, implement [`SignatureVerifier`]
719/// directly and fall back to `DefaultVerifier` for the rest.
720#[cfg(any(
721    feature = "p256",
722    feature = "p384",
723    feature = "p521",
724    feature = "rsa",
725    feature = "ed25519"
726))]
727#[cfg_attr(
728    docsrs,
729    doc(cfg(any(
730        feature = "p256",
731        feature = "p384",
732        feature = "p521",
733        feature = "rsa",
734        feature = "ed25519"
735    )))
736)]
737#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
738pub struct DefaultVerifier;
739
740#[cfg(any(
741    feature = "p256",
742    feature = "p384",
743    feature = "p521",
744    feature = "rsa",
745    feature = "ed25519"
746))]
747impl SignatureVerifier for DefaultVerifier {
748    fn verify_signature(
749        &self,
750        algorithm: AlgorithmIdentifierRef<'_>,
751        issuer_spki: SubjectPublicKeyInfoRef<'_>,
752        message: &[u8],
753        signature: &[u8],
754    ) -> VerifyResult {
755        let oid = algorithm.oid;
756        if ecdsa_digest(oid).is_some() {
757            let curves = Curves {
758                p256: cfg!(feature = "p256"),
759                p384: cfg!(feature = "p384"),
760                p521: cfg!(feature = "p521"),
761            };
762            return verify_ecdsa(curves, algorithm, issuer_spki, message, signature);
763        }
764        #[cfg(feature = "rsa")]
765        {
766            let digest = match oid {
767                OID_SHA256_WITH_RSA => Some(Sha2::Sha256),
768                OID_SHA384_WITH_RSA => Some(Sha2::Sha384),
769                OID_SHA512_WITH_RSA => Some(Sha2::Sha512),
770                _ => None,
771            };
772            if let Some(digest) = digest {
773                return verify_rsa_pkcs1v15(digest, algorithm, issuer_spki, message, signature);
774            }
775            if oid == OID_RSASSA_PSS {
776                return verify_rsa_pss(algorithm, issuer_spki, message, signature);
777            }
778        }
779        #[cfg(feature = "ed25519")]
780        if oid == OID_ED25519 {
781            return Ed25519Verifier.verify_signature(algorithm, issuer_spki, message, signature);
782        }
783        // Legacy SHA-1, last and only when asked for. Placed after every
784        // modern algorithm so enabling it cannot change how anything else
785        // is dispatched.
786        #[cfg(feature = "rsa-sha1")]
787        if oid == OID_SHA1_WITH_RSA {
788            return RsaPkcs1v15Sha1Verifier.verify_signature(
789                algorithm,
790                issuer_spki,
791                message,
792                signature,
793            );
794        }
795        #[cfg(feature = "ecdsa-sha1")]
796        if oid == OID_ECDSA_WITH_SHA1 {
797            return EcdsaP256Sha1Verifier.verify_signature(
798                algorithm,
799                issuer_spki,
800                message,
801                signature,
802            );
803        }
804        Err(VerificationError::unsupported_algorithm())
805    }
806}