rand_lib.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. 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 = OPENSSL_zalloc(sizeof(*pool));
  369. size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
  370. if (pool == NULL) {
  371. RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
  372. return NULL;
  373. }
  374. pool->min_len = min_len;
  375. pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
  376. RAND_POOL_MAX_LENGTH : max_len;
  377. pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
  378. if (pool->alloc_len > pool->max_len)
  379. pool->alloc_len = pool->max_len;
  380. if (secure)
  381. pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
  382. else
  383. pool->buffer = OPENSSL_zalloc(pool->alloc_len);
  384. if (pool->buffer == NULL) {
  385. RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
  386. goto err;
  387. }
  388. pool->entropy_requested = entropy_requested;
  389. pool->secure = secure;
  390. return pool;
  391. err:
  392. OPENSSL_free(pool);
  393. return NULL;
  394. }
  395. /*
  396. * Attach new random pool to the given buffer
  397. *
  398. * This function is intended to be used only for feeding random data
  399. * provided by RAND_add() and RAND_seed() into the <master> DRBG.
  400. */
  401. RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
  402. size_t entropy)
  403. {
  404. RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
  405. if (pool == NULL) {
  406. RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
  407. return NULL;
  408. }
  409. /*
  410. * The const needs to be cast away, but attached buffers will not be
  411. * modified (in contrary to allocated buffers which are zeroed and
  412. * freed in the end).
  413. */
  414. pool->buffer = (unsigned char *) buffer;
  415. pool->len = len;
  416. pool->attached = 1;
  417. pool->min_len = pool->max_len = pool->alloc_len = pool->len;
  418. pool->entropy = entropy;
  419. return pool;
  420. }
  421. /*
  422. * Free |pool|, securely erasing its buffer.
  423. */
  424. void rand_pool_free(RAND_POOL *pool)
  425. {
  426. if (pool == NULL)
  427. return;
  428. /*
  429. * Although it would be advisable from a cryptographical viewpoint,
  430. * we are not allowed to clear attached buffers, since they are passed
  431. * to rand_pool_attach() as `const unsigned char*`.
  432. * (see corresponding comment in rand_pool_attach()).
  433. */
  434. if (!pool->attached) {
  435. if (pool->secure)
  436. OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
  437. else
  438. OPENSSL_clear_free(pool->buffer, pool->alloc_len);
  439. }
  440. OPENSSL_free(pool);
  441. }
  442. /*
  443. * Return the |pool|'s buffer to the caller (readonly).
  444. */
  445. const unsigned char *rand_pool_buffer(RAND_POOL *pool)
  446. {
  447. return pool->buffer;
  448. }
  449. /*
  450. * Return the |pool|'s entropy to the caller.
  451. */
  452. size_t rand_pool_entropy(RAND_POOL *pool)
  453. {
  454. return pool->entropy;
  455. }
  456. /*
  457. * Return the |pool|'s buffer length to the caller.
  458. */
  459. size_t rand_pool_length(RAND_POOL *pool)
  460. {
  461. return pool->len;
  462. }
  463. /*
  464. * Detach the |pool| buffer and return it to the caller.
  465. * It's the responsibility of the caller to free the buffer
  466. * using OPENSSL_secure_clear_free() or to re-attach it
  467. * again to the pool using rand_pool_reattach().
  468. */
  469. unsigned char *rand_pool_detach(RAND_POOL *pool)
  470. {
  471. unsigned char *ret = pool->buffer;
  472. pool->buffer = NULL;
  473. pool->entropy = 0;
  474. return ret;
  475. }
  476. /*
  477. * Re-attach the |pool| buffer. It is only allowed to pass
  478. * the |buffer| which was previously detached from the same pool.
  479. */
  480. void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
  481. {
  482. pool->buffer = buffer;
  483. OPENSSL_cleanse(pool->buffer, pool->len);
  484. pool->len = 0;
  485. }
  486. /*
  487. * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
  488. * need to obtain at least |bits| bits of entropy?
  489. */
  490. #define ENTROPY_TO_BYTES(bits, entropy_factor) \
  491. (((bits) * (entropy_factor) + 7) / 8)
  492. /*
  493. * Checks whether the |pool|'s entropy is available to the caller.
  494. * This is the case when entropy count and buffer length are high enough.
  495. * Returns
  496. *
  497. * |entropy| if the entropy count and buffer size is large enough
  498. * 0 otherwise
  499. */
  500. size_t rand_pool_entropy_available(RAND_POOL *pool)
  501. {
  502. if (pool->entropy < pool->entropy_requested)
  503. return 0;
  504. if (pool->len < pool->min_len)
  505. return 0;
  506. return pool->entropy;
  507. }
  508. /*
  509. * Returns the (remaining) amount of entropy needed to fill
  510. * the random pool.
  511. */
  512. size_t rand_pool_entropy_needed(RAND_POOL *pool)
  513. {
  514. if (pool->entropy < pool->entropy_requested)
  515. return pool->entropy_requested - pool->entropy;
  516. return 0;
  517. }
  518. /* Increase the allocation size -- not usable for an attached pool */
  519. static int rand_pool_grow(RAND_POOL *pool, size_t len)
  520. {
  521. if (len > pool->alloc_len - pool->len) {
  522. unsigned char *p;
  523. const size_t limit = pool->max_len / 2;
  524. size_t newlen = pool->alloc_len;
  525. if (pool->attached || len > pool->max_len - pool->len) {
  526. RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_INTERNAL_ERROR);
  527. return 0;
  528. }
  529. do
  530. newlen = newlen < limit ? newlen * 2 : pool->max_len;
  531. while (len > newlen - pool->len);
  532. if (pool->secure)
  533. p = OPENSSL_secure_zalloc(newlen);
  534. else
  535. p = OPENSSL_zalloc(newlen);
  536. if (p == NULL) {
  537. RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_MALLOC_FAILURE);
  538. return 0;
  539. }
  540. memcpy(p, pool->buffer, pool->len);
  541. if (pool->secure)
  542. OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
  543. else
  544. OPENSSL_clear_free(pool->buffer, pool->alloc_len);
  545. pool->buffer = p;
  546. pool->alloc_len = newlen;
  547. }
  548. return 1;
  549. }
  550. /*
  551. * Returns the number of bytes needed to fill the pool, assuming
  552. * the input has 1 / |entropy_factor| entropy bits per data bit.
  553. * In case of an error, 0 is returned.
  554. */
  555. size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
  556. {
  557. size_t bytes_needed;
  558. size_t entropy_needed = rand_pool_entropy_needed(pool);
  559. if (entropy_factor < 1) {
  560. RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
  561. return 0;
  562. }
  563. bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
  564. if (bytes_needed > pool->max_len - pool->len) {
  565. /* not enough space left */
  566. RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
  567. return 0;
  568. }
  569. if (pool->len < pool->min_len &&
  570. bytes_needed < pool->min_len - pool->len)
  571. /* to meet the min_len requirement */
  572. bytes_needed = pool->min_len - pool->len;
  573. /*
  574. * Make sure the buffer is large enough for the requested amount
  575. * of data. This guarantees that existing code patterns where
  576. * rand_pool_add_begin, rand_pool_add_end or rand_pool_add
  577. * are used to collect entropy data without any error handling
  578. * whatsoever, continue to be valid.
  579. * Furthermore if the allocation here fails once, make sure that
  580. * we don't fall back to a less secure or even blocking random source,
  581. * as that could happen by the existing code patterns.
  582. * This is not a concern for additional data, therefore that
  583. * is not needed if rand_pool_grow fails in other places.
  584. */
  585. if (!rand_pool_grow(pool, bytes_needed)) {
  586. /* persistent error for this pool */
  587. pool->max_len = pool->len = 0;
  588. return 0;
  589. }
  590. return bytes_needed;
  591. }
  592. /* Returns the remaining number of bytes available */
  593. size_t rand_pool_bytes_remaining(RAND_POOL *pool)
  594. {
  595. return pool->max_len - pool->len;
  596. }
  597. /*
  598. * Add random bytes to the random pool.
  599. *
  600. * It is expected that the |buffer| contains |len| bytes of
  601. * random input which contains at least |entropy| bits of
  602. * randomness.
  603. *
  604. * Returns 1 if the added amount is adequate, otherwise 0
  605. */
  606. int rand_pool_add(RAND_POOL *pool,
  607. const unsigned char *buffer, size_t len, size_t entropy)
  608. {
  609. if (len > pool->max_len - pool->len) {
  610. RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
  611. return 0;
  612. }
  613. if (pool->buffer == NULL) {
  614. RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
  615. return 0;
  616. }
  617. if (len > 0) {
  618. /*
  619. * This is to protect us from accidentally passing the buffer
  620. * returned from rand_pool_add_begin.
  621. * The check for alloc_len makes sure we do not compare the
  622. * address of the end of the allocated memory to something
  623. * different, since that comparison would have an
  624. * indeterminate result.
  625. */
  626. if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
  627. RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
  628. return 0;
  629. }
  630. /*
  631. * We have that only for cases when a pool is used to collect
  632. * additional data.
  633. * For entropy data, as long as the allocation request stays within
  634. * the limits given by rand_pool_bytes_needed this rand_pool_grow
  635. * below is guaranteed to succeed, thus no allocation happens.
  636. */
  637. if (!rand_pool_grow(pool, len))
  638. return 0;
  639. memcpy(pool->buffer + pool->len, buffer, len);
  640. pool->len += len;
  641. pool->entropy += entropy;
  642. }
  643. return 1;
  644. }
  645. /*
  646. * Start to add random bytes to the random pool in-place.
  647. *
  648. * Reserves the next |len| bytes for adding random bytes in-place
  649. * and returns a pointer to the buffer.
  650. * The caller is allowed to copy up to |len| bytes into the buffer.
  651. * If |len| == 0 this is considered a no-op and a NULL pointer
  652. * is returned without producing an error message.
  653. *
  654. * After updating the buffer, rand_pool_add_end() needs to be called
  655. * to finish the update operation (see next comment).
  656. */
  657. unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
  658. {
  659. if (len == 0)
  660. return NULL;
  661. if (len > pool->max_len - pool->len) {
  662. RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
  663. return NULL;
  664. }
  665. if (pool->buffer == NULL) {
  666. RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
  667. return NULL;
  668. }
  669. /*
  670. * As long as the allocation request stays within the limits given
  671. * by rand_pool_bytes_needed this rand_pool_grow below is guaranteed
  672. * to succeed, thus no allocation happens.
  673. * We have that only for cases when a pool is used to collect
  674. * additional data. Then the buffer might need to grow here,
  675. * and of course the caller is responsible to check the return
  676. * value of this function.
  677. */
  678. if (!rand_pool_grow(pool, len))
  679. return NULL;
  680. return pool->buffer + pool->len;
  681. }
  682. /*
  683. * Finish to add random bytes to the random pool in-place.
  684. *
  685. * Finishes an in-place update of the random pool started by
  686. * rand_pool_add_begin() (see previous comment).
  687. * It is expected that |len| bytes of random input have been added
  688. * to the buffer which contain at least |entropy| bits of randomness.
  689. * It is allowed to add less bytes than originally reserved.
  690. */
  691. int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
  692. {
  693. if (len > pool->alloc_len - pool->len) {
  694. RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
  695. return 0;
  696. }
  697. if (len > 0) {
  698. pool->len += len;
  699. pool->entropy += entropy;
  700. }
  701. return 1;
  702. }
  703. int RAND_set_rand_method(const RAND_METHOD *meth)
  704. {
  705. if (!RUN_ONCE(&rand_init, do_rand_init))
  706. return 0;
  707. CRYPTO_THREAD_write_lock(rand_meth_lock);
  708. #ifndef OPENSSL_NO_ENGINE
  709. ENGINE_finish(funct_ref);
  710. funct_ref = NULL;
  711. #endif
  712. default_RAND_meth = meth;
  713. CRYPTO_THREAD_unlock(rand_meth_lock);
  714. return 1;
  715. }
  716. const RAND_METHOD *RAND_get_rand_method(void)
  717. {
  718. const RAND_METHOD *tmp_meth = NULL;
  719. if (!RUN_ONCE(&rand_init, do_rand_init))
  720. return NULL;
  721. CRYPTO_THREAD_write_lock(rand_meth_lock);
  722. if (default_RAND_meth == NULL) {
  723. #ifndef OPENSSL_NO_ENGINE
  724. ENGINE *e;
  725. /* If we have an engine that can do RAND, use it. */
  726. if ((e = ENGINE_get_default_RAND()) != NULL
  727. && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
  728. funct_ref = e;
  729. default_RAND_meth = tmp_meth;
  730. } else {
  731. ENGINE_finish(e);
  732. default_RAND_meth = &rand_meth;
  733. }
  734. #else
  735. default_RAND_meth = &rand_meth;
  736. #endif
  737. }
  738. tmp_meth = default_RAND_meth;
  739. CRYPTO_THREAD_unlock(rand_meth_lock);
  740. return tmp_meth;
  741. }
  742. #ifndef OPENSSL_NO_ENGINE
  743. int RAND_set_rand_engine(ENGINE *engine)
  744. {
  745. const RAND_METHOD *tmp_meth = NULL;
  746. if (!RUN_ONCE(&rand_init, do_rand_init))
  747. return 0;
  748. if (engine != NULL) {
  749. if (!ENGINE_init(engine))
  750. return 0;
  751. tmp_meth = ENGINE_get_RAND(engine);
  752. if (tmp_meth == NULL) {
  753. ENGINE_finish(engine);
  754. return 0;
  755. }
  756. }
  757. CRYPTO_THREAD_write_lock(rand_engine_lock);
  758. /* This function releases any prior ENGINE so call it first */
  759. RAND_set_rand_method(tmp_meth);
  760. funct_ref = engine;
  761. CRYPTO_THREAD_unlock(rand_engine_lock);
  762. return 1;
  763. }
  764. #endif
  765. void RAND_seed(const void *buf, int num)
  766. {
  767. const RAND_METHOD *meth = RAND_get_rand_method();
  768. if (meth != NULL && meth->seed != NULL)
  769. meth->seed(buf, num);
  770. }
  771. void RAND_add(const void *buf, int num, double randomness)
  772. {
  773. const RAND_METHOD *meth = RAND_get_rand_method();
  774. if (meth != NULL && meth->add != NULL)
  775. meth->add(buf, num, randomness);
  776. }
  777. /*
  778. * This function is not part of RAND_METHOD, so if we're not using
  779. * the default method, then just call RAND_bytes(). Otherwise make
  780. * sure we're instantiated and use the private DRBG.
  781. */
  782. int RAND_priv_bytes(unsigned char *buf, int num)
  783. {
  784. const RAND_METHOD *meth = RAND_get_rand_method();
  785. RAND_DRBG *drbg;
  786. if (meth != NULL && meth != RAND_OpenSSL())
  787. return RAND_bytes(buf, num);
  788. drbg = RAND_DRBG_get0_private();
  789. if (drbg != NULL)
  790. return RAND_DRBG_bytes(drbg, buf, num);
  791. return 0;
  792. }
  793. int RAND_bytes(unsigned char *buf, int num)
  794. {
  795. const RAND_METHOD *meth = RAND_get_rand_method();
  796. if (meth != NULL && meth->bytes != NULL)
  797. return meth->bytes(buf, num);
  798. RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
  799. return -1;
  800. }
  801. #if OPENSSL_API_COMPAT < 0x10100000L
  802. int RAND_pseudo_bytes(unsigned char *buf, int num)
  803. {
  804. const RAND_METHOD *meth = RAND_get_rand_method();
  805. if (meth != NULL && meth->pseudorand != NULL)
  806. return meth->pseudorand(buf, num);
  807. RANDerr(RAND_F_RAND_PSEUDO_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
  808. return -1;
  809. }
  810. #endif
  811. int RAND_status(void)
  812. {
  813. const RAND_METHOD *meth = RAND_get_rand_method();
  814. if (meth != NULL && meth->status != NULL)
  815. return meth->status();
  816. return 0;
  817. }