rand_lib.c 26 KB

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