rand_lib.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. /*
  2. * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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 <openssl/opensslconf.h>
  13. #include "crypto/rand.h"
  14. #include <openssl/engine.h>
  15. #include "internal/thread_once.h"
  16. #include "rand_local.h"
  17. #include "e_os.h"
  18. #ifndef OPENSSL_NO_ENGINE
  19. /* non-NULL if default_RAND_meth is ENGINE-provided */
  20. static ENGINE *funct_ref;
  21. static CRYPTO_RWLOCK *rand_engine_lock;
  22. #endif
  23. static CRYPTO_RWLOCK *rand_meth_lock;
  24. static const RAND_METHOD *default_RAND_meth;
  25. static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
  26. static CRYPTO_RWLOCK *rand_nonce_lock;
  27. static int rand_nonce_count;
  28. static int rand_inited = 0;
  29. #ifdef OPENSSL_RAND_SEED_RDTSC
  30. /*
  31. * IMPORTANT NOTE: It is not currently possible to use this code
  32. * because we are not sure about the amount of randomness it provides.
  33. * Some SP900 tests have been run, but there is internal skepticism.
  34. * So for now this code is not used.
  35. */
  36. # error "RDTSC enabled? Should not be possible!"
  37. /*
  38. * Acquire entropy from high-speed clock
  39. *
  40. * Since we get some randomness from the low-order bits of the
  41. * high-speed clock, it can help.
  42. *
  43. * Returns the total entropy count, if it exceeds the requested
  44. * entropy count. Otherwise, returns an entropy count of 0.
  45. */
  46. size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
  47. {
  48. unsigned char c;
  49. int i;
  50. if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
  51. for (i = 0; i < TSC_READ_COUNT; i++) {
  52. c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
  53. rand_pool_add(pool, &c, 1, 4);
  54. }
  55. }
  56. return rand_pool_entropy_available(pool);
  57. }
  58. #endif
  59. #ifdef OPENSSL_RAND_SEED_RDCPU
  60. size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
  61. size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
  62. extern unsigned int OPENSSL_ia32cap_P[];
  63. /*
  64. * Acquire entropy using Intel-specific cpu instructions
  65. *
  66. * Uses the RDSEED instruction if available, otherwise uses
  67. * RDRAND if available.
  68. *
  69. * For the differences between RDSEED and RDRAND, and why RDSEED
  70. * is the preferred choice, see https://goo.gl/oK3KcN
  71. *
  72. * Returns the total entropy count, if it exceeds the requested
  73. * entropy count. Otherwise, returns an entropy count of 0.
  74. */
  75. size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
  76. {
  77. size_t bytes_needed;
  78. unsigned char *buffer;
  79. bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  80. if (bytes_needed > 0) {
  81. buffer = rand_pool_add_begin(pool, bytes_needed);
  82. if (buffer != NULL) {
  83. /* Whichever comes first, use RDSEED, RDRAND or nothing */
  84. if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
  85. if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
  86. == bytes_needed) {
  87. rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
  88. }
  89. } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
  90. if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
  91. == bytes_needed) {
  92. rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
  93. }
  94. } else {
  95. rand_pool_add_end(pool, 0, 0);
  96. }
  97. }
  98. }
  99. return rand_pool_entropy_available(pool);
  100. }
  101. #endif
  102. /*
  103. * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
  104. *
  105. * If the DRBG has a parent, then the required amount of entropy input
  106. * is fetched using the parent's RAND_DRBG_generate().
  107. *
  108. * Otherwise, the entropy is polled from the system entropy sources
  109. * using rand_pool_acquire_entropy().
  110. *
  111. * If a random pool has been added to the DRBG using RAND_add(), then
  112. * its entropy will be used up first.
  113. */
  114. size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
  115. unsigned char **pout,
  116. int entropy, size_t min_len, size_t max_len,
  117. int prediction_resistance)
  118. {
  119. size_t ret = 0;
  120. size_t entropy_available = 0;
  121. RAND_POOL *pool;
  122. if (drbg->parent != NULL && drbg->strength > drbg->parent->strength) {
  123. /*
  124. * We currently don't support the algorithm from NIST SP 800-90C
  125. * 10.1.2 to use a weaker DRBG as source
  126. */
  127. RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
  128. return 0;
  129. }
  130. if (drbg->seed_pool != NULL) {
  131. pool = drbg->seed_pool;
  132. pool->entropy_requested = entropy;
  133. } else {
  134. pool = rand_pool_new(entropy, drbg->secure, min_len, max_len);
  135. if (pool == NULL)
  136. return 0;
  137. }
  138. if (drbg->parent != NULL) {
  139. size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  140. unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
  141. if (buffer != NULL) {
  142. size_t bytes = 0;
  143. /*
  144. * Get random data from parent. Include our address as additional input,
  145. * in order to provide some additional distinction between different
  146. * DRBG child instances.
  147. * Our lock is already held, but we need to lock our parent before
  148. * generating bits from it. (Note: taking the lock will be a no-op
  149. * if locking if drbg->parent->lock == NULL.)
  150. */
  151. rand_drbg_lock(drbg->parent);
  152. if (RAND_DRBG_generate(drbg->parent,
  153. buffer, bytes_needed,
  154. prediction_resistance,
  155. (unsigned char *)&drbg, sizeof(drbg)) != 0)
  156. bytes = bytes_needed;
  157. drbg->reseed_next_counter
  158. = tsan_load(&drbg->parent->reseed_prop_counter);
  159. rand_drbg_unlock(drbg->parent);
  160. rand_pool_add_end(pool, bytes, 8 * bytes);
  161. entropy_available = rand_pool_entropy_available(pool);
  162. }
  163. } else {
  164. if (prediction_resistance) {
  165. /*
  166. * We don't have any entropy sources that comply with the NIST
  167. * standard to provide prediction resistance (see NIST SP 800-90C,
  168. * Section 5.4).
  169. */
  170. RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY,
  171. RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED);
  172. goto err;
  173. }
  174. /* Get entropy by polling system entropy sources. */
  175. entropy_available = rand_pool_acquire_entropy(pool);
  176. }
  177. if (entropy_available > 0) {
  178. ret = rand_pool_length(pool);
  179. *pout = rand_pool_detach(pool);
  180. }
  181. err:
  182. if (drbg->seed_pool == NULL)
  183. rand_pool_free(pool);
  184. return ret;
  185. }
  186. /*
  187. * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
  188. *
  189. */
  190. void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
  191. unsigned char *out, size_t outlen)
  192. {
  193. if (drbg->seed_pool == NULL) {
  194. if (drbg->secure)
  195. OPENSSL_secure_clear_free(out, outlen);
  196. else
  197. OPENSSL_clear_free(out, outlen);
  198. }
  199. }
  200. /*
  201. * Implements the get_nonce() callback (see RAND_DRBG_set_callbacks())
  202. *
  203. */
  204. size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
  205. unsigned char **pout,
  206. int entropy, size_t min_len, size_t max_len)
  207. {
  208. size_t ret = 0;
  209. RAND_POOL *pool;
  210. struct {
  211. void * instance;
  212. int count;
  213. } data;
  214. memset(&data, 0, sizeof(data));
  215. pool = rand_pool_new(0, 0, min_len, max_len);
  216. if (pool == NULL)
  217. return 0;
  218. if (rand_pool_add_nonce_data(pool) == 0)
  219. goto err;
  220. data.instance = drbg;
  221. CRYPTO_atomic_add(&rand_nonce_count, 1, &data.count, rand_nonce_lock);
  222. if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
  223. goto err;
  224. ret = rand_pool_length(pool);
  225. *pout = rand_pool_detach(pool);
  226. err:
  227. rand_pool_free(pool);
  228. return ret;
  229. }
  230. /*
  231. * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
  232. *
  233. */
  234. void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
  235. unsigned char *out, size_t outlen)
  236. {
  237. OPENSSL_clear_free(out, outlen);
  238. }
  239. /*
  240. * Generate additional data that can be used for the drbg. The data does
  241. * not need to contain entropy, but it's useful if it contains at least
  242. * some bits that are unpredictable.
  243. *
  244. * Returns 0 on failure.
  245. *
  246. * On success it allocates a buffer at |*pout| and returns the length of
  247. * the data. The buffer should get freed using OPENSSL_secure_clear_free().
  248. */
  249. size_t rand_drbg_get_additional_data(RAND_POOL *pool, unsigned char **pout)
  250. {
  251. size_t ret = 0;
  252. if (rand_pool_add_additional_data(pool) == 0)
  253. goto err;
  254. ret = rand_pool_length(pool);
  255. *pout = rand_pool_detach(pool);
  256. err:
  257. return ret;
  258. }
  259. void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
  260. {
  261. rand_pool_reattach(pool, out);
  262. }
  263. DEFINE_RUN_ONCE_STATIC(do_rand_init)
  264. {
  265. #ifndef OPENSSL_NO_ENGINE
  266. rand_engine_lock = CRYPTO_THREAD_lock_new();
  267. if (rand_engine_lock == NULL)
  268. return 0;
  269. #endif
  270. rand_meth_lock = CRYPTO_THREAD_lock_new();
  271. if (rand_meth_lock == NULL)
  272. goto err1;
  273. rand_nonce_lock = CRYPTO_THREAD_lock_new();
  274. if (rand_nonce_lock == NULL)
  275. goto err2;
  276. if (!rand_pool_init())
  277. goto err3;
  278. rand_inited = 1;
  279. return 1;
  280. err3:
  281. CRYPTO_THREAD_lock_free(rand_nonce_lock);
  282. rand_nonce_lock = NULL;
  283. err2:
  284. CRYPTO_THREAD_lock_free(rand_meth_lock);
  285. rand_meth_lock = NULL;
  286. err1:
  287. #ifndef OPENSSL_NO_ENGINE
  288. CRYPTO_THREAD_lock_free(rand_engine_lock);
  289. rand_engine_lock = NULL;
  290. #endif
  291. return 0;
  292. }
  293. void rand_cleanup_int(void)
  294. {
  295. const RAND_METHOD *meth = default_RAND_meth;
  296. if (!rand_inited)
  297. return;
  298. if (meth != NULL && meth->cleanup != NULL)
  299. meth->cleanup();
  300. RAND_set_rand_method(NULL);
  301. rand_pool_cleanup();
  302. #ifndef OPENSSL_NO_ENGINE
  303. CRYPTO_THREAD_lock_free(rand_engine_lock);
  304. rand_engine_lock = NULL;
  305. #endif
  306. CRYPTO_THREAD_lock_free(rand_meth_lock);
  307. rand_meth_lock = NULL;
  308. CRYPTO_THREAD_lock_free(rand_nonce_lock);
  309. rand_nonce_lock = NULL;
  310. rand_inited = 0;
  311. }
  312. /*
  313. * RAND_close_seed_files() ensures that any seed file descriptors are
  314. * closed after use.
  315. */
  316. void RAND_keep_random_devices_open(int keep)
  317. {
  318. if (RUN_ONCE(&rand_init, do_rand_init))
  319. rand_pool_keep_random_devices_open(keep);
  320. }
  321. /*
  322. * RAND_poll() reseeds the default RNG using random input
  323. *
  324. * The random input is obtained from polling various entropy
  325. * sources which depend on the operating system and are
  326. * configurable via the --with-rand-seed configure option.
  327. */
  328. int RAND_poll(void)
  329. {
  330. int ret = 0;
  331. RAND_POOL *pool = NULL;
  332. const RAND_METHOD *meth = RAND_get_rand_method();
  333. if (meth == NULL)
  334. return 0;
  335. if (meth == RAND_OpenSSL()) {
  336. /* fill random pool and seed the master DRBG */
  337. RAND_DRBG *drbg = RAND_DRBG_get0_master();
  338. if (drbg == NULL)
  339. return 0;
  340. rand_drbg_lock(drbg);
  341. ret = rand_drbg_restart(drbg, NULL, 0, 0);
  342. rand_drbg_unlock(drbg);
  343. return ret;
  344. } else {
  345. /* fill random pool and seed the current legacy RNG */
  346. pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
  347. (RAND_DRBG_STRENGTH + 7) / 8,
  348. RAND_POOL_MAX_LENGTH);
  349. if (pool == NULL)
  350. return 0;
  351. if (rand_pool_acquire_entropy(pool) == 0)
  352. goto err;
  353. if (meth->add == NULL
  354. || meth->add(rand_pool_buffer(pool),
  355. rand_pool_length(pool),
  356. (rand_pool_entropy(pool) / 8.0)) == 0)
  357. goto err;
  358. ret = 1;
  359. }
  360. err:
  361. rand_pool_free(pool);
  362. return ret;
  363. }
  364. /*
  365. * Allocate memory and initialize a new random pool
  366. */
  367. RAND_POOL *rand_pool_new(int entropy_requested, int secure,
  368. size_t min_len, size_t max_len)
  369. {
  370. RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
  371. size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
  372. if (pool == NULL) {
  373. RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
  374. return NULL;
  375. }
  376. pool->min_len = min_len;
  377. pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
  378. RAND_POOL_MAX_LENGTH : max_len;
  379. pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
  380. if (pool->alloc_len > pool->max_len)
  381. pool->alloc_len = pool->max_len;
  382. if (secure)
  383. pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
  384. else
  385. pool->buffer = OPENSSL_zalloc(pool->alloc_len);
  386. if (pool->buffer == NULL) {
  387. RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
  388. goto err;
  389. }
  390. pool->entropy_requested = entropy_requested;
  391. pool->secure = secure;
  392. return pool;
  393. err:
  394. OPENSSL_free(pool);
  395. return NULL;
  396. }
  397. /*
  398. * Attach new random pool to the given buffer
  399. *
  400. * This function is intended to be used only for feeding random data
  401. * provided by RAND_add() and RAND_seed() into the <master> DRBG.
  402. */
  403. RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
  404. size_t entropy)
  405. {
  406. RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
  407. if (pool == NULL) {
  408. RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
  409. return NULL;
  410. }
  411. /*
  412. * The const needs to be cast away, but attached buffers will not be
  413. * modified (in contrary to allocated buffers which are zeroed and
  414. * freed in the end).
  415. */
  416. pool->buffer = (unsigned char *) buffer;
  417. pool->len = len;
  418. pool->attached = 1;
  419. pool->min_len = pool->max_len = pool->alloc_len = pool->len;
  420. pool->entropy = entropy;
  421. return pool;
  422. }
  423. /*
  424. * Free |pool|, securely erasing its buffer.
  425. */
  426. void rand_pool_free(RAND_POOL *pool)
  427. {
  428. if (pool == NULL)
  429. return;
  430. /*
  431. * Although it would be advisable from a cryptographical viewpoint,
  432. * we are not allowed to clear attached buffers, since they are passed
  433. * to rand_pool_attach() as `const unsigned char*`.
  434. * (see corresponding comment in rand_pool_attach()).
  435. */
  436. if (!pool->attached) {
  437. if (pool->secure)
  438. OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
  439. else
  440. OPENSSL_clear_free(pool->buffer, pool->alloc_len);
  441. }
  442. OPENSSL_free(pool);
  443. }
  444. /*
  445. * Return the |pool|'s buffer to the caller (readonly).
  446. */
  447. const unsigned char *rand_pool_buffer(RAND_POOL *pool)
  448. {
  449. return pool->buffer;
  450. }
  451. /*
  452. * Return the |pool|'s entropy to the caller.
  453. */
  454. size_t rand_pool_entropy(RAND_POOL *pool)
  455. {
  456. return pool->entropy;
  457. }
  458. /*
  459. * Return the |pool|'s buffer length to the caller.
  460. */
  461. size_t rand_pool_length(RAND_POOL *pool)
  462. {
  463. return pool->len;
  464. }
  465. /*
  466. * Detach the |pool| buffer and return it to the caller.
  467. * It's the responsibility of the caller to free the buffer
  468. * using OPENSSL_secure_clear_free() or to re-attach it
  469. * again to the pool using rand_pool_reattach().
  470. */
  471. unsigned char *rand_pool_detach(RAND_POOL *pool)
  472. {
  473. unsigned char *ret = pool->buffer;
  474. pool->buffer = NULL;
  475. pool->entropy = 0;
  476. return ret;
  477. }
  478. /*
  479. * Re-attach the |pool| buffer. It is only allowed to pass
  480. * the |buffer| which was previously detached from the same pool.
  481. */
  482. void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
  483. {
  484. pool->buffer = buffer;
  485. OPENSSL_cleanse(pool->buffer, pool->len);
  486. pool->len = 0;
  487. }
  488. /*
  489. * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
  490. * need to obtain at least |bits| bits of entropy?
  491. */
  492. #define ENTROPY_TO_BYTES(bits, entropy_factor) \
  493. (((bits) * (entropy_factor) + 7) / 8)
  494. /*
  495. * Checks whether the |pool|'s entropy is available to the caller.
  496. * This is the case when entropy count and buffer length are high enough.
  497. * Returns
  498. *
  499. * |entropy| if the entropy count and buffer size is large enough
  500. * 0 otherwise
  501. */
  502. size_t rand_pool_entropy_available(RAND_POOL *pool)
  503. {
  504. if (pool->entropy < pool->entropy_requested)
  505. return 0;
  506. if (pool->len < pool->min_len)
  507. return 0;
  508. return pool->entropy;
  509. }
  510. /*
  511. * Returns the (remaining) amount of entropy needed to fill
  512. * the random pool.
  513. */
  514. size_t rand_pool_entropy_needed(RAND_POOL *pool)
  515. {
  516. if (pool->entropy < pool->entropy_requested)
  517. return pool->entropy_requested - pool->entropy;
  518. return 0;
  519. }
  520. /* Increase the allocation size -- not usable for an attached pool */
  521. static int rand_pool_grow(RAND_POOL *pool, size_t len)
  522. {
  523. if (len > pool->alloc_len - pool->len) {
  524. unsigned char *p;
  525. const size_t limit = pool->max_len / 2;
  526. size_t newlen = pool->alloc_len;
  527. if (pool->attached || len > pool->max_len - pool->len) {
  528. RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_INTERNAL_ERROR);
  529. return 0;
  530. }
  531. do
  532. newlen = newlen < limit ? newlen * 2 : pool->max_len;
  533. while (len > newlen - pool->len);
  534. if (pool->secure)
  535. p = OPENSSL_secure_zalloc(newlen);
  536. else
  537. p = OPENSSL_zalloc(newlen);
  538. if (p == NULL) {
  539. RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_MALLOC_FAILURE);
  540. return 0;
  541. }
  542. memcpy(p, pool->buffer, pool->len);
  543. if (pool->secure)
  544. OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
  545. else
  546. OPENSSL_clear_free(pool->buffer, pool->alloc_len);
  547. pool->buffer = p;
  548. pool->alloc_len = newlen;
  549. }
  550. return 1;
  551. }
  552. /*
  553. * Returns the number of bytes needed to fill the pool, assuming
  554. * the input has 1 / |entropy_factor| entropy bits per data bit.
  555. * In case of an error, 0 is returned.
  556. */
  557. size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
  558. {
  559. size_t bytes_needed;
  560. size_t entropy_needed = rand_pool_entropy_needed(pool);
  561. if (entropy_factor < 1) {
  562. RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
  563. return 0;
  564. }
  565. bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
  566. if (bytes_needed > pool->max_len - pool->len) {
  567. /* not enough space left */
  568. RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
  569. return 0;
  570. }
  571. if (pool->len < pool->min_len &&
  572. bytes_needed < pool->min_len - pool->len)
  573. /* to meet the min_len requirement */
  574. bytes_needed = pool->min_len - pool->len;
  575. /*
  576. * Make sure the buffer is large enough for the requested amount
  577. * of data. This guarantees that existing code patterns where
  578. * rand_pool_add_begin, rand_pool_add_end or rand_pool_add
  579. * are used to collect entropy data without any error handling
  580. * whatsoever, continue to be valid.
  581. * Furthermore if the allocation here fails once, make sure that
  582. * we don't fall back to a less secure or even blocking random source,
  583. * as that could happen by the existing code patterns.
  584. * This is not a concern for additional data, therefore that
  585. * is not needed if rand_pool_grow fails in other places.
  586. */
  587. if (!rand_pool_grow(pool, bytes_needed)) {
  588. /* persistent error for this pool */
  589. pool->max_len = pool->len = 0;
  590. return 0;
  591. }
  592. return bytes_needed;
  593. }
  594. /* Returns the remaining number of bytes available */
  595. size_t rand_pool_bytes_remaining(RAND_POOL *pool)
  596. {
  597. return pool->max_len - pool->len;
  598. }
  599. /*
  600. * Add random bytes to the random pool.
  601. *
  602. * It is expected that the |buffer| contains |len| bytes of
  603. * random input which contains at least |entropy| bits of
  604. * randomness.
  605. *
  606. * Returns 1 if the added amount is adequate, otherwise 0
  607. */
  608. int rand_pool_add(RAND_POOL *pool,
  609. const unsigned char *buffer, size_t len, size_t entropy)
  610. {
  611. if (len > pool->max_len - pool->len) {
  612. RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
  613. return 0;
  614. }
  615. if (pool->buffer == NULL) {
  616. RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
  617. return 0;
  618. }
  619. if (len > 0) {
  620. /*
  621. * This is to protect us from accidentally passing the buffer
  622. * returned from rand_pool_add_begin.
  623. * The check for alloc_len makes sure we do not compare the
  624. * address of the end of the allocated memory to something
  625. * different, since that comparison would have an
  626. * indeterminate result.
  627. */
  628. if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
  629. RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
  630. return 0;
  631. }
  632. /*
  633. * We have that only for cases when a pool is used to collect
  634. * additional data.
  635. * For entropy data, as long as the allocation request stays within
  636. * the limits given by rand_pool_bytes_needed this rand_pool_grow
  637. * below is guaranteed to succeed, thus no allocation happens.
  638. */
  639. if (!rand_pool_grow(pool, len))
  640. return 0;
  641. memcpy(pool->buffer + pool->len, buffer, len);
  642. pool->len += len;
  643. pool->entropy += entropy;
  644. }
  645. return 1;
  646. }
  647. /*
  648. * Start to add random bytes to the random pool in-place.
  649. *
  650. * Reserves the next |len| bytes for adding random bytes in-place
  651. * and returns a pointer to the buffer.
  652. * The caller is allowed to copy up to |len| bytes into the buffer.
  653. * If |len| == 0 this is considered a no-op and a NULL pointer
  654. * is returned without producing an error message.
  655. *
  656. * After updating the buffer, rand_pool_add_end() needs to be called
  657. * to finish the update operation (see next comment).
  658. */
  659. unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
  660. {
  661. if (len == 0)
  662. return NULL;
  663. if (len > pool->max_len - pool->len) {
  664. RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
  665. return NULL;
  666. }
  667. if (pool->buffer == NULL) {
  668. RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
  669. return NULL;
  670. }
  671. /*
  672. * As long as the allocation request stays within the limits given
  673. * by rand_pool_bytes_needed this rand_pool_grow below is guaranteed
  674. * to succeed, thus no allocation happens.
  675. * We have that only for cases when a pool is used to collect
  676. * additional data. Then the buffer might need to grow here,
  677. * and of course the caller is responsible to check the return
  678. * value of this function.
  679. */
  680. if (!rand_pool_grow(pool, len))
  681. return NULL;
  682. return pool->buffer + pool->len;
  683. }
  684. /*
  685. * Finish to add random bytes to the random pool in-place.
  686. *
  687. * Finishes an in-place update of the random pool started by
  688. * rand_pool_add_begin() (see previous comment).
  689. * It is expected that |len| bytes of random input have been added
  690. * to the buffer which contain at least |entropy| bits of randomness.
  691. * It is allowed to add less bytes than originally reserved.
  692. */
  693. int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
  694. {
  695. if (len > pool->alloc_len - pool->len) {
  696. RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
  697. return 0;
  698. }
  699. if (len > 0) {
  700. pool->len += len;
  701. pool->entropy += entropy;
  702. }
  703. return 1;
  704. }
  705. int RAND_set_rand_method(const RAND_METHOD *meth)
  706. {
  707. if (!RUN_ONCE(&rand_init, do_rand_init))
  708. return 0;
  709. CRYPTO_THREAD_write_lock(rand_meth_lock);
  710. #ifndef OPENSSL_NO_ENGINE
  711. ENGINE_finish(funct_ref);
  712. funct_ref = NULL;
  713. #endif
  714. default_RAND_meth = meth;
  715. CRYPTO_THREAD_unlock(rand_meth_lock);
  716. return 1;
  717. }
  718. const RAND_METHOD *RAND_get_rand_method(void)
  719. {
  720. const RAND_METHOD *tmp_meth = NULL;
  721. if (!RUN_ONCE(&rand_init, do_rand_init))
  722. return NULL;
  723. CRYPTO_THREAD_write_lock(rand_meth_lock);
  724. if (default_RAND_meth == NULL) {
  725. #ifndef OPENSSL_NO_ENGINE
  726. ENGINE *e;
  727. /* If we have an engine that can do RAND, use it. */
  728. if ((e = ENGINE_get_default_RAND()) != NULL
  729. && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
  730. funct_ref = e;
  731. default_RAND_meth = tmp_meth;
  732. } else {
  733. ENGINE_finish(e);
  734. default_RAND_meth = &rand_meth;
  735. }
  736. #else
  737. default_RAND_meth = &rand_meth;
  738. #endif
  739. }
  740. tmp_meth = default_RAND_meth;
  741. CRYPTO_THREAD_unlock(rand_meth_lock);
  742. return tmp_meth;
  743. }
  744. #ifndef OPENSSL_NO_ENGINE
  745. int RAND_set_rand_engine(ENGINE *engine)
  746. {
  747. const RAND_METHOD *tmp_meth = NULL;
  748. if (!RUN_ONCE(&rand_init, do_rand_init))
  749. return 0;
  750. if (engine != NULL) {
  751. if (!ENGINE_init(engine))
  752. return 0;
  753. tmp_meth = ENGINE_get_RAND(engine);
  754. if (tmp_meth == NULL) {
  755. ENGINE_finish(engine);
  756. return 0;
  757. }
  758. }
  759. CRYPTO_THREAD_write_lock(rand_engine_lock);
  760. /* This function releases any prior ENGINE so call it first */
  761. RAND_set_rand_method(tmp_meth);
  762. funct_ref = engine;
  763. CRYPTO_THREAD_unlock(rand_engine_lock);
  764. return 1;
  765. }
  766. #endif
  767. void RAND_seed(const void *buf, int num)
  768. {
  769. const RAND_METHOD *meth = RAND_get_rand_method();
  770. if (meth != NULL && meth->seed != NULL)
  771. meth->seed(buf, num);
  772. }
  773. void RAND_add(const void *buf, int num, double randomness)
  774. {
  775. const RAND_METHOD *meth = RAND_get_rand_method();
  776. if (meth != NULL && meth->add != NULL)
  777. meth->add(buf, num, randomness);
  778. }
  779. /*
  780. * This function is not part of RAND_METHOD, so if we're not using
  781. * the default method, then just call RAND_bytes(). Otherwise make
  782. * sure we're instantiated and use the private DRBG.
  783. */
  784. int RAND_priv_bytes(unsigned char *buf, int num)
  785. {
  786. const RAND_METHOD *meth = RAND_get_rand_method();
  787. RAND_DRBG *drbg;
  788. if (meth != NULL && meth != RAND_OpenSSL())
  789. return RAND_bytes(buf, num);
  790. drbg = RAND_DRBG_get0_private();
  791. if (drbg != NULL)
  792. return RAND_DRBG_bytes(drbg, buf, num);
  793. return 0;
  794. }
  795. int RAND_bytes(unsigned char *buf, int num)
  796. {
  797. const RAND_METHOD *meth = RAND_get_rand_method();
  798. if (meth != NULL && meth->bytes != NULL)
  799. return meth->bytes(buf, num);
  800. RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
  801. return -1;
  802. }
  803. #if OPENSSL_API_COMPAT < 0x10100000L
  804. int RAND_pseudo_bytes(unsigned char *buf, int num)
  805. {
  806. const RAND_METHOD *meth = RAND_get_rand_method();
  807. if (meth != NULL && meth->pseudorand != NULL)
  808. return meth->pseudorand(buf, num);
  809. RANDerr(RAND_F_RAND_PSEUDO_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
  810. return -1;
  811. }
  812. #endif
  813. int RAND_status(void)
  814. {
  815. const RAND_METHOD *meth = RAND_get_rand_method();
  816. if (meth != NULL && meth->status != NULL)
  817. return meth->status();
  818. return 0;
  819. }