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
170/// Left-pads a digest shorter than the curve order with zero bytes.
171///
172/// SEC 1 v2 §4.1.4 step 5 converts the digest to an integer, so leading
173/// zero bytes do not change the value. The `ecdsa` crate rejects prehashes
174/// shorter than half the field size, which would otherwise refuse, for
175/// example, P-521 with `ecdsa-with-SHA256`.
176#[cfg(any(feature = "p256", feature = "p384", feature = "p521"))]
177fn pad_prehash(mut digest: Vec<u8>, field_len: usize) -> Vec<u8> {
178    if digest.len() < field_len {
179        let mut padded = vec![0u8; field_len - digest.len()];
180        padded.append(&mut digest);
181        padded
182    } else {
183        digest
184    }
185}
186
187macro_rules! ecdsa_curve_verify {
188    ($fn_name:ident, $feature:literal, $krate:ident, $field_len:expr) => {
189        #[cfg(feature = $feature)]
190        fn $fn_name(
191            spki: SubjectPublicKeyInfoRef<'_>,
192            digest: Sha2,
193            message: &[u8],
194            signature: &[u8],
195        ) -> VerifyResult {
196            use signature::hazmat::PrehashVerifier as _;
197            use $krate::ecdsa::{DerSignature, VerifyingKey};
198
199            let vk =
200                VerifyingKey::try_from(spki).map_err(|_| VerificationError::malformed_key())?;
201            let sig = DerSignature::try_from(signature)
202                .map_err(|_| VerificationError::invalid_signature())?;
203            let prehash = pad_prehash(sha2_digest(digest, message), $field_len);
204            vk.verify_prehash(&prehash, &sig).map_err(|e| {
205                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
206            })
207        }
208    };
209}
210
211ecdsa_curve_verify!(verify_ecdsa_p256, "p256", p256, 32);
212ecdsa_curve_verify!(verify_ecdsa_p384, "p384", p384, 48);
213ecdsa_curve_verify!(verify_ecdsa_p521, "p521", p521, 66);
214
215/// Which curves an ECDSA verifier accepts.
216#[derive(Clone, Copy)]
217struct Curves {
218    p256: bool,
219    p384: bool,
220    p521: bool,
221}
222
223/// ECDSA dispatch: digest from `algorithm`, curve from `issuer_spki`.
224fn verify_ecdsa(
225    curves: Curves,
226    algorithm: AlgorithmIdentifierRef<'_>,
227    issuer_spki: SubjectPublicKeyInfoRef<'_>,
228    message: &[u8],
229    signature: &[u8],
230) -> VerifyResult {
231    let digest =
232        ecdsa_digest(algorithm.oid).ok_or_else(VerificationError::unsupported_algorithm)?;
233    // RFC 5758 §3.2: the parameters field MUST be absent.
234    if algorithm.parameters.is_some() {
235        return Err(VerificationError::unsupported_algorithm());
236    }
237    let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
238    match curve {
239        #[cfg(feature = "p256")]
240        OID_SECP256R1 if curves.p256 => verify_ecdsa_p256(issuer_spki, digest, message, signature),
241        #[cfg(feature = "p384")]
242        OID_SECP384R1 if curves.p384 => verify_ecdsa_p384(issuer_spki, digest, message, signature),
243        #[cfg(feature = "p521")]
244        OID_SECP521R1 if curves.p521 => verify_ecdsa_p521(issuer_spki, digest, message, signature),
245        _ => Err(VerificationError::unsupported_key()),
246    }
247}
248
249macro_rules! ecdsa_verifier {
250    ($(#[$doc:meta])* $name:ident, $feature:literal, $field:ident) => {
251        $(#[$doc])*
252        #[cfg(feature = $feature)]
253        #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
254        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
255        pub struct $name;
256
257        #[cfg(feature = $feature)]
258        impl SignatureVerifier for $name {
259            fn verify_signature(
260                &self,
261                algorithm: AlgorithmIdentifierRef<'_>,
262                issuer_spki: SubjectPublicKeyInfoRef<'_>,
263                message: &[u8],
264                signature: &[u8],
265            ) -> VerifyResult {
266                let curves = Curves {
267                    p256: false,
268                    p384: false,
269                    p521: false,
270                };
271                let curves = Curves {
272                    $field: true,
273                    ..curves
274                };
275                verify_ecdsa(curves, algorithm, issuer_spki, message, signature)
276            }
277        }
278    };
279}
280
281ecdsa_verifier!(
282    /// ECDSA verifier for P-256 (`secp256r1`) issuer keys.
283    ///
284    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
285    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
286    /// absent). Rejects issuer keys on any other curve.
287    /// Feature-gated behind `p256`.
288    EcdsaP256Verifier,
289    "p256",
290    p256
291);
292
293ecdsa_verifier!(
294    /// ECDSA verifier for P-384 (`secp384r1`) issuer keys.
295    ///
296    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
297    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
298    /// absent). Rejects issuer keys on any other curve.
299    /// Feature-gated behind `p384`.
300    EcdsaP384Verifier,
301    "p384",
302    p384
303);
304
305ecdsa_verifier!(
306    /// ECDSA verifier for P-521 (`secp521r1`) issuer keys.
307    ///
308    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
309    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
310    /// absent). Rejects issuer keys on any other curve.
311    /// Feature-gated behind `p521`.
312    EcdsaP521Verifier,
313    "p521",
314    p521
315);
316
317// ---------------------------------------------------------------------------
318// RSA
319// ---------------------------------------------------------------------------
320
321/// Decodes an RSA public key from an SPKI whose algorithm is `rsaEncryption`
322/// (parameters NULL or absent, RFC 3279 §2.3.1) or, when `allow_pss_key` is
323/// set, `id-RSASSA-PSS` (RFC 4055 §1.2).
324///
325/// Moduli from 1024 to 8192 bits are accepted (the `rsa` crate's limits).
326#[cfg(feature = "rsa")]
327fn rsa_public_key(
328    spki: &SubjectPublicKeyInfoRef<'_>,
329    allow_pss_key: bool,
330) -> core::result::Result<rsa::PublicKey, VerificationError> {
331    use rsa::pkcs1::DecodeRsaPublicKey as _;
332
333    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
334        && spki.algorithm.parameters.is_none_or(|p| p.is_null());
335    let pss_ok = allow_pss_key && spki.algorithm.oid == OID_RSASSA_PSS;
336    if !(oid_ok || pss_ok) {
337        return Err(VerificationError::unsupported_key());
338    }
339    let key_bytes = spki
340        .subject_public_key
341        .as_bytes()
342        .ok_or_else(VerificationError::malformed_key)?;
343    rsa::PublicKey::from_pkcs1_der(key_bytes)
344        .map_err(|e| VerificationError::with_source(VerificationErrorKind::MalformedKey, e))
345}
346
347/// RSA PKCS#1 v1.5 verification with the given digest.
348#[cfg(feature = "rsa")]
349fn verify_rsa_pkcs1v15(
350    digest: Sha2,
351    algorithm: AlgorithmIdentifierRef<'_>,
352    issuer_spki: SubjectPublicKeyInfoRef<'_>,
353    message: &[u8],
354    signature: &[u8],
355) -> VerifyResult {
356    use rsa::pkcs1v15::{Signature, VerifyingKey};
357    use rsa::signature::Verifier as _;
358
359    // RFC 4055 §5: parameters MUST be NULL; absent is accepted for
360    // interoperability, matching the issuer-key decoding above.
361    if !algorithm.parameters.is_none_or(|p| p.is_null()) {
362        return Err(VerificationError::unsupported_algorithm());
363    }
364    let key = rsa_public_key(&issuer_spki, false)?;
365    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
366    let result = match digest {
367        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new(key).verify(message, &sig),
368        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new(key).verify(message, &sig),
369        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new(key).verify(message, &sig),
370    };
371    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
372}
373
374/// Hash named by an RFC 4055 `HashAlgorithm` identifier (parameters NULL or
375/// absent, RFC 4055 §2.1).
376#[cfg(feature = "rsa")]
377fn rfc4055_hash(alg: &spki::AlgorithmIdentifierOwned) -> Option<Sha2> {
378    if !alg.parameters.as_ref().is_none_or(der::Any::is_null) {
379        return None;
380    }
381    match alg.oid {
382        OID_SHA256 => Some(Sha2::Sha256),
383        OID_SHA384 => Some(Sha2::Sha384),
384        OID_SHA512 => Some(Sha2::Sha512),
385        _ => None,
386    }
387}
388
389/// RSASSA-PSS verification (RFC 4055 §3.1, RFC 8017 §8.1.2).
390///
391/// Supported parameters: `hashAlgorithm` SHA-256, SHA-384 or SHA-512;
392/// `maskGenAlgorithm` MGF1 over the same hash; any `saltLength`;
393/// `trailerField` 1. The default parameters (SHA-1) are rejected.
394#[cfg(feature = "rsa")]
395fn verify_rsa_pss(
396    algorithm: AlgorithmIdentifierRef<'_>,
397    issuer_spki: SubjectPublicKeyInfoRef<'_>,
398    message: &[u8],
399    signature: &[u8],
400) -> VerifyResult {
401    use der::{Decode as _, Encode as _};
402    use rsa::pkcs1::{RsaPssParamsOwned, TrailerField};
403    use rsa::pss::{Signature, VerifyingKey};
404    use rsa::signature::hazmat::PrehashVerifier as _;
405
406    let params_der = algorithm
407        .parameters
408        .ok_or_else(VerificationError::unsupported_algorithm)?
409        .to_der()
410        .map_err(|_| VerificationError::unsupported_algorithm())?;
411    let params = RsaPssParamsOwned::from_der(&params_der)
412        .map_err(|_| VerificationError::unsupported_algorithm())?;
413    let hash = rfc4055_hash(&params.hash).ok_or_else(VerificationError::unsupported_algorithm)?;
414    if params.mask_gen.oid != OID_MGF1 {
415        return Err(VerificationError::unsupported_algorithm());
416    }
417    let mgf_hash = params
418        .mask_gen
419        .parameters
420        .as_ref()
421        .and_then(rfc4055_hash)
422        .ok_or_else(VerificationError::unsupported_algorithm)?;
423    if mgf_hash != hash || params.trailer_field != TrailerField::BC {
424        return Err(VerificationError::unsupported_algorithm());
425    }
426    // RFC 4055 §3.1: when the issuer key is an id-RSASSA-PSS key with
427    // parameters, the signature must use the same hash and MGF and a salt
428    // at least as long. We check the hash and MGF; a key restricted that
429    // way still verifies only signatures that match its own parameters.
430    if issuer_spki.algorithm.oid == OID_RSASSA_PSS {
431        if let Some(key_params) = issuer_spki.algorithm.parameters {
432            let key_params_der = key_params
433                .to_der()
434                .map_err(|_| VerificationError::malformed_key())?;
435            let key_params = RsaPssParamsOwned::from_der(&key_params_der)
436                .map_err(|_| VerificationError::malformed_key())?;
437            let key_hash =
438                rfc4055_hash(&key_params.hash).ok_or_else(VerificationError::unsupported_key)?;
439            if key_hash != hash || params.salt_len < key_params.salt_len {
440                return Err(VerificationError::unsupported_key());
441            }
442        }
443    }
444    let key = rsa_public_key(&issuer_spki, true)?;
445    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
446    let salt_len = usize::from(params.salt_len);
447    let prehash = sha2_digest(hash, message);
448    let result = match hash {
449        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new_with_salt_len(key, salt_len)
450            .verify_prehash(&prehash, &sig),
451        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new_with_salt_len(key, salt_len)
452            .verify_prehash(&prehash, &sig),
453        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new_with_salt_len(key, salt_len)
454            .verify_prehash(&prehash, &sig),
455    };
456    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
457}
458
459macro_rules! rsa_pkcs1v15_verifier {
460    ($(#[$doc:meta])* $name:ident, $oid:ident, $digest:ident) => {
461        $(#[$doc])*
462        #[cfg(feature = "rsa")]
463        #[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
464        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
465        pub struct $name;
466
467        #[cfg(feature = "rsa")]
468        impl SignatureVerifier for $name {
469            fn verify_signature(
470                &self,
471                algorithm: AlgorithmIdentifierRef<'_>,
472                issuer_spki: SubjectPublicKeyInfoRef<'_>,
473                message: &[u8],
474                signature: &[u8],
475            ) -> VerifyResult {
476                if algorithm.oid != $oid {
477                    return Err(VerificationError::unsupported_algorithm());
478                }
479                verify_rsa_pkcs1v15(Sha2::$digest, algorithm, issuer_spki, message, signature)
480            }
481        }
482    };
483}
484
485rsa_pkcs1v15_verifier!(
486    /// RSA with PKCS#1 v1.5 padding and SHA-256 signature verifier.
487    ///
488    /// Handles OID `sha256WithRSAEncryption` (1.2.840.113549.1.1.11).
489    /// Feature-gated behind `rsa`.
490    RsaPkcs1v15Sha256Verifier,
491    OID_SHA256_WITH_RSA,
492    Sha256
493);
494
495rsa_pkcs1v15_verifier!(
496    /// RSA with PKCS#1 v1.5 padding and SHA-384 signature verifier.
497    ///
498    /// Handles OID `sha384WithRSAEncryption` (1.2.840.113549.1.1.12).
499    /// Feature-gated behind `rsa`.
500    RsaPkcs1v15Sha384Verifier,
501    OID_SHA384_WITH_RSA,
502    Sha384
503);
504
505rsa_pkcs1v15_verifier!(
506    /// RSA with PKCS#1 v1.5 padding and SHA-512 signature verifier.
507    ///
508    /// Handles OID `sha512WithRSAEncryption` (1.2.840.113549.1.1.13).
509    /// Feature-gated behind `rsa`.
510    RsaPkcs1v15Sha512Verifier,
511    OID_SHA512_WITH_RSA,
512    Sha512
513);
514
515/// Verifies RSA PKCS#1 v1.5 signatures over SHA-1. **Legacy interop only.**
516///
517/// # Security
518///
519/// SHA-1 collisions are practical. SHAttered (2017) produced a colliding
520/// pair for roughly 2^63 operations, and chosen-prefix collisions followed
521/// in 2020 at lower cost. An attacker able to mint a certificate that
522/// collides with one a CA signed can substitute it, and the signature will
523/// verify. Treat a SHA-1-signed chain as evidence of provenance, not as
524/// proof of identity.
525///
526/// It exists because messages outlive algorithms. S/MIME signed in 2015
527/// sits in a mailbox today, and a client that cannot check its chain can
528/// tell the user nothing useful — "verify, then warn" is what clients
529/// actually do. CA/Browser Forum rules forbid new SHA-1 issuance; they do
530/// not delete the archive.
531///
532/// Off by default, behind the `rsa-sha1` feature, and deliberately *not*
533/// in the `rustcrypto` umbrella — that umbrella means "algorithms we
534/// recommend". New deployments MUST NOT enable this.
535///
536/// Verification only. Nothing in this workspace signs with SHA-1 and
537/// nothing is intended to.
538#[cfg(feature = "rsa-sha1")]
539#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
540#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
541pub struct RsaPkcs1v15Sha1Verifier;
542
543#[cfg(feature = "rsa-sha1")]
544impl SignatureVerifier for RsaPkcs1v15Sha1Verifier {
545    fn verify_signature(
546        &self,
547        algorithm: AlgorithmIdentifierRef<'_>,
548        issuer_spki: SubjectPublicKeyInfoRef<'_>,
549        message: &[u8],
550        signature: &[u8],
551    ) -> VerifyResult {
552        use rsa::pkcs1v15::{Signature, VerifyingKey};
553        use rsa::signature::Verifier as _;
554
555        if algorithm.oid != OID_SHA1_WITH_RSA {
556            return Err(VerificationError::unsupported_algorithm());
557        }
558        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
559            return Err(VerificationError::unsupported_algorithm());
560        }
561        let key = rsa_public_key(&issuer_spki, false)?;
562        let sig =
563            Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
564        VerifyingKey::<sha1::Sha1>::new(key)
565            .verify(message, &sig)
566            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
567    }
568}
569
570/// Verifies ECDSA P-256 signatures over SHA-1. **Legacy interop only.**
571///
572/// # Security
573///
574/// See [`RsaPkcs1v15Sha1Verifier`]: the same practical collision attacks
575/// apply and the same conclusion follows. A SHA-1-signed chain is
576/// provenance, not proof.
577///
578/// Off by default, behind the `ecdsa-sha1` feature, outside the
579/// `rustcrypto` umbrella. New deployments MUST NOT enable this.
580///
581/// # Scope
582///
583/// P-256 only. `ecdsa-with-SHA1` names no curve, so P-384 and P-521 with
584/// SHA-1 are expressible and do occur, but a deployment old enough to
585/// still sign with SHA-1 is overwhelmingly on P-256 or RSA. Those
586/// combinations are out of scope rather than overlooked, and surface as
587/// [`UnsupportedKey`](VerificationErrorKind::UnsupportedKey), which says
588/// the curve was the problem.
589///
590/// Verification only.
591#[cfg(feature = "ecdsa-sha1")]
592#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
593#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
594pub struct EcdsaP256Sha1Verifier;
595
596#[cfg(feature = "ecdsa-sha1")]
597impl SignatureVerifier for EcdsaP256Sha1Verifier {
598    fn verify_signature(
599        &self,
600        algorithm: AlgorithmIdentifierRef<'_>,
601        issuer_spki: SubjectPublicKeyInfoRef<'_>,
602        message: &[u8],
603        signature: &[u8],
604    ) -> VerifyResult {
605        use p256::ecdsa::{DerSignature, VerifyingKey};
606        use signature::hazmat::PrehashVerifier as _;
607
608        if algorithm.oid != OID_ECDSA_WITH_SHA1 {
609            return Err(VerificationError::unsupported_algorithm());
610        }
611        if algorithm.parameters.is_some() {
612            return Err(VerificationError::unsupported_algorithm());
613        }
614        // P-256 only, so a P-384 or P-521 key is reported as an
615        // unsupported key rather than checked against the wrong curve.
616        if ec_named_curve(&issuer_spki) != Some(OID_SECP256R1) {
617            return Err(VerificationError::unsupported_key());
618        }
619        let vk =
620            VerifyingKey::try_from(issuer_spki).map_err(|_| VerificationError::malformed_key())?;
621        let sig = DerSignature::try_from(signature)
622            .map_err(|_| VerificationError::invalid_signature())?;
623        // Left-padded to the field width: FIPS 186-4 uses the leftmost
624        // min(N, outlen) bits of the hash, which for a 160-bit digest and
625        // a 256-bit field is all of it, and zero-padding on the left
626        // preserves the integer value.
627        let prehash = pad_prehash(sha1_digest(message), 32);
628        vk.verify_prehash(&prehash, &sig)
629            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
630    }
631}
632
633/// RSASSA-PSS signature verifier (RFC 4055 §3.1).
634///
635/// Handles OID `id-RSASSA-PSS` (1.2.840.113549.1.1.10) with
636/// `hashAlgorithm` SHA-256, SHA-384 or SHA-512, `maskGenAlgorithm` MGF1
637/// over the same hash, any `saltLength`, and `trailerField` 1. The issuer
638/// key may be `rsaEncryption` or `id-RSASSA-PSS`. Feature-gated behind
639/// `rsa`.
640#[cfg(feature = "rsa")]
641#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
642#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
643pub struct RsaPssVerifier;
644
645#[cfg(feature = "rsa")]
646impl SignatureVerifier for RsaPssVerifier {
647    fn verify_signature(
648        &self,
649        algorithm: AlgorithmIdentifierRef<'_>,
650        issuer_spki: SubjectPublicKeyInfoRef<'_>,
651        message: &[u8],
652        signature: &[u8],
653    ) -> VerifyResult {
654        if algorithm.oid != OID_RSASSA_PSS {
655            return Err(VerificationError::unsupported_algorithm());
656        }
657        verify_rsa_pss(algorithm, issuer_spki, message, signature)
658    }
659}
660
661// ---------------------------------------------------------------------------
662// Ed25519
663// ---------------------------------------------------------------------------
664
665/// Ed25519 signature verifier (RFC 8410, RFC 8032 §5.1.7).
666///
667/// Handles OID `id-Ed25519` (1.3.101.112) for both the signature algorithm
668/// and the issuer key; RFC 8410 §3 requires absent parameters in both.
669/// Verification uses `ed25519-dalek`'s `verify_strict`, which also rejects
670/// small-order public keys and non-canonical signatures.
671/// Feature-gated behind `ed25519`.
672#[cfg(feature = "ed25519")]
673#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
674#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
675pub struct Ed25519Verifier;
676
677#[cfg(feature = "ed25519")]
678impl SignatureVerifier for Ed25519Verifier {
679    fn verify_signature(
680        &self,
681        algorithm: AlgorithmIdentifierRef<'_>,
682        issuer_spki: SubjectPublicKeyInfoRef<'_>,
683        message: &[u8],
684        signature: &[u8],
685    ) -> VerifyResult {
686        if algorithm.oid != OID_ED25519 || algorithm.parameters.is_some() {
687            return Err(VerificationError::unsupported_algorithm());
688        }
689        if issuer_spki.algorithm.oid != OID_ED25519 || issuer_spki.algorithm.parameters.is_some() {
690            return Err(VerificationError::unsupported_key());
691        }
692        let key_bytes: &[u8; 32] = issuer_spki
693            .subject_public_key
694            .as_bytes()
695            .and_then(|b| b.try_into().ok())
696            .ok_or_else(VerificationError::malformed_key)?;
697        let vk = ed25519_dalek::VerifyingKey::from_bytes(key_bytes)
698            .map_err(|_| VerificationError::malformed_key())?;
699        let sig = ed25519_dalek::Signature::from_slice(signature)
700            .map_err(|_| VerificationError::invalid_signature())?;
701        vk.verify_strict(message, &sig)
702            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
703    }
704}
705
706// ---------------------------------------------------------------------------
707// DefaultVerifier
708// ---------------------------------------------------------------------------
709
710/// A [`SignatureVerifier`] covering every `RustCrypto` backend enabled at
711/// build time.
712///
713/// This is the recommended out-of-the-box verifier. With all backend
714/// features on (`rustcrypto`) it supports:
715///
716/// - ECDSA (`ecdsa-with-SHA256`, `-SHA384`, `-SHA512`) on P-256, P-384 and
717///   P-521 issuer keys (features `p256`, `p384`, `p521`). The curve is taken
718///   from the issuer's `SubjectPublicKeyInfo`, not from the signature OID.
719/// - RSA PKCS#1 v1.5 with SHA-256, SHA-384 or SHA-512 (feature `rsa`).
720/// - RSASSA-PSS as described on [`RsaPssVerifier`] (feature `rsa`).
721/// - Ed25519 (feature `ed25519`).
722///
723/// Anything else returns an [`UnsupportedAlgorithm`] error, including
724/// SHA-1 based algorithms.
725///
726/// [`UnsupportedAlgorithm`]: crate::VerificationErrorKind::UnsupportedAlgorithm
727///
728/// To support additional algorithms, implement [`SignatureVerifier`]
729/// directly and fall back to `DefaultVerifier` for the rest.
730#[cfg(any(
731    feature = "p256",
732    feature = "p384",
733    feature = "p521",
734    feature = "rsa",
735    feature = "ed25519"
736))]
737#[cfg_attr(
738    docsrs,
739    doc(cfg(any(
740        feature = "p256",
741        feature = "p384",
742        feature = "p521",
743        feature = "rsa",
744        feature = "ed25519"
745    )))
746)]
747#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
748pub struct DefaultVerifier;
749
750#[cfg(any(
751    feature = "p256",
752    feature = "p384",
753    feature = "p521",
754    feature = "rsa",
755    feature = "ed25519"
756))]
757impl SignatureVerifier for DefaultVerifier {
758    fn verify_signature(
759        &self,
760        algorithm: AlgorithmIdentifierRef<'_>,
761        issuer_spki: SubjectPublicKeyInfoRef<'_>,
762        message: &[u8],
763        signature: &[u8],
764    ) -> VerifyResult {
765        let oid = algorithm.oid;
766        if ecdsa_digest(oid).is_some() {
767            let curves = Curves {
768                p256: cfg!(feature = "p256"),
769                p384: cfg!(feature = "p384"),
770                p521: cfg!(feature = "p521"),
771            };
772            return verify_ecdsa(curves, algorithm, issuer_spki, message, signature);
773        }
774        #[cfg(feature = "rsa")]
775        {
776            let digest = match oid {
777                OID_SHA256_WITH_RSA => Some(Sha2::Sha256),
778                OID_SHA384_WITH_RSA => Some(Sha2::Sha384),
779                OID_SHA512_WITH_RSA => Some(Sha2::Sha512),
780                _ => None,
781            };
782            if let Some(digest) = digest {
783                return verify_rsa_pkcs1v15(digest, algorithm, issuer_spki, message, signature);
784            }
785            if oid == OID_RSASSA_PSS {
786                return verify_rsa_pss(algorithm, issuer_spki, message, signature);
787            }
788        }
789        #[cfg(feature = "ed25519")]
790        if oid == OID_ED25519 {
791            return Ed25519Verifier.verify_signature(algorithm, issuer_spki, message, signature);
792        }
793        // Legacy SHA-1, last and only when asked for. Placed after every
794        // modern algorithm so enabling it cannot change how anything else
795        // is dispatched.
796        #[cfg(feature = "rsa-sha1")]
797        if oid == OID_SHA1_WITH_RSA {
798            return RsaPkcs1v15Sha1Verifier.verify_signature(
799                algorithm,
800                issuer_spki,
801                message,
802                signature,
803            );
804        }
805        #[cfg(feature = "ecdsa-sha1")]
806        if oid == OID_ECDSA_WITH_SHA1 {
807            return EcdsaP256Sha1Verifier.verify_signature(
808                algorithm,
809                issuer_spki,
810                message,
811                signature,
812            );
813        }
814        Err(VerificationError::unsupported_algorithm())
815    }
816}