xref: /aosp_15_r20/external/boringssl/src/crypto/fipsmodule/rsa/rsa.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson ([email protected]).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young ([email protected])"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson ([email protected])"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <openssl/rsa.h>
58 
59 #include <assert.h>
60 #include <limits.h>
61 #include <string.h>
62 
63 #include <openssl/bn.h>
64 #include <openssl/digest.h>
65 #include <openssl/engine.h>
66 #include <openssl/err.h>
67 #include <openssl/ex_data.h>
68 #include <openssl/md5.h>
69 #include <openssl/mem.h>
70 #include <openssl/nid.h>
71 #include <openssl/sha.h>
72 #include <openssl/thread.h>
73 
74 #include "../bn/internal.h"
75 #include "../delocate.h"
76 #include "../../internal.h"
77 #include "internal.h"
78 
79 
80 // RSA_R_BLOCK_TYPE_IS_NOT_02 is part of the legacy SSLv23 padding scheme.
81 // Cryptography.io depends on this error code.
OPENSSL_DECLARE_ERROR_REASON(RSA,BLOCK_TYPE_IS_NOT_02)82 OPENSSL_DECLARE_ERROR_REASON(RSA, BLOCK_TYPE_IS_NOT_02)
83 
84 DEFINE_STATIC_EX_DATA_CLASS(g_rsa_ex_data_class)
85 
86 static int bn_dup_into(BIGNUM **dst, const BIGNUM *src) {
87   if (src == NULL) {
88     OPENSSL_PUT_ERROR(RSA, ERR_R_PASSED_NULL_PARAMETER);
89     return 0;
90   }
91 
92   BN_free(*dst);
93   *dst = BN_dup(src);
94   return *dst != NULL;
95 }
96 
RSA_new_public_key(const BIGNUM * n,const BIGNUM * e)97 RSA *RSA_new_public_key(const BIGNUM *n, const BIGNUM *e) {
98   RSA *rsa = RSA_new();
99   if (rsa == NULL ||               //
100       !bn_dup_into(&rsa->n, n) ||  //
101       !bn_dup_into(&rsa->e, e) ||  //
102       !RSA_check_key(rsa)) {
103     RSA_free(rsa);
104     return NULL;
105   }
106 
107   return rsa;
108 }
109 
RSA_new_private_key(const BIGNUM * n,const BIGNUM * e,const BIGNUM * d,const BIGNUM * p,const BIGNUM * q,const BIGNUM * dmp1,const BIGNUM * dmq1,const BIGNUM * iqmp)110 RSA *RSA_new_private_key(const BIGNUM *n, const BIGNUM *e, const BIGNUM *d,
111                          const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp1,
112                          const BIGNUM *dmq1, const BIGNUM *iqmp) {
113   RSA *rsa = RSA_new();
114   if (rsa == NULL ||                     //
115       !bn_dup_into(&rsa->n, n) ||        //
116       !bn_dup_into(&rsa->e, e) ||        //
117       !bn_dup_into(&rsa->d, d) ||        //
118       !bn_dup_into(&rsa->p, p) ||        //
119       !bn_dup_into(&rsa->q, q) ||        //
120       !bn_dup_into(&rsa->dmp1, dmp1) ||  //
121       !bn_dup_into(&rsa->dmq1, dmq1) ||  //
122       !bn_dup_into(&rsa->iqmp, iqmp) ||  //
123       !RSA_check_key(rsa)) {
124     RSA_free(rsa);
125     return NULL;
126   }
127 
128   return rsa;
129 }
130 
RSA_new_private_key_no_crt(const BIGNUM * n,const BIGNUM * e,const BIGNUM * d)131 RSA *RSA_new_private_key_no_crt(const BIGNUM *n, const BIGNUM *e,
132                                 const BIGNUM *d) {
133   RSA *rsa = RSA_new();
134   if (rsa == NULL ||               //
135       !bn_dup_into(&rsa->n, n) ||  //
136       !bn_dup_into(&rsa->e, e) ||  //
137       !bn_dup_into(&rsa->d, d) ||  //
138       !RSA_check_key(rsa)) {
139     RSA_free(rsa);
140     return NULL;
141   }
142 
143   return rsa;
144 }
145 
RSA_new_private_key_no_e(const BIGNUM * n,const BIGNUM * d)146 RSA *RSA_new_private_key_no_e(const BIGNUM *n, const BIGNUM *d) {
147   RSA *rsa = RSA_new();
148   if (rsa == NULL) {
149     return NULL;
150   }
151 
152   rsa->flags |= RSA_FLAG_NO_PUBLIC_EXPONENT;
153   if (!bn_dup_into(&rsa->n, n) ||  //
154       !bn_dup_into(&rsa->d, d) ||  //
155       !RSA_check_key(rsa)) {
156     RSA_free(rsa);
157     return NULL;
158   }
159 
160   return rsa;
161 }
162 
RSA_new_public_key_large_e(const BIGNUM * n,const BIGNUM * e)163 RSA *RSA_new_public_key_large_e(const BIGNUM *n, const BIGNUM *e) {
164   RSA *rsa = RSA_new();
165   if (rsa == NULL) {
166     return NULL;
167   }
168 
169   rsa->flags |= RSA_FLAG_LARGE_PUBLIC_EXPONENT;
170   if (!bn_dup_into(&rsa->n, n) ||  //
171       !bn_dup_into(&rsa->e, e) ||  //
172       !RSA_check_key(rsa)) {
173     RSA_free(rsa);
174     return NULL;
175   }
176 
177   return rsa;
178 }
179 
RSA_new_private_key_large_e(const BIGNUM * n,const BIGNUM * e,const BIGNUM * d,const BIGNUM * p,const BIGNUM * q,const BIGNUM * dmp1,const BIGNUM * dmq1,const BIGNUM * iqmp)180 RSA *RSA_new_private_key_large_e(const BIGNUM *n, const BIGNUM *e,
181                                  const BIGNUM *d, const BIGNUM *p,
182                                  const BIGNUM *q, const BIGNUM *dmp1,
183                                  const BIGNUM *dmq1, const BIGNUM *iqmp) {
184   RSA *rsa = RSA_new();
185   if (rsa == NULL) {
186     return NULL;
187   }
188 
189   rsa->flags |= RSA_FLAG_LARGE_PUBLIC_EXPONENT;
190   if (!bn_dup_into(&rsa->n, n) ||        //
191       !bn_dup_into(&rsa->e, e) ||        //
192       !bn_dup_into(&rsa->d, d) ||        //
193       !bn_dup_into(&rsa->p, p) ||        //
194       !bn_dup_into(&rsa->q, q) ||        //
195       !bn_dup_into(&rsa->dmp1, dmp1) ||  //
196       !bn_dup_into(&rsa->dmq1, dmq1) ||  //
197       !bn_dup_into(&rsa->iqmp, iqmp) ||  //
198       !RSA_check_key(rsa)) {
199     RSA_free(rsa);
200     return NULL;
201   }
202 
203   return rsa;
204 }
205 
RSA_new(void)206 RSA *RSA_new(void) { return RSA_new_method(NULL); }
207 
RSA_new_method(const ENGINE * engine)208 RSA *RSA_new_method(const ENGINE *engine) {
209   RSA *rsa = OPENSSL_zalloc(sizeof(RSA));
210   if (rsa == NULL) {
211     return NULL;
212   }
213 
214   if (engine) {
215     rsa->meth = ENGINE_get_RSA_method(engine);
216   }
217 
218   if (rsa->meth == NULL) {
219     rsa->meth = (RSA_METHOD *) RSA_default_method();
220   }
221   METHOD_ref(rsa->meth);
222 
223   rsa->references = 1;
224   rsa->flags = rsa->meth->flags;
225   CRYPTO_MUTEX_init(&rsa->lock);
226   CRYPTO_new_ex_data(&rsa->ex_data);
227 
228   if (rsa->meth->init && !rsa->meth->init(rsa)) {
229     CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), rsa, &rsa->ex_data);
230     CRYPTO_MUTEX_cleanup(&rsa->lock);
231     METHOD_unref(rsa->meth);
232     OPENSSL_free(rsa);
233     return NULL;
234   }
235 
236   return rsa;
237 }
238 
RSA_new_method_no_e(const ENGINE * engine,const BIGNUM * n)239 RSA *RSA_new_method_no_e(const ENGINE *engine, const BIGNUM *n) {
240   RSA *rsa = RSA_new_method(engine);
241   if (rsa == NULL ||
242       !bn_dup_into(&rsa->n, n)) {
243     RSA_free(rsa);
244     return NULL;
245   }
246   rsa->flags |= RSA_FLAG_NO_PUBLIC_EXPONENT;
247   return rsa;
248 }
249 
RSA_free(RSA * rsa)250 void RSA_free(RSA *rsa) {
251   if (rsa == NULL) {
252     return;
253   }
254 
255   if (!CRYPTO_refcount_dec_and_test_zero(&rsa->references)) {
256     return;
257   }
258 
259   if (rsa->meth->finish) {
260     rsa->meth->finish(rsa);
261   }
262   METHOD_unref(rsa->meth);
263 
264   CRYPTO_free_ex_data(g_rsa_ex_data_class_bss_get(), rsa, &rsa->ex_data);
265 
266   BN_free(rsa->n);
267   BN_free(rsa->e);
268   BN_free(rsa->d);
269   BN_free(rsa->p);
270   BN_free(rsa->q);
271   BN_free(rsa->dmp1);
272   BN_free(rsa->dmq1);
273   BN_free(rsa->iqmp);
274   rsa_invalidate_key(rsa);
275   CRYPTO_MUTEX_cleanup(&rsa->lock);
276   OPENSSL_free(rsa);
277 }
278 
RSA_up_ref(RSA * rsa)279 int RSA_up_ref(RSA *rsa) {
280   CRYPTO_refcount_inc(&rsa->references);
281   return 1;
282 }
283 
RSA_bits(const RSA * rsa)284 unsigned RSA_bits(const RSA *rsa) { return BN_num_bits(rsa->n); }
285 
RSA_get0_n(const RSA * rsa)286 const BIGNUM *RSA_get0_n(const RSA *rsa) { return rsa->n; }
287 
RSA_get0_e(const RSA * rsa)288 const BIGNUM *RSA_get0_e(const RSA *rsa) { return rsa->e; }
289 
RSA_get0_d(const RSA * rsa)290 const BIGNUM *RSA_get0_d(const RSA *rsa) { return rsa->d; }
291 
RSA_get0_p(const RSA * rsa)292 const BIGNUM *RSA_get0_p(const RSA *rsa) { return rsa->p; }
293 
RSA_get0_q(const RSA * rsa)294 const BIGNUM *RSA_get0_q(const RSA *rsa) { return rsa->q; }
295 
RSA_get0_dmp1(const RSA * rsa)296 const BIGNUM *RSA_get0_dmp1(const RSA *rsa) { return rsa->dmp1; }
297 
RSA_get0_dmq1(const RSA * rsa)298 const BIGNUM *RSA_get0_dmq1(const RSA *rsa) { return rsa->dmq1; }
299 
RSA_get0_iqmp(const RSA * rsa)300 const BIGNUM *RSA_get0_iqmp(const RSA *rsa) { return rsa->iqmp; }
301 
RSA_get0_key(const RSA * rsa,const BIGNUM ** out_n,const BIGNUM ** out_e,const BIGNUM ** out_d)302 void RSA_get0_key(const RSA *rsa, const BIGNUM **out_n, const BIGNUM **out_e,
303                   const BIGNUM **out_d) {
304   if (out_n != NULL) {
305     *out_n = rsa->n;
306   }
307   if (out_e != NULL) {
308     *out_e = rsa->e;
309   }
310   if (out_d != NULL) {
311     *out_d = rsa->d;
312   }
313 }
314 
RSA_get0_factors(const RSA * rsa,const BIGNUM ** out_p,const BIGNUM ** out_q)315 void RSA_get0_factors(const RSA *rsa, const BIGNUM **out_p,
316                       const BIGNUM **out_q) {
317   if (out_p != NULL) {
318     *out_p = rsa->p;
319   }
320   if (out_q != NULL) {
321     *out_q = rsa->q;
322   }
323 }
324 
RSA_get0_pss_params(const RSA * rsa)325 const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *rsa) {
326   // We do not support the id-RSASSA-PSS key encoding. If we add support later,
327   // the |maskHash| field should be filled in for OpenSSL compatibility.
328   return NULL;
329 }
330 
RSA_get0_crt_params(const RSA * rsa,const BIGNUM ** out_dmp1,const BIGNUM ** out_dmq1,const BIGNUM ** out_iqmp)331 void RSA_get0_crt_params(const RSA *rsa, const BIGNUM **out_dmp1,
332                          const BIGNUM **out_dmq1, const BIGNUM **out_iqmp) {
333   if (out_dmp1 != NULL) {
334     *out_dmp1 = rsa->dmp1;
335   }
336   if (out_dmq1 != NULL) {
337     *out_dmq1 = rsa->dmq1;
338   }
339   if (out_iqmp != NULL) {
340     *out_iqmp = rsa->iqmp;
341   }
342 }
343 
RSA_set0_key(RSA * rsa,BIGNUM * n,BIGNUM * e,BIGNUM * d)344 int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
345   if ((rsa->n == NULL && n == NULL) ||
346       (rsa->e == NULL && e == NULL)) {
347     return 0;
348   }
349 
350   if (n != NULL) {
351     BN_free(rsa->n);
352     rsa->n = n;
353   }
354   if (e != NULL) {
355     BN_free(rsa->e);
356     rsa->e = e;
357   }
358   if (d != NULL) {
359     BN_free(rsa->d);
360     rsa->d = d;
361   }
362 
363   rsa_invalidate_key(rsa);
364   return 1;
365 }
366 
RSA_set0_factors(RSA * rsa,BIGNUM * p,BIGNUM * q)367 int RSA_set0_factors(RSA *rsa, BIGNUM *p, BIGNUM *q) {
368   if ((rsa->p == NULL && p == NULL) ||
369       (rsa->q == NULL && q == NULL)) {
370     return 0;
371   }
372 
373   if (p != NULL) {
374     BN_free(rsa->p);
375     rsa->p = p;
376   }
377   if (q != NULL) {
378     BN_free(rsa->q);
379     rsa->q = q;
380   }
381 
382   rsa_invalidate_key(rsa);
383   return 1;
384 }
385 
RSA_set0_crt_params(RSA * rsa,BIGNUM * dmp1,BIGNUM * dmq1,BIGNUM * iqmp)386 int RSA_set0_crt_params(RSA *rsa, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) {
387   if ((rsa->dmp1 == NULL && dmp1 == NULL) ||
388       (rsa->dmq1 == NULL && dmq1 == NULL) ||
389       (rsa->iqmp == NULL && iqmp == NULL)) {
390     return 0;
391   }
392 
393   if (dmp1 != NULL) {
394     BN_free(rsa->dmp1);
395     rsa->dmp1 = dmp1;
396   }
397   if (dmq1 != NULL) {
398     BN_free(rsa->dmq1);
399     rsa->dmq1 = dmq1;
400   }
401   if (iqmp != NULL) {
402     BN_free(rsa->iqmp);
403     rsa->iqmp = iqmp;
404   }
405 
406   rsa_invalidate_key(rsa);
407   return 1;
408 }
409 
rsa_sign_raw_no_self_test(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)410 static int rsa_sign_raw_no_self_test(RSA *rsa, size_t *out_len, uint8_t *out,
411                                      size_t max_out, const uint8_t *in,
412                                      size_t in_len, int padding) {
413   if (rsa->meth->sign_raw) {
414     return rsa->meth->sign_raw(rsa, out_len, out, max_out, in, in_len, padding);
415   }
416 
417   return rsa_default_sign_raw(rsa, out_len, out, max_out, in, in_len, padding);
418 }
419 
RSA_sign_raw(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * in,size_t in_len,int padding)420 int RSA_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
421                  const uint8_t *in, size_t in_len, int padding) {
422   boringssl_ensure_rsa_self_test();
423   return rsa_sign_raw_no_self_test(rsa, out_len, out, max_out, in, in_len,
424                                    padding);
425 }
426 
RSA_size(const RSA * rsa)427 unsigned RSA_size(const RSA *rsa) {
428   size_t ret = rsa->meth->size ? rsa->meth->size(rsa) : rsa_default_size(rsa);
429   // RSA modulus sizes are bounded by |BIGNUM|, which must fit in |unsigned|.
430   //
431   // TODO(https://crbug.com/boringssl/516): Should we make this return |size_t|?
432   assert(ret < UINT_MAX);
433   return (unsigned)ret;
434 }
435 
RSA_is_opaque(const RSA * rsa)436 int RSA_is_opaque(const RSA *rsa) {
437   return rsa->meth && (rsa->meth->flags & RSA_FLAG_OPAQUE);
438 }
439 
RSA_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)440 int RSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
441                          CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
442   return CRYPTO_get_ex_new_index_ex(g_rsa_ex_data_class_bss_get(), argl, argp,
443                                  free_func);
444 }
445 
RSA_set_ex_data(RSA * rsa,int idx,void * arg)446 int RSA_set_ex_data(RSA *rsa, int idx, void *arg) {
447   return CRYPTO_set_ex_data(&rsa->ex_data, idx, arg);
448 }
449 
RSA_get_ex_data(const RSA * rsa,int idx)450 void *RSA_get_ex_data(const RSA *rsa, int idx) {
451   return CRYPTO_get_ex_data(&rsa->ex_data, idx);
452 }
453 
454 // SSL_SIG_LENGTH is the size of an SSL/TLS (prior to TLS 1.2) signature: it's
455 // the length of an MD5 and SHA1 hash.
456 static const unsigned SSL_SIG_LENGTH = 36;
457 
458 // pkcs1_sig_prefix contains the ASN.1, DER encoded prefix for a hash that is
459 // to be signed with PKCS#1.
460 struct pkcs1_sig_prefix {
461   // nid identifies the hash function.
462   int nid;
463   // hash_len is the expected length of the hash function.
464   uint8_t hash_len;
465   // len is the number of bytes of |bytes| which are valid.
466   uint8_t len;
467   // bytes contains the DER bytes.
468   uint8_t bytes[19];
469 };
470 
471 // kPKCS1SigPrefixes contains the ASN.1 prefixes for PKCS#1 signatures with
472 // different hash functions.
473 static const struct pkcs1_sig_prefix kPKCS1SigPrefixes[] = {
474     {
475      NID_md5,
476      MD5_DIGEST_LENGTH,
477      18,
478      {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
479       0x02, 0x05, 0x05, 0x00, 0x04, 0x10},
480     },
481     {
482      NID_sha1,
483      SHA_DIGEST_LENGTH,
484      15,
485      {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05,
486       0x00, 0x04, 0x14},
487     },
488     {
489      NID_sha224,
490      SHA224_DIGEST_LENGTH,
491      19,
492      {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
493       0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
494     },
495     {
496      NID_sha256,
497      SHA256_DIGEST_LENGTH,
498      19,
499      {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
500       0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
501     },
502     {
503      NID_sha384,
504      SHA384_DIGEST_LENGTH,
505      19,
506      {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
507       0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
508     },
509     {
510      NID_sha512,
511      SHA512_DIGEST_LENGTH,
512      19,
513      {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
514       0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
515     },
516     {
517      NID_undef, 0, 0, {0},
518     },
519 };
520 
rsa_check_digest_size(int hash_nid,size_t digest_len)521 static int rsa_check_digest_size(int hash_nid, size_t digest_len) {
522   if (hash_nid == NID_md5_sha1) {
523     if (digest_len != SSL_SIG_LENGTH) {
524       OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
525       return 0;
526     }
527     return 1;
528   }
529 
530   for (size_t i = 0; kPKCS1SigPrefixes[i].nid != NID_undef; i++) {
531     const struct pkcs1_sig_prefix *sig_prefix = &kPKCS1SigPrefixes[i];
532     if (sig_prefix->nid == hash_nid) {
533       if (digest_len != sig_prefix->hash_len) {
534         OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
535         return 0;
536       }
537       return 1;
538     }
539   }
540 
541   OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
542   return 0;
543 
544 }
545 
RSA_add_pkcs1_prefix(uint8_t ** out_msg,size_t * out_msg_len,int * is_alloced,int hash_nid,const uint8_t * digest,size_t digest_len)546 int RSA_add_pkcs1_prefix(uint8_t **out_msg, size_t *out_msg_len,
547                          int *is_alloced, int hash_nid, const uint8_t *digest,
548                          size_t digest_len) {
549   if (!rsa_check_digest_size(hash_nid, digest_len)) {
550     return 0;
551   }
552 
553   if (hash_nid == NID_md5_sha1) {
554     // The length should already have been checked.
555     assert(digest_len == SSL_SIG_LENGTH);
556     *out_msg = (uint8_t *)digest;
557     *out_msg_len = digest_len;
558     *is_alloced = 0;
559     return 1;
560   }
561 
562   for (size_t i = 0; kPKCS1SigPrefixes[i].nid != NID_undef; i++) {
563     const struct pkcs1_sig_prefix *sig_prefix = &kPKCS1SigPrefixes[i];
564     if (sig_prefix->nid != hash_nid) {
565       continue;
566     }
567 
568     // The length should already have been checked.
569     assert(digest_len == sig_prefix->hash_len);
570     const uint8_t* prefix = sig_prefix->bytes;
571     size_t prefix_len = sig_prefix->len;
572     size_t signed_msg_len = prefix_len + digest_len;
573     if (signed_msg_len < prefix_len) {
574       OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_LONG);
575       return 0;
576     }
577 
578     uint8_t *signed_msg = OPENSSL_malloc(signed_msg_len);
579     if (!signed_msg) {
580       return 0;
581     }
582 
583     OPENSSL_memcpy(signed_msg, prefix, prefix_len);
584     OPENSSL_memcpy(signed_msg + prefix_len, digest, digest_len);
585 
586     *out_msg = signed_msg;
587     *out_msg_len = signed_msg_len;
588     *is_alloced = 1;
589 
590     return 1;
591   }
592 
593   OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
594   return 0;
595 }
596 
rsa_sign_no_self_test(int hash_nid,const uint8_t * digest,size_t digest_len,uint8_t * out,unsigned * out_len,RSA * rsa)597 int rsa_sign_no_self_test(int hash_nid, const uint8_t *digest,
598                           size_t digest_len, uint8_t *out, unsigned *out_len,
599                           RSA *rsa) {
600   if (rsa->meth->sign) {
601     if (!rsa_check_digest_size(hash_nid, digest_len)) {
602       return 0;
603     }
604     // All supported digest lengths fit in |unsigned|.
605     assert(digest_len <= EVP_MAX_MD_SIZE);
606     static_assert(EVP_MAX_MD_SIZE <= UINT_MAX, "digest too long");
607     return rsa->meth->sign(hash_nid, digest, (unsigned)digest_len, out, out_len,
608                            rsa);
609   }
610 
611   const unsigned rsa_size = RSA_size(rsa);
612   int ret = 0;
613   uint8_t *signed_msg = NULL;
614   size_t signed_msg_len = 0;
615   int signed_msg_is_alloced = 0;
616   size_t size_t_out_len;
617   if (!RSA_add_pkcs1_prefix(&signed_msg, &signed_msg_len,
618                             &signed_msg_is_alloced, hash_nid, digest,
619                             digest_len) ||
620       !rsa_sign_raw_no_self_test(rsa, &size_t_out_len, out, rsa_size,
621                                  signed_msg, signed_msg_len,
622                                  RSA_PKCS1_PADDING)) {
623     goto err;
624   }
625 
626   if (size_t_out_len > UINT_MAX) {
627     OPENSSL_PUT_ERROR(RSA, ERR_R_OVERFLOW);
628     goto err;
629   }
630 
631   *out_len = (unsigned)size_t_out_len;
632   ret = 1;
633 
634 err:
635   if (signed_msg_is_alloced) {
636     OPENSSL_free(signed_msg);
637   }
638   return ret;
639 }
640 
RSA_sign(int hash_nid,const uint8_t * digest,size_t digest_len,uint8_t * out,unsigned * out_len,RSA * rsa)641 int RSA_sign(int hash_nid, const uint8_t *digest, size_t digest_len,
642              uint8_t *out, unsigned *out_len, RSA *rsa) {
643   boringssl_ensure_rsa_self_test();
644 
645   return rsa_sign_no_self_test(hash_nid, digest, digest_len, out, out_len, rsa);
646 }
647 
RSA_sign_pss_mgf1(RSA * rsa,size_t * out_len,uint8_t * out,size_t max_out,const uint8_t * digest,size_t digest_len,const EVP_MD * md,const EVP_MD * mgf1_md,int salt_len)648 int RSA_sign_pss_mgf1(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
649                       const uint8_t *digest, size_t digest_len,
650                       const EVP_MD *md, const EVP_MD *mgf1_md, int salt_len) {
651   if (digest_len != EVP_MD_size(md)) {
652     OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
653     return 0;
654   }
655 
656   size_t padded_len = RSA_size(rsa);
657   uint8_t *padded = OPENSSL_malloc(padded_len);
658   if (padded == NULL) {
659     return 0;
660   }
661 
662   int ret = RSA_padding_add_PKCS1_PSS_mgf1(rsa, padded, digest, md, mgf1_md,
663                                            salt_len) &&
664             RSA_sign_raw(rsa, out_len, out, max_out, padded, padded_len,
665                          RSA_NO_PADDING);
666   OPENSSL_free(padded);
667   return ret;
668 }
669 
rsa_verify_no_self_test(int hash_nid,const uint8_t * digest,size_t digest_len,const uint8_t * sig,size_t sig_len,RSA * rsa)670 int rsa_verify_no_self_test(int hash_nid, const uint8_t *digest,
671                             size_t digest_len, const uint8_t *sig,
672                             size_t sig_len, RSA *rsa) {
673   if (rsa->n == NULL || rsa->e == NULL) {
674     OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
675     return 0;
676   }
677 
678   const size_t rsa_size = RSA_size(rsa);
679   uint8_t *buf = NULL;
680   int ret = 0;
681   uint8_t *signed_msg = NULL;
682   size_t signed_msg_len = 0, len;
683   int signed_msg_is_alloced = 0;
684 
685   if (hash_nid == NID_md5_sha1 && digest_len != SSL_SIG_LENGTH) {
686     OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
687     return 0;
688   }
689 
690   buf = OPENSSL_malloc(rsa_size);
691   if (!buf) {
692     return 0;
693   }
694 
695   if (!rsa_verify_raw_no_self_test(rsa, &len, buf, rsa_size, sig, sig_len,
696                                    RSA_PKCS1_PADDING) ||
697       !RSA_add_pkcs1_prefix(&signed_msg, &signed_msg_len,
698                             &signed_msg_is_alloced, hash_nid, digest,
699                             digest_len)) {
700     goto out;
701   }
702 
703   // Check that no other information follows the hash value (FIPS 186-4 Section
704   // 5.5) and it matches the expected hash.
705   if (len != signed_msg_len || OPENSSL_memcmp(buf, signed_msg, len) != 0) {
706     OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_SIGNATURE);
707     goto out;
708   }
709 
710   ret = 1;
711 
712 out:
713   OPENSSL_free(buf);
714   if (signed_msg_is_alloced) {
715     OPENSSL_free(signed_msg);
716   }
717   return ret;
718 }
719 
RSA_verify(int hash_nid,const uint8_t * digest,size_t digest_len,const uint8_t * sig,size_t sig_len,RSA * rsa)720 int RSA_verify(int hash_nid, const uint8_t *digest, size_t digest_len,
721                const uint8_t *sig, size_t sig_len, RSA *rsa) {
722   boringssl_ensure_rsa_self_test();
723   return rsa_verify_no_self_test(hash_nid, digest, digest_len, sig, sig_len,
724                                  rsa);
725 }
726 
RSA_verify_pss_mgf1(RSA * rsa,const uint8_t * digest,size_t digest_len,const EVP_MD * md,const EVP_MD * mgf1_md,int salt_len,const uint8_t * sig,size_t sig_len)727 int RSA_verify_pss_mgf1(RSA *rsa, const uint8_t *digest, size_t digest_len,
728                         const EVP_MD *md, const EVP_MD *mgf1_md, int salt_len,
729                         const uint8_t *sig, size_t sig_len) {
730   if (digest_len != EVP_MD_size(md)) {
731     OPENSSL_PUT_ERROR(RSA, RSA_R_INVALID_MESSAGE_LENGTH);
732     return 0;
733   }
734 
735   size_t em_len = RSA_size(rsa);
736   uint8_t *em = OPENSSL_malloc(em_len);
737   if (em == NULL) {
738     return 0;
739   }
740 
741   int ret = 0;
742   if (!RSA_verify_raw(rsa, &em_len, em, em_len, sig, sig_len, RSA_NO_PADDING)) {
743     goto err;
744   }
745 
746   if (em_len != RSA_size(rsa)) {
747     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
748     goto err;
749   }
750 
751   ret = RSA_verify_PKCS1_PSS_mgf1(rsa, digest, md, mgf1_md, em, salt_len);
752 
753 err:
754   OPENSSL_free(em);
755   return ret;
756 }
757 
check_mod_inverse(int * out_ok,const BIGNUM * a,const BIGNUM * ainv,const BIGNUM * m,unsigned m_min_bits,BN_CTX * ctx)758 static int check_mod_inverse(int *out_ok, const BIGNUM *a, const BIGNUM *ainv,
759                              const BIGNUM *m, unsigned m_min_bits,
760                              BN_CTX *ctx) {
761   if (BN_is_negative(ainv) ||
762       constant_time_declassify_int(BN_cmp(ainv, m) >= 0)) {
763     *out_ok = 0;
764     return 1;
765   }
766 
767   // Note |bn_mul_consttime| and |bn_div_consttime| do not scale linearly, but
768   // checking |ainv| is in range bounds the running time, assuming |m|'s bounds
769   // were checked by the caller.
770   BN_CTX_start(ctx);
771   BIGNUM *tmp = BN_CTX_get(ctx);
772   int ret = tmp != NULL &&
773             bn_mul_consttime(tmp, a, ainv, ctx) &&
774             bn_div_consttime(NULL, tmp, tmp, m, m_min_bits, ctx);
775   if (ret) {
776     *out_ok = constant_time_declassify_int(BN_is_one(tmp));
777   }
778   BN_CTX_end(ctx);
779   return ret;
780 }
781 
RSA_check_key(const RSA * key)782 int RSA_check_key(const RSA *key) {
783   // TODO(davidben): RSA key initialization is spread across
784   // |rsa_check_public_key|, |RSA_check_key|, |freeze_private_key|, and
785   // |BN_MONT_CTX_set_locked| as a result of API issues. See
786   // https://crbug.com/boringssl/316. As a result, we inconsistently check RSA
787   // invariants. We should fix this and integrate that logic.
788 
789   if (RSA_is_opaque(key)) {
790     // Opaque keys can't be checked.
791     return 1;
792   }
793 
794   if (!rsa_check_public_key(key)) {
795     return 0;
796   }
797 
798   if ((key->p != NULL) != (key->q != NULL)) {
799     OPENSSL_PUT_ERROR(RSA, RSA_R_ONLY_ONE_OF_P_Q_GIVEN);
800     return 0;
801   }
802 
803   // |key->d| must be bounded by |key->n|. This ensures bounds on |RSA_bits|
804   // translate to bounds on the running time of private key operations.
805   if (key->d != NULL &&
806       (BN_is_negative(key->d) || BN_cmp(key->d, key->n) >= 0)) {
807     OPENSSL_PUT_ERROR(RSA, RSA_R_D_OUT_OF_RANGE);
808     return 0;
809   }
810 
811   if (key->d == NULL || key->p == NULL) {
812     // For a public key, or without p and q, there's nothing that can be
813     // checked.
814     return 1;
815   }
816 
817   BN_CTX *ctx = BN_CTX_new();
818   if (ctx == NULL) {
819     return 0;
820   }
821 
822   BIGNUM tmp, de, pm1, qm1, dmp1, dmq1;
823   int ok = 0;
824   BN_init(&tmp);
825   BN_init(&de);
826   BN_init(&pm1);
827   BN_init(&qm1);
828   BN_init(&dmp1);
829   BN_init(&dmq1);
830 
831   // Check that p * q == n. Before we multiply, we check that p and q are in
832   // bounds, to avoid a DoS vector in |bn_mul_consttime| below. Note that
833   // n was bound by |rsa_check_public_key|. This also implicitly checks p and q
834   // are odd, which is a necessary condition for Montgomery reduction.
835   if (BN_is_negative(key->p) ||
836       constant_time_declassify_int(BN_cmp(key->p, key->n) >= 0) ||
837       BN_is_negative(key->q) ||
838       constant_time_declassify_int(BN_cmp(key->q, key->n) >= 0)) {
839     OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
840     goto out;
841   }
842   if (!bn_mul_consttime(&tmp, key->p, key->q, ctx)) {
843     OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
844     goto out;
845   }
846   if (BN_cmp(&tmp, key->n) != 0) {
847     OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q);
848     goto out;
849   }
850 
851   // d must be an inverse of e mod the Carmichael totient, lcm(p-1, q-1), but it
852   // may be unreduced because other implementations use the Euler totient. We
853   // simply check that d * e is one mod p-1 and mod q-1. Note d and e were bound
854   // by earlier checks in this function.
855   if (!bn_usub_consttime(&pm1, key->p, BN_value_one()) ||
856       !bn_usub_consttime(&qm1, key->q, BN_value_one())) {
857     OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
858     goto out;
859   }
860   const unsigned pm1_bits = BN_num_bits(&pm1);
861   const unsigned qm1_bits = BN_num_bits(&qm1);
862   if (!bn_mul_consttime(&de, key->d, key->e, ctx) ||
863       !bn_div_consttime(NULL, &tmp, &de, &pm1, pm1_bits, ctx) ||
864       !bn_div_consttime(NULL, &de, &de, &qm1, qm1_bits, ctx)) {
865     OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
866     goto out;
867   }
868 
869   if (constant_time_declassify_int(!BN_is_one(&tmp)) ||
870       constant_time_declassify_int(!BN_is_one(&de))) {
871     OPENSSL_PUT_ERROR(RSA, RSA_R_D_E_NOT_CONGRUENT_TO_1);
872     goto out;
873   }
874 
875   int has_crt_values = key->dmp1 != NULL;
876   if (has_crt_values != (key->dmq1 != NULL) ||
877       has_crt_values != (key->iqmp != NULL)) {
878     OPENSSL_PUT_ERROR(RSA, RSA_R_INCONSISTENT_SET_OF_CRT_VALUES);
879     goto out;
880   }
881 
882   if (has_crt_values) {
883     int dmp1_ok, dmq1_ok, iqmp_ok;
884     if (!check_mod_inverse(&dmp1_ok, key->e, key->dmp1, &pm1, pm1_bits, ctx) ||
885         !check_mod_inverse(&dmq1_ok, key->e, key->dmq1, &qm1, qm1_bits, ctx) ||
886         // |p| is odd, so |pm1| and |p| have the same bit width. If they didn't,
887         // we only need a lower bound anyway.
888         !check_mod_inverse(&iqmp_ok, key->q, key->iqmp, key->p, pm1_bits,
889                            ctx)) {
890       OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
891       goto out;
892     }
893 
894     if (!dmp1_ok || !dmq1_ok || !iqmp_ok) {
895       OPENSSL_PUT_ERROR(RSA, RSA_R_CRT_VALUES_INCORRECT);
896       goto out;
897     }
898   }
899 
900   ok = 1;
901 
902 out:
903   BN_free(&tmp);
904   BN_free(&de);
905   BN_free(&pm1);
906   BN_free(&qm1);
907   BN_free(&dmp1);
908   BN_free(&dmq1);
909   BN_CTX_free(ctx);
910 
911   return ok;
912 }
913 
914 
915 // This is the product of the 132 smallest odd primes, from 3 to 751.
916 static const BN_ULONG kSmallFactorsLimbs[] = {
917     TOBN(0xc4309333, 0x3ef4e3e1), TOBN(0x71161eb6, 0xcd2d655f),
918     TOBN(0x95e2238c, 0x0bf94862), TOBN(0x3eb233d3, 0x24f7912b),
919     TOBN(0x6b55514b, 0xbf26c483), TOBN(0x0a84d817, 0x5a144871),
920     TOBN(0x77d12fee, 0x9b82210a), TOBN(0xdb5b93c2, 0x97f050b3),
921     TOBN(0x4acad6b9, 0x4d6c026b), TOBN(0xeb7751f3, 0x54aec893),
922     TOBN(0xdba53368, 0x36bc85c4), TOBN(0xd85a1b28, 0x7f5ec78e),
923     TOBN(0x2eb072d8, 0x6b322244), TOBN(0xbba51112, 0x5e2b3aea),
924     TOBN(0x36ed1a6c, 0x0e2486bf), TOBN(0x5f270460, 0xec0c5727),
925     0x000017b1
926 };
927 
DEFINE_LOCAL_DATA(BIGNUM,g_small_factors)928 DEFINE_LOCAL_DATA(BIGNUM, g_small_factors) {
929   out->d = (BN_ULONG *) kSmallFactorsLimbs;
930   out->width = OPENSSL_ARRAY_SIZE(kSmallFactorsLimbs);
931   out->dmax = out->width;
932   out->neg = 0;
933   out->flags = BN_FLG_STATIC_DATA;
934 }
935 
RSA_check_fips(RSA * key)936 int RSA_check_fips(RSA *key) {
937   if (RSA_is_opaque(key)) {
938     // Opaque keys can't be checked.
939     OPENSSL_PUT_ERROR(RSA, RSA_R_PUBLIC_KEY_VALIDATION_FAILED);
940     return 0;
941   }
942 
943   if (!RSA_check_key(key)) {
944     return 0;
945   }
946 
947   BN_CTX *ctx = BN_CTX_new();
948   if (ctx == NULL) {
949     return 0;
950   }
951 
952   BIGNUM small_gcd;
953   BN_init(&small_gcd);
954 
955   int ret = 1;
956 
957   // Perform partial public key validation of RSA keys (SP 800-89 5.3.3).
958   // Although this is not for primality testing, SP 800-89 cites an RSA
959   // primality testing algorithm, so we use |BN_prime_checks_for_generation| to
960   // match. This is only a plausibility test and we expect the value to be
961   // composite, so too few iterations will cause us to reject the key, not use
962   // an implausible one.
963   enum bn_primality_result_t primality_result;
964   if (BN_num_bits(key->e) <= 16 ||
965       BN_num_bits(key->e) > 256 ||
966       !BN_is_odd(key->n) ||
967       !BN_is_odd(key->e) ||
968       !BN_gcd(&small_gcd, key->n, g_small_factors(), ctx) ||
969       !BN_is_one(&small_gcd) ||
970       !BN_enhanced_miller_rabin_primality_test(&primality_result, key->n,
971                                                BN_prime_checks_for_generation,
972                                                ctx, NULL) ||
973       primality_result != bn_non_prime_power_composite) {
974     OPENSSL_PUT_ERROR(RSA, RSA_R_PUBLIC_KEY_VALIDATION_FAILED);
975     ret = 0;
976   }
977 
978   BN_free(&small_gcd);
979   BN_CTX_free(ctx);
980 
981   if (!ret || key->d == NULL || key->p == NULL) {
982     // On a failure or on only a public key, there's nothing else can be
983     // checked.
984     return ret;
985   }
986 
987   // FIPS pairwise consistency test (FIPS 140-2 4.9.2). Per FIPS 140-2 IG,
988   // section 9.9, it is not known whether |rsa| will be used for signing or
989   // encryption, so either pair-wise consistency self-test is acceptable. We
990   // perform a signing test.
991   uint8_t data[32] = {0};
992   unsigned sig_len = RSA_size(key);
993   uint8_t *sig = OPENSSL_malloc(sig_len);
994   if (sig == NULL) {
995     return 0;
996   }
997 
998   if (!RSA_sign(NID_sha256, data, sizeof(data), sig, &sig_len, key)) {
999     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
1000     ret = 0;
1001     goto cleanup;
1002   }
1003   if (boringssl_fips_break_test("RSA_PWCT")) {
1004     data[0] = ~data[0];
1005   }
1006   if (!RSA_verify(NID_sha256, data, sizeof(data), sig, sig_len, key)) {
1007     OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
1008     ret = 0;
1009   }
1010 
1011 cleanup:
1012   OPENSSL_free(sig);
1013 
1014   return ret;
1015 }
1016 
rsa_private_transform_no_self_test(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)1017 int rsa_private_transform_no_self_test(RSA *rsa, uint8_t *out,
1018                                        const uint8_t *in, size_t len) {
1019   if (rsa->meth->private_transform) {
1020     return rsa->meth->private_transform(rsa, out, in, len);
1021   }
1022 
1023   return rsa_default_private_transform(rsa, out, in, len);
1024 }
1025 
rsa_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)1026 int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
1027                           size_t len) {
1028   boringssl_ensure_rsa_self_test();
1029   return rsa_private_transform_no_self_test(rsa, out, in, len);
1030 }
1031 
RSA_flags(const RSA * rsa)1032 int RSA_flags(const RSA *rsa) { return rsa->flags; }
1033 
RSA_test_flags(const RSA * rsa,int flags)1034 int RSA_test_flags(const RSA *rsa, int flags) { return rsa->flags & flags; }
1035 
RSA_blinding_on(RSA * rsa,BN_CTX * ctx)1036 int RSA_blinding_on(RSA *rsa, BN_CTX *ctx) {
1037   return 1;
1038 }
1039