A local copy of OpenSSL from GitHub
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

654 lines
18 KiB

Deprecate RAND_pseudo_bytes The justification for RAND_pseudo_bytes is somewhat dubious, and the reality is that it is frequently being misused. RAND_bytes and RAND_pseudo_bytes in the default implementation both end up calling ssleay_rand_bytes. Both may return -1 in an error condition. If there is insufficient entropy then both will return 0, but RAND_bytes will additionally add an error to the error queue. They both return 1 on success. Therefore the fundamental difference between the two is that one will add an error to the error queue with insufficient entory whilst the other will not. Frequently there are constructions of this form: if(RAND_pseudo_bytes(...) <= 1) goto err; In the above form insufficient entropy is treated as an error anyway, so RAND_bytes is probably the better form to use. This form is also seen: if(!RAND_pseudo_bytes(...)) goto err; This is technically not correct at all since a -1 return value is incorrectly handled - but this form will also treat insufficient entropy as an error. Within libssl it is required that you have correctly seeded your entropy pool and so there seems little benefit in using RAND_pseudo_bytes. Similarly in libcrypto many operations also require a correctly seeded entropy pool and so in most interesting cases you would be better off using RAND_bytes anyway. There is a significant risk of RAND_pseudo_bytes being incorrectly used in scenarios where security can be compromised by insufficient entropy. If you are not using the default implementation, then most engines use the same function to implement RAND_bytes and RAND_pseudo_bytes in any case. Given its misuse, limited benefit, and potential to compromise security, RAND_pseudo_bytes has been deprecated. Reviewed-by: Richard Levitte <levitte@openssl.org>
8 years ago
Deprecate RAND_pseudo_bytes The justification for RAND_pseudo_bytes is somewhat dubious, and the reality is that it is frequently being misused. RAND_bytes and RAND_pseudo_bytes in the default implementation both end up calling ssleay_rand_bytes. Both may return -1 in an error condition. If there is insufficient entropy then both will return 0, but RAND_bytes will additionally add an error to the error queue. They both return 1 on success. Therefore the fundamental difference between the two is that one will add an error to the error queue with insufficient entory whilst the other will not. Frequently there are constructions of this form: if(RAND_pseudo_bytes(...) <= 1) goto err; In the above form insufficient entropy is treated as an error anyway, so RAND_bytes is probably the better form to use. This form is also seen: if(!RAND_pseudo_bytes(...)) goto err; This is technically not correct at all since a -1 return value is incorrectly handled - but this form will also treat insufficient entropy as an error. Within libssl it is required that you have correctly seeded your entropy pool and so there seems little benefit in using RAND_pseudo_bytes. Similarly in libcrypto many operations also require a correctly seeded entropy pool and so in most interesting cases you would be better off using RAND_bytes anyway. There is a significant risk of RAND_pseudo_bytes being incorrectly used in scenarios where security can be compromised by insufficient entropy. If you are not using the default implementation, then most engines use the same function to implement RAND_bytes and RAND_pseudo_bytes in any case. Given its misuse, limited benefit, and potential to compromise security, RAND_pseudo_bytes has been deprecated. Reviewed-by: Richard Levitte <levitte@openssl.org>
8 years ago
23 years ago
23 years ago
Deprecate RAND_pseudo_bytes The justification for RAND_pseudo_bytes is somewhat dubious, and the reality is that it is frequently being misused. RAND_bytes and RAND_pseudo_bytes in the default implementation both end up calling ssleay_rand_bytes. Both may return -1 in an error condition. If there is insufficient entropy then both will return 0, but RAND_bytes will additionally add an error to the error queue. They both return 1 on success. Therefore the fundamental difference between the two is that one will add an error to the error queue with insufficient entory whilst the other will not. Frequently there are constructions of this form: if(RAND_pseudo_bytes(...) <= 1) goto err; In the above form insufficient entropy is treated as an error anyway, so RAND_bytes is probably the better form to use. This form is also seen: if(!RAND_pseudo_bytes(...)) goto err; This is technically not correct at all since a -1 return value is incorrectly handled - but this form will also treat insufficient entropy as an error. Within libssl it is required that you have correctly seeded your entropy pool and so there seems little benefit in using RAND_pseudo_bytes. Similarly in libcrypto many operations also require a correctly seeded entropy pool and so in most interesting cases you would be better off using RAND_bytes anyway. There is a significant risk of RAND_pseudo_bytes being incorrectly used in scenarios where security can be compromised by insufficient entropy. If you are not using the default implementation, then most engines use the same function to implement RAND_bytes and RAND_pseudo_bytes in any case. Given its misuse, limited benefit, and potential to compromise security, RAND_pseudo_bytes has been deprecated. Reviewed-by: Richard Levitte <levitte@openssl.org>
8 years ago
  1. /*
  2. * Copyright 1995-2016 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 <string.h>
  11. #include "e_os.h"
  12. #if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
  13. # include <sys/time.h>
  14. #endif
  15. #if defined(OPENSSL_SYS_VXWORKS)
  16. # include <time.h>
  17. #endif
  18. #include <openssl/opensslconf.h>
  19. #include <openssl/crypto.h>
  20. #include <openssl/rand.h>
  21. #include <openssl/async.h>
  22. #include "rand_lcl.h"
  23. #include <openssl/err.h>
  24. #ifdef OPENSSL_FIPS
  25. # include <openssl/fips.h>
  26. #endif
  27. #ifdef BN_DEBUG
  28. # define PREDICT
  29. #endif
  30. /* #define PREDICT 1 */
  31. #define STATE_SIZE 1023
  32. static int state_num = 0, state_index = 0;
  33. static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
  34. static unsigned char md[MD_DIGEST_LENGTH];
  35. static long md_count[2] = { 0, 0 };
  36. static double entropy = 0;
  37. static int initialized = 0;
  38. static CRYPTO_RWLOCK *rand_lock = NULL;
  39. static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
  40. static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
  41. /* May be set only when a thread holds rand_lock (to prevent double locking) */
  42. static unsigned int crypto_lock_rand = 0;
  43. /* access to locking_threadid is synchronized by rand_tmp_lock */
  44. /* valid iff crypto_lock_rand is set */
  45. static CRYPTO_THREAD_ID locking_threadid;
  46. #ifdef PREDICT
  47. int rand_predictable = 0;
  48. #endif
  49. static void rand_hw_seed(EVP_MD_CTX *ctx);
  50. static void rand_cleanup(void);
  51. static int rand_seed(const void *buf, int num);
  52. static int rand_add(const void *buf, int num, double add_entropy);
  53. static int rand_bytes(unsigned char *buf, int num, int pseudo);
  54. static int rand_nopseudo_bytes(unsigned char *buf, int num);
  55. #if OPENSSL_API_COMPAT < 0x10100000L
  56. static int rand_pseudo_bytes(unsigned char *buf, int num);
  57. #endif
  58. static int rand_status(void);
  59. static RAND_METHOD rand_meth = {
  60. rand_seed,
  61. rand_nopseudo_bytes,
  62. rand_cleanup,
  63. rand_add,
  64. #if OPENSSL_API_COMPAT < 0x10100000L
  65. rand_pseudo_bytes,
  66. #else
  67. NULL,
  68. #endif
  69. rand_status
  70. };
  71. static void do_rand_lock_init(void)
  72. {
  73. rand_lock = CRYPTO_THREAD_lock_new();
  74. rand_tmp_lock = CRYPTO_THREAD_lock_new();
  75. }
  76. RAND_METHOD *RAND_OpenSSL(void)
  77. {
  78. return (&rand_meth);
  79. }
  80. static void rand_cleanup(void)
  81. {
  82. OPENSSL_cleanse(state, sizeof(state));
  83. state_num = 0;
  84. state_index = 0;
  85. OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
  86. md_count[0] = 0;
  87. md_count[1] = 0;
  88. entropy = 0;
  89. initialized = 0;
  90. CRYPTO_THREAD_lock_free(rand_lock);
  91. CRYPTO_THREAD_lock_free(rand_tmp_lock);
  92. }
  93. static int rand_add(const void *buf, int num, double add)
  94. {
  95. int i, j, k, st_idx;
  96. long md_c[2];
  97. unsigned char local_md[MD_DIGEST_LENGTH];
  98. EVP_MD_CTX *m;
  99. int do_not_lock;
  100. int rv = 0;
  101. if (!num)
  102. return 1;
  103. /*
  104. * (Based on the rand(3) manpage)
  105. *
  106. * The input is chopped up into units of 20 bytes (or less for
  107. * the last block). Each of these blocks is run through the hash
  108. * function as follows: The data passed to the hash function
  109. * is the current 'md', the same number of bytes from the 'state'
  110. * (the location determined by in incremented looping index) as
  111. * the current 'block', the new key data 'block', and 'count'
  112. * (which is incremented after each use).
  113. * The result of this is kept in 'md' and also xored into the
  114. * 'state' at the same locations that were used as input into the
  115. * hash function.
  116. */
  117. m = EVP_MD_CTX_new();
  118. if (m == NULL)
  119. goto err;
  120. CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
  121. /* check if we already have the lock */
  122. if (crypto_lock_rand) {
  123. CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
  124. CRYPTO_THREAD_read_lock(rand_tmp_lock);
  125. do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
  126. CRYPTO_THREAD_unlock(rand_tmp_lock);
  127. } else
  128. do_not_lock = 0;
  129. if (!do_not_lock)
  130. CRYPTO_THREAD_write_lock(rand_lock);
  131. st_idx = state_index;
  132. /*
  133. * use our own copies of the counters so that even if a concurrent thread
  134. * seeds with exactly the same data and uses the same subarray there's
  135. * _some_ difference
  136. */
  137. md_c[0] = md_count[0];
  138. md_c[1] = md_count[1];
  139. memcpy(local_md, md, sizeof md);
  140. /* state_index <= state_num <= STATE_SIZE */
  141. state_index += num;
  142. if (state_index >= STATE_SIZE) {
  143. state_index %= STATE_SIZE;
  144. state_num = STATE_SIZE;
  145. } else if (state_num < STATE_SIZE) {
  146. if (state_index > state_num)
  147. state_num = state_index;
  148. }
  149. /* state_index <= state_num <= STATE_SIZE */
  150. /*
  151. * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
  152. * will use now, but other threads may use them as well
  153. */
  154. md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
  155. if (!do_not_lock)
  156. CRYPTO_THREAD_unlock(rand_lock);
  157. for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
  158. j = (num - i);
  159. j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
  160. if (!MD_Init(m))
  161. goto err;
  162. if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
  163. goto err;
  164. k = (st_idx + j) - STATE_SIZE;
  165. if (k > 0) {
  166. if (!MD_Update(m, &(state[st_idx]), j - k))
  167. goto err;
  168. if (!MD_Update(m, &(state[0]), k))
  169. goto err;
  170. } else if (!MD_Update(m, &(state[st_idx]), j))
  171. goto err;
  172. /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
  173. if (!MD_Update(m, buf, j))
  174. goto err;
  175. /*
  176. * We know that line may cause programs such as purify and valgrind
  177. * to complain about use of uninitialized data. The problem is not,
  178. * it's with the caller. Removing that line will make sure you get
  179. * really bad randomness and thereby other problems such as very
  180. * insecure keys.
  181. */
  182. if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
  183. goto err;
  184. if (!MD_Final(m, local_md))
  185. goto err;
  186. md_c[1]++;
  187. buf = (const char *)buf + j;
  188. for (k = 0; k < j; k++) {
  189. /*
  190. * Parallel threads may interfere with this, but always each byte
  191. * of the new state is the XOR of some previous value of its and
  192. * local_md (intermediate values may be lost). Alway using locking
  193. * could hurt performance more than necessary given that
  194. * conflicts occur only when the total seeding is longer than the
  195. * random state.
  196. */
  197. state[st_idx++] ^= local_md[k];
  198. if (st_idx >= STATE_SIZE)
  199. st_idx = 0;
  200. }
  201. }
  202. if (!do_not_lock)
  203. CRYPTO_THREAD_write_lock(rand_lock);
  204. /*
  205. * Don't just copy back local_md into md -- this could mean that other
  206. * thread's seeding remains without effect (except for the incremented
  207. * counter). By XORing it we keep at least as much entropy as fits into
  208. * md.
  209. */
  210. for (k = 0; k < (int)sizeof(md); k++) {
  211. md[k] ^= local_md[k];
  212. }
  213. if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
  214. entropy += add;
  215. if (!do_not_lock)
  216. CRYPTO_THREAD_unlock(rand_lock);
  217. rv = 1;
  218. err:
  219. EVP_MD_CTX_free(m);
  220. return rv;
  221. }
  222. static int rand_seed(const void *buf, int num)
  223. {
  224. return rand_add(buf, num, (double)num);
  225. }
  226. static int rand_bytes(unsigned char *buf, int num, int pseudo)
  227. {
  228. static volatile int stirred_pool = 0;
  229. int i, j, k, st_num, st_idx;
  230. int num_ceil;
  231. int ok;
  232. long md_c[2];
  233. unsigned char local_md[MD_DIGEST_LENGTH];
  234. EVP_MD_CTX *m;
  235. #ifndef GETPID_IS_MEANINGLESS
  236. pid_t curr_pid = getpid();
  237. #endif
  238. time_t curr_time = time(NULL);
  239. int do_stir_pool = 0;
  240. /* time value for various platforms */
  241. #ifdef OPENSSL_SYS_WIN32
  242. FILETIME tv;
  243. # ifdef _WIN32_WCE
  244. SYSTEMTIME t;
  245. GetSystemTime(&t);
  246. SystemTimeToFileTime(&t, &tv);
  247. # else
  248. GetSystemTimeAsFileTime(&tv);
  249. # endif
  250. #elif defined(OPENSSL_SYS_VXWORKS)
  251. struct timespec tv;
  252. clock_gettime(CLOCK_REALTIME, &ts);
  253. #elif defined(OPENSSL_SYS_DSPBIOS)
  254. unsigned long long tv, OPENSSL_rdtsc();
  255. tv = OPENSSL_rdtsc();
  256. #else
  257. struct timeval tv;
  258. gettimeofday(&tv, NULL);
  259. #endif
  260. #ifdef PREDICT
  261. if (rand_predictable) {
  262. static unsigned char val = 0;
  263. for (i = 0; i < num; i++)
  264. buf[i] = val++;
  265. return (1);
  266. }
  267. #endif
  268. if (num <= 0)
  269. return 1;
  270. m = EVP_MD_CTX_new();
  271. if (m == NULL)
  272. goto err_mem;
  273. /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
  274. num_ceil =
  275. (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
  276. /*
  277. * (Based on the rand(3) manpage:)
  278. *
  279. * For each group of 10 bytes (or less), we do the following:
  280. *
  281. * Input into the hash function the local 'md' (which is initialized from
  282. * the global 'md' before any bytes are generated), the bytes that are to
  283. * be overwritten by the random bytes, and bytes from the 'state'
  284. * (incrementing looping index). From this digest output (which is kept
  285. * in 'md'), the top (up to) 10 bytes are returned to the caller and the
  286. * bottom 10 bytes are xored into the 'state'.
  287. *
  288. * Finally, after we have finished 'num' random bytes for the
  289. * caller, 'count' (which is incremented) and the local and global 'md'
  290. * are fed into the hash function and the results are kept in the
  291. * global 'md'.
  292. */
  293. CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
  294. CRYPTO_THREAD_write_lock(rand_lock);
  295. /*
  296. * We could end up in an async engine while holding this lock so ensure
  297. * we don't pause and cause a deadlock
  298. */
  299. ASYNC_block_pause();
  300. /* prevent rand_bytes() from trying to obtain the lock again */
  301. CRYPTO_THREAD_write_lock(rand_tmp_lock);
  302. locking_threadid = CRYPTO_THREAD_get_current_id();
  303. CRYPTO_THREAD_unlock(rand_tmp_lock);
  304. crypto_lock_rand = 1;
  305. if (!initialized) {
  306. RAND_poll();
  307. initialized = 1;
  308. }
  309. if (!stirred_pool)
  310. do_stir_pool = 1;
  311. ok = (entropy >= ENTROPY_NEEDED);
  312. if (!ok) {
  313. /*
  314. * If the PRNG state is not yet unpredictable, then seeing the PRNG
  315. * output may help attackers to determine the new state; thus we have
  316. * to decrease the entropy estimate. Once we've had enough initial
  317. * seeding we don't bother to adjust the entropy count, though,
  318. * because we're not ambitious to provide *information-theoretic*
  319. * randomness. NOTE: This approach fails if the program forks before
  320. * we have enough entropy. Entropy should be collected in a separate
  321. * input pool and be transferred to the output pool only when the
  322. * entropy limit has been reached.
  323. */
  324. entropy -= num;
  325. if (entropy < 0)
  326. entropy = 0;
  327. }
  328. if (do_stir_pool) {
  329. /*
  330. * In the output function only half of 'md' remains secret, so we
  331. * better make sure that the required entropy gets 'evenly
  332. * distributed' through 'state', our randomness pool. The input
  333. * function (rand_add) chains all of 'md', which makes it more
  334. * suitable for this purpose.
  335. */
  336. int n = STATE_SIZE; /* so that the complete pool gets accessed */
  337. while (n > 0) {
  338. #if MD_DIGEST_LENGTH > 20
  339. # error "Please adjust DUMMY_SEED."
  340. #endif
  341. #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
  342. /*
  343. * Note that the seed does not matter, it's just that
  344. * rand_add expects to have something to hash.
  345. */
  346. rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
  347. n -= MD_DIGEST_LENGTH;
  348. }
  349. if (ok)
  350. stirred_pool = 1;
  351. }
  352. st_idx = state_index;
  353. st_num = state_num;
  354. md_c[0] = md_count[0];
  355. md_c[1] = md_count[1];
  356. memcpy(local_md, md, sizeof md);
  357. state_index += num_ceil;
  358. if (state_index > state_num)
  359. state_index %= state_num;
  360. /*
  361. * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
  362. * ours (but other threads may use them too)
  363. */
  364. md_count[0] += 1;
  365. /* before unlocking, we must clear 'crypto_lock_rand' */
  366. crypto_lock_rand = 0;
  367. ASYNC_unblock_pause();
  368. CRYPTO_THREAD_unlock(rand_lock);
  369. while (num > 0) {
  370. /* num_ceil -= MD_DIGEST_LENGTH/2 */
  371. j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
  372. num -= j;
  373. if (!MD_Init(m))
  374. goto err;
  375. #ifndef GETPID_IS_MEANINGLESS
  376. if (curr_pid) { /* just in the first iteration to save time */
  377. if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
  378. goto err;
  379. curr_pid = 0;
  380. }
  381. #endif
  382. if (curr_time) { /* just in the first iteration to save time */
  383. if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
  384. goto err;
  385. if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
  386. goto err;
  387. curr_time = 0;
  388. rand_hw_seed(m);
  389. }
  390. if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
  391. goto err;
  392. if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
  393. goto err;
  394. k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
  395. if (k > 0) {
  396. if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
  397. goto err;
  398. if (!MD_Update(m, &(state[0]), k))
  399. goto err;
  400. } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
  401. goto err;
  402. if (!MD_Final(m, local_md))
  403. goto err;
  404. for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
  405. /* may compete with other threads */
  406. state[st_idx++] ^= local_md[i];
  407. if (st_idx >= st_num)
  408. st_idx = 0;
  409. if (i < j)
  410. *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
  411. }
  412. }
  413. if (!MD_Init(m)
  414. || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
  415. || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
  416. goto err;
  417. CRYPTO_THREAD_write_lock(rand_lock);
  418. /*
  419. * Prevent deadlocks if we end up in an async engine
  420. */
  421. ASYNC_block_pause();
  422. if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
  423. CRYPTO_THREAD_unlock(rand_lock);
  424. goto err;
  425. }
  426. ASYNC_unblock_pause();
  427. CRYPTO_THREAD_unlock(rand_lock);
  428. EVP_MD_CTX_free(m);
  429. if (ok)
  430. return (1);
  431. else if (pseudo)
  432. return 0;
  433. else {
  434. RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
  435. ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
  436. "https://www.openssl.org/docs/faq.html");
  437. return (0);
  438. }
  439. err:
  440. RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
  441. EVP_MD_CTX_free(m);
  442. return 0;
  443. err_mem:
  444. RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
  445. EVP_MD_CTX_free(m);
  446. return 0;
  447. }
  448. static int rand_nopseudo_bytes(unsigned char *buf, int num)
  449. {
  450. return rand_bytes(buf, num, 0);
  451. }
  452. #if OPENSSL_API_COMPAT < 0x10100000L
  453. /*
  454. * pseudo-random bytes that are guaranteed to be unique but not unpredictable
  455. */
  456. static int rand_pseudo_bytes(unsigned char *buf, int num)
  457. {
  458. return rand_bytes(buf, num, 1);
  459. }
  460. #endif
  461. static int rand_status(void)
  462. {
  463. CRYPTO_THREAD_ID cur;
  464. int ret;
  465. int do_not_lock;
  466. CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
  467. cur = CRYPTO_THREAD_get_current_id();
  468. /*
  469. * check if we already have the lock (could happen if a RAND_poll()
  470. * implementation calls RAND_status())
  471. */
  472. if (crypto_lock_rand) {
  473. CRYPTO_THREAD_read_lock(rand_tmp_lock);
  474. do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
  475. CRYPTO_THREAD_unlock(rand_tmp_lock);
  476. } else
  477. do_not_lock = 0;
  478. if (!do_not_lock) {
  479. CRYPTO_THREAD_write_lock(rand_lock);
  480. /*
  481. * Prevent deadlocks in case we end up in an async engine
  482. */
  483. ASYNC_block_pause();
  484. /*
  485. * prevent rand_bytes() from trying to obtain the lock again
  486. */
  487. CRYPTO_THREAD_write_lock(rand_tmp_lock);
  488. locking_threadid = cur;
  489. CRYPTO_THREAD_unlock(rand_tmp_lock);
  490. crypto_lock_rand = 1;
  491. }
  492. if (!initialized) {
  493. RAND_poll();
  494. initialized = 1;
  495. }
  496. ret = entropy >= ENTROPY_NEEDED;
  497. if (!do_not_lock) {
  498. /* before unlocking, we must clear 'crypto_lock_rand' */
  499. crypto_lock_rand = 0;
  500. ASYNC_unblock_pause();
  501. CRYPTO_THREAD_unlock(rand_lock);
  502. }
  503. return ret;
  504. }
  505. /*
  506. * rand_hw_seed: get seed data from any available hardware RNG. only
  507. * currently supports rdrand.
  508. */
  509. /* Adapted from eng_rdrand.c */
  510. #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
  511. defined(__x86_64) || defined(__x86_64__) || \
  512. defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
  513. && !defined(OPENSSL_NO_RDRAND)
  514. # define RDRAND_CALLS 4
  515. size_t OPENSSL_ia32_rdrand(void);
  516. extern unsigned int OPENSSL_ia32cap_P[];
  517. static void rand_hw_seed(EVP_MD_CTX *ctx)
  518. {
  519. int i;
  520. if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
  521. return;
  522. for (i = 0; i < RDRAND_CALLS; i++) {
  523. size_t rnd;
  524. rnd = OPENSSL_ia32_rdrand();
  525. if (rnd == 0)
  526. return;
  527. MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
  528. }
  529. }
  530. /* XOR an existing buffer with random data */
  531. void rand_hw_xor(unsigned char *buf, size_t num)
  532. {
  533. size_t rnd;
  534. if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
  535. return;
  536. while (num >= sizeof(size_t)) {
  537. rnd = OPENSSL_ia32_rdrand();
  538. if (rnd == 0)
  539. return;
  540. *((size_t *)buf) ^= rnd;
  541. buf += sizeof(size_t);
  542. num -= sizeof(size_t);
  543. }
  544. if (num) {
  545. rnd = OPENSSL_ia32_rdrand();
  546. if (rnd == 0)
  547. return;
  548. while (num) {
  549. *buf ^= rnd & 0xff;
  550. rnd >>= 8;
  551. buf++;
  552. num--;
  553. }
  554. }
  555. }
  556. #else
  557. static void rand_hw_seed(EVP_MD_CTX *ctx)
  558. {
  559. return;
  560. }
  561. void rand_hw_xor(unsigned char *buf, size_t num)
  562. {
  563. return;
  564. }
  565. #endif