rsa_gen.c 16 KB

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