rsa_gen.c 16 KB

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