Skip to main content

pdfcer_model/crypto/
rsa.rs

1//! RSA signature **verification** — RSASSA-PKCS1-v1_5 and RSASSA-PSS (RFC 8017
2//! §8.2.2, §8.1.2), over [`super::bignum`].
3//!
4//! Verification only: there is no private key anywhere in this module, and
5//! nothing here is constant-time (see `bignum.rs` for why that is the right
6//! posture for a public-key operation on public data).
7//!
8//! # PKCS#1 v1.5 — the comparison is over the WHOLE encoded message
9//!
10//! RFC 8017 §8.2.2 step 4: *"Compare the encoded message EM and the second
11//! encoded message EM'. If they are the same, output 'valid signature';
12//! otherwise, output 'invalid signature'."* This module builds `EM'` from
13//! the expected `DigestInfo` and compares all `k` bytes. It does **not**
14//! parse the decrypted block and look for a `DigestInfo` inside it — that
15//! lenient shape is Bleichenbacher's 2006 forgery against low-exponent keys
16//! (a parser that skips over garbage after the hash accepts a cube root
17//! nobody signed). The strict comparison makes the padding bytes, the
18//! `DigestInfo` DER and the hash all part of one equality.
19//!
20//! # PSS
21//!
22//! `EMSA-PSS-VERIFY` (RFC 8017 §9.1.2) with the hash, MGF1 hash and salt
23//! length taken from the `RSASSA-PSS-params` the CMS carries (RFC 4055). The
24//! trailer field must be `0xBC`; the salt length is the signer's, not a
25//! guess — a mismatch is a `false`, never a search over salt lengths.
26//!
27//! # Digest algorithms
28//!
29//! SHA-1, SHA-256, SHA-384 and SHA-512, by the `DigestInfo` prefixes RFC
30//! 8017 §9.2 note 1 tabulates. Anything else is refused by the caller
31//! before this module is reached.
32
33use super::bignum::Uint;
34
35/// The digest algorithms this verifier can compute.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Hash {
38    Sha1,
39    Sha256,
40    Sha384,
41    Sha512,
42}
43
44impl Hash {
45    /// Output length in bytes. (Never zero, so there is no `is_empty` to
46    /// pair it with; the lint that asks for one is about containers.)
47    #[must_use]
48    #[allow(clippy::len_without_is_empty)]
49    pub const fn len(self) -> usize {
50        match self {
51            Self::Sha1 => 20,
52            Self::Sha256 => 32,
53            Self::Sha384 => 48,
54            Self::Sha512 => 64,
55        }
56    }
57
58    /// The digest of `data`.
59    #[must_use]
60    pub fn digest(self, data: &[u8]) -> Vec<u8> {
61        use sha2::Digest as _;
62        match self {
63            Self::Sha1 => super::sha1::sha1(data).to_vec(),
64            Self::Sha256 => sha2::Sha256::digest(data).to_vec(),
65            Self::Sha384 => sha2::Sha384::digest(data).to_vec(),
66            Self::Sha512 => sha2::Sha512::digest(data).to_vec(),
67        }
68    }
69
70    /// The `DigestInfo` DER prefix (RFC 8017 §9.2 note 1): the bytes that
71    /// precede the raw hash inside a PKCS#1 v1.5 encoded message.
72    #[must_use]
73    pub const fn digest_info_prefix(self) -> &'static [u8] {
74        match self {
75            Self::Sha1 => &[
76                0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04,
77                0x14,
78            ],
79            Self::Sha256 => &[
80                0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
81                0x01, 0x05, 0x00, 0x04, 0x20,
82            ],
83            Self::Sha384 => &[
84                0x30, 0x41, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
85                0x02, 0x05, 0x00, 0x04, 0x30,
86            ],
87            Self::Sha512 => &[
88                0x30, 0x51, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
89                0x03, 0x05, 0x00, 0x04, 0x40,
90            ],
91        }
92    }
93
94    /// The algorithm's name, for a verdict.
95    #[must_use]
96    pub const fn name(self) -> &'static str {
97        match self {
98            Self::Sha1 => "SHA-1",
99            Self::Sha256 => "SHA-256",
100            Self::Sha384 => "SHA-384",
101            Self::Sha512 => "SHA-512",
102        }
103    }
104}
105
106/// An RSA public key: modulus and exponent, big-endian.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct RsaPublicKey {
109    pub n: Uint,
110    pub e: Uint,
111}
112
113impl RsaPublicKey {
114    /// `k`, the modulus length in bytes.
115    #[must_use]
116    pub fn k(&self) -> usize {
117        self.n.bits().div_ceil(8)
118    }
119
120    /// RSAVP1 (RFC 8017 §5.2.2): `s^e mod n` as a `k`-byte string, or `None`
121    /// when `s` is out of range.
122    fn rsavp1(&self, s: &[u8]) -> Option<Vec<u8>> {
123        let sig = Uint::from_be_bytes(s);
124        if sig >= self.n {
125            return None;
126        }
127        sig.modpow(&self.e, &self.n).to_be_bytes(self.k())
128    }
129
130    /// RSASSA-PKCS1-v1_5-VERIFY (RFC 8017 §8.2.2) of `signature` over a
131    /// message whose `hash` digest is `digest`.
132    #[must_use]
133    pub fn verify_pkcs1v15(&self, hash: Hash, digest: &[u8], signature: &[u8]) -> bool {
134        let k = self.k();
135        if signature.len() != k || digest.len() != hash.len() {
136            return false;
137        }
138        let Some(em) = self.rsavp1(signature) else {
139            return false;
140        };
141        // EMSA-PKCS1-v1_5-ENCODE (§9.2): 00 01 FF…FF 00 T, with ≥ 8 FF bytes.
142        let t_len = hash.digest_info_prefix().len() + digest.len();
143        if k < t_len + 11 {
144            return false;
145        }
146        let mut expected = Vec::with_capacity(k);
147        expected.push(0x00);
148        expected.push(0x01);
149        expected.resize(k - t_len - 1, 0xFF);
150        expected.push(0x00);
151        expected.extend_from_slice(hash.digest_info_prefix());
152        expected.extend_from_slice(digest);
153        em == expected
154    }
155
156    /// RSASSA-PSS-VERIFY (RFC 8017 §8.1.2) of `signature` over a message
157    /// whose `hash` digest is `digest`, with MGF1 over `mgf_hash` and the
158    /// signer's `salt_len`.
159    ///
160    /// Every slice is bounded by the overflow-checked `h_len + salt_len + 2 ≤ em_len`
161    /// and by `em_len ≤ k` (`emBits = modBits − 1`), which the two early
162    /// returns establish before any index is formed.
163    #[must_use]
164    #[allow(clippy::indexing_slicing)]
165    pub fn verify_pss(
166        &self,
167        hash: Hash,
168        mgf_hash: Hash,
169        salt_len: usize,
170        digest: &[u8],
171        signature: &[u8],
172    ) -> bool {
173        let k = self.k();
174        if signature.len() != k || digest.len() != hash.len() {
175            return false;
176        }
177        let Some(em) = self.rsavp1(signature) else {
178            return false;
179        };
180        // EMSA-PSS-VERIFY (§9.1.2), emBits = modBits − 1.
181        let em_bits = self.n.bits() - 1;
182        let em_len = em_bits.div_ceil(8);
183        // RSAVP1 gave k bytes; the encoded message is the low emLen of them.
184        let em = &em[k - em_len..];
185        let h_len = hash.len();
186        // `salt_len` comes from the signature's PSS parameters: a hostile value
187        // must not wrap this sum (and later `ps_len`) into a passing check.
188        if h_len
189            .checked_add(salt_len)
190            .and_then(|x| x.checked_add(2))
191            .is_none_or(|need| em_len < need)
192        {
193            return false;
194        }
195        if em.last() != Some(&0xBC) {
196            return false;
197        }
198        let db_len = em_len - h_len - 1;
199        let masked_db = &em[..db_len];
200        let h = &em[db_len..db_len + h_len];
201        // The top 8·emLen − emBits bits of maskedDB must be zero.
202        let top_bits = 8 * em_len - em_bits;
203        if top_bits > 0 && masked_db[0] >> (8 - top_bits) != 0 {
204            return false;
205        }
206        let mask = mgf1(mgf_hash, h, db_len);
207        let mut db: Vec<u8> = masked_db.iter().zip(&mask).map(|(a, b)| a ^ b).collect();
208        if top_bits > 0 {
209            db[0] &= 0xFF >> top_bits;
210        }
211        // DB = PS (zeros) || 0x01 || salt
212        let ps_len = em_len - h_len - salt_len - 2;
213        if db[..ps_len].iter().any(|&b| b != 0) || db[ps_len] != 0x01 {
214            return false;
215        }
216        let salt = &db[ps_len + 1..];
217        let mut m_prime = vec![0u8; 8];
218        m_prime.extend_from_slice(digest);
219        m_prime.extend_from_slice(salt);
220        hash.digest(&m_prime) == h
221    }
222}
223
224/// MGF1 (RFC 8017 Appendix B.2.1).
225fn mgf1(hash: Hash, seed: &[u8], len: usize) -> Vec<u8> {
226    let mut out = Vec::with_capacity(len + hash.len());
227    let mut counter = 0u32;
228    while out.len() < len {
229        let mut input = seed.to_vec();
230        input.extend_from_slice(&counter.to_be_bytes());
231        out.extend_from_slice(&hash.digest(&input));
232        counter += 1;
233    }
234    out.truncate(len);
235    out
236}
237
238#[cfg(test)]
239#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
240mod tests {
241    use super::*;
242
243    fn hex(s: &str) -> Vec<u8> {
244        (0..s.len())
245            .step_by(2)
246            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
247            .collect()
248    }
249
250    /// A tiny toy key (p=61, q=53 → n=3233, e=17) exercises the arithmetic
251    /// end to end; the padding check needs a real-sized key, which the
252    /// signature fixtures provide through `signature_verify`'s tests.
253    #[test]
254    fn rsavp1_recovers_the_message_on_a_toy_key() {
255        let key = RsaPublicKey {
256            n: Uint::from_u64(3233),
257            e: Uint::from_u64(17),
258        };
259        // m = 65, d = 2753: s = 65^2753 mod 3233 = 588 (Python: pow(65, 2753, 3233)),
260        // and 588^17 mod 3233 = 65 recovers it.
261        let s = Uint::from_u64(588).to_be_bytes(2).unwrap();
262        assert_eq!(
263            key.rsavp1(&s).unwrap(),
264            Uint::from_u64(65).to_be_bytes(2).unwrap()
265        );
266        // Out-of-range signature is refused.
267        assert!(
268            key.rsavp1(&Uint::from_u64(4000).to_be_bytes(2).unwrap())
269                .is_none()
270        );
271    }
272
273    #[test]
274    fn digest_info_prefixes_are_valid_der_of_the_right_length() {
275        for h in [Hash::Sha1, Hash::Sha256, Hash::Sha384, Hash::Sha512] {
276            let p = h.digest_info_prefix();
277            // Outer SEQUENCE length covers everything after its 2-byte header.
278            assert_eq!(usize::from(p[1]), p.len() - 2 + h.len(), "{}", h.name());
279            // Last two bytes: OCTET STRING tag and the hash length.
280            assert_eq!(&p[p.len() - 2..], &[0x04, h.len() as u8]);
281        }
282    }
283
284    /// A hostile PSS salt length near `usize::MAX` once wrapped the length
285    /// check and panicked slicing `DB`; it is a failed verification. With
286    /// `e = 1` (the certificate is attacker-supplied) `EM` is the signature
287    /// itself, so it passes the trailer and top-bit checks first.
288    #[test]
289    fn a_hostile_pss_salt_length_fails_verification_without_panicking() {
290        let key = RsaPublicKey {
291            n: Uint::from_be_bytes(&[0xFF; 256]),
292            e: Uint::from_u64(1),
293        };
294        let mut sig = vec![0u8; 256];
295        sig[0] = 0x7F;
296        sig[255] = 0xBC;
297        let digest = vec![0u8; 32];
298        for salt_len in [usize::MAX, usize::MAX - 33, usize::MAX - 32, 300] {
299            assert!(!key.verify_pss(Hash::Sha256, Hash::Sha256, salt_len, &digest, &sig));
300        }
301    }
302
303    #[test]
304    fn mgf1_matches_a_known_answer() {
305        // MGF1-SHA256("foo", 8) computed with Python's pyca implementation of
306        // the same algorithm: sha256(b"foo" + b"\x00\x00\x00\x00")[:8]
307        let out = mgf1(Hash::Sha256, b"foo", 8);
308        assert_eq!(out, hex("3bdaba83cff13337"));
309    }
310}