rsa_gen.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * Copyright 1995-2023 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. ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
  81. return 0;
  82. }
  83. if (e_value == NULL) {
  84. ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE);
  85. return 0;
  86. }
  87. /* A bad value for e can cause infinite loops */
  88. if (!ossl_rsa_check_public_exponent(e_value)) {
  89. ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
  90. return 0;
  91. }
  92. if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
  93. ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
  94. return 0;
  95. }
  96. ctx = BN_CTX_new_ex(rsa->libctx);
  97. if (ctx == NULL)
  98. goto err;
  99. BN_CTX_start(ctx);
  100. r0 = BN_CTX_get(ctx);
  101. r1 = BN_CTX_get(ctx);
  102. r2 = BN_CTX_get(ctx);
  103. if (r2 == NULL)
  104. goto err;
  105. /* divide bits into 'primes' pieces evenly */
  106. quo = bits / primes;
  107. rmd = bits % primes;
  108. for (i = 0; i < primes; i++)
  109. bitsr[i] = (i < rmd) ? quo + 1 : quo;
  110. rsa->dirty_cnt++;
  111. /* We need the RSA components non-NULL */
  112. if (!rsa->n && ((rsa->n = BN_new()) == NULL))
  113. goto err;
  114. if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
  115. goto err;
  116. BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
  117. if (!rsa->e && ((rsa->e = BN_new()) == NULL))
  118. goto err;
  119. if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
  120. goto err;
  121. BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
  122. if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
  123. goto err;
  124. BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
  125. if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
  126. goto err;
  127. BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
  128. if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
  129. goto err;
  130. BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
  131. if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
  132. goto err;
  133. BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
  134. /* initialize multi-prime components */
  135. if (primes > RSA_DEFAULT_PRIME_NUM) {
  136. rsa->version = RSA_ASN1_VERSION_MULTI;
  137. prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
  138. if (prime_infos == NULL)
  139. goto err;
  140. if (rsa->prime_infos != NULL) {
  141. /* could this happen? */
  142. sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
  143. ossl_rsa_multip_info_free);
  144. }
  145. rsa->prime_infos = prime_infos;
  146. /* prime_info from 2 to |primes| -1 */
  147. for (i = 2; i < primes; i++) {
  148. pinfo = ossl_rsa_multip_info_new();
  149. if (pinfo == NULL)
  150. goto err;
  151. (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
  152. }
  153. }
  154. if (BN_copy(rsa->e, e_value) == NULL)
  155. goto err;
  156. /* generate p, q and other primes (if any) */
  157. for (i = 0; i < primes; i++) {
  158. adj = 0;
  159. retries = 0;
  160. if (i == 0) {
  161. prime = rsa->p;
  162. } else if (i == 1) {
  163. prime = rsa->q;
  164. } else {
  165. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  166. prime = pinfo->r;
  167. }
  168. BN_set_flags(prime, BN_FLG_CONSTTIME);
  169. for (;;) {
  170. redo:
  171. if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
  172. cb, ctx))
  173. goto err;
  174. /*
  175. * prime should not be equal to p, q, r_3...
  176. * (those primes prior to this one)
  177. */
  178. {
  179. int j;
  180. for (j = 0; j < i; j++) {
  181. BIGNUM *prev_prime;
  182. if (j == 0)
  183. prev_prime = rsa->p;
  184. else if (j == 1)
  185. prev_prime = rsa->q;
  186. else
  187. prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
  188. j - 2)->r;
  189. if (!BN_cmp(prime, prev_prime)) {
  190. goto redo;
  191. }
  192. }
  193. }
  194. if (!BN_sub(r2, prime, BN_value_one()))
  195. goto err;
  196. ERR_set_mark();
  197. BN_set_flags(r2, BN_FLG_CONSTTIME);
  198. if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
  199. /* GCD == 1 since inverse exists */
  200. break;
  201. }
  202. error = ERR_peek_last_error();
  203. if (ERR_GET_LIB(error) == ERR_LIB_BN
  204. && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
  205. /* GCD != 1 */
  206. ERR_pop_to_mark();
  207. } else {
  208. goto err;
  209. }
  210. if (!BN_GENCB_call(cb, 2, n++))
  211. goto err;
  212. }
  213. bitse += bitsr[i];
  214. /* calculate n immediately to see if it's sufficient */
  215. if (i == 1) {
  216. /* we get at least 2 primes */
  217. if (!BN_mul(r1, rsa->p, rsa->q, ctx))
  218. goto err;
  219. } else if (i != 0) {
  220. /* modulus n = p * q * r_3 * r_4 ... */
  221. if (!BN_mul(r1, rsa->n, prime, ctx))
  222. goto err;
  223. } else {
  224. /* i == 0, do nothing */
  225. if (!BN_GENCB_call(cb, 3, i))
  226. goto err;
  227. continue;
  228. }
  229. /*
  230. * if |r1|, product of factors so far, is not as long as expected
  231. * (by checking the first 4 bits are less than 0x9 or greater than
  232. * 0xF). If so, re-generate the last prime.
  233. *
  234. * NOTE: This actually can't happen in two-prime case, because of
  235. * the way factors are generated.
  236. *
  237. * Besides, another consideration is, for multi-prime case, even the
  238. * length modulus is as long as expected, the modulus could start at
  239. * 0x8, which could be utilized to distinguish a multi-prime private
  240. * key by using the modulus in a certificate. This is also covered
  241. * by checking the length should not be less than 0x9.
  242. */
  243. if (!BN_rshift(r2, r1, bitse - 4))
  244. goto err;
  245. bitst = BN_get_word(r2);
  246. if (bitst < 0x9 || bitst > 0xF) {
  247. /*
  248. * For keys with more than 4 primes, we attempt longer factor to
  249. * meet length requirement.
  250. *
  251. * Otherwise, we just re-generate the prime with the same length.
  252. *
  253. * This strategy has the following goals:
  254. *
  255. * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
  256. * 2. stay the same logic with normal 2-prime key
  257. */
  258. bitse -= bitsr[i];
  259. if (!BN_GENCB_call(cb, 2, n++))
  260. goto err;
  261. if (primes > 4) {
  262. if (bitst < 0x9)
  263. adj++;
  264. else
  265. adj--;
  266. } else if (retries == 4) {
  267. /*
  268. * re-generate all primes from scratch, mainly used
  269. * in 4 prime case to avoid long loop. Max retry times
  270. * is set to 4.
  271. */
  272. i = -1;
  273. bitse = 0;
  274. continue;
  275. }
  276. retries++;
  277. goto redo;
  278. }
  279. /* save product of primes for further use, for multi-prime only */
  280. if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
  281. goto err;
  282. if (BN_copy(rsa->n, r1) == NULL)
  283. goto err;
  284. if (!BN_GENCB_call(cb, 3, i))
  285. goto err;
  286. }
  287. if (BN_cmp(rsa->p, rsa->q) < 0) {
  288. tmp = rsa->p;
  289. rsa->p = rsa->q;
  290. rsa->q = tmp;
  291. }
  292. /* calculate d */
  293. /* p - 1 */
  294. if (!BN_sub(r1, rsa->p, BN_value_one()))
  295. goto err;
  296. /* q - 1 */
  297. if (!BN_sub(r2, rsa->q, BN_value_one()))
  298. goto err;
  299. /* (p - 1)(q - 1) */
  300. if (!BN_mul(r0, r1, r2, ctx))
  301. goto err;
  302. /* multi-prime */
  303. for (i = 2; i < primes; i++) {
  304. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  305. /* save r_i - 1 to pinfo->d temporarily */
  306. if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
  307. goto err;
  308. if (!BN_mul(r0, r0, pinfo->d, ctx))
  309. goto err;
  310. }
  311. {
  312. BIGNUM *pr0 = BN_new();
  313. if (pr0 == NULL)
  314. goto err;
  315. BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
  316. if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
  317. BN_free(pr0);
  318. goto err; /* d */
  319. }
  320. /* We MUST free pr0 before any further use of r0 */
  321. BN_free(pr0);
  322. }
  323. {
  324. BIGNUM *d = BN_new();
  325. if (d == NULL)
  326. goto err;
  327. BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
  328. /* calculate d mod (p-1) and d mod (q - 1) */
  329. if (!BN_mod(rsa->dmp1, d, r1, ctx)
  330. || !BN_mod(rsa->dmq1, d, r2, ctx)) {
  331. BN_free(d);
  332. goto err;
  333. }
  334. /* calculate CRT exponents */
  335. for (i = 2; i < primes; i++) {
  336. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  337. /* pinfo->d == r_i - 1 */
  338. if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
  339. BN_free(d);
  340. goto err;
  341. }
  342. }
  343. /* We MUST free d before any further use of rsa->d */
  344. BN_free(d);
  345. }
  346. {
  347. BIGNUM *p = BN_new();
  348. if (p == NULL)
  349. goto err;
  350. BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
  351. /* calculate inverse of q mod p */
  352. if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
  353. BN_free(p);
  354. goto err;
  355. }
  356. /* calculate CRT coefficient for other primes */
  357. for (i = 2; i < primes; i++) {
  358. pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
  359. BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
  360. if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
  361. BN_free(p);
  362. goto err;
  363. }
  364. }
  365. /* We MUST free p before any further use of rsa->p */
  366. BN_free(p);
  367. }
  368. ok = 1;
  369. err:
  370. if (ok == -1) {
  371. ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
  372. ok = 0;
  373. }
  374. BN_CTX_end(ctx);
  375. BN_CTX_free(ctx);
  376. return ok;
  377. }
  378. #endif /* FIPS_MODULE */
  379. static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
  380. BIGNUM *e_value, BN_GENCB *cb, int pairwise_test)
  381. {
  382. int ok = 0;
  383. #ifdef FIPS_MODULE
  384. ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
  385. pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
  386. #else
  387. /*
  388. * Only multi-prime keys or insecure keys with a small key length or a
  389. * public exponent <= 2^16 will use the older rsa_multiprime_keygen().
  390. */
  391. if (primes == 2
  392. && bits >= 2048
  393. && (e_value == NULL || BN_num_bits(e_value) > 16))
  394. ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
  395. else
  396. ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
  397. #endif /* FIPS_MODULE */
  398. if (pairwise_test && ok > 0) {
  399. OSSL_CALLBACK *stcb = NULL;
  400. void *stcbarg = NULL;
  401. OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
  402. ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
  403. if (!ok) {
  404. ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
  405. /* Clear intermediate results */
  406. BN_clear_free(rsa->d);
  407. BN_clear_free(rsa->p);
  408. BN_clear_free(rsa->q);
  409. BN_clear_free(rsa->dmp1);
  410. BN_clear_free(rsa->dmq1);
  411. BN_clear_free(rsa->iqmp);
  412. rsa->d = NULL;
  413. rsa->p = NULL;
  414. rsa->q = NULL;
  415. rsa->dmp1 = NULL;
  416. rsa->dmq1 = NULL;
  417. rsa->iqmp = NULL;
  418. }
  419. }
  420. return ok;
  421. }
  422. /*
  423. * For RSA key generation it is not known whether the key pair will be used
  424. * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case
  425. * either a signature verification OR an encryption operation may be used to
  426. * perform the pairwise consistency check. The simpler encrypt/decrypt operation
  427. * has been chosen for this case.
  428. */
  429. static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
  430. {
  431. int ret = 0;
  432. unsigned int ciphertxt_len;
  433. unsigned char *ciphertxt = NULL;
  434. const unsigned char plaintxt[16] = {0};
  435. unsigned char *decoded = NULL;
  436. unsigned int decoded_len;
  437. unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
  438. int padding = RSA_PKCS1_PADDING;
  439. OSSL_SELF_TEST *st = NULL;
  440. st = OSSL_SELF_TEST_new(cb, cbarg);
  441. if (st == NULL)
  442. goto err;
  443. OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
  444. OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
  445. ciphertxt_len = RSA_size(rsa);
  446. /*
  447. * RSA_private_encrypt() and RSA_private_decrypt() requires the 'to'
  448. * parameter to be a maximum of RSA_size() - allocate space for both.
  449. */
  450. ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2);
  451. if (ciphertxt == NULL)
  452. goto err;
  453. decoded = ciphertxt + ciphertxt_len;
  454. ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
  455. padding);
  456. if (ciphertxt_len <= 0)
  457. goto err;
  458. if (ciphertxt_len == plaintxt_len
  459. && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
  460. goto err;
  461. OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
  462. decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
  463. padding);
  464. if (decoded_len != plaintxt_len
  465. || memcmp(decoded, plaintxt, decoded_len) != 0)
  466. goto err;
  467. ret = 1;
  468. err:
  469. OSSL_SELF_TEST_onend(st, ret);
  470. OSSL_SELF_TEST_free(st);
  471. OPENSSL_free(ciphertxt);
  472. return ret;
  473. }