rand_lib.c 27 KB

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