bn_rand.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * Copyright 1995-2024 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. #include <stdio.h>
  10. #include <time.h>
  11. #include "internal/cryptlib.h"
  12. #include "crypto/rand.h"
  13. #include "bn_local.h"
  14. #include <openssl/rand.h>
  15. #include <openssl/sha.h>
  16. #include <openssl/evp.h>
  17. typedef enum bnrand_flag_e {
  18. NORMAL, TESTING, PRIVATE
  19. } BNRAND_FLAG;
  20. static int bnrand(BNRAND_FLAG flag, BIGNUM *rnd, int bits, int top, int bottom,
  21. unsigned int strength, BN_CTX *ctx)
  22. {
  23. unsigned char *buf = NULL;
  24. int b, ret = 0, bit, bytes, mask;
  25. OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx);
  26. if (bits == 0) {
  27. if (top != BN_RAND_TOP_ANY || bottom != BN_RAND_BOTTOM_ANY)
  28. goto toosmall;
  29. BN_zero(rnd);
  30. return 1;
  31. }
  32. if (bits < 0 || (bits == 1 && top > 0))
  33. goto toosmall;
  34. bytes = (bits + 7) / 8;
  35. bit = (bits - 1) % 8;
  36. mask = 0xff << (bit + 1);
  37. buf = OPENSSL_malloc(bytes);
  38. if (buf == NULL)
  39. goto err;
  40. /* make a random number and set the top and bottom bits */
  41. b = flag == NORMAL ? RAND_bytes_ex(libctx, buf, bytes, strength)
  42. : RAND_priv_bytes_ex(libctx, buf, bytes, strength);
  43. if (b <= 0)
  44. goto err;
  45. if (flag == TESTING) {
  46. /*
  47. * generate patterns that are more likely to trigger BN library bugs
  48. */
  49. int i;
  50. unsigned char c;
  51. for (i = 0; i < bytes; i++) {
  52. if (RAND_bytes_ex(libctx, &c, 1, strength) <= 0)
  53. goto err;
  54. if (c >= 128 && i > 0)
  55. buf[i] = buf[i - 1];
  56. else if (c < 42)
  57. buf[i] = 0;
  58. else if (c < 84)
  59. buf[i] = 255;
  60. }
  61. }
  62. if (top >= 0) {
  63. if (top) {
  64. if (bit == 0) {
  65. buf[0] = 1;
  66. buf[1] |= 0x80;
  67. } else {
  68. buf[0] |= (3 << (bit - 1));
  69. }
  70. } else {
  71. buf[0] |= (1 << bit);
  72. }
  73. }
  74. buf[0] &= ~mask;
  75. if (bottom) /* set bottom bit if requested */
  76. buf[bytes - 1] |= 1;
  77. if (!BN_bin2bn(buf, bytes, rnd))
  78. goto err;
  79. ret = 1;
  80. err:
  81. OPENSSL_clear_free(buf, bytes);
  82. bn_check_top(rnd);
  83. return ret;
  84. toosmall:
  85. ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL);
  86. return 0;
  87. }
  88. int BN_rand_ex(BIGNUM *rnd, int bits, int top, int bottom,
  89. unsigned int strength, BN_CTX *ctx)
  90. {
  91. return bnrand(NORMAL, rnd, bits, top, bottom, strength, ctx);
  92. }
  93. #ifndef FIPS_MODULE
  94. int BN_rand(BIGNUM *rnd, int bits, int top, int bottom)
  95. {
  96. return bnrand(NORMAL, rnd, bits, top, bottom, 0, NULL);
  97. }
  98. int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom)
  99. {
  100. return bnrand(TESTING, rnd, bits, top, bottom, 0, NULL);
  101. }
  102. #endif
  103. int BN_priv_rand_ex(BIGNUM *rnd, int bits, int top, int bottom,
  104. unsigned int strength, BN_CTX *ctx)
  105. {
  106. return bnrand(PRIVATE, rnd, bits, top, bottom, strength, ctx);
  107. }
  108. #ifndef FIPS_MODULE
  109. int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom)
  110. {
  111. return bnrand(PRIVATE, rnd, bits, top, bottom, 0, NULL);
  112. }
  113. #endif
  114. /* random number r: 0 <= r < range */
  115. static int bnrand_range(BNRAND_FLAG flag, BIGNUM *r, const BIGNUM *range,
  116. unsigned int strength, BN_CTX *ctx)
  117. {
  118. int n;
  119. int count = 100;
  120. if (r == NULL) {
  121. ERR_raise(ERR_LIB_BN, ERR_R_PASSED_NULL_PARAMETER);
  122. return 0;
  123. }
  124. if (range->neg || BN_is_zero(range)) {
  125. ERR_raise(ERR_LIB_BN, BN_R_INVALID_RANGE);
  126. return 0;
  127. }
  128. n = BN_num_bits(range); /* n > 0 */
  129. /* BN_is_bit_set(range, n - 1) always holds */
  130. if (n == 1)
  131. BN_zero(r);
  132. else if (!BN_is_bit_set(range, n - 2) && !BN_is_bit_set(range, n - 3)) {
  133. /*
  134. * range = 100..._2, so 3*range (= 11..._2) is exactly one bit longer
  135. * than range
  136. */
  137. do {
  138. if (!bnrand(flag, r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY,
  139. strength, ctx))
  140. return 0;
  141. /*
  142. * If r < 3*range, use r := r MOD range (which is either r, r -
  143. * range, or r - 2*range). Otherwise, iterate once more. Since
  144. * 3*range = 11..._2, each iteration succeeds with probability >=
  145. * .75.
  146. */
  147. if (BN_cmp(r, range) >= 0) {
  148. if (!BN_sub(r, r, range))
  149. return 0;
  150. if (BN_cmp(r, range) >= 0)
  151. if (!BN_sub(r, r, range))
  152. return 0;
  153. }
  154. if (!--count) {
  155. ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
  156. return 0;
  157. }
  158. }
  159. while (BN_cmp(r, range) >= 0);
  160. } else {
  161. do {
  162. /* range = 11..._2 or range = 101..._2 */
  163. if (!bnrand(flag, r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY,
  164. strength, ctx))
  165. return 0;
  166. if (!--count) {
  167. ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
  168. return 0;
  169. }
  170. }
  171. while (BN_cmp(r, range) >= 0);
  172. }
  173. bn_check_top(r);
  174. return 1;
  175. }
  176. int BN_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength,
  177. BN_CTX *ctx)
  178. {
  179. return bnrand_range(NORMAL, r, range, strength, ctx);
  180. }
  181. #ifndef FIPS_MODULE
  182. int BN_rand_range(BIGNUM *r, const BIGNUM *range)
  183. {
  184. return bnrand_range(NORMAL, r, range, 0, NULL);
  185. }
  186. #endif
  187. int BN_priv_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength,
  188. BN_CTX *ctx)
  189. {
  190. return bnrand_range(PRIVATE, r, range, strength, ctx);
  191. }
  192. #ifndef FIPS_MODULE
  193. int BN_priv_rand_range(BIGNUM *r, const BIGNUM *range)
  194. {
  195. return bnrand_range(PRIVATE, r, range, 0, NULL);
  196. }
  197. # ifndef OPENSSL_NO_DEPRECATED_3_0
  198. int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom)
  199. {
  200. return BN_rand(rnd, bits, top, bottom);
  201. }
  202. int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range)
  203. {
  204. return BN_rand_range(r, range);
  205. }
  206. # endif
  207. #endif
  208. int ossl_bn_priv_rand_range_fixed_top(BIGNUM *r, const BIGNUM *range,
  209. unsigned int strength, BN_CTX *ctx)
  210. {
  211. int n;
  212. int count = 100;
  213. if (r == NULL) {
  214. ERR_raise(ERR_LIB_BN, ERR_R_PASSED_NULL_PARAMETER);
  215. return 0;
  216. }
  217. if (range->neg || BN_is_zero(range)) {
  218. ERR_raise(ERR_LIB_BN, BN_R_INVALID_RANGE);
  219. return 0;
  220. }
  221. n = BN_num_bits(range); /* n > 0 */
  222. /* BN_is_bit_set(range, n - 1) always holds */
  223. if (n == 1) {
  224. BN_zero(r);
  225. } else {
  226. BN_set_flags(r, BN_FLG_CONSTTIME);
  227. do {
  228. if (!bnrand(PRIVATE, r, n + 1, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY,
  229. strength, ctx))
  230. return 0;
  231. if (!--count) {
  232. ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
  233. return 0;
  234. }
  235. ossl_bn_mask_bits_fixed_top(r, n);
  236. }
  237. while (BN_ucmp(r, range) >= 0);
  238. #ifdef BN_DEBUG
  239. /* With BN_DEBUG on a fixed top number cannot be returned */
  240. bn_correct_top(r);
  241. #endif
  242. }
  243. return 1;
  244. }
  245. /*
  246. * ossl_bn_gen_dsa_nonce_fixed_top generates a random number 0 <= out < range.
  247. * Unlike BN_rand_range, it also includes the contents of |priv| and |message|
  248. * in the generation so that an RNG failure isn't fatal as long as |priv|
  249. * remains secret. This is intended for use in DSA and ECDSA where an RNG
  250. * weakness leads directly to private key exposure unless this function is
  251. * used.
  252. */
  253. int ossl_bn_gen_dsa_nonce_fixed_top(BIGNUM *out, const BIGNUM *range,
  254. const BIGNUM *priv,
  255. const unsigned char *message,
  256. size_t message_len, BN_CTX *ctx)
  257. {
  258. EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
  259. /*
  260. * We use 512 bits of random data per iteration to ensure that we have at
  261. * least |range| bits of randomness.
  262. */
  263. unsigned char random_bytes[64];
  264. unsigned char digest[SHA512_DIGEST_LENGTH];
  265. unsigned done, todo;
  266. /* We generate |range|+1 bytes of random output. */
  267. const unsigned num_k_bytes = BN_num_bytes(range) + 1;
  268. unsigned char private_bytes[96];
  269. unsigned char *k_bytes = NULL;
  270. const int max_n = 64; /* Pr(failure to generate) < 2^max_n */
  271. int n;
  272. int ret = 0;
  273. EVP_MD *md = NULL;
  274. OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx);
  275. if (mdctx == NULL)
  276. goto end;
  277. k_bytes = OPENSSL_malloc(num_k_bytes);
  278. if (k_bytes == NULL)
  279. goto end;
  280. /* Ensure top byte is set to avoid non-constant time in bin2bn */
  281. k_bytes[0] = 0xff;
  282. /* We copy |priv| into a local buffer to avoid exposing its length. */
  283. if (BN_bn2binpad(priv, private_bytes, sizeof(private_bytes)) < 0) {
  284. /*
  285. * No reasonable DSA or ECDSA key should have a private key this
  286. * large and we don't handle this case in order to avoid leaking the
  287. * length of the private key.
  288. */
  289. ERR_raise(ERR_LIB_BN, BN_R_PRIVATE_KEY_TOO_LARGE);
  290. goto end;
  291. }
  292. md = EVP_MD_fetch(libctx, "SHA512", NULL);
  293. if (md == NULL) {
  294. ERR_raise(ERR_LIB_BN, BN_R_NO_SUITABLE_DIGEST);
  295. goto end;
  296. }
  297. for (n = 0; n < max_n; n++) {
  298. unsigned char i = 0;
  299. for (done = 1; done < num_k_bytes;) {
  300. if (RAND_priv_bytes_ex(libctx, random_bytes, sizeof(random_bytes),
  301. 0) <= 0)
  302. goto end;
  303. if (!EVP_DigestInit_ex(mdctx, md, NULL)
  304. || !EVP_DigestUpdate(mdctx, &i, sizeof(i))
  305. || !EVP_DigestUpdate(mdctx, private_bytes,
  306. sizeof(private_bytes))
  307. || !EVP_DigestUpdate(mdctx, message, message_len)
  308. || !EVP_DigestUpdate(mdctx, random_bytes,
  309. sizeof(random_bytes))
  310. || !EVP_DigestFinal_ex(mdctx, digest, NULL))
  311. goto end;
  312. todo = num_k_bytes - done;
  313. if (todo > SHA512_DIGEST_LENGTH)
  314. todo = SHA512_DIGEST_LENGTH;
  315. memcpy(k_bytes + done, digest, todo);
  316. done += todo;
  317. ++i;
  318. }
  319. if (!BN_bin2bn(k_bytes, num_k_bytes, out))
  320. goto end;
  321. /* Clear out the top bits and rejection filter into range */
  322. BN_set_flags(out, BN_FLG_CONSTTIME);
  323. ossl_bn_mask_bits_fixed_top(out, BN_num_bits(range));
  324. if (BN_ucmp(out, range) < 0) {
  325. ret = 1;
  326. #ifdef BN_DEBUG
  327. /* With BN_DEBUG on a fixed top number cannot be returned */
  328. bn_correct_top(out);
  329. #endif
  330. goto end;
  331. }
  332. }
  333. /* Failed to generate anything */
  334. ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR);
  335. end:
  336. EVP_MD_CTX_free(mdctx);
  337. EVP_MD_free(md);
  338. OPENSSL_clear_free(k_bytes, num_k_bytes);
  339. OPENSSL_cleanse(digest, sizeof(digest));
  340. OPENSSL_cleanse(random_bytes, sizeof(random_bytes));
  341. OPENSSL_cleanse(private_bytes, sizeof(private_bytes));
  342. return ret;
  343. }
  344. int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
  345. const BIGNUM *priv, const unsigned char *message,
  346. size_t message_len, BN_CTX *ctx)
  347. {
  348. int ret;
  349. ret = ossl_bn_gen_dsa_nonce_fixed_top(out, range, priv, message,
  350. message_len, ctx);
  351. /*
  352. * This call makes the BN_generate_dsa_nonce non-const-time, thus we
  353. * do not use it internally. But fixed_top BNs currently cannot be returned
  354. * from public API calls.
  355. */
  356. bn_correct_top(out);
  357. return ret;
  358. }