2
0

rsa_gen.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /*
  10. * NB: these functions have been "upgraded", the deprecated versions (which
  11. * are compatibility wrappers using these functions) are in rsa_depr.c. -
  12. * Geoff
  13. */
  14. /*
  15. * RSA low level APIs are deprecated for public use, but still ok for
  16. * internal use.
  17. */
  18. #include "internal/deprecated.h"
  19. #include <stdio.h>
  20. #include <time.h>
  21. #include "internal/cryptlib.h"
  22. #include <openssl/bn.h>
  23. #include <openssl/self_test.h>
  24. #include "prov/providercommon.h"
  25. #include "rsa_local.h"
  26. static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg);
  27. static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
  28. BIGNUM *e_value, BN_GENCB *cb, int pairwise_test);
  29. /*
  30. * NB: this wrapper would normally be placed in rsa_lib.c and the static
  31. * implementation would probably be in rsa_eay.c. Nonetheless, is kept here
  32. * so that we don't introduce a new linker dependency. Eg. any application
  33. * that wasn't previously linking object code related to key-generation won't
  34. * have to now just because key-generation is part of RSA_METHOD.
  35. */
  36. int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
  37. {
  38. if (rsa->meth->rsa_keygen != NULL)
  39. return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
  40. return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
  41. e_value, cb);
  42. }
  43. int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
  44. BIGNUM *e_value, BN_GENCB *cb)
  45. {
  46. #ifndef FIPS_MODULE
  47. /* multi-prime is only supported with the builtin key generation */
  48. if (rsa->meth->rsa_multi_prime_keygen != NULL) {
  49. return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
  50. e_value, cb);
  51. } else if (rsa->meth->rsa_keygen != NULL) {
  52. /*
  53. * However, if rsa->meth implements only rsa_keygen, then we
  54. * have to honour it in 2-prime case and assume that it wouldn't
  55. * know what to do with multi-prime key generated by builtin
  56. * subroutine...
  57. */
  58. if (primes == 2)
  59. return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
  60. else
  61. return 0;
  62. }
  63. #endif /* FIPS_MODULE */
  64. return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0);
  65. }
  66. #ifndef FIPS_MODULE
  67. static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
  68. BIGNUM *e_value, BN_GENCB *cb)
  69. {
  70. BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime;
  71. int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
  72. int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
  73. RSA_PRIME_INFO *pinfo = NULL;
  74. STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
  75. BN_CTX *ctx = NULL;
  76. BN_ULONG bitst = 0;
  77. unsigned long error = 0;
  78. int ok = -1;
  79. if (bits < RSA_MIN_MODULUS_BITS) {
  80. ok = 0; /* we set our own err */
  81. ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
  82. goto err;
  83. }
  84. /* A bad value for e can cause infinite loops */
  85. if (e_value != NULL && !ossl_rsa_check_public_exponent(e_value)) {
  86. ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
  87. return 0;
  88. }
  89. if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
  90. ok = 0; /* we set our own err */
  91. ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
  92. goto err;
  93. }
  94. ctx = BN_CTX_new_ex(rsa->libctx);
  95. if (ctx == NULL)
  96. goto err;
  97. BN_CTX_start(ctx);
  98. r0 = BN_CTX_get(ctx);
  99. r1 = BN_CTX_get(ctx);
  100. r2 = BN_CTX_get(ctx);
  101. if (r2 == NULL)
  102. goto err;
  103. /* divide bits into 'primes' pieces evenly */
  104. quo = bits / primes;
  105. rmd = bits % primes;
  106. for (i = 0; i < primes; i++)
  107. bitsr[i] = (i < rmd) ? quo + 1 : quo;
  108. rsa->dirty_cnt++;
  109. /* We need the RSA components non-NULL */
  110. if (!rsa->n && ((rsa->n = BN_new()) == NULL))
  111. goto err;
  112. if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
  113. goto err;
  114. BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
  115. if (!rsa->e && ((rsa->e = BN_new()) == NULL))
  116. goto err;
  117. if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
  118. goto err;
  119. BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
  120. if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
  121. goto err;
  122. BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
  123. if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
  124. goto err;
  125. BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
  126. if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
  127. goto err;
  128. BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
  129. if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
  130. goto err;
  131. BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
  132. /* initialize multi-prime components */
  133. if (primes > RSA_DEFAULT_PRIME_NUM) {
  134. rsa->version = RSA_ASN1_VERSION_MULTI;
  135. prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
  136. if (prime_infos == NULL)
  137. goto err;
  138. if (rsa->prime_infos != NULL) {
  139. /* could this happen? */
  140. sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
  141. ossl_rsa_multip_info_free);
  142. }
  143. rsa->prime_infos = prime_infos;
  144. /* prime_info from 2 to |primes| -1 */
  145. for (i = 2; i < primes; i++) {
  146. pinfo = ossl_rsa_multip_info_new();
  147. if (pinfo == NULL)
  148. goto err;
  149. (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
  150. }
  151. }
  152. if (BN_copy(rsa->e, e_value) == NULL)
  153. goto err;
  154. /* generate p, q and other primes (if any) */
  155. for (i = 0; i < primes; i++) {
  156. adj = 0;
  157. retries = 0;
  158. if (i == 0) {
  159. prime = rsa->p;
  160. } else if (i == 1) {
  161. prime = rsa->q;
  162. } else {
  163. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  164. prime = pinfo->r;
  165. }
  166. BN_set_flags(prime, BN_FLG_CONSTTIME);
  167. for (;;) {
  168. redo:
  169. if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
  170. cb, ctx))
  171. goto err;
  172. /*
  173. * prime should not be equal to p, q, r_3...
  174. * (those primes prior to this one)
  175. */
  176. {
  177. int j;
  178. for (j = 0; j < i; j++) {
  179. BIGNUM *prev_prime;
  180. if (j == 0)
  181. prev_prime = rsa->p;
  182. else if (j == 1)
  183. prev_prime = rsa->q;
  184. else
  185. prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
  186. j - 2)->r;
  187. if (!BN_cmp(prime, prev_prime)) {
  188. goto redo;
  189. }
  190. }
  191. }
  192. if (!BN_sub(r2, prime, BN_value_one()))
  193. goto err;
  194. ERR_set_mark();
  195. BN_set_flags(r2, BN_FLG_CONSTTIME);
  196. if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
  197. /* GCD == 1 since inverse exists */
  198. break;
  199. }
  200. error = ERR_peek_last_error();
  201. if (ERR_GET_LIB(error) == ERR_LIB_BN
  202. && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
  203. /* GCD != 1 */
  204. ERR_pop_to_mark();
  205. } else {
  206. goto err;
  207. }
  208. if (!BN_GENCB_call(cb, 2, n++))
  209. goto err;
  210. }
  211. bitse += bitsr[i];
  212. /* calculate n immediately to see if it's sufficient */
  213. if (i == 1) {
  214. /* we get at least 2 primes */
  215. if (!BN_mul(r1, rsa->p, rsa->q, ctx))
  216. goto err;
  217. } else if (i != 0) {
  218. /* modulus n = p * q * r_3 * r_4 ... */
  219. if (!BN_mul(r1, rsa->n, prime, ctx))
  220. goto err;
  221. } else {
  222. /* i == 0, do nothing */
  223. if (!BN_GENCB_call(cb, 3, i))
  224. goto err;
  225. continue;
  226. }
  227. /*
  228. * if |r1|, product of factors so far, is not as long as expected
  229. * (by checking the first 4 bits are less than 0x9 or greater than
  230. * 0xF). If so, re-generate the last prime.
  231. *
  232. * NOTE: This actually can't happen in two-prime case, because of
  233. * the way factors are generated.
  234. *
  235. * Besides, another consideration is, for multi-prime case, even the
  236. * length modulus is as long as expected, the modulus could start at
  237. * 0x8, which could be utilized to distinguish a multi-prime private
  238. * key by using the modulus in a certificate. This is also covered
  239. * by checking the length should not be less than 0x9.
  240. */
  241. if (!BN_rshift(r2, r1, bitse - 4))
  242. goto err;
  243. bitst = BN_get_word(r2);
  244. if (bitst < 0x9 || bitst > 0xF) {
  245. /*
  246. * For keys with more than 4 primes, we attempt longer factor to
  247. * meet length requirement.
  248. *
  249. * Otherwise, we just re-generate the prime with the same length.
  250. *
  251. * This strategy has the following goals:
  252. *
  253. * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
  254. * 2. stay the same logic with normal 2-prime key
  255. */
  256. bitse -= bitsr[i];
  257. if (!BN_GENCB_call(cb, 2, n++))
  258. goto err;
  259. if (primes > 4) {
  260. if (bitst < 0x9)
  261. adj++;
  262. else
  263. adj--;
  264. } else if (retries == 4) {
  265. /*
  266. * re-generate all primes from scratch, mainly used
  267. * in 4 prime case to avoid long loop. Max retry times
  268. * is set to 4.
  269. */
  270. i = -1;
  271. bitse = 0;
  272. continue;
  273. }
  274. retries++;
  275. goto redo;
  276. }
  277. /* save product of primes for further use, for multi-prime only */
  278. if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
  279. goto err;
  280. if (BN_copy(rsa->n, r1) == NULL)
  281. goto err;
  282. if (!BN_GENCB_call(cb, 3, i))
  283. goto err;
  284. }
  285. if (BN_cmp(rsa->p, rsa->q) < 0) {
  286. tmp = rsa->p;
  287. rsa->p = rsa->q;
  288. rsa->q = tmp;
  289. }
  290. /* calculate d */
  291. /* p - 1 */
  292. if (!BN_sub(r1, rsa->p, BN_value_one()))
  293. goto err;
  294. /* q - 1 */
  295. if (!BN_sub(r2, rsa->q, BN_value_one()))
  296. goto err;
  297. /* (p - 1)(q - 1) */
  298. if (!BN_mul(r0, r1, r2, ctx))
  299. goto err;
  300. /* multi-prime */
  301. for (i = 2; i < primes; i++) {
  302. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  303. /* save r_i - 1 to pinfo->d temporarily */
  304. if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
  305. goto err;
  306. if (!BN_mul(r0, r0, pinfo->d, ctx))
  307. goto err;
  308. }
  309. {
  310. BIGNUM *pr0 = BN_new();
  311. if (pr0 == NULL)
  312. goto err;
  313. BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
  314. if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
  315. BN_free(pr0);
  316. goto err; /* d */
  317. }
  318. /* We MUST free pr0 before any further use of r0 */
  319. BN_free(pr0);
  320. }
  321. {
  322. BIGNUM *d = BN_new();
  323. if (d == NULL)
  324. goto err;
  325. BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
  326. /* calculate d mod (p-1) and d mod (q - 1) */
  327. if (!BN_mod(rsa->dmp1, d, r1, ctx)
  328. || !BN_mod(rsa->dmq1, d, r2, ctx)) {
  329. BN_free(d);
  330. goto err;
  331. }
  332. /* calculate CRT exponents */
  333. for (i = 2; i < primes; i++) {
  334. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  335. /* pinfo->d == r_i - 1 */
  336. if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
  337. BN_free(d);
  338. goto err;
  339. }
  340. }
  341. /* We MUST free d before any further use of rsa->d */
  342. BN_free(d);
  343. }
  344. {
  345. BIGNUM *p = BN_new();
  346. if (p == NULL)
  347. goto err;
  348. BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
  349. /* calculate inverse of q mod p */
  350. if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
  351. BN_free(p);
  352. goto err;
  353. }
  354. /* calculate CRT coefficient for other primes */
  355. for (i = 2; i < primes; i++) {
  356. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  357. BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
  358. if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
  359. BN_free(p);
  360. goto err;
  361. }
  362. }
  363. /* We MUST free p before any further use of rsa->p */
  364. BN_free(p);
  365. }
  366. ok = 1;
  367. err:
  368. if (ok == -1) {
  369. ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
  370. ok = 0;
  371. }
  372. BN_CTX_end(ctx);
  373. BN_CTX_free(ctx);
  374. return ok;
  375. }
  376. #endif /* FIPS_MODULE */
  377. static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
  378. BIGNUM *e_value, BN_GENCB *cb, int pairwise_test)
  379. {
  380. int ok = 0;
  381. /*
  382. * Only multi-prime keys or insecure keys with a small key length will use
  383. * the older rsa_multiprime_keygen().
  384. */
  385. if (primes == 2 && bits >= 2048)
  386. ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
  387. #ifndef FIPS_MODULE
  388. else
  389. ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
  390. #endif /* FIPS_MODULE */
  391. #ifdef FIPS_MODULE
  392. pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
  393. #endif
  394. if (pairwise_test && ok > 0) {
  395. OSSL_CALLBACK *stcb = NULL;
  396. void *stcbarg = NULL;
  397. OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
  398. ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
  399. if (!ok) {
  400. ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
  401. /* Clear intermediate results */
  402. BN_clear_free(rsa->d);
  403. BN_clear_free(rsa->p);
  404. BN_clear_free(rsa->q);
  405. BN_clear_free(rsa->dmp1);
  406. BN_clear_free(rsa->dmq1);
  407. BN_clear_free(rsa->iqmp);
  408. rsa->d = NULL;
  409. rsa->p = NULL;
  410. rsa->q = NULL;
  411. rsa->dmp1 = NULL;
  412. rsa->dmq1 = NULL;
  413. rsa->iqmp = NULL;
  414. }
  415. }
  416. return ok;
  417. }
  418. /*
  419. * For RSA key generation it is not known whether the key pair will be used
  420. * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case
  421. * either a signature verification OR an encryption operation may be used to
  422. * perform the pairwise consistency check. The simpler encrypt/decrypt operation
  423. * has been chosen for this case.
  424. */
  425. static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
  426. {
  427. int ret = 0;
  428. unsigned int ciphertxt_len;
  429. unsigned char *ciphertxt = NULL;
  430. const unsigned char plaintxt[16] = {0};
  431. unsigned char *decoded = NULL;
  432. unsigned int decoded_len;
  433. unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
  434. int padding = RSA_PKCS1_PADDING;
  435. OSSL_SELF_TEST *st = NULL;
  436. st = OSSL_SELF_TEST_new(cb, cbarg);
  437. if (st == NULL)
  438. goto err;
  439. OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
  440. OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
  441. ciphertxt_len = RSA_size(rsa);
  442. /*
  443. * RSA_private_encrypt() and RSA_private_decrypt() requires the 'to'
  444. * parameter to be a maximum of RSA_size() - allocate space for both.
  445. */
  446. ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2);
  447. if (ciphertxt == NULL)
  448. goto err;
  449. decoded = ciphertxt + ciphertxt_len;
  450. ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
  451. padding);
  452. if (ciphertxt_len <= 0)
  453. goto err;
  454. if (ciphertxt_len == plaintxt_len
  455. && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
  456. goto err;
  457. OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
  458. decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
  459. padding);
  460. if (decoded_len != plaintxt_len
  461. || memcmp(decoded, plaintxt, decoded_len) != 0)
  462. goto err;
  463. ret = 1;
  464. err:
  465. OSSL_SELF_TEST_onend(st, ret);
  466. OSSL_SELF_TEST_free(st);
  467. OPENSSL_free(ciphertxt);
  468. return ret;
  469. }