diff --git a/crates/sign/README.md b/crates/sign/README.md index 126e938786..a5289cbe30 100644 --- a/crates/sign/README.md +++ b/crates/sign/README.md @@ -118,9 +118,9 @@ needs a prompt to open is listed and asks at signing (issue #179). SHA3-224/256/384/512 and RIPEMD-160. RSA PKCS #1 v1.5 and RSASSA-PSS (the hash, MGF1 hash and salt length the signature declares), ECDSA on P-256, P-384, P-521, brainpoolP256r1, P384r1 and P512r1 (also BSI "plain" ECDSA), and Ed25519 (RFC 8419, over the signed attributes). - Signing: RSA, P-256, P-384 with SHA-256/384/512. The RSA padding checks and brainpoolP512r1 are - written here (`rsa_pad`, `ec512`) on `crypto-bigint`, because the typed APIs of the `rsa` crate - and RustCrypto don't cover them. + Signing: RSA, P-256, P-384 with SHA-256/384/512. Verification delegates to the existing pinned `craft-pkcs7` implementation, including + RSA padding checks and brainpoolP512r1 arithmetic. PdfCraft keeps its document trust policy, + platform signing and user-facing error/diagnostic vocabulary. Oracles: poppler's `pdfsig` reports our signatures valid; OpenSSL reads our `.p12` files and verifies our CMS; `tests/data/openssl-signed.pdf` is a signature OpenSSL made, which we validate. diff --git a/crates/sign/src/der.rs b/crates/sign/src/der.rs index f51937acec..055adef6fa 100644 --- a/crates/sign/src/der.rs +++ b/crates/sign/src/der.rs @@ -8,7 +8,7 @@ use craft_pkcs7::der as shared; pub use shared::{Form, Time, algorithm, bit_string, boolean, explicit, ia5, int, null, octets, oid, printable, seq, set_of, tag, tlv, uint, utf8}; use std::borrow::Cow; -fn app_error(error: craft_pkcs7::Error) -> SignError { +pub(crate) fn app_error(error: craft_pkcs7::Error) -> SignError { match error { craft_pkcs7::Error::Malformed(message) => SignError::Malformed(message), craft_pkcs7::Error::Unsupported(message) => SignError::Unsupported(message), diff --git a/crates/sign/src/ec512.rs b/crates/sign/src/ec512.rs index 3e4c0e307c..6637746f46 100644 --- a/crates/sign/src/ec512.rs +++ b/crates/sign/src/ec512.rs @@ -1,155 +1,12 @@ -//! ECDSA verification on brainpoolP512r1 (RFC 5639), for which no RustCrypto curve crate exists. -//! -//! Verification only, on public data, so plain affine arithmetic over `crypto-bigint` is enough: -//! no secret is involved, and a verification takes a few milliseconds. Checked against -//! signatures made by OpenSSL (`tests/it/crypto.rs`). - -use rsa::BoxedUint; - +//! Regression fixtures for the shared brainpool verification route (test-only). +use crate::keys::{DigestAlg, PublicKey, Scheme}; const P: &str = "aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3"; -const A: &str = "7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca"; -const B: &str = "3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723"; const GX: &str = "81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822"; const GY: &str = "7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892"; const N: &str = "aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069"; - -const BITS: u32 = 512; -const BYTES: usize = 64; - -type Point = Option<(BoxedUint, BoxedUint)>; - -fn big(bytes: &[u8]) -> Option { - let pad = BYTES.checked_sub(bytes.len())?; - let mut v = vec![0u8; pad]; - v.extend_from_slice(bytes); - BoxedUint::from_be_slice(&v, BITS).ok() +fn verify(public: &[u8], digest: &[u8], rs: &[u8]) -> Option { + PublicKey::BrainpoolP512(public.to_vec()).verify(Scheme::Ecdsa, DigestAlg::Sha512, digest, rs).ok() } - -fn hex(s: &str) -> Option { - let bytes: Option> = (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect(); - big(&bytes?) -} - -/// Arithmetic modulo a prime. -struct Field { - nz: crypto_bigint::NonZero, -} - -impl Field { - fn new(p: BoxedUint) -> Option { - let nz = Option::from(crypto_bigint::NonZero::new(p))?; - Some(Field { nz }) - } - fn add(&self, a: &BoxedUint, b: &BoxedUint) -> BoxedUint { - a.add_mod(b, &self.nz) - } - fn sub(&self, a: &BoxedUint, b: &BoxedUint) -> BoxedUint { - a.sub_mod(b, &self.nz) - } - fn mul(&self, a: &BoxedUint, b: &BoxedUint) -> BoxedUint { - a.mul_mod(b, &self.nz) - } - fn inv(&self, a: &BoxedUint) -> Option { - Option::from(a.invert_mod(&self.nz)) - } - /// Whether `v` is reduced (`v < p`). `add_mod`, `sub_mod` and friends assert it, and panic on - /// anything else, so nothing from outside may reach them without this check. - fn is_reduced(&self, v: &BoxedUint) -> bool { - v < self.nz.as_ref() - } -} - -struct Curve { - f: Field, - a: BoxedUint, - b: BoxedUint, - g: (BoxedUint, BoxedUint), - n: BoxedUint, -} - -impl Curve { - fn brainpool_p512r1() -> Option { - Some(Curve { f: Field::new(hex(P)?)?, a: hex(A)?, b: hex(B)?, g: (hex(GX)?, hex(GY)?), n: hex(N)? }) - } - - fn on_curve(&self, x: &BoxedUint, y: &BoxedUint) -> bool { - let f = &self.f; - let lhs = f.mul(y, y); - let rhs = f.add(&f.add(&f.mul(&f.mul(x, x), x), &f.mul(&self.a, x)), &self.b); - lhs == rhs - } - - fn double(&self, p: &Point) -> Point { - let (x, y) = p.as_ref()?; - let f = &self.f; - if bool::from(y.is_zero()) { - return None; - } - let three = big(&[3])?; - let two = big(&[2])?; - let num = f.add(&f.mul(&three, &f.mul(x, x)), &self.a); - let lambda = f.mul(&num, &f.inv(&f.mul(&two, y))?); - let x3 = f.sub(&f.sub(&f.mul(&lambda, &lambda), x), x); - let y3 = f.sub(&f.mul(&lambda, &f.sub(x, &x3)), y); - Some((x3, y3)) - } - - fn add(&self, p: &Point, q: &Point) -> Point { - let (Some((x1, y1)), Some((x2, y2))) = (p, q) else { return p.clone().or_else(|| q.clone()) }; - let f = &self.f; - if x1 == x2 { - return if y1 == y2 { self.double(p) } else { None }; - } - let lambda = f.mul(&f.sub(y2, y1), &f.inv(&f.sub(x2, x1))?); - let x3 = f.sub(&f.sub(&f.mul(&lambda, &lambda), x1), x2); - let y3 = f.sub(&f.mul(&lambda, &f.sub(x1, &x3)), y1); - Some((x3, y3)) - } - - /// `k · p`, double-and-add from the top bit. - fn mul(&self, k: &BoxedUint, p: &Point) -> Point { - let mut acc: Point = None; - for i in (0..k.bit_width_vartime()).rev() { - acc = self.double(&acc); - if bool::from(k.bit(i)) { - acc = self.add(&acc, p); - } - } - acc - } -} - -/// Check the ECDSA signature `r ‖ s` (64 bytes each) of `digest` with the SEC1 uncompressed -/// point `public` (`04 ‖ x ‖ y`). `None`: the key is not a valid point or the input is malformed. -pub fn verify(public: &[u8], digest: &[u8], rs: &[u8]) -> Option { - let c = Curve::brainpool_p512r1()?; - let [0x04, xy @ ..] = public else { return None }; - if xy.len() != 2 * BYTES || rs.len() != 2 * BYTES { - return None; - } - let (qx, qy) = (big(xy.get(..BYTES)?)?, big(xy.get(BYTES..)?)?); - // SEC 1 §2.3.4: coordinates are field elements. The field arithmetic panics on unreduced ones. - if !c.f.is_reduced(&qx) || !c.f.is_reduced(&qy) || !c.on_curve(&qx, &qy) { - return None; - } - let (r, s) = (big(rs.get(..BYTES)?)?, big(rs.get(BYTES..)?)?); - let n = crypto_bigint::NonZero::new(c.n.clone()); - let n: crypto_bigint::NonZero = Option::from(n)?; - let zero = |v: &BoxedUint| bool::from(v.is_zero()); - if zero(&r) || zero(&s) || r >= c.n || s >= c.n { - return Some(false); - } - // The leftmost 512 bits of the digest (all of it, for digests up to SHA-512). - let e = big(digest.get(..digest.len().min(BYTES))?)?.rem_vartime(&n); - let w: BoxedUint = Option::from(s.invert_mod(&n))?; - let u1 = e.mul_mod(&w, &n); - let u2 = r.mul_mod(&w, &n); - let point = c.add(&c.mul(&u1, &Some(c.g.clone())), &c.mul(&u2, &Some((qx, qy)))); - // The point at infinity is no valid result (X9.62 §7.4.1 step 5): the signature is wrong. - let Some((x, _)) = point else { return Some(false) }; - Some(x.rem_vartime(&n) == r) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/sign/src/keys.rs b/crates/sign/src/keys.rs index b5d466ae81..e4dff006c1 100644 --- a/crates/sign/src/keys.rs +++ b/crates/sign/src/keys.rs @@ -443,7 +443,7 @@ impl PublicKey { } /// Check `sig` over a message whose digest (with `alg`) is `digest`. Encodings are read - /// leniently (see [`crate::rsa_pad`], [`ecdsa_rs`]); the cryptographic check never is. + /// leniently by the existing shared `craft-pkcs7` verifier; the cryptographic check never is. /// `Err(Unsupported)` means "can't tell", as opposed to `Ok(false)`: "doesn't match". pub fn verify(&self, scheme: Scheme, alg: DigestAlg, digest: &[u8], sig: &[u8]) -> Result { self.verify_noting(scheme, alg, digest, sig, &mut Vec::new()) @@ -453,13 +453,7 @@ impl PublicKey { /// too small to rely on ([`PublicKey::weakness`]). Only meaningful when it returns `Ok(true)`: /// a signature that doesn't verify may leave notes about how far it got. pub fn verify_noting(&self, scheme: Scheme, alg: DigestAlg, digest: &[u8], sig: &[u8], notes: &mut Vec<&'static str>) -> Result { - let verified = self.verify_scheme(scheme, alg, digest, sig, notes); - if let Ok(true) = verified - && let Some(weak) = self.weakness() - { - notes.push(weak); - } - verified + self.shared_key().verify_noting(shared_scheme(scheme), shared_digest(alg), digest, sig, notes).map_err(crate::der::app_error) } /// What to tell the user when a signature that still validates was made with this key, or @@ -473,99 +467,55 @@ impl PublicKey { } } - fn verify_scheme(&self, scheme: Scheme, alg: DigestAlg, digest: &[u8], sig: &[u8], notes: &mut Vec<&'static str>) -> Result { - match (self, scheme) { - (PublicKey::Unsupported { what, .. }, _) => Err(SignError::Unsupported(what.clone())), - (PublicKey::Rsa { n, e }, Scheme::RsaPkcs1) => crate::rsa_pad::pkcs1_verify(n, e, alg, digest, sig, notes), - (PublicKey::Rsa { n, e }, Scheme::RsaPss(params)) => crate::rsa_pad::pss_verify(n, e, alg, params, digest, sig, notes), - (PublicKey::Ed25519(_), _) => Err(SignError::Unsupported("Ed25519 signs the message, not a digest".into())), - (PublicKey::P256(p), Scheme::Ecdsa) => { - use p256::ecdsa::signature::hazmat::PrehashVerifier; - let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(p).map_err(|_| SignError::Malformed("P-256 key".into()))?; - let Some(s) = ecdsa_rs(sig, 32, notes).and_then(|rs| p256::ecdsa::Signature::from_slice(&rs).ok()) else { return Ok(false) }; - Ok(key.verify_prehash(digest, &s).is_ok()) - } - (PublicKey::P384(p), Scheme::Ecdsa) => { - use p384::ecdsa::signature::hazmat::PrehashVerifier; - let key = p384::ecdsa::VerifyingKey::from_sec1_bytes(p).map_err(|_| SignError::Malformed("P-384 key".into()))?; - let Some(s) = ecdsa_rs(sig, 48, notes).and_then(|rs| p384::ecdsa::Signature::from_slice(&rs).ok()) else { return Ok(false) }; - Ok(key.verify_prehash(digest, &s).is_ok()) - } - (PublicKey::P521(p), Scheme::Ecdsa) => { - use p521::ecdsa::signature::hazmat::PrehashVerifier; - let key = p521::ecdsa::VerifyingKey::from_sec1_bytes(p).map_err(|_| SignError::Malformed("P-521 key".into()))?; - let Some(s) = ecdsa_rs(sig, 66, notes).and_then(|rs| p521::ecdsa::Signature::from_slice(&rs).ok()) else { return Ok(false) }; - Ok(key.verify_prehash(digest, &s).is_ok()) - } - (PublicKey::BrainpoolP256(p), Scheme::Ecdsa) => { - use ecdsa::signature::hazmat::PrehashVerifier; - type Curve = bp256::BrainpoolP256r1; - let key = ecdsa::VerifyingKey::::from_sec1_bytes(p).map_err(|_| SignError::Malformed("brainpoolP256r1 key".into()))?; - let Some(s) = ecdsa_rs(sig, 32, notes).and_then(|rs| ecdsa::Signature::::from_slice(&rs).ok()) else { return Ok(false) }; - Ok(key.verify_prehash(digest, &s).is_ok()) - } - (PublicKey::BrainpoolP384(p), Scheme::Ecdsa) => { - use ecdsa::signature::hazmat::PrehashVerifier; - type Curve = bp384::BrainpoolP384r1; - let key = ecdsa::VerifyingKey::::from_sec1_bytes(p).map_err(|_| SignError::Malformed("brainpoolP384r1 key".into()))?; - let Some(s) = ecdsa_rs(sig, 48, notes).and_then(|rs| ecdsa::Signature::::from_slice(&rs).ok()) else { return Ok(false) }; - Ok(key.verify_prehash(digest, &s).is_ok()) - } - (PublicKey::BrainpoolP512(p), Scheme::Ecdsa) => { - let Some(rs) = ecdsa_rs(sig, 64, notes) else { return Ok(false) }; - crate::ec512::verify(p, digest, &rs).ok_or_else(|| SignError::Malformed("brainpoolP512r1 key or signature".into())) - } - _ => Ok(false), + /// Translate representation only; trust decisions and platform signing stay in PdfCraft. + fn shared_key(&self) -> craft_pkcs7::PublicKey { + use craft_pkcs7::PublicKey as Shared; + match self { + Self::Rsa { n, e } => Shared::Rsa { n: n.clone(), e: e.clone() }, + Self::P256(p) => Shared::P256(p.clone()), + Self::P384(p) => Shared::P384(p.clone()), + Self::P521(p) => Shared::P521(p.clone()), + Self::BrainpoolP256(p) => Shared::BrainpoolP256(p.clone()), + Self::BrainpoolP384(p) => Shared::BrainpoolP384(p.clone()), + Self::BrainpoolP512(p) => Shared::BrainpoolP512(p.clone()), + Self::Ed25519(p) => Shared::Ed25519(p.clone()), + Self::Unsupported { what, spki } => Shared::Unsupported { what: what.clone(), spki: spki.clone() }, } } /// Check `sig` over `msg` itself, for the schemes that don't sign a digest (Ed25519, /// RFC 8419: with signed attributes, the message is their DER encoding). pub fn verify_message(&self, scheme: Scheme, msg: &[u8], sig: &[u8]) -> Result { - match (self, scheme) { - (PublicKey::Unsupported { what, .. }, _) => Err(SignError::Unsupported(what.clone())), - (PublicKey::Ed25519(k), Scheme::Ed25519) => { - let bytes: [u8; 32] = k.as_slice().try_into().map_err(|_| SignError::Malformed("Ed25519 key".into()))?; - let key = ed25519_dalek::VerifyingKey::from_bytes(&bytes).map_err(|_| SignError::Malformed("Ed25519 key".into()))?; - let Ok(sig) = ed25519_dalek::Signature::from_slice(sig) else { return Ok(false) }; - Ok(key.verify_strict(msg, &sig).is_ok()) - } - _ => Ok(false), - } + self.shared_key().verify_message(shared_scheme(scheme), msg, sig).map_err(crate::der::app_error) } } -/// An ECDSA signature as the fixed-width `r ‖ s` the curve crates read: from the standard DER -/// `SEQUENCE { INTEGER r, INTEGER s }` (also with integers that have redundant leading zeros or -/// the sign byte missing), or already raw `r ‖ s` as PKCS #11 tokens return it. `notes` gets an -/// entry when the signature was not canonical DER. -fn ecdsa_rs(sig: &[u8], field_len: usize, notes: &mut Vec<&'static str>) -> Option> { - let pad = |int: &[u8]| -> Option> { - let int = int.get(int.iter().position(|b| *b != 0).unwrap_or(int.len())..).unwrap_or_default(); - let zeros = field_len.checked_sub(int.len())?; - Some(std::iter::repeat_n(0u8, zeros).chain(int.iter().copied()).collect()) - }; - if let Ok((t, rest)) = Tlv::parse(sig) - && t.tag == tag::SEQUENCE - && rest.iter().all(|b| *b == 0) - && let Ok(parts) = t.children() - && let [r, s] = parts.as_slice() - && r.tag == tag::INTEGER - && s.tag == tag::INTEGER - { - // Canonical DER: nothing after the sequence, minimal positive integers. - let minimal = |i: &Tlv<'_>| i.value.first().is_some_and(|b| b & 0x80 == 0) && !matches!(i.value, [0, b, ..] if b & 0x80 == 0); - if !rest.is_empty() || !minimal(r) || !minimal(s) { - notes.push("The ECDSA signature is not in canonical DER (trailing bytes, padding or a missing sign byte); it was read anyway."); - } - let mut out = pad(r.value)?; - out.extend(pad(s.value)?); - return Some(out); +fn shared_digest(alg: DigestAlg) -> craft_pkcs7::DigestAlg { + use craft_pkcs7::DigestAlg as Shared; + match alg { + DigestAlg::Sha1 => Shared::Sha1, + DigestAlg::Sha224 => Shared::Sha224, + DigestAlg::Sha256 => Shared::Sha256, + DigestAlg::Sha384 => Shared::Sha384, + DigestAlg::Sha512 => Shared::Sha512, + DigestAlg::Sha512_224 => Shared::Sha512_224, + DigestAlg::Sha512_256 => Shared::Sha512_256, + DigestAlg::Sha3_224 => Shared::Sha3_224, + DigestAlg::Sha3_256 => Shared::Sha3_256, + DigestAlg::Sha3_384 => Shared::Sha3_384, + DigestAlg::Sha3_512 => Shared::Sha3_512, + DigestAlg::Ripemd160 => Shared::Ripemd160, + } +} + +fn shared_scheme(scheme: Scheme) -> craft_pkcs7::keys::Scheme { + use craft_pkcs7::keys::{PssParams as Params, Scheme as Shared}; + match scheme { + Scheme::RsaPkcs1 => Shared::RsaPkcs1, + Scheme::RsaPss(params) => Shared::RsaPss(Params { mgf: shared_digest(params.mgf), salt_len: params.salt_len }), + Scheme::Ecdsa => Shared::Ecdsa, + Scheme::Ed25519 => Shared::Ed25519, } - (sig.len() == field_len * 2).then(|| { - notes.push("The ECDSA signature is the raw r and s values instead of a DER sequence; it was read anyway."); - sig.to_vec() - }) } enum Inner { @@ -767,3 +717,32 @@ impl PrivateKey { } } } + +#[cfg(test)] +mod shared_verification_tests { + use super::*; + + #[test] + fn adapters_preserve_all_hashes_and_pss_parameters() { + for alg in DigestAlg::ALL { + assert_eq!(shared_digest(alg).oid(), alg.oid()); + for salt_len in [None, Some(0), Some(20), Some(usize::MAX)] { + assert_eq!( + shared_scheme(Scheme::RsaPss(PssParams { mgf: alg, salt_len })), + craft_pkcs7::keys::Scheme::RsaPss(craft_pkcs7::keys::PssParams { mgf: shared_digest(alg), salt_len }), + ); + } + } + } + + #[test] + fn adapter_keeps_unsupported_distinct_from_invalid() { + let key = PublicKey::Unsupported { what: "unknown signature algorithm".into(), spki: vec![] }; + assert!( + matches!(key.verify(Scheme::Ecdsa, DigestAlg::Sha256, &[], &[]), Err(SignError::Unsupported(s)) if s == "unknown signature algorithm") + ); + assert!(matches!(PublicKey::P256(vec![]).verify(Scheme::Ecdsa, DigestAlg::Sha256, &[], &[]), Err(SignError::Malformed(_)))); + assert!(matches!(PublicKey::Ed25519(vec![]).verify_message(Scheme::Ed25519, &[], &[]), Err(SignError::Malformed(_)))); + assert!(matches!(PublicKey::P256(vec![]).verify_message(Scheme::Ed25519, &[], &[]), Ok(false))); + } +} diff --git a/crates/sign/src/lib.rs b/crates/sign/src/lib.rs index bfea4aecfa..a34c1f2f1c 100644 --- a/crates/sign/src/lib.rs +++ b/crates/sign/src/lib.rs @@ -10,6 +10,7 @@ pub mod cms; pub mod der; pub mod dss; +#[cfg(test)] mod ec512; pub mod graphic; #[cfg(target_os = "macos")] @@ -18,7 +19,6 @@ pub mod keys; pub mod pdf; pub mod pkcs12; pub mod revocation; -mod rsa_pad; pub mod status_layers; pub mod timestamp; #[cfg(target_os = "windows")] diff --git a/crates/sign/src/rsa_pad.rs b/crates/sign/src/rsa_pad.rs deleted file mode 100644 index 531f703d52..0000000000 --- a/crates/sign/src/rsa_pad.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! RSA signature checks with the padding done here: the raw public-key operation comes from the -//! `rsa` crate, and the EMSA-PKCS1-v1_5 / EMSA-PSS encodings (RFC 8017 §9) are checked against -//! any digest, any MGF1 hash and any salt length, which the `rsa` crate's typed API can't do. -//! Verification only; public data, so nothing here needs to be constant-time. - -use rsa::{BoxedUint, RsaPublicKey}; - -use crate::SignError; -use crate::der; -use crate::keys::{DigestAlg, PssParams}; - -/// The encoded message `sig^e mod n` as exactly `n.len()` bytes, or `None` if the signature is -/// out of range. `n` is the modulus without leading zeros. `notes` gets an entry when the -/// signature value was not written with exactly the modulus' length (RFC 8017 §8.2.2 wants -/// that); some signers drop or add leading zero bytes. -fn encoded_message(n: &[u8], e: &[u8], sig: &[u8], notes: &mut Vec<&'static str>) -> Result>, SignError> { - // Redundant leading zeros would size the big-integer arithmetic (and the backend's own size - // limit) by the encoding rather than the number, so they are dropped before anything is built. - let (n, e) = (trim_zeros(n), trim_zeros(e)); - let k = n.len(); - let key = RsaPublicKey::new(BoxedUint::from_be_slice_vartime(n), BoxedUint::from_be_slice_vartime(e)) - .map_err(|e| SignError::Malformed(format!("RSA key: {e}")))?; - if sig.len() != k { - notes - .push("The RSA signature value does not have the length of the key's modulus (leading zero bytes dropped or added); it was read anyway."); - } - let sig = match sig.iter().position(|b| *b != 0) { - Some(i) => sig.get(i..).unwrap_or_default(), - None => return Ok(None), - }; - // RFC 8017 §5.2.2: the signature representative must be below the modulus. Otherwise s and - // s + n are the same number modulo n and both would verify. Both are big-endian without - // leading zeros here, so a longer one is larger and equal lengths compare byte by byte. - let modulus = n.get(n.iter().position(|b| *b != 0).unwrap_or(n.len())..).unwrap_or_default(); - if sig.len() > modulus.len() || (sig.len() == modulus.len() && sig >= modulus) { - return Ok(None); - } - let Ok(em) = rsa::hazmat::rsa_encrypt(&key, &BoxedUint::from_be_slice_vartime(sig)) else { return Ok(None) }; - let bytes = em.to_be_bytes(); - let mut out = vec![0u8; k.saturating_sub(bytes.len())]; - let skip = bytes.len().saturating_sub(k); - out.extend_from_slice(bytes.get(skip..).unwrap_or_default()); - Ok(Some(out)) -} - -fn trim_zeros(b: &[u8]) -> &[u8] { - b.get(b.iter().position(|x| *x != 0).unwrap_or(b.len())..).unwrap_or_default() -} - -/// `DigestInfo ::= SEQUENCE { AlgorithmIdentifier, OCTET STRING }`. -fn digest_info(alg: DigestAlg, digest: &[u8], null_params: bool) -> Vec { - let id = der::algorithm(alg.oid(), null_params.then(der::null).as_deref()); - der::seq(&[&id, &der::octets(digest)]) -} - -/// RSASSA-PKCS1-v1_5 (RFC 8017 §8.2.2): the signature is checked against the one encoding the -/// message digest should have, built here and compared byte for byte, so there is nothing for a -/// forger to put in trailing or padding bytes. Two `DigestInfo` encodings are accepted: with the -/// NULL parameter (the standard one) and without it, which older signers write (RFC 8017 App. B.1 -/// has verifiers accept both); the second is noted in `notes`. A signature over the bare digest, -/// without any `DigestInfo`, is not accepted: it does not say which hash algorithm it uses. -pub fn pkcs1_verify(n: &[u8], e: &[u8], alg: DigestAlg, digest: &[u8], sig: &[u8], notes: &mut Vec<&'static str>) -> Result { - let Some(em) = encoded_message(n, e, sig, notes)? else { return Ok(false) }; - let k = em.len(); - let forms = [ - (digest_info(alg, digest, true), None), - ( - digest_info(alg, digest, false), - Some("The RSA signature's DigestInfo has no NULL parameter (older signers write it so); it was read anyway."), - ), - ]; - for (t, note) in forms { - let Some(ps) = k.checked_sub(t.len() + 3).filter(|ps| *ps >= 8) else { continue }; - let mut expected = vec![0x00, 0x01]; - expected.extend(std::iter::repeat_n(0xFF, ps)); - expected.push(0x00); - expected.extend_from_slice(&t); - if expected == em { - notes.extend(note); - return Ok(true); - } - } - Ok(false) -} - -/// MGF1 (RFC 8017 §B.2.1). -fn mgf1(hash: DigestAlg, seed: &[u8], len: usize) -> Vec { - let mut out = Vec::with_capacity(len + hash.output_len()); - let mut counter = 0u32; - while out.len() < len { - out.extend(hash.digest(&[seed, &counter.to_be_bytes()])); - counter = counter.wrapping_add(1); - } - out.truncate(len); - out -} - -/// EMSA-PSS-VERIFY (RFC 8017 §9.1.2) with `digest` (of the message, with `alg`) as `mHash`. -pub fn pss_verify( - n: &[u8], - e: &[u8], - alg: DigestAlg, - params: PssParams, - digest: &[u8], - sig: &[u8], - notes: &mut Vec<&'static str>, -) -> Result { - let Some(raw) = encoded_message(n, e, sig, notes)? else { return Ok(false) }; - let n = trim_zeros(n); - let mod_bits = n.first().map_or(0, |b| (n.len() * 8) as u32 - b.leading_zeros()); - let Some(em_bits) = mod_bits.checked_sub(1) else { return Ok(false) }; - let em_len = em_bits.div_ceil(8) as usize; - // emLen is k, or k - 1 when the modulus is 8m+1 bits (then the top byte must be zero). - let Some(lead) = raw.len().checked_sub(em_len) else { return Ok(false) }; - if raw.get(..lead).is_none_or(|l| l.iter().any(|b| *b != 0)) { - return Ok(false); - } - let em = raw.get(lead..).unwrap_or_default(); - let h_len = alg.output_len(); - if digest.len() != h_len { - return Ok(false); - } - let Some(db_len) = em_len.checked_sub(h_len + 1).filter(|l| *l >= 1) else { return Ok(false) }; - if em.last() != Some(&0xBC) { - return Ok(false); - } - let Some((masked_db, rest)) = em.split_at_checked(db_len) else { return Ok(false) }; - let Some(h) = rest.get(..h_len) else { return Ok(false) }; - let spare = (8 * em_len as u32).saturating_sub(em_bits); - let top_mask = 0xFFu8.checked_shr(spare).unwrap_or(0); - if masked_db.first().is_none_or(|b| b & !top_mask != 0) { - return Ok(false); - } - let mut db: Vec = masked_db.iter().zip(mgf1(params.mgf, h, db_len)).map(|(a, b)| a ^ b).collect(); - if let Some(b) = db.first_mut() { - *b &= top_mask; - } - let Some(sep) = db.iter().position(|b| *b != 0) else { return Ok(false) }; - if db.get(sep) != Some(&1) { - return Ok(false); - } - let salt = db.get(sep + 1..).unwrap_or_default(); - if params.salt_len.is_some_and(|l| l != salt.len()) { - return Ok(false); - } - Ok(alg.digest(&[&[0u8; 8], digest, salt]) == h) -} diff --git a/crates/sign/tests/it/pdf.rs b/crates/sign/tests/it/pdf.rs index 6e88830a7a..f1053ed2f1 100644 --- a/crates/sign/tests/it/pdf.rs +++ b/crates/sign/tests/it/pdf.rs @@ -3003,12 +3003,7 @@ fn wordings_are_complete() { let source = source.as_str(); // The modules below `pdf` word whole sentences too: how a signature value had to be read, and // what a certificate does not allow. - let elsewhere = [ - include_str!("../../src/x509.rs"), - include_str!("../../src/cms.rs"), - include_str!("../../src/keys.rs"), - include_str!("../../src/rsa_pad.rs"), - ]; + let elsewhere = [include_str!("../../src/x509.rs"), include_str!("../../src/cms.rs"), include_str!("../../src/keys.rs")]; /// A sentence said to the user, as opposed to an OID, a name or a tag: it reads as English. fn is_sentence(s: &str) -> bool { s.len() > 24 && s.ends_with('.') && s.contains(' ') && s.starts_with(|c: char| c.is_ascii_uppercase()) @@ -3041,6 +3036,15 @@ fn wordings_are_complete() { out } let mut said = after(source, &["Detail::plain(", "Detail::of("]); + // These existing diagnostics now come from pinned craft-pkcs7 instead of local source. + // Keep their translation coverage; crypto.rs exercises the corresponding tolerated forms. + said.extend([ + "The RSA signature value does not have the length of the key's modulus (leading zero bytes dropped or added); it was read anyway.", + "The RSA signature's DigestInfo has no NULL parameter (older signers write it so); it was read anyway.", + "The ECDSA signature is not in canonical DER (trailing bytes, padding or a missing sign byte); it was read anyway.", + "The ECDSA signature is the raw r and s values instead of a DER sequence; it was read anyway.", + ]); + let at_hand = ["Detail::plain(", "Detail::of(", ".push(", "Some("]; said.extend(elsewhere.iter().flat_map(|s| after(s, &at_hand)).filter(|s| is_sentence(s))); let summary = source.split("pub fn summary").nth(1).and_then(|s| s.split("\n }").next()).unwrap_or_default();