1 // Copyright 2015-2016 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15 //! Verification of RSA signatures.
16
17 use super::{parse_public_key, RsaParameters, N, PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN};
18 use crate::{
19 arithmetic::{bigint, montgomery::Unencoded},
20 bits, cpu, digest, error,
21 limb::LIMB_BYTES,
22 sealed, signature,
23 };
24
25 use untrusted;
26
27 #[derive(Debug)]
28 pub struct Key {
29 pub n: bigint::Modulus<N>,
30 pub e: bigint::PublicExponent,
31 pub n_bits: bits::BitLength,
32 }
33
34 impl Key {
from_modulus_and_exponent( n: untrusted::Input, e: untrusted::Input, n_min_bits: bits::BitLength, n_max_bits: bits::BitLength, e_min_value: u64, ) -> Result<Self, error::KeyRejected>35 pub fn from_modulus_and_exponent(
36 n: untrusted::Input,
37 e: untrusted::Input,
38 n_min_bits: bits::BitLength,
39 n_max_bits: bits::BitLength,
40 e_min_value: u64,
41 ) -> Result<Self, error::KeyRejected> {
42 // This is an incomplete implementation of NIST SP800-56Br1 Section
43 // 6.4.2.2, "Partial Public-Key Validation for RSA." That spec defers
44 // to NIST SP800-89 Section 5.3.3, "(Explicit) Partial Public Key
45 // Validation for RSA," "with the caveat that the length of the modulus
46 // shall be a length that is specified in this Recommendation." In
47 // SP800-89, two different sets of steps are given, one set numbered,
48 // and one set lettered. TODO: Document this in the end-user
49 // documentation for RSA keys.
50
51 // Step 3 / Step c for `n` (out of order).
52 let (n, n_bits) = bigint::Modulus::from_be_bytes_with_bit_length(n)?;
53
54 // `pkcs1_encode` depends on this not being small. Otherwise,
55 // `pkcs1_encode` would generate padding that is invalid (too few 0xFF
56 // bytes) for very small keys.
57 const N_MIN_BITS: bits::BitLength = bits::BitLength::from_usize_bits(1024);
58
59 // Step 1 / Step a. XXX: SP800-56Br1 and SP800-89 require the length of
60 // the public modulus to be exactly 2048 or 3072 bits, but we are more
61 // flexible to be compatible with other commonly-used crypto libraries.
62 assert!(n_min_bits >= N_MIN_BITS);
63 let n_bits_rounded_up =
64 bits::BitLength::from_usize_bytes(n_bits.as_usize_bytes_rounded_up())
65 .map_err(|error::Unspecified| error::KeyRejected::unexpected_error())?;
66 if n_bits_rounded_up < n_min_bits {
67 return Err(error::KeyRejected::too_small());
68 }
69 if n_bits > n_max_bits {
70 return Err(error::KeyRejected::too_large());
71 }
72
73 // Step 2 / Step b.
74 // Step 3 / Step c for `e`.
75 let e = bigint::PublicExponent::from_be_bytes(e, e_min_value)?;
76
77 // If `n` is less than `e` then somebody has probably accidentally swapped
78 // them. The largest acceptable `e` is smaller than the smallest acceptable
79 // `n`, so no additional checks need to be done.
80
81 // XXX: Steps 4 & 5 / Steps d, e, & f are not implemented. This is also the
82 // case in most other commonly-used crypto libraries.
83
84 Ok(Self { n, e, n_bits })
85 }
86 }
87
88 impl signature::VerificationAlgorithm for RsaParameters {
verify( &self, public_key: untrusted::Input, msg: untrusted::Input, signature: untrusted::Input, ) -> Result<(), error::Unspecified>89 fn verify(
90 &self,
91 public_key: untrusted::Input,
92 msg: untrusted::Input,
93 signature: untrusted::Input,
94 ) -> Result<(), error::Unspecified> {
95 let (n, e) = parse_public_key(public_key)?;
96 verify_rsa_(
97 self,
98 (
99 n.big_endian_without_leading_zero_as_input(),
100 e.big_endian_without_leading_zero_as_input(),
101 ),
102 msg,
103 signature,
104 )
105 }
106 }
107
108 impl sealed::Sealed for RsaParameters {}
109
110 macro_rules! rsa_params {
111 ( $VERIFY_ALGORITHM:ident, $min_bits:expr, $PADDING_ALGORITHM:expr,
112 $doc_str:expr ) => {
113 #[doc=$doc_str]
114 ///
115 /// Only available in `alloc` mode.
116 pub static $VERIFY_ALGORITHM: RsaParameters = RsaParameters {
117 padding_alg: $PADDING_ALGORITHM,
118 min_bits: bits::BitLength::from_usize_bits($min_bits),
119 };
120 };
121 }
122
123 rsa_params!(
124 RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
125 1024,
126 &super::padding::RSA_PKCS1_SHA1_FOR_LEGACY_USE_ONLY,
127 "Verification of signatures using RSA keys of 1024-8192 bits,
128 PKCS#1.5 padding, and SHA-1.\n\nSee \"`RSA_PKCS1_*` Details\" in
129 `ring::signature`'s module-level documentation for more details."
130 );
131 rsa_params!(
132 RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY,
133 2048,
134 &super::padding::RSA_PKCS1_SHA1_FOR_LEGACY_USE_ONLY,
135 "Verification of signatures using RSA keys of 2048-8192 bits,
136 PKCS#1.5 padding, and SHA-1.\n\nSee \"`RSA_PKCS1_*` Details\" in
137 `ring::signature`'s module-level documentation for more details."
138 );
139 rsa_params!(
140 RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY,
141 1024,
142 &super::RSA_PKCS1_SHA256,
143 "Verification of signatures using RSA keys of 1024-8192 bits,
144 PKCS#1.5 padding, and SHA-256.\n\nSee \"`RSA_PKCS1_*` Details\" in
145 `ring::signature`'s module-level documentation for more details."
146 );
147 rsa_params!(
148 RSA_PKCS1_2048_8192_SHA256,
149 2048,
150 &super::RSA_PKCS1_SHA256,
151 "Verification of signatures using RSA keys of 2048-8192 bits,
152 PKCS#1.5 padding, and SHA-256.\n\nSee \"`RSA_PKCS1_*` Details\" in
153 `ring::signature`'s module-level documentation for more details."
154 );
155 rsa_params!(
156 RSA_PKCS1_2048_8192_SHA384,
157 2048,
158 &super::RSA_PKCS1_SHA384,
159 "Verification of signatures using RSA keys of 2048-8192 bits,
160 PKCS#1.5 padding, and SHA-384.\n\nSee \"`RSA_PKCS1_*` Details\" in
161 `ring::signature`'s module-level documentation for more details."
162 );
163 rsa_params!(
164 RSA_PKCS1_2048_8192_SHA512,
165 2048,
166 &super::RSA_PKCS1_SHA512,
167 "Verification of signatures using RSA keys of 2048-8192 bits,
168 PKCS#1.5 padding, and SHA-512.\n\nSee \"`RSA_PKCS1_*` Details\" in
169 `ring::signature`'s module-level documentation for more details."
170 );
171 rsa_params!(
172 RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY,
173 1024,
174 &super::RSA_PKCS1_SHA512,
175 "Verification of signatures using RSA keys of 1024-8192 bits,
176 PKCS#1.5 padding, and SHA-512.\n\nSee \"`RSA_PKCS1_*` Details\" in
177 `ring::signature`'s module-level documentation for more details."
178 );
179 rsa_params!(
180 RSA_PKCS1_3072_8192_SHA384,
181 3072,
182 &super::RSA_PKCS1_SHA384,
183 "Verification of signatures using RSA keys of 3072-8192 bits,
184 PKCS#1.5 padding, and SHA-384.\n\nSee \"`RSA_PKCS1_*` Details\" in
185 `ring::signature`'s module-level documentation for more details."
186 );
187
188 rsa_params!(
189 RSA_PSS_2048_8192_SHA256,
190 2048,
191 &super::RSA_PSS_SHA256,
192 "Verification of signatures using RSA keys of 2048-8192 bits,
193 PSS padding, and SHA-256.\n\nSee \"`RSA_PSS_*` Details\" in
194 `ring::signature`'s module-level documentation for more details."
195 );
196 rsa_params!(
197 RSA_PSS_2048_8192_SHA384,
198 2048,
199 &super::RSA_PSS_SHA384,
200 "Verification of signatures using RSA keys of 2048-8192 bits,
201 PSS padding, and SHA-384.\n\nSee \"`RSA_PSS_*` Details\" in
202 `ring::signature`'s module-level documentation for more details."
203 );
204 rsa_params!(
205 RSA_PSS_2048_8192_SHA512,
206 2048,
207 &super::RSA_PSS_SHA512,
208 "Verification of signatures using RSA keys of 2048-8192 bits,
209 PSS padding, and SHA-512.\n\nSee \"`RSA_PSS_*` Details\" in
210 `ring::signature`'s module-level documentation for more details."
211 );
212
213 /// Low-level API for the verification of RSA signatures.
214 ///
215 /// When the public key is in DER-encoded PKCS#1 ASN.1 format, it is
216 /// recommended to use `ring::signature::verify()` with
217 /// `ring::signature::RSA_PKCS1_*`, because `ring::signature::verify()`
218 /// will handle the parsing in that case. Otherwise, this function can be used
219 /// to pass in the raw bytes for the public key components as
220 /// `untrusted::Input` arguments.
221 //
222 // There are a small number of tests that test this directly, but the
223 // test coverage for this function mostly depends on the test coverage for the
224 // `signature::VerificationAlgorithm` implementation for `RsaParameters`. If we
225 // change that, test coverage for `verify_rsa()` will need to be reconsidered.
226 // (The NIST test vectors were originally in a form that was optimized for
227 // testing `verify_rsa` directly, but the testing work for RSA PKCS#1
228 // verification was done during the implementation of
229 // `signature::VerificationAlgorithm`, before `verify_rsa` was factored out).
230 #[derive(Debug)]
231 pub struct RsaPublicKeyComponents<B: AsRef<[u8]> + core::fmt::Debug> {
232 /// The public modulus, encoded in big-endian bytes without leading zeros.
233 pub n: B,
234
235 /// The public exponent, encoded in big-endian bytes without leading zeros.
236 pub e: B,
237 }
238
239 impl<B: Copy> Copy for RsaPublicKeyComponents<B> where B: AsRef<[u8]> + core::fmt::Debug {}
240
241 impl<B: Clone> Clone for RsaPublicKeyComponents<B>
242 where
243 B: AsRef<[u8]> + core::fmt::Debug,
244 {
clone(&self) -> Self245 fn clone(&self) -> Self {
246 Self {
247 n: self.n.clone(),
248 e: self.e.clone(),
249 }
250 }
251 }
252
253 impl<B> RsaPublicKeyComponents<B>
254 where
255 B: AsRef<[u8]> + core::fmt::Debug,
256 {
257 /// Verifies that `signature` is a valid signature of `message` using `self`
258 /// as the public key. `params` determine what algorithm parameters
259 /// (padding, digest algorithm, key length range, etc.) are used in the
260 /// verification.
verify( &self, params: &RsaParameters, message: &[u8], signature: &[u8], ) -> Result<(), error::Unspecified>261 pub fn verify(
262 &self,
263 params: &RsaParameters,
264 message: &[u8],
265 signature: &[u8],
266 ) -> Result<(), error::Unspecified> {
267 let _ = cpu::features();
268 verify_rsa_(
269 params,
270 (
271 untrusted::Input::from(self.n.as_ref()),
272 untrusted::Input::from(self.e.as_ref()),
273 ),
274 untrusted::Input::from(message),
275 untrusted::Input::from(signature),
276 )
277 }
278 }
279
verify_rsa_( params: &RsaParameters, (n, e): (untrusted::Input, untrusted::Input), msg: untrusted::Input, signature: untrusted::Input, ) -> Result<(), error::Unspecified>280 pub(crate) fn verify_rsa_(
281 params: &RsaParameters,
282 (n, e): (untrusted::Input, untrusted::Input),
283 msg: untrusted::Input,
284 signature: untrusted::Input,
285 ) -> Result<(), error::Unspecified> {
286 let max_bits = bits::BitLength::from_usize_bytes(PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN)?;
287
288 // XXX: FIPS 186-4 seems to indicate that the minimum
289 // exponent value is 2**16 + 1, but it isn't clear if this is just for
290 // signing or also for verification. We support exponents of 3 and larger
291 // for compatibility with other commonly-used crypto libraries.
292 let Key { n, e, n_bits } = Key::from_modulus_and_exponent(n, e, params.min_bits, max_bits, 3)?;
293
294 // The signature must be the same length as the modulus, in bytes.
295 if signature.len() != n_bits.as_usize_bytes_rounded_up() {
296 return Err(error::Unspecified);
297 }
298
299 // RFC 8017 Section 5.2.2: RSAVP1.
300
301 // Step 1.
302 let s = bigint::Elem::from_be_bytes_padded(signature, &n)?;
303 if s.is_zero() {
304 return Err(error::Unspecified);
305 }
306
307 // Step 2.
308 let m = bigint::elem_exp_vartime(s, e, &n);
309 let m = m.into_unencoded(&n);
310
311 // Step 3.
312 let mut decoded = [0u8; PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN];
313 let decoded = fill_be_bytes_n(m, n_bits, &mut decoded);
314
315 // Verify the padded message is correct.
316 let m_hash = digest::digest(params.padding_alg.digest_alg(), msg.as_slice_less_safe());
317 untrusted::Input::from(decoded).read_all(error::Unspecified, |m| {
318 params.padding_alg.verify(&m_hash, m, n_bits)
319 })
320 }
321
322 /// Returns the big-endian representation of `elem` that is
323 /// the same length as the minimal-length big-endian representation of
324 /// the modulus `n`.
325 ///
326 /// `n_bits` must be the bit length of the public modulus `n`.
fill_be_bytes_n( elem: bigint::Elem<N, Unencoded>, n_bits: bits::BitLength, out: &mut [u8; PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN], ) -> &[u8]327 fn fill_be_bytes_n(
328 elem: bigint::Elem<N, Unencoded>,
329 n_bits: bits::BitLength,
330 out: &mut [u8; PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN],
331 ) -> &[u8] {
332 let n_bytes = n_bits.as_usize_bytes_rounded_up();
333 let n_bytes_padded = ((n_bytes + (LIMB_BYTES - 1)) / LIMB_BYTES) * LIMB_BYTES;
334 let out = &mut out[..n_bytes_padded];
335 elem.fill_be_bytes(out);
336 let (padding, out) = out.split_at(n_bytes_padded - n_bytes);
337 assert!(padding.iter().all(|&b| b == 0));
338 out
339 }
340