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