rsa_impl.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  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 (tjh@cryptsoft.com).
  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 (eay@cryptsoft.com)"
  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 (tjh@cryptsoft.com)"
  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. #include <openssl/rsa.h>
  57. #include <assert.h>
  58. #include <limits.h>
  59. #include <string.h>
  60. #include <openssl/bn.h>
  61. #include <openssl/err.h>
  62. #include <openssl/mem.h>
  63. #include <openssl/thread.h>
  64. #include <openssl/type_check.h>
  65. #include "internal.h"
  66. #include "../bn/internal.h"
  67. #include "../../internal.h"
  68. #include "../delocate.h"
  69. static int check_modulus_and_exponent_sizes(const RSA *rsa) {
  70. unsigned rsa_bits = BN_num_bits(rsa->n);
  71. if (rsa_bits > 16 * 1024) {
  72. OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE);
  73. return 0;
  74. }
  75. // Mitigate DoS attacks by limiting the exponent size. 33 bits was chosen as
  76. // the limit based on the recommendations in [1] and [2]. Windows CryptoAPI
  77. // doesn't support values larger than 32 bits [3], so it is unlikely that
  78. // exponents larger than 32 bits are being used for anything Windows commonly
  79. // does.
  80. //
  81. // [1] https://www.imperialviolet.org/2012/03/16/rsae.html
  82. // [2] https://www.imperialviolet.org/2012/03/17/rsados.html
  83. // [3] https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx
  84. static const unsigned kMaxExponentBits = 33;
  85. if (BN_num_bits(rsa->e) > kMaxExponentBits) {
  86. OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
  87. return 0;
  88. }
  89. // Verify |n > e|. Comparing |rsa_bits| to |kMaxExponentBits| is a small
  90. // shortcut to comparing |n| and |e| directly. In reality, |kMaxExponentBits|
  91. // is much smaller than the minimum RSA key size that any application should
  92. // accept.
  93. if (rsa_bits <= kMaxExponentBits) {
  94. OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
  95. return 0;
  96. }
  97. assert(BN_ucmp(rsa->n, rsa->e) > 0);
  98. return 1;
  99. }
  100. static int ensure_fixed_copy(BIGNUM **out, const BIGNUM *in, int width) {
  101. if (*out != NULL) {
  102. return 1;
  103. }
  104. BIGNUM *copy = BN_dup(in);
  105. if (copy == NULL ||
  106. !bn_resize_words(copy, width)) {
  107. BN_free(copy);
  108. return 0;
  109. }
  110. *out = copy;
  111. return 1;
  112. }
  113. // freeze_private_key finishes initializing |rsa|'s private key components.
  114. // After this function has returned, |rsa| may not be changed. This is needed
  115. // because |RSA| is a public struct and, additionally, OpenSSL 1.1.0 opaquified
  116. // it wrong (see https://github.com/openssl/openssl/issues/5158).
  117. static int freeze_private_key(RSA *rsa, BN_CTX *ctx) {
  118. CRYPTO_MUTEX_lock_read(&rsa->lock);
  119. int frozen = rsa->private_key_frozen;
  120. CRYPTO_MUTEX_unlock_read(&rsa->lock);
  121. if (frozen) {
  122. return 1;
  123. }
  124. int ret = 0;
  125. CRYPTO_MUTEX_lock_write(&rsa->lock);
  126. if (rsa->private_key_frozen) {
  127. ret = 1;
  128. goto err;
  129. }
  130. // Pre-compute various intermediate values, as well as copies of private
  131. // exponents with correct widths. Note that other threads may concurrently
  132. // read from |rsa->n|, |rsa->e|, etc., so any fixes must be in separate
  133. // copies. We use |mont_n->N|, |mont_p->N|, and |mont_q->N| as copies of |n|,
  134. // |p|, and |q| with the correct minimal widths.
  135. if (rsa->mont_n == NULL) {
  136. rsa->mont_n = BN_MONT_CTX_new_for_modulus(rsa->n, ctx);
  137. if (rsa->mont_n == NULL) {
  138. goto err;
  139. }
  140. }
  141. const BIGNUM *n_fixed = &rsa->mont_n->N;
  142. // The only public upper-bound of |rsa->d| is the bit length of |rsa->n|. The
  143. // ASN.1 serialization of RSA private keys unfortunately leaks the byte length
  144. // of |rsa->d|, but normalize it so we only leak it once, rather than per
  145. // operation.
  146. if (rsa->d != NULL &&
  147. !ensure_fixed_copy(&rsa->d_fixed, rsa->d, n_fixed->width)) {
  148. goto err;
  149. }
  150. if (rsa->p != NULL && rsa->q != NULL) {
  151. if (rsa->mont_p == NULL) {
  152. rsa->mont_p = BN_MONT_CTX_new_for_modulus(rsa->p, ctx);
  153. if (rsa->mont_p == NULL) {
  154. goto err;
  155. }
  156. }
  157. const BIGNUM *p_fixed = &rsa->mont_p->N;
  158. if (rsa->mont_q == NULL) {
  159. rsa->mont_q = BN_MONT_CTX_new_for_modulus(rsa->q, ctx);
  160. if (rsa->mont_q == NULL) {
  161. goto err;
  162. }
  163. }
  164. const BIGNUM *q_fixed = &rsa->mont_q->N;
  165. if (rsa->dmp1 != NULL && rsa->dmq1 != NULL) {
  166. // Key generation relies on this function to compute |iqmp|.
  167. if (rsa->iqmp == NULL) {
  168. BIGNUM *iqmp = BN_new();
  169. if (iqmp == NULL ||
  170. !bn_mod_inverse_secret_prime(iqmp, rsa->q, rsa->p, ctx,
  171. rsa->mont_p)) {
  172. BN_free(iqmp);
  173. goto err;
  174. }
  175. rsa->iqmp = iqmp;
  176. }
  177. // CRT components are only publicly bounded by their corresponding
  178. // moduli's bit lengths. |rsa->iqmp| is unused outside of this one-time
  179. // setup, so we do not compute a fixed-width version of it.
  180. if (!ensure_fixed_copy(&rsa->dmp1_fixed, rsa->dmp1, p_fixed->width) ||
  181. !ensure_fixed_copy(&rsa->dmq1_fixed, rsa->dmq1, q_fixed->width)) {
  182. goto err;
  183. }
  184. // Compute |inv_small_mod_large_mont|. Note that it is always modulo the
  185. // larger prime, independent of what is stored in |rsa->iqmp|.
  186. if (rsa->inv_small_mod_large_mont == NULL) {
  187. BIGNUM *inv_small_mod_large_mont = BN_new();
  188. int ok;
  189. if (BN_cmp(rsa->p, rsa->q) < 0) {
  190. ok = inv_small_mod_large_mont != NULL &&
  191. bn_mod_inverse_secret_prime(inv_small_mod_large_mont, rsa->p,
  192. rsa->q, ctx, rsa->mont_q) &&
  193. BN_to_montgomery(inv_small_mod_large_mont,
  194. inv_small_mod_large_mont, rsa->mont_q, ctx);
  195. } else {
  196. ok = inv_small_mod_large_mont != NULL &&
  197. BN_to_montgomery(inv_small_mod_large_mont, rsa->iqmp,
  198. rsa->mont_p, ctx);
  199. }
  200. if (!ok) {
  201. BN_free(inv_small_mod_large_mont);
  202. goto err;
  203. }
  204. rsa->inv_small_mod_large_mont = inv_small_mod_large_mont;
  205. }
  206. }
  207. }
  208. rsa->private_key_frozen = 1;
  209. ret = 1;
  210. err:
  211. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  212. return ret;
  213. }
  214. size_t rsa_default_size(const RSA *rsa) {
  215. return BN_num_bytes(rsa->n);
  216. }
  217. int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
  218. const uint8_t *in, size_t in_len, int padding) {
  219. if (rsa->n == NULL || rsa->e == NULL) {
  220. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
  221. return 0;
  222. }
  223. const unsigned rsa_size = RSA_size(rsa);
  224. BIGNUM *f, *result;
  225. uint8_t *buf = NULL;
  226. BN_CTX *ctx = NULL;
  227. int i, ret = 0;
  228. if (max_out < rsa_size) {
  229. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  230. return 0;
  231. }
  232. if (!check_modulus_and_exponent_sizes(rsa)) {
  233. return 0;
  234. }
  235. ctx = BN_CTX_new();
  236. if (ctx == NULL) {
  237. goto err;
  238. }
  239. BN_CTX_start(ctx);
  240. f = BN_CTX_get(ctx);
  241. result = BN_CTX_get(ctx);
  242. buf = OPENSSL_malloc(rsa_size);
  243. if (!f || !result || !buf) {
  244. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  245. goto err;
  246. }
  247. switch (padding) {
  248. case RSA_PKCS1_PADDING:
  249. i = RSA_padding_add_PKCS1_type_2(buf, rsa_size, in, in_len);
  250. break;
  251. case RSA_PKCS1_OAEP_PADDING:
  252. // Use the default parameters: SHA-1 for both hashes and no label.
  253. i = RSA_padding_add_PKCS1_OAEP_mgf1(buf, rsa_size, in, in_len,
  254. NULL, 0, NULL, NULL);
  255. break;
  256. case RSA_NO_PADDING:
  257. i = RSA_padding_add_none(buf, rsa_size, in, in_len);
  258. break;
  259. default:
  260. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  261. goto err;
  262. }
  263. if (i <= 0) {
  264. goto err;
  265. }
  266. if (BN_bin2bn(buf, rsa_size, f) == NULL) {
  267. goto err;
  268. }
  269. if (BN_ucmp(f, rsa->n) >= 0) {
  270. // usually the padding functions would catch this
  271. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
  272. goto err;
  273. }
  274. if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
  275. !BN_mod_exp_mont(result, f, rsa->e, &rsa->mont_n->N, ctx, rsa->mont_n)) {
  276. goto err;
  277. }
  278. // put in leading 0 bytes if the number is less than the length of the
  279. // modulus
  280. if (!BN_bn2bin_padded(out, rsa_size, result)) {
  281. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  282. goto err;
  283. }
  284. *out_len = rsa_size;
  285. ret = 1;
  286. err:
  287. if (ctx != NULL) {
  288. BN_CTX_end(ctx);
  289. BN_CTX_free(ctx);
  290. }
  291. OPENSSL_free(buf);
  292. return ret;
  293. }
  294. // MAX_BLINDINGS_PER_RSA defines the maximum number of cached BN_BLINDINGs per
  295. // RSA*. Then this limit is exceeded, BN_BLINDING objects will be created and
  296. // destroyed as needed.
  297. #define MAX_BLINDINGS_PER_RSA 1024
  298. // rsa_blinding_get returns a BN_BLINDING to use with |rsa|. It does this by
  299. // allocating one of the cached BN_BLINDING objects in |rsa->blindings|. If
  300. // none are free, the cache will be extended by a extra element and the new
  301. // BN_BLINDING is returned.
  302. //
  303. // On success, the index of the assigned BN_BLINDING is written to
  304. // |*index_used| and must be passed to |rsa_blinding_release| when finished.
  305. static BN_BLINDING *rsa_blinding_get(RSA *rsa, unsigned *index_used,
  306. BN_CTX *ctx) {
  307. assert(ctx != NULL);
  308. assert(rsa->mont_n != NULL);
  309. BN_BLINDING *ret = NULL;
  310. BN_BLINDING **new_blindings;
  311. uint8_t *new_blindings_inuse;
  312. char overflow = 0;
  313. CRYPTO_MUTEX_lock_write(&rsa->lock);
  314. unsigned i;
  315. for (i = 0; i < rsa->num_blindings; i++) {
  316. if (rsa->blindings_inuse[i] == 0) {
  317. rsa->blindings_inuse[i] = 1;
  318. ret = rsa->blindings[i];
  319. *index_used = i;
  320. break;
  321. }
  322. }
  323. if (ret != NULL) {
  324. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  325. return ret;
  326. }
  327. overflow = rsa->num_blindings >= MAX_BLINDINGS_PER_RSA;
  328. // We didn't find a free BN_BLINDING to use so increase the length of
  329. // the arrays by one and use the newly created element.
  330. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  331. ret = BN_BLINDING_new();
  332. if (ret == NULL) {
  333. return NULL;
  334. }
  335. if (overflow) {
  336. // We cannot add any more cached BN_BLINDINGs so we use |ret|
  337. // and mark it for destruction in |rsa_blinding_release|.
  338. *index_used = MAX_BLINDINGS_PER_RSA;
  339. return ret;
  340. }
  341. CRYPTO_MUTEX_lock_write(&rsa->lock);
  342. new_blindings =
  343. OPENSSL_malloc(sizeof(BN_BLINDING *) * (rsa->num_blindings + 1));
  344. if (new_blindings == NULL) {
  345. goto err1;
  346. }
  347. OPENSSL_memcpy(new_blindings, rsa->blindings,
  348. sizeof(BN_BLINDING *) * rsa->num_blindings);
  349. new_blindings[rsa->num_blindings] = ret;
  350. new_blindings_inuse = OPENSSL_malloc(rsa->num_blindings + 1);
  351. if (new_blindings_inuse == NULL) {
  352. goto err2;
  353. }
  354. OPENSSL_memcpy(new_blindings_inuse, rsa->blindings_inuse, rsa->num_blindings);
  355. new_blindings_inuse[rsa->num_blindings] = 1;
  356. *index_used = rsa->num_blindings;
  357. OPENSSL_free(rsa->blindings);
  358. rsa->blindings = new_blindings;
  359. OPENSSL_free(rsa->blindings_inuse);
  360. rsa->blindings_inuse = new_blindings_inuse;
  361. rsa->num_blindings++;
  362. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  363. return ret;
  364. err2:
  365. OPENSSL_free(new_blindings);
  366. err1:
  367. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  368. BN_BLINDING_free(ret);
  369. return NULL;
  370. }
  371. // rsa_blinding_release marks the cached BN_BLINDING at the given index as free
  372. // for other threads to use.
  373. static void rsa_blinding_release(RSA *rsa, BN_BLINDING *blinding,
  374. unsigned blinding_index) {
  375. if (blinding_index == MAX_BLINDINGS_PER_RSA) {
  376. // This blinding wasn't cached.
  377. BN_BLINDING_free(blinding);
  378. return;
  379. }
  380. CRYPTO_MUTEX_lock_write(&rsa->lock);
  381. rsa->blindings_inuse[blinding_index] = 0;
  382. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  383. }
  384. // signing
  385. int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out,
  386. size_t max_out, const uint8_t *in, size_t in_len,
  387. int padding) {
  388. const unsigned rsa_size = RSA_size(rsa);
  389. uint8_t *buf = NULL;
  390. int i, ret = 0;
  391. if (max_out < rsa_size) {
  392. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  393. return 0;
  394. }
  395. buf = OPENSSL_malloc(rsa_size);
  396. if (buf == NULL) {
  397. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  398. goto err;
  399. }
  400. switch (padding) {
  401. case RSA_PKCS1_PADDING:
  402. i = RSA_padding_add_PKCS1_type_1(buf, rsa_size, in, in_len);
  403. break;
  404. case RSA_NO_PADDING:
  405. i = RSA_padding_add_none(buf, rsa_size, in, in_len);
  406. break;
  407. default:
  408. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  409. goto err;
  410. }
  411. if (i <= 0) {
  412. goto err;
  413. }
  414. if (!RSA_private_transform(rsa, out, buf, rsa_size)) {
  415. goto err;
  416. }
  417. *out_len = rsa_size;
  418. ret = 1;
  419. err:
  420. OPENSSL_free(buf);
  421. return ret;
  422. }
  423. int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
  424. const uint8_t *in, size_t in_len, int padding) {
  425. const unsigned rsa_size = RSA_size(rsa);
  426. uint8_t *buf = NULL;
  427. int ret = 0;
  428. if (max_out < rsa_size) {
  429. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  430. return 0;
  431. }
  432. if (padding == RSA_NO_PADDING) {
  433. buf = out;
  434. } else {
  435. // Allocate a temporary buffer to hold the padded plaintext.
  436. buf = OPENSSL_malloc(rsa_size);
  437. if (buf == NULL) {
  438. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  439. goto err;
  440. }
  441. }
  442. if (in_len != rsa_size) {
  443. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
  444. goto err;
  445. }
  446. if (!RSA_private_transform(rsa, buf, in, rsa_size)) {
  447. goto err;
  448. }
  449. switch (padding) {
  450. case RSA_PKCS1_PADDING:
  451. ret =
  452. RSA_padding_check_PKCS1_type_2(out, out_len, rsa_size, buf, rsa_size);
  453. break;
  454. case RSA_PKCS1_OAEP_PADDING:
  455. // Use the default parameters: SHA-1 for both hashes and no label.
  456. ret = RSA_padding_check_PKCS1_OAEP_mgf1(out, out_len, rsa_size, buf,
  457. rsa_size, NULL, 0, NULL, NULL);
  458. break;
  459. case RSA_NO_PADDING:
  460. *out_len = rsa_size;
  461. ret = 1;
  462. break;
  463. default:
  464. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  465. goto err;
  466. }
  467. if (!ret) {
  468. OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
  469. }
  470. err:
  471. if (padding != RSA_NO_PADDING) {
  472. OPENSSL_free(buf);
  473. }
  474. return ret;
  475. }
  476. static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
  477. int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
  478. const uint8_t *in, size_t in_len, int padding) {
  479. if (rsa->n == NULL || rsa->e == NULL) {
  480. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
  481. return 0;
  482. }
  483. const unsigned rsa_size = RSA_size(rsa);
  484. BIGNUM *f, *result;
  485. if (max_out < rsa_size) {
  486. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  487. return 0;
  488. }
  489. if (in_len != rsa_size) {
  490. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
  491. return 0;
  492. }
  493. if (!check_modulus_and_exponent_sizes(rsa)) {
  494. return 0;
  495. }
  496. BN_CTX *ctx = BN_CTX_new();
  497. if (ctx == NULL) {
  498. return 0;
  499. }
  500. int ret = 0;
  501. uint8_t *buf = NULL;
  502. BN_CTX_start(ctx);
  503. f = BN_CTX_get(ctx);
  504. result = BN_CTX_get(ctx);
  505. if (f == NULL || result == NULL) {
  506. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  507. goto err;
  508. }
  509. if (padding == RSA_NO_PADDING) {
  510. buf = out;
  511. } else {
  512. // Allocate a temporary buffer to hold the padded plaintext.
  513. buf = OPENSSL_malloc(rsa_size);
  514. if (buf == NULL) {
  515. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  516. goto err;
  517. }
  518. }
  519. if (BN_bin2bn(in, in_len, f) == NULL) {
  520. goto err;
  521. }
  522. if (BN_ucmp(f, rsa->n) >= 0) {
  523. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
  524. goto err;
  525. }
  526. if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
  527. !BN_mod_exp_mont(result, f, rsa->e, &rsa->mont_n->N, ctx, rsa->mont_n)) {
  528. goto err;
  529. }
  530. if (!BN_bn2bin_padded(buf, rsa_size, result)) {
  531. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  532. goto err;
  533. }
  534. switch (padding) {
  535. case RSA_PKCS1_PADDING:
  536. ret =
  537. RSA_padding_check_PKCS1_type_1(out, out_len, rsa_size, buf, rsa_size);
  538. break;
  539. case RSA_NO_PADDING:
  540. ret = 1;
  541. *out_len = rsa_size;
  542. break;
  543. default:
  544. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  545. goto err;
  546. }
  547. if (!ret) {
  548. OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
  549. goto err;
  550. }
  551. err:
  552. BN_CTX_end(ctx);
  553. BN_CTX_free(ctx);
  554. if (buf != out) {
  555. OPENSSL_free(buf);
  556. }
  557. return ret;
  558. }
  559. int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
  560. size_t len) {
  561. if (rsa->n == NULL || rsa->d == NULL) {
  562. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
  563. return 0;
  564. }
  565. BIGNUM *f, *result;
  566. BN_CTX *ctx = NULL;
  567. unsigned blinding_index = 0;
  568. BN_BLINDING *blinding = NULL;
  569. int ret = 0;
  570. ctx = BN_CTX_new();
  571. if (ctx == NULL) {
  572. goto err;
  573. }
  574. BN_CTX_start(ctx);
  575. f = BN_CTX_get(ctx);
  576. result = BN_CTX_get(ctx);
  577. if (f == NULL || result == NULL) {
  578. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  579. goto err;
  580. }
  581. if (BN_bin2bn(in, len, f) == NULL) {
  582. goto err;
  583. }
  584. if (BN_ucmp(f, rsa->n) >= 0) {
  585. // Usually the padding functions would catch this.
  586. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
  587. goto err;
  588. }
  589. if (!freeze_private_key(rsa, ctx)) {
  590. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  591. goto err;
  592. }
  593. const int do_blinding = (rsa->flags & RSA_FLAG_NO_BLINDING) == 0;
  594. if (rsa->e == NULL && do_blinding) {
  595. // We cannot do blinding or verification without |e|, and continuing without
  596. // those countermeasures is dangerous. However, the Java/Android RSA API
  597. // requires support for keys where only |d| and |n| (and not |e|) are known.
  598. // The callers that require that bad behavior set |RSA_FLAG_NO_BLINDING|.
  599. OPENSSL_PUT_ERROR(RSA, RSA_R_NO_PUBLIC_EXPONENT);
  600. goto err;
  601. }
  602. if (do_blinding) {
  603. blinding = rsa_blinding_get(rsa, &blinding_index, ctx);
  604. if (blinding == NULL) {
  605. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  606. goto err;
  607. }
  608. if (!BN_BLINDING_convert(f, blinding, rsa->e, rsa->mont_n, ctx)) {
  609. goto err;
  610. }
  611. }
  612. if (rsa->p != NULL && rsa->q != NULL && rsa->e != NULL && rsa->dmp1 != NULL &&
  613. rsa->dmq1 != NULL && rsa->iqmp != NULL) {
  614. if (!mod_exp(result, f, rsa, ctx)) {
  615. goto err;
  616. }
  617. } else if (!BN_mod_exp_mont_consttime(result, f, rsa->d_fixed, rsa->n, ctx,
  618. rsa->mont_n)) {
  619. goto err;
  620. }
  621. // Verify the result to protect against fault attacks as described in the
  622. // 1997 paper "On the Importance of Checking Cryptographic Protocols for
  623. // Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton. Some
  624. // implementations do this only when the CRT is used, but we do it in all
  625. // cases. Section 6 of the aforementioned paper describes an attack that
  626. // works when the CRT isn't used. That attack is much less likely to succeed
  627. // than the CRT attack, but there have likely been improvements since 1997.
  628. //
  629. // This check is cheap assuming |e| is small; it almost always is.
  630. if (rsa->e != NULL) {
  631. BIGNUM *vrfy = BN_CTX_get(ctx);
  632. if (vrfy == NULL ||
  633. !BN_mod_exp_mont(vrfy, result, rsa->e, rsa->n, ctx, rsa->mont_n) ||
  634. !BN_equal_consttime(vrfy, f)) {
  635. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  636. goto err;
  637. }
  638. }
  639. if (do_blinding &&
  640. !BN_BLINDING_invert(result, blinding, rsa->mont_n, ctx)) {
  641. goto err;
  642. }
  643. // The computation should have left |result| as a maximally-wide number, so
  644. // that it and serializing does not leak information about the magnitude of
  645. // the result.
  646. //
  647. // See Falko Stenzke, "Manger's Attack revisited", ICICS 2010.
  648. assert(result->width == rsa->mont_n->N.width);
  649. if (!BN_bn2bin_padded(out, len, result)) {
  650. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  651. goto err;
  652. }
  653. ret = 1;
  654. err:
  655. if (ctx != NULL) {
  656. BN_CTX_end(ctx);
  657. BN_CTX_free(ctx);
  658. }
  659. if (blinding != NULL) {
  660. rsa_blinding_release(rsa, blinding, blinding_index);
  661. }
  662. return ret;
  663. }
  664. // mod_montgomery sets |r| to |I| mod |p|. |I| must already be fully reduced
  665. // modulo |p| times |q|. It returns one on success and zero on error.
  666. static int mod_montgomery(BIGNUM *r, const BIGNUM *I, const BIGNUM *p,
  667. const BN_MONT_CTX *mont_p, const BIGNUM *q,
  668. BN_CTX *ctx) {
  669. // Reducing in constant-time with Montgomery reduction requires I <= p * R. We
  670. // have I < p * q, so this follows if q < R. In particular, this always holds
  671. // if p and q are the same size, which is true for any RSA keys we or anyone
  672. // sane generates. For other keys, we fall back to |BN_mod|.
  673. if (!bn_less_than_montgomery_R(q, mont_p)) {
  674. return BN_mod(r, I, p, ctx);
  675. }
  676. if (// Reduce mod p with Montgomery reduction. This computes I * R^-1 mod p.
  677. !BN_from_montgomery(r, I, mont_p, ctx) ||
  678. // Multiply by R^2 and do another Montgomery reduction to compute
  679. // I * R^-1 * R^2 * R^-1 = I mod p.
  680. !BN_to_montgomery(r, r, mont_p, ctx)) {
  681. return 0;
  682. }
  683. // By precomputing R^3 mod p (normally |BN_MONT_CTX| only uses R^2 mod p) and
  684. // adjusting the API for |BN_mod_exp_mont_consttime|, we could instead compute
  685. // I * R mod p here and save a reduction per prime. But this would require
  686. // changing the RSAZ code and may not be worth it. Note that the RSAZ code
  687. // uses a different radix, so it uses R' = 2^1044. There we'd actually want
  688. // R^2 * R', and would futher benefit from a precomputed R'^2. It currently
  689. // converts |mont_p->RR| to R'^2.
  690. return 1;
  691. }
  692. static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) {
  693. assert(ctx != NULL);
  694. assert(rsa->n != NULL);
  695. assert(rsa->e != NULL);
  696. assert(rsa->d != NULL);
  697. assert(rsa->p != NULL);
  698. assert(rsa->q != NULL);
  699. assert(rsa->dmp1 != NULL);
  700. assert(rsa->dmq1 != NULL);
  701. assert(rsa->iqmp != NULL);
  702. BIGNUM *r1, *m1;
  703. int ret = 0;
  704. BN_CTX_start(ctx);
  705. r1 = BN_CTX_get(ctx);
  706. m1 = BN_CTX_get(ctx);
  707. if (r1 == NULL ||
  708. m1 == NULL) {
  709. goto err;
  710. }
  711. if (!freeze_private_key(rsa, ctx)) {
  712. goto err;
  713. }
  714. // Implementing RSA with CRT in constant-time is sensitive to which prime is
  715. // larger. Canonicalize fields so that |p| is the larger prime.
  716. const BIGNUM *dmp1 = rsa->dmp1_fixed, *dmq1 = rsa->dmq1_fixed;
  717. const BN_MONT_CTX *mont_p = rsa->mont_p, *mont_q = rsa->mont_q;
  718. if (BN_cmp(rsa->p, rsa->q) < 0) {
  719. mont_p = rsa->mont_q;
  720. mont_q = rsa->mont_p;
  721. dmp1 = rsa->dmq1_fixed;
  722. dmq1 = rsa->dmp1_fixed;
  723. }
  724. // Use the minimal-width versions of |n|, |p|, and |q|. Either works, but if
  725. // someone gives us non-minimal values, these will be slightly more efficient
  726. // on the non-Montgomery operations.
  727. const BIGNUM *n = &rsa->mont_n->N;
  728. const BIGNUM *p = &mont_p->N;
  729. const BIGNUM *q = &mont_q->N;
  730. // This is a pre-condition for |mod_montgomery|. It was already checked by the
  731. // caller.
  732. assert(BN_ucmp(I, n) < 0);
  733. if (// |m1| is the result modulo |q|.
  734. !mod_montgomery(r1, I, q, mont_q, p, ctx) ||
  735. !BN_mod_exp_mont_consttime(m1, r1, dmq1, q, ctx, mont_q) ||
  736. // |r0| is the result modulo |p|.
  737. !mod_montgomery(r1, I, p, mont_p, q, ctx) ||
  738. !BN_mod_exp_mont_consttime(r0, r1, dmp1, p, ctx, mont_p) ||
  739. // Compute r0 = r0 - m1 mod p. |p| is the larger prime, so |m1| is already
  740. // fully reduced mod |p|.
  741. !bn_mod_sub_consttime(r0, r0, m1, p, ctx) ||
  742. // r0 = r0 * iqmp mod p. We use Montgomery multiplication to compute this
  743. // in constant time. |inv_small_mod_large_mont| is in Montgomery form and
  744. // r0 is not, so the result is taken out of Montgomery form.
  745. !BN_mod_mul_montgomery(r0, r0, rsa->inv_small_mod_large_mont, mont_p,
  746. ctx) ||
  747. // r0 = r0 * q + m1 gives the final result. Reducing modulo q gives m1, so
  748. // it is correct mod p. Reducing modulo p gives (r0-m1)*iqmp*q + m1 = r0,
  749. // so it is correct mod q. Finally, the result is bounded by [m1, n + m1),
  750. // and the result is at least |m1|, so this must be the unique answer in
  751. // [0, n).
  752. !bn_mul_consttime(r0, r0, q, ctx) ||
  753. !bn_uadd_consttime(r0, r0, m1) ||
  754. // The result should be bounded by |n|, but fixed-width operations may
  755. // bound the width slightly higher, so fix it.
  756. !bn_resize_words(r0, n->width)) {
  757. goto err;
  758. }
  759. ret = 1;
  760. err:
  761. BN_CTX_end(ctx);
  762. return ret;
  763. }
  764. static int ensure_bignum(BIGNUM **out) {
  765. if (*out == NULL) {
  766. *out = BN_new();
  767. }
  768. return *out != NULL;
  769. }
  770. // kBoringSSLRSASqrtTwo is the BIGNUM representation of ⌊2¹⁵³⁵×√2⌋. This is
  771. // chosen to give enough precision for 3072-bit RSA, the largest key size FIPS
  772. // specifies. Key sizes beyond this will round up.
  773. //
  774. // To verify this number, check that n² < 2³⁰⁷¹ < (n+1)², where n is value
  775. // represented here. Note the components are listed in little-endian order. Here
  776. // is some sample Python code to check:
  777. //
  778. // >>> TOBN = lambda a, b: a << 32 | b
  779. // >>> l = [ <paste the contents of kSqrtTwo> ]
  780. // >>> n = sum(a * 2**(64*i) for i, a in enumerate(l))
  781. // >>> n**2 < 2**3071 < (n+1)**2
  782. // True
  783. const BN_ULONG kBoringSSLRSASqrtTwo[] = {
  784. TOBN(0xdea06241, 0xf7aa81c2), TOBN(0xf6a1be3f, 0xca221307),
  785. TOBN(0x332a5e9f, 0x7bda1ebf), TOBN(0x0104dc01, 0xfe32352f),
  786. TOBN(0xb8cf341b, 0x6f8236c7), TOBN(0x4264dabc, 0xd528b651),
  787. TOBN(0xf4d3a02c, 0xebc93e0c), TOBN(0x81394ab6, 0xd8fd0efd),
  788. TOBN(0xeaa4a089, 0x9040ca4a), TOBN(0xf52f120f, 0x836e582e),
  789. TOBN(0xcb2a6343, 0x31f3c84d), TOBN(0xc6d5a8a3, 0x8bb7e9dc),
  790. TOBN(0x460abc72, 0x2f7c4e33), TOBN(0xcab1bc91, 0x1688458a),
  791. TOBN(0x53059c60, 0x11bc337b), TOBN(0xd2202e87, 0x42af1f4e),
  792. TOBN(0x78048736, 0x3dfa2768), TOBN(0x0f74a85e, 0x439c7b4a),
  793. TOBN(0xa8b1fe6f, 0xdc83db39), TOBN(0x4afc8304, 0x3ab8a2c3),
  794. TOBN(0xed17ac85, 0x83339915), TOBN(0x1d6f60ba, 0x893ba84c),
  795. TOBN(0x597d89b3, 0x754abe9f), TOBN(0xb504f333, 0xf9de6484),
  796. };
  797. const size_t kBoringSSLRSASqrtTwoLen = OPENSSL_ARRAY_SIZE(kBoringSSLRSASqrtTwo);
  798. // generate_prime sets |out| to a prime with length |bits| such that |out|-1 is
  799. // relatively prime to |e|. If |p| is non-NULL, |out| will also not be close to
  800. // |p|. |sqrt2| must be ⌊2^(bits-1)×√2⌋ (or a slightly overestimate for large
  801. // sizes), and |pow2_bits_100| must be 2^(bits-100).
  802. static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e,
  803. const BIGNUM *p, const BIGNUM *sqrt2,
  804. const BIGNUM *pow2_bits_100, BN_CTX *ctx,
  805. BN_GENCB *cb) {
  806. if (bits < 128 || (bits % BN_BITS2) != 0) {
  807. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  808. return 0;
  809. }
  810. assert(BN_is_pow2(pow2_bits_100));
  811. assert(BN_is_bit_set(pow2_bits_100, bits - 100));
  812. // See FIPS 186-4 appendix B.3.3, steps 4 and 5. Note |bits| here is nlen/2.
  813. // Use the limit from steps 4.7 and 5.8 for most values of |e|. When |e| is 3,
  814. // the 186-4 limit is too low, so we use a higher one. Note this case is not
  815. // reachable from |RSA_generate_key_fips|.
  816. if (bits >= INT_MAX/32) {
  817. OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE);
  818. return 0;
  819. }
  820. int limit = BN_is_word(e, 3) ? bits * 32 : bits * 5;
  821. int ret = 0, tries = 0, rand_tries = 0;
  822. BN_CTX_start(ctx);
  823. BIGNUM *tmp = BN_CTX_get(ctx);
  824. if (tmp == NULL) {
  825. goto err;
  826. }
  827. for (;;) {
  828. // Generate a random number of length |bits| where the bottom bit is set
  829. // (steps 4.2, 4.3, 5.2 and 5.3) and the top bit is set (implied by the
  830. // bound checked below in steps 4.4 and 5.5).
  831. if (!BN_rand(out, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD) ||
  832. !BN_GENCB_call(cb, BN_GENCB_GENERATED, rand_tries++)) {
  833. goto err;
  834. }
  835. if (p != NULL) {
  836. // If |p| and |out| are too close, try again (step 5.4).
  837. if (!bn_abs_sub_consttime(tmp, out, p, ctx)) {
  838. goto err;
  839. }
  840. if (BN_cmp(tmp, pow2_bits_100) <= 0) {
  841. continue;
  842. }
  843. }
  844. // If out < 2^(bits-1)×√2, try again (steps 4.4 and 5.5). This is equivalent
  845. // to out <= ⌊2^(bits-1)×√2⌋, or out <= sqrt2 for FIPS key sizes.
  846. //
  847. // For larger keys, the comparison is approximate, leaning towards
  848. // retrying. That is, we reject a negligible fraction of primes that are
  849. // within the FIPS bound, but we will never accept a prime outside the
  850. // bound, ensuring the resulting RSA key is the right size.
  851. if (BN_cmp(out, sqrt2) <= 0) {
  852. continue;
  853. }
  854. // RSA key generation's bottleneck is discarding composites. If it fails
  855. // trial division, do not bother computing a GCD or performing Rabin-Miller.
  856. if (!bn_odd_number_is_obviously_composite(out)) {
  857. // Check gcd(out-1, e) is one (steps 4.5 and 5.6).
  858. int relatively_prime;
  859. if (!BN_sub(tmp, out, BN_value_one()) ||
  860. !bn_is_relatively_prime(&relatively_prime, tmp, e, ctx)) {
  861. goto err;
  862. }
  863. if (relatively_prime) {
  864. // Test |out| for primality (steps 4.5.1 and 5.6.1).
  865. int is_probable_prime;
  866. if (!BN_primality_test(&is_probable_prime, out, BN_prime_checks, ctx, 0,
  867. cb)) {
  868. goto err;
  869. }
  870. if (is_probable_prime) {
  871. ret = 1;
  872. goto err;
  873. }
  874. }
  875. }
  876. // If we've tried too many times to find a prime, abort (steps 4.7 and
  877. // 5.8).
  878. tries++;
  879. if (tries >= limit) {
  880. OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_MANY_ITERATIONS);
  881. goto err;
  882. }
  883. if (!BN_GENCB_call(cb, 2, tries)) {
  884. goto err;
  885. }
  886. }
  887. err:
  888. BN_CTX_end(ctx);
  889. return ret;
  890. }
  891. int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) {
  892. // See FIPS 186-4 appendix B.3. This function implements a generalized version
  893. // of the FIPS algorithm. |RSA_generate_key_fips| performs additional checks
  894. // for FIPS-compliant key generation.
  895. // Always generate RSA keys which are a multiple of 128 bits. Round |bits|
  896. // down as needed.
  897. bits &= ~127;
  898. // Reject excessively small keys.
  899. if (bits < 256) {
  900. OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
  901. return 0;
  902. }
  903. // Reject excessively large public exponents. Windows CryptoAPI and Go don't
  904. // support values larger than 32 bits, so match their limits for generating
  905. // keys. (|check_modulus_and_exponent_sizes| uses a slightly more conservative
  906. // value, but we don't need to support generating such keys.)
  907. // https://github.com/golang/go/issues/3161
  908. // https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx
  909. if (BN_num_bits(e_value) > 32) {
  910. OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE);
  911. return 0;
  912. }
  913. int ret = 0;
  914. int prime_bits = bits / 2;
  915. BN_CTX *ctx = BN_CTX_new();
  916. if (ctx == NULL) {
  917. goto bn_err;
  918. }
  919. BN_CTX_start(ctx);
  920. BIGNUM *totient = BN_CTX_get(ctx);
  921. BIGNUM *pm1 = BN_CTX_get(ctx);
  922. BIGNUM *qm1 = BN_CTX_get(ctx);
  923. BIGNUM *sqrt2 = BN_CTX_get(ctx);
  924. BIGNUM *pow2_prime_bits_100 = BN_CTX_get(ctx);
  925. BIGNUM *pow2_prime_bits = BN_CTX_get(ctx);
  926. if (totient == NULL || pm1 == NULL || qm1 == NULL || sqrt2 == NULL ||
  927. pow2_prime_bits_100 == NULL || pow2_prime_bits == NULL ||
  928. !BN_set_bit(pow2_prime_bits_100, prime_bits - 100) ||
  929. !BN_set_bit(pow2_prime_bits, prime_bits)) {
  930. goto bn_err;
  931. }
  932. // We need the RSA components non-NULL.
  933. if (!ensure_bignum(&rsa->n) ||
  934. !ensure_bignum(&rsa->d) ||
  935. !ensure_bignum(&rsa->e) ||
  936. !ensure_bignum(&rsa->p) ||
  937. !ensure_bignum(&rsa->q) ||
  938. !ensure_bignum(&rsa->dmp1) ||
  939. !ensure_bignum(&rsa->dmq1)) {
  940. goto bn_err;
  941. }
  942. if (!BN_copy(rsa->e, e_value)) {
  943. goto bn_err;
  944. }
  945. // Compute sqrt2 >= ⌊2^(prime_bits-1)×√2⌋.
  946. if (!bn_set_words(sqrt2, kBoringSSLRSASqrtTwo, kBoringSSLRSASqrtTwoLen)) {
  947. goto bn_err;
  948. }
  949. int sqrt2_bits = kBoringSSLRSASqrtTwoLen * BN_BITS2;
  950. assert(sqrt2_bits == (int)BN_num_bits(sqrt2));
  951. if (sqrt2_bits > prime_bits) {
  952. // For key sizes up to 3072 (prime_bits = 1536), this is exactly
  953. // ⌊2^(prime_bits-1)×√2⌋.
  954. if (!BN_rshift(sqrt2, sqrt2, sqrt2_bits - prime_bits)) {
  955. goto bn_err;
  956. }
  957. } else if (prime_bits > sqrt2_bits) {
  958. // For key sizes beyond 3072, this is approximate. We err towards retrying
  959. // to ensure our key is the right size and round up.
  960. if (!BN_add_word(sqrt2, 1) ||
  961. !BN_lshift(sqrt2, sqrt2, prime_bits - sqrt2_bits)) {
  962. goto bn_err;
  963. }
  964. }
  965. assert(prime_bits == (int)BN_num_bits(sqrt2));
  966. do {
  967. // Generate p and q, each of size |prime_bits|, using the steps outlined in
  968. // appendix FIPS 186-4 appendix B.3.3.
  969. if (!generate_prime(rsa->p, prime_bits, rsa->e, NULL, sqrt2,
  970. pow2_prime_bits_100, ctx, cb) ||
  971. !BN_GENCB_call(cb, 3, 0) ||
  972. !generate_prime(rsa->q, prime_bits, rsa->e, rsa->p, sqrt2,
  973. pow2_prime_bits_100, ctx, cb) ||
  974. !BN_GENCB_call(cb, 3, 1)) {
  975. goto bn_err;
  976. }
  977. if (BN_cmp(rsa->p, rsa->q) < 0) {
  978. BIGNUM *tmp = rsa->p;
  979. rsa->p = rsa->q;
  980. rsa->q = tmp;
  981. }
  982. // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-4. This differs
  983. // from typical RSA implementations which use (p-1)*(q-1).
  984. //
  985. // Note this means the size of d might reveal information about p-1 and
  986. // q-1. However, we do operations with Chinese Remainder Theorem, so we only
  987. // use d (mod p-1) and d (mod q-1) as exponents. Using a minimal totient
  988. // does not affect those two values.
  989. int no_inverse;
  990. if (!bn_usub_consttime(pm1, rsa->p, BN_value_one()) ||
  991. !bn_usub_consttime(qm1, rsa->q, BN_value_one()) ||
  992. !bn_lcm_consttime(totient, pm1, qm1, ctx) ||
  993. !bn_mod_inverse_consttime(rsa->d, &no_inverse, rsa->e, totient, ctx)) {
  994. goto bn_err;
  995. }
  996. // Retry if |rsa->d| <= 2^|prime_bits|. See appendix B.3.1's guidance on
  997. // values for d.
  998. } while (BN_cmp(rsa->d, pow2_prime_bits) <= 0);
  999. if (// Calculate n.
  1000. !bn_mul_consttime(rsa->n, rsa->p, rsa->q, ctx) ||
  1001. // Calculate d mod (p-1).
  1002. !bn_div_consttime(NULL, rsa->dmp1, rsa->d, pm1, ctx) ||
  1003. // Calculate d mod (q-1)
  1004. !bn_div_consttime(NULL, rsa->dmq1, rsa->d, qm1, ctx)) {
  1005. goto bn_err;
  1006. }
  1007. bn_set_minimal_width(rsa->n);
  1008. // Sanity-check that |rsa->n| has the specified size. This is implied by
  1009. // |generate_prime|'s bounds.
  1010. if (BN_num_bits(rsa->n) != (unsigned)bits) {
  1011. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  1012. goto err;
  1013. }
  1014. // Call |freeze_private_key| to compute the inverse of q mod p, by way of
  1015. // |rsa->mont_p|.
  1016. if (!freeze_private_key(rsa, ctx)) {
  1017. goto bn_err;
  1018. }
  1019. // The key generation process is complex and thus error-prone. It could be
  1020. // disastrous to generate and then use a bad key so double-check that the key
  1021. // makes sense.
  1022. if (!RSA_check_key(rsa)) {
  1023. OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR);
  1024. goto err;
  1025. }
  1026. ret = 1;
  1027. bn_err:
  1028. if (!ret) {
  1029. OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
  1030. }
  1031. err:
  1032. if (ctx != NULL) {
  1033. BN_CTX_end(ctx);
  1034. BN_CTX_free(ctx);
  1035. }
  1036. return ret;
  1037. }
  1038. int RSA_generate_key_fips(RSA *rsa, int bits, BN_GENCB *cb) {
  1039. // FIPS 186-4 allows 2048-bit and 3072-bit RSA keys (1024-bit and 1536-bit
  1040. // primes, respectively) with the prime generation method we use.
  1041. if (bits != 2048 && bits != 3072) {
  1042. OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS);
  1043. return 0;
  1044. }
  1045. BIGNUM *e = BN_new();
  1046. int ret = e != NULL &&
  1047. BN_set_word(e, RSA_F4) &&
  1048. RSA_generate_key_ex(rsa, bits, e, cb) &&
  1049. RSA_check_fips(rsa);
  1050. BN_free(e);
  1051. return ret;
  1052. }
  1053. DEFINE_METHOD_FUNCTION(RSA_METHOD, RSA_default_method) {
  1054. // All of the methods are NULL to make it easier for the compiler/linker to
  1055. // drop unused functions. The wrapper functions will select the appropriate
  1056. // |rsa_default_*| implementation.
  1057. OPENSSL_memset(out, 0, sizeof(RSA_METHOD));
  1058. out->common.is_static = 1;
  1059. }