rsa_impl.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. size_t rsa_default_size(const RSA *rsa) {
  101. return BN_num_bytes(rsa->n);
  102. }
  103. int RSA_encrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
  104. const uint8_t *in, size_t in_len, int padding) {
  105. if (rsa->n == NULL || rsa->e == NULL) {
  106. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
  107. return 0;
  108. }
  109. const unsigned rsa_size = RSA_size(rsa);
  110. BIGNUM *f, *result;
  111. uint8_t *buf = NULL;
  112. BN_CTX *ctx = NULL;
  113. int i, ret = 0;
  114. if (max_out < rsa_size) {
  115. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  116. return 0;
  117. }
  118. if (!check_modulus_and_exponent_sizes(rsa)) {
  119. return 0;
  120. }
  121. ctx = BN_CTX_new();
  122. if (ctx == NULL) {
  123. goto err;
  124. }
  125. BN_CTX_start(ctx);
  126. f = BN_CTX_get(ctx);
  127. result = BN_CTX_get(ctx);
  128. buf = OPENSSL_malloc(rsa_size);
  129. if (!f || !result || !buf) {
  130. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  131. goto err;
  132. }
  133. switch (padding) {
  134. case RSA_PKCS1_PADDING:
  135. i = RSA_padding_add_PKCS1_type_2(buf, rsa_size, in, in_len);
  136. break;
  137. case RSA_PKCS1_OAEP_PADDING:
  138. // Use the default parameters: SHA-1 for both hashes and no label.
  139. i = RSA_padding_add_PKCS1_OAEP_mgf1(buf, rsa_size, in, in_len,
  140. NULL, 0, NULL, NULL);
  141. break;
  142. case RSA_NO_PADDING:
  143. i = RSA_padding_add_none(buf, rsa_size, in, in_len);
  144. break;
  145. default:
  146. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  147. goto err;
  148. }
  149. if (i <= 0) {
  150. goto err;
  151. }
  152. if (BN_bin2bn(buf, rsa_size, f) == NULL) {
  153. goto err;
  154. }
  155. if (BN_ucmp(f, rsa->n) >= 0) {
  156. // usually the padding functions would catch this
  157. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
  158. goto err;
  159. }
  160. if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
  161. !BN_mod_exp_mont(result, f, rsa->e, rsa->n, ctx, rsa->mont_n)) {
  162. goto err;
  163. }
  164. // put in leading 0 bytes if the number is less than the length of the
  165. // modulus
  166. if (!BN_bn2bin_padded(out, rsa_size, result)) {
  167. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  168. goto err;
  169. }
  170. *out_len = rsa_size;
  171. ret = 1;
  172. err:
  173. if (ctx != NULL) {
  174. BN_CTX_end(ctx);
  175. BN_CTX_free(ctx);
  176. }
  177. OPENSSL_free(buf);
  178. return ret;
  179. }
  180. // MAX_BLINDINGS_PER_RSA defines the maximum number of cached BN_BLINDINGs per
  181. // RSA*. Then this limit is exceeded, BN_BLINDING objects will be created and
  182. // destroyed as needed.
  183. #define MAX_BLINDINGS_PER_RSA 1024
  184. // rsa_blinding_get returns a BN_BLINDING to use with |rsa|. It does this by
  185. // allocating one of the cached BN_BLINDING objects in |rsa->blindings|. If
  186. // none are free, the cache will be extended by a extra element and the new
  187. // BN_BLINDING is returned.
  188. //
  189. // On success, the index of the assigned BN_BLINDING is written to
  190. // |*index_used| and must be passed to |rsa_blinding_release| when finished.
  191. static BN_BLINDING *rsa_blinding_get(RSA *rsa, unsigned *index_used,
  192. BN_CTX *ctx) {
  193. assert(ctx != NULL);
  194. assert(rsa->mont_n != NULL);
  195. BN_BLINDING *ret = NULL;
  196. BN_BLINDING **new_blindings;
  197. uint8_t *new_blindings_inuse;
  198. char overflow = 0;
  199. CRYPTO_MUTEX_lock_write(&rsa->lock);
  200. unsigned i;
  201. for (i = 0; i < rsa->num_blindings; i++) {
  202. if (rsa->blindings_inuse[i] == 0) {
  203. rsa->blindings_inuse[i] = 1;
  204. ret = rsa->blindings[i];
  205. *index_used = i;
  206. break;
  207. }
  208. }
  209. if (ret != NULL) {
  210. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  211. return ret;
  212. }
  213. overflow = rsa->num_blindings >= MAX_BLINDINGS_PER_RSA;
  214. // We didn't find a free BN_BLINDING to use so increase the length of
  215. // the arrays by one and use the newly created element.
  216. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  217. ret = BN_BLINDING_new();
  218. if (ret == NULL) {
  219. return NULL;
  220. }
  221. if (overflow) {
  222. // We cannot add any more cached BN_BLINDINGs so we use |ret|
  223. // and mark it for destruction in |rsa_blinding_release|.
  224. *index_used = MAX_BLINDINGS_PER_RSA;
  225. return ret;
  226. }
  227. CRYPTO_MUTEX_lock_write(&rsa->lock);
  228. new_blindings =
  229. OPENSSL_malloc(sizeof(BN_BLINDING *) * (rsa->num_blindings + 1));
  230. if (new_blindings == NULL) {
  231. goto err1;
  232. }
  233. OPENSSL_memcpy(new_blindings, rsa->blindings,
  234. sizeof(BN_BLINDING *) * rsa->num_blindings);
  235. new_blindings[rsa->num_blindings] = ret;
  236. new_blindings_inuse = OPENSSL_malloc(rsa->num_blindings + 1);
  237. if (new_blindings_inuse == NULL) {
  238. goto err2;
  239. }
  240. OPENSSL_memcpy(new_blindings_inuse, rsa->blindings_inuse, rsa->num_blindings);
  241. new_blindings_inuse[rsa->num_blindings] = 1;
  242. *index_used = rsa->num_blindings;
  243. OPENSSL_free(rsa->blindings);
  244. rsa->blindings = new_blindings;
  245. OPENSSL_free(rsa->blindings_inuse);
  246. rsa->blindings_inuse = new_blindings_inuse;
  247. rsa->num_blindings++;
  248. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  249. return ret;
  250. err2:
  251. OPENSSL_free(new_blindings);
  252. err1:
  253. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  254. BN_BLINDING_free(ret);
  255. return NULL;
  256. }
  257. // rsa_blinding_release marks the cached BN_BLINDING at the given index as free
  258. // for other threads to use.
  259. static void rsa_blinding_release(RSA *rsa, BN_BLINDING *blinding,
  260. unsigned blinding_index) {
  261. if (blinding_index == MAX_BLINDINGS_PER_RSA) {
  262. // This blinding wasn't cached.
  263. BN_BLINDING_free(blinding);
  264. return;
  265. }
  266. CRYPTO_MUTEX_lock_write(&rsa->lock);
  267. rsa->blindings_inuse[blinding_index] = 0;
  268. CRYPTO_MUTEX_unlock_write(&rsa->lock);
  269. }
  270. // signing
  271. int rsa_default_sign_raw(RSA *rsa, size_t *out_len, uint8_t *out,
  272. size_t max_out, const uint8_t *in, size_t in_len,
  273. int padding) {
  274. const unsigned rsa_size = RSA_size(rsa);
  275. uint8_t *buf = NULL;
  276. int i, ret = 0;
  277. if (max_out < rsa_size) {
  278. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  279. return 0;
  280. }
  281. buf = OPENSSL_malloc(rsa_size);
  282. if (buf == NULL) {
  283. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  284. goto err;
  285. }
  286. switch (padding) {
  287. case RSA_PKCS1_PADDING:
  288. i = RSA_padding_add_PKCS1_type_1(buf, rsa_size, in, in_len);
  289. break;
  290. case RSA_NO_PADDING:
  291. i = RSA_padding_add_none(buf, rsa_size, in, in_len);
  292. break;
  293. default:
  294. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  295. goto err;
  296. }
  297. if (i <= 0) {
  298. goto err;
  299. }
  300. if (!RSA_private_transform(rsa, out, buf, rsa_size)) {
  301. goto err;
  302. }
  303. *out_len = rsa_size;
  304. ret = 1;
  305. err:
  306. OPENSSL_free(buf);
  307. return ret;
  308. }
  309. int rsa_default_decrypt(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
  310. const uint8_t *in, size_t in_len, int padding) {
  311. const unsigned rsa_size = RSA_size(rsa);
  312. uint8_t *buf = NULL;
  313. int ret = 0;
  314. if (max_out < rsa_size) {
  315. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  316. return 0;
  317. }
  318. if (padding == RSA_NO_PADDING) {
  319. buf = out;
  320. } else {
  321. // Allocate a temporary buffer to hold the padded plaintext.
  322. buf = OPENSSL_malloc(rsa_size);
  323. if (buf == NULL) {
  324. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  325. goto err;
  326. }
  327. }
  328. if (in_len != rsa_size) {
  329. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
  330. goto err;
  331. }
  332. if (!RSA_private_transform(rsa, buf, in, rsa_size)) {
  333. goto err;
  334. }
  335. switch (padding) {
  336. case RSA_PKCS1_PADDING:
  337. ret =
  338. RSA_padding_check_PKCS1_type_2(out, out_len, rsa_size, buf, rsa_size);
  339. break;
  340. case RSA_PKCS1_OAEP_PADDING:
  341. // Use the default parameters: SHA-1 for both hashes and no label.
  342. ret = RSA_padding_check_PKCS1_OAEP_mgf1(out, out_len, rsa_size, buf,
  343. rsa_size, NULL, 0, NULL, NULL);
  344. break;
  345. case RSA_NO_PADDING:
  346. *out_len = rsa_size;
  347. ret = 1;
  348. break;
  349. default:
  350. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  351. goto err;
  352. }
  353. if (!ret) {
  354. OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
  355. }
  356. err:
  357. if (padding != RSA_NO_PADDING) {
  358. OPENSSL_free(buf);
  359. }
  360. return ret;
  361. }
  362. static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
  363. int RSA_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out, size_t max_out,
  364. const uint8_t *in, size_t in_len, int padding) {
  365. if (rsa->n == NULL || rsa->e == NULL) {
  366. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
  367. return 0;
  368. }
  369. const unsigned rsa_size = RSA_size(rsa);
  370. BIGNUM *f, *result;
  371. if (max_out < rsa_size) {
  372. OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
  373. return 0;
  374. }
  375. if (in_len != rsa_size) {
  376. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
  377. return 0;
  378. }
  379. if (!check_modulus_and_exponent_sizes(rsa)) {
  380. return 0;
  381. }
  382. BN_CTX *ctx = BN_CTX_new();
  383. if (ctx == NULL) {
  384. return 0;
  385. }
  386. int ret = 0;
  387. uint8_t *buf = NULL;
  388. BN_CTX_start(ctx);
  389. f = BN_CTX_get(ctx);
  390. result = BN_CTX_get(ctx);
  391. if (f == NULL || result == NULL) {
  392. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  393. goto err;
  394. }
  395. if (padding == RSA_NO_PADDING) {
  396. buf = out;
  397. } else {
  398. // Allocate a temporary buffer to hold the padded plaintext.
  399. buf = OPENSSL_malloc(rsa_size);
  400. if (buf == NULL) {
  401. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  402. goto err;
  403. }
  404. }
  405. if (BN_bin2bn(in, in_len, f) == NULL) {
  406. goto err;
  407. }
  408. if (BN_ucmp(f, rsa->n) >= 0) {
  409. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
  410. goto err;
  411. }
  412. if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) ||
  413. !BN_mod_exp_mont(result, f, rsa->e, rsa->n, ctx, rsa->mont_n)) {
  414. goto err;
  415. }
  416. if (!BN_bn2bin_padded(buf, rsa_size, result)) {
  417. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  418. goto err;
  419. }
  420. switch (padding) {
  421. case RSA_PKCS1_PADDING:
  422. ret =
  423. RSA_padding_check_PKCS1_type_1(out, out_len, rsa_size, buf, rsa_size);
  424. break;
  425. case RSA_NO_PADDING:
  426. ret = 1;
  427. *out_len = rsa_size;
  428. break;
  429. default:
  430. OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
  431. goto err;
  432. }
  433. if (!ret) {
  434. OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
  435. goto err;
  436. }
  437. err:
  438. BN_CTX_end(ctx);
  439. BN_CTX_free(ctx);
  440. if (buf != out) {
  441. OPENSSL_free(buf);
  442. }
  443. return ret;
  444. }
  445. int rsa_default_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in,
  446. size_t len) {
  447. if (rsa->n == NULL || rsa->d == NULL) {
  448. OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING);
  449. return 0;
  450. }
  451. BIGNUM *f, *result;
  452. BN_CTX *ctx = NULL;
  453. unsigned blinding_index = 0;
  454. BN_BLINDING *blinding = NULL;
  455. int ret = 0;
  456. ctx = BN_CTX_new();
  457. if (ctx == NULL) {
  458. goto err;
  459. }
  460. BN_CTX_start(ctx);
  461. f = BN_CTX_get(ctx);
  462. result = BN_CTX_get(ctx);
  463. if (f == NULL || result == NULL) {
  464. OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
  465. goto err;
  466. }
  467. if (BN_bin2bn(in, len, f) == NULL) {
  468. goto err;
  469. }
  470. if (BN_ucmp(f, rsa->n) >= 0) {
  471. // Usually the padding functions would catch this.
  472. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
  473. goto err;
  474. }
  475. if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx)) {
  476. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  477. goto err;
  478. }
  479. const int do_blinding = (rsa->flags & RSA_FLAG_NO_BLINDING) == 0;
  480. if (rsa->e == NULL && do_blinding) {
  481. // We cannot do blinding or verification without |e|, and continuing without
  482. // those countermeasures is dangerous. However, the Java/Android RSA API
  483. // requires support for keys where only |d| and |n| (and not |e|) are known.
  484. // The callers that require that bad behavior set |RSA_FLAG_NO_BLINDING|.
  485. OPENSSL_PUT_ERROR(RSA, RSA_R_NO_PUBLIC_EXPONENT);
  486. goto err;
  487. }
  488. if (do_blinding) {
  489. blinding = rsa_blinding_get(rsa, &blinding_index, ctx);
  490. if (blinding == NULL) {
  491. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  492. goto err;
  493. }
  494. if (!BN_BLINDING_convert(f, blinding, rsa->e, rsa->mont_n, ctx)) {
  495. goto err;
  496. }
  497. }
  498. if (rsa->p != NULL && rsa->q != NULL && rsa->e != NULL && rsa->dmp1 != NULL &&
  499. rsa->dmq1 != NULL && rsa->iqmp != NULL) {
  500. if (!mod_exp(result, f, rsa, ctx)) {
  501. goto err;
  502. }
  503. } else if (!BN_mod_exp_mont_consttime(result, f, rsa->d, rsa->n, ctx,
  504. rsa->mont_n)) {
  505. goto err;
  506. }
  507. // Verify the result to protect against fault attacks as described in the
  508. // 1997 paper "On the Importance of Checking Cryptographic Protocols for
  509. // Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton. Some
  510. // implementations do this only when the CRT is used, but we do it in all
  511. // cases. Section 6 of the aforementioned paper describes an attack that
  512. // works when the CRT isn't used. That attack is much less likely to succeed
  513. // than the CRT attack, but there have likely been improvements since 1997.
  514. //
  515. // This check is cheap assuming |e| is small; it almost always is.
  516. if (rsa->e != NULL) {
  517. BIGNUM *vrfy = BN_CTX_get(ctx);
  518. if (vrfy == NULL ||
  519. !BN_mod_exp_mont(vrfy, result, rsa->e, rsa->n, ctx, rsa->mont_n) ||
  520. !BN_equal_consttime(vrfy, f)) {
  521. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  522. goto err;
  523. }
  524. }
  525. if (do_blinding &&
  526. !BN_BLINDING_invert(result, blinding, rsa->mont_n, ctx)) {
  527. goto err;
  528. }
  529. if (!BN_bn2bin_padded(out, len, result)) {
  530. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  531. goto err;
  532. }
  533. ret = 1;
  534. err:
  535. if (ctx != NULL) {
  536. BN_CTX_end(ctx);
  537. BN_CTX_free(ctx);
  538. }
  539. if (blinding != NULL) {
  540. rsa_blinding_release(rsa, blinding, blinding_index);
  541. }
  542. return ret;
  543. }
  544. static int mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) {
  545. assert(ctx != NULL);
  546. assert(rsa->n != NULL);
  547. assert(rsa->e != NULL);
  548. assert(rsa->d != NULL);
  549. assert(rsa->p != NULL);
  550. assert(rsa->q != NULL);
  551. assert(rsa->dmp1 != NULL);
  552. assert(rsa->dmq1 != NULL);
  553. assert(rsa->iqmp != NULL);
  554. BIGNUM *r1, *m1, *vrfy;
  555. int ret = 0;
  556. BN_CTX_start(ctx);
  557. r1 = BN_CTX_get(ctx);
  558. m1 = BN_CTX_get(ctx);
  559. vrfy = BN_CTX_get(ctx);
  560. if (r1 == NULL ||
  561. m1 == NULL ||
  562. vrfy == NULL) {
  563. goto err;
  564. }
  565. if (!BN_MONT_CTX_set_locked(&rsa->mont_p, &rsa->lock, rsa->p, ctx) ||
  566. !BN_MONT_CTX_set_locked(&rsa->mont_q, &rsa->lock, rsa->q, ctx)) {
  567. goto err;
  568. }
  569. if (!BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx)) {
  570. goto err;
  571. }
  572. // compute I mod q
  573. if (!BN_mod(r1, I, rsa->q, ctx)) {
  574. goto err;
  575. }
  576. // compute r1^dmq1 mod q
  577. if (!BN_mod_exp_mont_consttime(m1, r1, rsa->dmq1, rsa->q, ctx, rsa->mont_q)) {
  578. goto err;
  579. }
  580. // compute I mod p
  581. if (!BN_mod(r1, I, rsa->p, ctx)) {
  582. goto err;
  583. }
  584. // compute r1^dmp1 mod p
  585. if (!BN_mod_exp_mont_consttime(r0, r1, rsa->dmp1, rsa->p, ctx, rsa->mont_p)) {
  586. goto err;
  587. }
  588. if (!BN_sub(r0, r0, m1)) {
  589. goto err;
  590. }
  591. // This will help stop the size of r0 increasing, which does
  592. // affect the multiply if it optimised for a power of 2 size
  593. if (BN_is_negative(r0)) {
  594. if (!BN_add(r0, r0, rsa->p)) {
  595. goto err;
  596. }
  597. }
  598. if (!BN_mul(r1, r0, rsa->iqmp, ctx)) {
  599. goto err;
  600. }
  601. if (!BN_mod(r0, r1, rsa->p, ctx)) {
  602. goto err;
  603. }
  604. // If p < q it is occasionally possible for the correction of
  605. // adding 'p' if r0 is negative above to leave the result still
  606. // negative. This can break the private key operations: the following
  607. // second correction should *always* correct this rare occurrence.
  608. // This will *never* happen with OpenSSL generated keys because
  609. // they ensure p > q [steve]
  610. if (BN_is_negative(r0)) {
  611. if (!BN_add(r0, r0, rsa->p)) {
  612. goto err;
  613. }
  614. }
  615. if (!BN_mul(r1, r0, rsa->q, ctx)) {
  616. goto err;
  617. }
  618. if (!BN_add(r0, r1, m1)) {
  619. goto err;
  620. }
  621. ret = 1;
  622. err:
  623. BN_CTX_end(ctx);
  624. return ret;
  625. }
  626. static int ensure_bignum(BIGNUM **out) {
  627. if (*out == NULL) {
  628. *out = BN_new();
  629. }
  630. return *out != NULL;
  631. }
  632. // kBoringSSLRSASqrtTwo is the BIGNUM representation of ⌊2¹⁵³⁵×√2⌋. This is
  633. // chosen to give enough precision for 3072-bit RSA, the largest key size FIPS
  634. // specifies. Key sizes beyond this will round up.
  635. //
  636. // To verify this number, check that n² < 2³⁰⁷¹ < (n+1)², where n is value
  637. // represented here. Note the components are listed in little-endian order. Here
  638. // is some sample Python code to check:
  639. //
  640. // >>> TOBN = lambda a, b: a << 32 | b
  641. // >>> l = [ <paste the contents of kSqrtTwo> ]
  642. // >>> n = sum(a * 2**(64*i) for i, a in enumerate(l))
  643. // >>> n**2 < 2**3071 < (n+1)**2
  644. // True
  645. const BN_ULONG kBoringSSLRSASqrtTwo[] = {
  646. TOBN(0xdea06241, 0xf7aa81c2), TOBN(0xf6a1be3f, 0xca221307),
  647. TOBN(0x332a5e9f, 0x7bda1ebf), TOBN(0x0104dc01, 0xfe32352f),
  648. TOBN(0xb8cf341b, 0x6f8236c7), TOBN(0x4264dabc, 0xd528b651),
  649. TOBN(0xf4d3a02c, 0xebc93e0c), TOBN(0x81394ab6, 0xd8fd0efd),
  650. TOBN(0xeaa4a089, 0x9040ca4a), TOBN(0xf52f120f, 0x836e582e),
  651. TOBN(0xcb2a6343, 0x31f3c84d), TOBN(0xc6d5a8a3, 0x8bb7e9dc),
  652. TOBN(0x460abc72, 0x2f7c4e33), TOBN(0xcab1bc91, 0x1688458a),
  653. TOBN(0x53059c60, 0x11bc337b), TOBN(0xd2202e87, 0x42af1f4e),
  654. TOBN(0x78048736, 0x3dfa2768), TOBN(0x0f74a85e, 0x439c7b4a),
  655. TOBN(0xa8b1fe6f, 0xdc83db39), TOBN(0x4afc8304, 0x3ab8a2c3),
  656. TOBN(0xed17ac85, 0x83339915), TOBN(0x1d6f60ba, 0x893ba84c),
  657. TOBN(0x597d89b3, 0x754abe9f), TOBN(0xb504f333, 0xf9de6484),
  658. };
  659. const size_t kBoringSSLRSASqrtTwoLen = OPENSSL_ARRAY_SIZE(kBoringSSLRSASqrtTwo);
  660. int rsa_greater_than_pow2(const BIGNUM *b, int n) {
  661. if (BN_is_negative(b) || n == INT_MAX) {
  662. return 0;
  663. }
  664. int b_bits = BN_num_bits(b);
  665. return b_bits > n + 1 || (b_bits == n + 1 && !BN_is_pow2(b));
  666. }
  667. // generate_prime sets |out| to a prime with length |bits| such that |out|-1 is
  668. // relatively prime to |e|. If |p| is non-NULL, |out| will also not be close to
  669. // |p|.
  670. static int generate_prime(BIGNUM *out, int bits, const BIGNUM *e,
  671. const BIGNUM *p, BN_CTX *ctx, BN_GENCB *cb) {
  672. if (bits < 128 || (bits % BN_BITS2) != 0) {
  673. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  674. return 0;
  675. }
  676. // See FIPS 186-4 appendix B.3.3, steps 4 and 5. Note |bits| here is nlen/2.
  677. // Use the limit from steps 4.7 and 5.8 for most values of |e|. When |e| is 3,
  678. // the 186-4 limit is too low, so we use a higher one. Note this case is not
  679. // reachable from |RSA_generate_key_fips|.
  680. if (bits >= INT_MAX/32) {
  681. OPENSSL_PUT_ERROR(RSA, RSA_R_MODULUS_TOO_LARGE);
  682. return 0;
  683. }
  684. int limit = BN_is_word(e, 3) ? bits * 32 : bits * 5;
  685. int ret = 0, tries = 0, rand_tries = 0;
  686. BN_CTX_start(ctx);
  687. BIGNUM *tmp = BN_CTX_get(ctx);
  688. if (tmp == NULL) {
  689. goto err;
  690. }
  691. for (;;) {
  692. // Generate a random number of length |bits| where the bottom bit is set
  693. // (steps 4.2, 4.3, 5.2 and 5.3) and the top bit is set (implied by the
  694. // bound checked below in steps 4.4 and 5.5).
  695. if (!BN_rand(out, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD) ||
  696. !BN_GENCB_call(cb, BN_GENCB_GENERATED, rand_tries++)) {
  697. goto err;
  698. }
  699. if (p != NULL) {
  700. // If |p| and |out| are too close, try again (step 5.4).
  701. if (!BN_sub(tmp, out, p)) {
  702. goto err;
  703. }
  704. BN_set_negative(tmp, 0);
  705. if (!rsa_greater_than_pow2(tmp, bits - 100)) {
  706. continue;
  707. }
  708. }
  709. // If out < 2^(bits-1)×√2, try again (steps 4.4 and 5.5).
  710. //
  711. // We check the most significant words, so we retry if ⌊out/2^k⌋ <= ⌊b/2^k⌋,
  712. // where b = 2^(bits-1)×√2 and k = max(0, bits - 1536). For key sizes up to
  713. // 3072 (bits = 1536), k = 0, so we are testing that ⌊out⌋ <= ⌊b⌋. out is an
  714. // integer and b is not, so this is equivalent to out < b. That is, the
  715. // comparison is exact for FIPS key sizes.
  716. //
  717. // For larger keys, the comparison is approximate, leaning towards
  718. // retrying. That is, we reject a negligible fraction of primes that are
  719. // within the FIPS bound, but we will never accept a prime outside the
  720. // bound, ensuring the resulting RSA key is the right size. Specifically, if
  721. // the FIPS bound holds, we have ⌊out/2^k⌋ < out/2^k < b/2^k. This implies
  722. // ⌊out/2^k⌋ <= ⌊b/2^k⌋. That is, the FIPS bound implies our bound and so we
  723. // are slightly tighter.
  724. size_t out_len = (size_t)out->top;
  725. assert(out_len == (size_t)bits / BN_BITS2);
  726. size_t to_check = kBoringSSLRSASqrtTwoLen;
  727. if (to_check > out_len) {
  728. to_check = out_len;
  729. }
  730. if (!bn_less_than_words(
  731. kBoringSSLRSASqrtTwo + kBoringSSLRSASqrtTwoLen - to_check,
  732. out->d + out_len - to_check, to_check)) {
  733. continue;
  734. }
  735. // Check gcd(out-1, e) is one (steps 4.5 and 5.6).
  736. if (!BN_sub(tmp, out, BN_value_one()) ||
  737. !BN_gcd(tmp, tmp, e, ctx)) {
  738. goto err;
  739. }
  740. if (BN_is_one(tmp)) {
  741. // Test |out| for primality (steps 4.5.1 and 5.6.1).
  742. int is_probable_prime;
  743. if (!BN_primality_test(&is_probable_prime, out, BN_prime_checks, ctx, 1,
  744. cb)) {
  745. goto err;
  746. }
  747. if (is_probable_prime) {
  748. ret = 1;
  749. goto err;
  750. }
  751. }
  752. // If we've tried too many times to find a prime, abort (steps 4.7 and
  753. // 5.8).
  754. tries++;
  755. if (tries >= limit) {
  756. OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_MANY_ITERATIONS);
  757. goto err;
  758. }
  759. if (!BN_GENCB_call(cb, 2, tries)) {
  760. goto err;
  761. }
  762. }
  763. err:
  764. BN_CTX_end(ctx);
  765. return ret;
  766. }
  767. int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) {
  768. // See FIPS 186-4 appendix B.3. This function implements a generalized version
  769. // of the FIPS algorithm. |RSA_generate_key_fips| performs additional checks
  770. // for FIPS-compliant key generation.
  771. // Always generate RSA keys which are a multiple of 128 bits. Round |bits|
  772. // down as needed.
  773. bits &= ~127;
  774. // Reject excessively small keys.
  775. if (bits < 256) {
  776. OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL);
  777. return 0;
  778. }
  779. int ret = 0;
  780. BN_CTX *ctx = BN_CTX_new();
  781. if (ctx == NULL) {
  782. goto bn_err;
  783. }
  784. BN_CTX_start(ctx);
  785. BIGNUM *totient = BN_CTX_get(ctx);
  786. BIGNUM *pm1 = BN_CTX_get(ctx);
  787. BIGNUM *qm1 = BN_CTX_get(ctx);
  788. BIGNUM *gcd = BN_CTX_get(ctx);
  789. if (totient == NULL || pm1 == NULL || qm1 == NULL || gcd == NULL) {
  790. goto bn_err;
  791. }
  792. // We need the RSA components non-NULL.
  793. if (!ensure_bignum(&rsa->n) ||
  794. !ensure_bignum(&rsa->d) ||
  795. !ensure_bignum(&rsa->e) ||
  796. !ensure_bignum(&rsa->p) ||
  797. !ensure_bignum(&rsa->q) ||
  798. !ensure_bignum(&rsa->dmp1) ||
  799. !ensure_bignum(&rsa->dmq1) ||
  800. !ensure_bignum(&rsa->iqmp)) {
  801. goto bn_err;
  802. }
  803. if (!BN_copy(rsa->e, e_value)) {
  804. goto bn_err;
  805. }
  806. int prime_bits = bits / 2;
  807. do {
  808. // Generate p and q, each of size |prime_bits|, using the steps outlined in
  809. // appendix FIPS 186-4 appendix B.3.3.
  810. if (!generate_prime(rsa->p, prime_bits, rsa->e, NULL, ctx, cb) ||
  811. !BN_GENCB_call(cb, 3, 0) ||
  812. !generate_prime(rsa->q, prime_bits, rsa->e, rsa->p, ctx, cb) ||
  813. !BN_GENCB_call(cb, 3, 1)) {
  814. goto bn_err;
  815. }
  816. if (BN_cmp(rsa->p, rsa->q) < 0) {
  817. BIGNUM *tmp = rsa->p;
  818. rsa->p = rsa->q;
  819. rsa->q = tmp;
  820. }
  821. // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-4. This differs
  822. // from typical RSA implementations which use (p-1)*(q-1).
  823. //
  824. // Note this means the size of d might reveal information about p-1 and
  825. // q-1. However, we do operations with Chinese Remainder Theorem, so we only
  826. // use d (mod p-1) and d (mod q-1) as exponents. Using a minimal totient
  827. // does not affect those two values.
  828. if (!BN_sub(pm1, rsa->p, BN_value_one()) ||
  829. !BN_sub(qm1, rsa->q, BN_value_one()) ||
  830. !BN_mul(totient, pm1, qm1, ctx) ||
  831. !BN_gcd(gcd, pm1, qm1, ctx) ||
  832. !BN_div(totient, NULL, totient, gcd, ctx) ||
  833. !BN_mod_inverse(rsa->d, rsa->e, totient, ctx)) {
  834. goto bn_err;
  835. }
  836. // Check that |rsa->d| > 2^|prime_bits| and try again if it fails. See
  837. // appendix B.3.1's guidance on values for d.
  838. } while (!rsa_greater_than_pow2(rsa->d, prime_bits));
  839. if (// Calculate n.
  840. !BN_mul(rsa->n, rsa->p, rsa->q, ctx) ||
  841. // Calculate d mod (p-1).
  842. !BN_mod(rsa->dmp1, rsa->d, pm1, ctx) ||
  843. // Calculate d mod (q-1)
  844. !BN_mod(rsa->dmq1, rsa->d, qm1, ctx)) {
  845. goto bn_err;
  846. }
  847. // Sanity-check that |rsa->n| has the specified size. This is implied by
  848. // |generate_prime|'s bounds.
  849. if (BN_num_bits(rsa->n) != (unsigned)bits) {
  850. OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
  851. goto err;
  852. }
  853. // Calculate inverse of q mod p. Note that although RSA key generation is far
  854. // from constant-time, |bn_mod_inverse_secret_prime| uses the same modular
  855. // exponentation logic as in RSA private key operations and, if the RSAZ-1024
  856. // code is enabled, will be optimized for common RSA prime sizes.
  857. if (!BN_MONT_CTX_set_locked(&rsa->mont_p, &rsa->lock, rsa->p, ctx) ||
  858. !bn_mod_inverse_secret_prime(rsa->iqmp, rsa->q, rsa->p, ctx,
  859. rsa->mont_p)) {
  860. goto bn_err;
  861. }
  862. // The key generation process is complex and thus error-prone. It could be
  863. // disastrous to generate and then use a bad key so double-check that the key
  864. // makes sense.
  865. if (!RSA_check_key(rsa)) {
  866. OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR);
  867. goto err;
  868. }
  869. ret = 1;
  870. bn_err:
  871. if (!ret) {
  872. OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN);
  873. }
  874. err:
  875. if (ctx != NULL) {
  876. BN_CTX_end(ctx);
  877. BN_CTX_free(ctx);
  878. }
  879. return ret;
  880. }
  881. int RSA_generate_key_fips(RSA *rsa, int bits, BN_GENCB *cb) {
  882. // FIPS 186-4 allows 2048-bit and 3072-bit RSA keys (1024-bit and 1536-bit
  883. // primes, respectively) with the prime generation method we use.
  884. if (bits != 2048 && bits != 3072) {
  885. OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_RSA_PARAMETERS);
  886. return 0;
  887. }
  888. BIGNUM *e = BN_new();
  889. int ret = e != NULL &&
  890. BN_set_word(e, RSA_F4) &&
  891. RSA_generate_key_ex(rsa, bits, e, cb) &&
  892. RSA_check_fips(rsa);
  893. BN_free(e);
  894. return ret;
  895. }
  896. DEFINE_METHOD_FUNCTION(RSA_METHOD, RSA_default_method) {
  897. // All of the methods are NULL to make it easier for the compiler/linker to
  898. // drop unused functions. The wrapper functions will select the appropriate
  899. // |rsa_default_*| implementation.
  900. OPENSSL_memset(out, 0, sizeof(RSA_METHOD));
  901. out->common.is_static = 1;
  902. out->flags = RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE;
  903. }