crypto_rand.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_rand.c
  8. *
  9. * \brief Functions for initialising and seeding (pseudo-)random
  10. * number generators, and working with randomness.
  11. **/
  12. #ifndef CRYPTO_RAND_PRIVATE
  13. #define CRYPTO_RAND_PRIVATE
  14. #include "lib/crypt_ops/crypto_rand.h"
  15. #ifdef _WIN32
  16. #include <windows.h>
  17. #include <wincrypt.h>
  18. #endif /* defined(_WIN32) */
  19. #include "lib/container/smartlist.h"
  20. #include "lib/crypt_ops/compat_openssl.h"
  21. #include "lib/crypt_ops/crypto_util.h"
  22. #include "lib/encoding/binascii.h"
  23. #include "lib/intmath/weakrng.h"
  24. #include "lib/log/log.h"
  25. #include "lib/log/util_bug.h"
  26. #include "lib/malloc/malloc.h"
  27. #include "lib/sandbox/sandbox.h"
  28. #include "lib/string/compat_string.h"
  29. #include "lib/string/util_string.h"
  30. #include "lib/testsupport/testsupport.h"
  31. #include "lib/fs/files.h"
  32. #include "lib/defs/digest_sizes.h"
  33. #include "lib/crypt_ops/crypto_digest.h"
  34. #ifdef ENABLE_NSS
  35. #include "lib/crypt_ops/crypto_nss_mgt.h"
  36. #endif
  37. #ifdef ENABLE_OPENSSL
  38. DISABLE_GCC_WARNING(redundant-decls)
  39. #include <openssl/rand.h>
  40. ENABLE_GCC_WARNING(redundant-decls)
  41. #endif
  42. #ifdef ENABLE_NSS
  43. #include <pk11pub.h>
  44. #include <secerr.h>
  45. #include <prerror.h>
  46. #endif
  47. #if __GNUC__ && GCC_VERSION >= 402
  48. #if GCC_VERSION >= 406
  49. #pragma GCC diagnostic pop
  50. #else
  51. #pragma GCC diagnostic warning "-Wredundant-decls"
  52. #endif
  53. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  54. #ifdef HAVE_FCNTL_H
  55. #include <fcntl.h>
  56. #endif
  57. #ifdef HAVE_SYS_FCNTL_H
  58. #include <sys/fcntl.h>
  59. #endif
  60. #ifdef HAVE_SYS_STAT_H
  61. #include <sys/stat.h>
  62. #endif
  63. #ifdef HAVE_UNISTD_H
  64. #include <unistd.h>
  65. #endif
  66. #ifdef HAVE_SYS_SYSCALL_H
  67. #include <sys/syscall.h>
  68. #endif
  69. #ifdef HAVE_SYS_RANDOM_H
  70. #include <sys/random.h>
  71. #endif
  72. #include <string.h>
  73. #include <errno.h>
  74. /**
  75. * How many bytes of entropy we add at once.
  76. *
  77. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  78. * work for us too.
  79. **/
  80. #define ADD_ENTROPY 32
  81. /**
  82. * Longest recognized DNS query.
  83. **/
  84. #define MAX_DNS_LABEL_SIZE 63
  85. /**
  86. * Largest strong entropy request permitted.
  87. **/
  88. #define MAX_STRONGEST_RAND_SIZE 256
  89. /**
  90. * Set the seed of the weak RNG to a random value.
  91. **/
  92. void
  93. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  94. {
  95. unsigned seed;
  96. crypto_rand((void*)&seed, sizeof(seed));
  97. tor_init_weak_random(rng, seed);
  98. }
  99. #ifdef TOR_UNIT_TESTS
  100. int break_strongest_rng_syscall = 0;
  101. int break_strongest_rng_fallback = 0;
  102. #endif
  103. /**
  104. * Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  105. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  106. * failure. A maximum request size of 256 bytes is imposed.
  107. **/
  108. static int
  109. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  110. {
  111. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  112. /* We only log at notice-level here because in the case that this function
  113. * fails the crypto_strongest_rand_raw() caller will log with a warning-level
  114. * message and let crypto_strongest_rand() error out and finally terminating
  115. * Tor with an assertion error.
  116. */
  117. #ifdef TOR_UNIT_TESTS
  118. if (break_strongest_rng_syscall)
  119. return -1;
  120. #endif
  121. #if defined(_WIN32)
  122. static int provider_set = 0;
  123. static HCRYPTPROV provider;
  124. if (!provider_set) {
  125. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  126. CRYPT_VERIFYCONTEXT)) {
  127. log_notice(LD_CRYPTO, "Unable to set Windows CryptoAPI provider [1].");
  128. return -1;
  129. }
  130. provider_set = 1;
  131. }
  132. if (!CryptGenRandom(provider, out_len, out)) {
  133. log_notice(LD_CRYPTO, "Unable get entropy from the Windows CryptoAPI.");
  134. return -1;
  135. }
  136. return 0;
  137. #elif defined(__linux__) && defined(SYS_getrandom)
  138. static int getrandom_works = 1; /* Be optimistic about our chances... */
  139. /* getrandom() isn't as straightforward as getentropy(), and has
  140. * no glibc wrapper.
  141. *
  142. * As far as I can tell from getrandom(2) and the source code, the
  143. * requests we issue will always succeed (though it will block on the
  144. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  145. * GRND_NONBLOCK and the request is <= 256 bytes.
  146. *
  147. * The manpage is unclear on what happens if a signal interrupts the call
  148. * while the request is blocked due to lack of entropy....
  149. *
  150. * We optimistically assume that getrandom() is available and functional
  151. * because it is the way of the future, and 2 branch mispredicts pale in
  152. * comparison to the overheads involved with failing to open
  153. * /dev/srandom followed by opening and reading from /dev/urandom.
  154. */
  155. if (PREDICT_LIKELY(getrandom_works)) {
  156. long ret;
  157. /* A flag of '0' here means to read from '/dev/urandom', and to
  158. * block if insufficient entropy is available to service the
  159. * request.
  160. */
  161. const unsigned int flags = 0;
  162. do {
  163. ret = syscall(SYS_getrandom, out, out_len, flags);
  164. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  165. if (PREDICT_UNLIKELY(ret == -1)) {
  166. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  167. tor_assert(errno != EAGAIN);
  168. tor_assert(errno != EINTR);
  169. /* Useful log message for errno. */
  170. if (errno == ENOSYS) {
  171. log_notice(LD_CRYPTO, "Can't get entropy from getrandom()."
  172. " You are running a version of Tor built to support"
  173. " getrandom(), but the kernel doesn't implement this"
  174. " function--probably because it is too old?"
  175. " Trying fallback method instead.");
  176. } else {
  177. log_notice(LD_CRYPTO, "Can't get entropy from getrandom(): %s."
  178. " Trying fallback method instead.",
  179. strerror(errno));
  180. }
  181. getrandom_works = 0; /* Don't bother trying again. */
  182. return -1;
  183. /* LCOV_EXCL_STOP */
  184. }
  185. tor_assert(ret == (long)out_len);
  186. return 0;
  187. }
  188. return -1; /* getrandom() previously failed unexpectedly. */
  189. #elif defined(HAVE_GETENTROPY)
  190. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  191. * the only gotcha is that requests are limited to 256 bytes.
  192. */
  193. return getentropy(out, out_len);
  194. #else
  195. (void) out;
  196. #endif /* defined(_WIN32) || ... */
  197. /* This platform doesn't have a supported syscall based random. */
  198. return -1;
  199. }
  200. /**
  201. * Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  202. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  203. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  204. * is imposed.
  205. **/
  206. static int
  207. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  208. {
  209. #ifdef TOR_UNIT_TESTS
  210. if (break_strongest_rng_fallback)
  211. return -1;
  212. #endif
  213. #ifdef _WIN32
  214. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  215. (void)out;
  216. (void)out_len;
  217. return -1;
  218. #else /* !(defined(_WIN32)) */
  219. static const char *filenames[] = {
  220. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  221. };
  222. int fd, i;
  223. size_t n;
  224. for (i = 0; filenames[i]; ++i) {
  225. log_debug(LD_FS, "Considering %s as entropy source", filenames[i]);
  226. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  227. if (fd<0) continue;
  228. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  229. n = read_all_from_fd(fd, (char*)out, out_len);
  230. close(fd);
  231. if (n != out_len) {
  232. /* LCOV_EXCL_START
  233. * We can't make /dev/foorandom actually fail. */
  234. log_notice(LD_CRYPTO,
  235. "Error reading from entropy source %s (read only %lu bytes).",
  236. filenames[i],
  237. (unsigned long)n);
  238. return -1;
  239. /* LCOV_EXCL_STOP */
  240. }
  241. return 0;
  242. }
  243. return -1;
  244. #endif /* defined(_WIN32) */
  245. }
  246. /**
  247. * Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  248. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  249. * request size of 256 bytes is imposed.
  250. **/
  251. STATIC int
  252. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  253. {
  254. static const size_t sanity_min_size = 16;
  255. static const int max_attempts = 3;
  256. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  257. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  258. * zero filling the buffer and ensuring that it actually was at least
  259. * partially modified.
  260. *
  261. * Checking that any individual byte is non-zero seems like it would
  262. * fail too often (p = out_len * 1/256) for comfort, but this is an
  263. * "adjust according to taste" sort of check.
  264. */
  265. memwipe(out, 0, out_len);
  266. for (int i = 0; i < max_attempts; i++) {
  267. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  268. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  269. /* Try to use the less-favored mechanism to get strong entropy. */
  270. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  271. /* Welp, we tried. Hopefully the calling code terminates the process
  272. * since we're basically boned without good entropy.
  273. */
  274. log_warn(LD_CRYPTO,
  275. "Cannot get strong entropy: no entropy source found.");
  276. return -1;
  277. }
  278. }
  279. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  280. return 0;
  281. }
  282. /* LCOV_EXCL_START
  283. *
  284. * We tried max_attempts times to fill a buffer >= 128 bits long,
  285. * and each time it returned all '0's. Either the system entropy
  286. * source is busted, or the user should go out and buy a ticket to
  287. * every lottery on the planet.
  288. */
  289. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  290. return -1;
  291. /* LCOV_EXCL_STOP */
  292. }
  293. /**
  294. * Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  295. * storing it into <b>out</b>.
  296. **/
  297. void
  298. crypto_strongest_rand(uint8_t *out, size_t out_len)
  299. {
  300. crypto_strongest_rand_(out, out_len);
  301. }
  302. /**
  303. * Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  304. * storing it into <b>out</b>. (Mockable version.)
  305. **/
  306. MOCK_IMPL(void,
  307. crypto_strongest_rand_,(uint8_t *out, size_t out_len))
  308. {
  309. #define DLEN DIGEST512_LEN
  310. /* We're going to hash DLEN bytes from the system RNG together with some
  311. * bytes from the PRNGs from our crypto librar(y/ies), in order to yield
  312. * DLEN bytes.
  313. */
  314. uint8_t inp[DLEN*3];
  315. uint8_t tmp[DLEN];
  316. tor_assert(out);
  317. while (out_len) {
  318. memset(inp, 0, sizeof(inp));
  319. #ifdef ENABLE_OPENSSL
  320. RAND_bytes(inp, DLEN);
  321. #endif
  322. #ifdef ENABLE_NSS
  323. PK11_GenerateRandom(inp+DLEN, DLEN);
  324. #endif
  325. if (crypto_strongest_rand_raw(inp+DLEN*2, DLEN) < 0) {
  326. // LCOV_EXCL_START
  327. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  328. "important key. Exiting.");
  329. /* Die with an assertion so we get a stack trace. */
  330. tor_assert(0);
  331. // LCOV_EXCL_STOP
  332. }
  333. if (out_len >= DLEN) {
  334. crypto_digest512((char*)out, (char*)inp, sizeof(inp), DIGEST_SHA512);
  335. out += DLEN;
  336. out_len -= DLEN;
  337. } else {
  338. crypto_digest512((char*)tmp, (char*)inp, sizeof(inp), DIGEST_SHA512);
  339. memcpy(out, tmp, out_len);
  340. break;
  341. }
  342. }
  343. memwipe(tmp, 0, sizeof(tmp));
  344. memwipe(inp, 0, sizeof(inp));
  345. #undef DLEN
  346. }
  347. #ifdef ENABLE_OPENSSL
  348. /**
  349. * Seed OpenSSL's random number generator with bytes from the operating
  350. * system. Return 0 on success, -1 on failure.
  351. **/
  352. static int
  353. crypto_seed_openssl_rng(void)
  354. {
  355. int rand_poll_ok = 0, load_entropy_ok = 0;
  356. uint8_t buf[ADD_ENTROPY];
  357. /* OpenSSL has a RAND_poll function that knows about more kinds of
  358. * entropy than we do. We'll try calling that, *and* calling our own entropy
  359. * functions. If one succeeds, we'll accept the RNG as seeded. */
  360. rand_poll_ok = RAND_poll();
  361. if (rand_poll_ok == 0)
  362. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  363. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  364. if (load_entropy_ok) {
  365. RAND_seed(buf, sizeof(buf));
  366. }
  367. memwipe(buf, 0, sizeof(buf));
  368. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  369. return 0;
  370. else
  371. return -1;
  372. }
  373. #endif
  374. #ifdef ENABLE_NSS
  375. /**
  376. * Seed OpenSSL's random number generator with bytes from the operating
  377. * system. Return 0 on success, -1 on failure.
  378. **/
  379. static int
  380. crypto_seed_nss_rng(void)
  381. {
  382. uint8_t buf[ADD_ENTROPY];
  383. int load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  384. if (load_entropy_ok) {
  385. if (PK11_RandomUpdate(buf, sizeof(buf)) != SECSuccess) {
  386. load_entropy_ok = 0;
  387. }
  388. }
  389. memwipe(buf, 0, sizeof(buf));
  390. return load_entropy_ok ? 0 : -1;
  391. }
  392. #endif
  393. /**
  394. * Seed the RNG for any and all crypto libraries that we're using with bytes
  395. * from the operating system. Return 0 on success, -1 on failure.
  396. */
  397. int
  398. crypto_seed_rng(void)
  399. {
  400. int seeded = 0;
  401. #ifdef ENABLE_NSS
  402. if (crypto_seed_nss_rng() < 0)
  403. return -1;
  404. ++seeded;
  405. #endif
  406. #ifdef ENABLE_OPENSSL
  407. if (crypto_seed_openssl_rng() < 0)
  408. return -1;
  409. ++seeded;
  410. #endif
  411. tor_assert(seeded);
  412. return 0;
  413. }
  414. /**
  415. * Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  416. * for unit tests.
  417. *
  418. * This function is not allowed to fail; if it would fail to generate strong
  419. * entropy, it must terminate the process instead.
  420. **/
  421. MOCK_IMPL(void,
  422. crypto_rand, (char *to, size_t n))
  423. {
  424. crypto_rand_unmocked(to, n);
  425. }
  426. /**
  427. * Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  428. * will want crypto_rand instead.
  429. *
  430. * This function is not allowed to fail; if it would fail to generate strong
  431. * entropy, it must terminate the process instead.
  432. **/
  433. void
  434. crypto_rand_unmocked(char *to, size_t n)
  435. {
  436. if (n == 0)
  437. return;
  438. tor_assert(n < INT_MAX);
  439. tor_assert(to);
  440. #ifdef ENABLE_NSS
  441. SECStatus s = PK11_GenerateRandom((unsigned char*)to, (int)n);
  442. if (s != SECSuccess) {
  443. /* NSS rather sensibly might refuse to generate huge amounts of random
  444. * data at once. Unfortunately, our unit test do this in a couple of
  445. * places. To solve this issue, we use our XOF to stretch a shorter
  446. * output when a longer one is needed.
  447. *
  448. * Yes, this is secure. */
  449. /* This is longer than it needs to be; 1600 bits == 200 bytes is the
  450. * state-size of SHA3. */
  451. #define BUFLEN 512
  452. tor_assert(PR_GetError() == SEC_ERROR_INVALID_ARGS && n > BUFLEN);
  453. unsigned char buf[BUFLEN];
  454. s = PK11_GenerateRandom(buf, BUFLEN);
  455. tor_assert(s == SECSuccess);
  456. crypto_xof_t *xof = crypto_xof_new();
  457. crypto_xof_add_bytes(xof, buf, BUFLEN);
  458. crypto_xof_squeeze_bytes(xof, (unsigned char *)to, n);
  459. crypto_xof_free(xof);
  460. memwipe(buf, 0, BUFLEN);
  461. #undef BUFLEN
  462. }
  463. #else
  464. int r = RAND_bytes((unsigned char*)to, (int)n);
  465. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  466. * stack trace about where it happened.
  467. */
  468. tor_assert(r >= 0);
  469. #endif
  470. }
  471. /**
  472. * Return a pseudorandom integer, chosen uniformly from the values
  473. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  474. * INT_MAX+1, inclusive.
  475. */
  476. int
  477. crypto_rand_int(unsigned int max)
  478. {
  479. unsigned int val;
  480. unsigned int cutoff;
  481. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  482. tor_assert(max > 0); /* don't div by 0 */
  483. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  484. * distribution with clipping at the upper end of unsigned int's
  485. * range.
  486. */
  487. cutoff = UINT_MAX - (UINT_MAX%max);
  488. while (1) {
  489. crypto_rand((char*)&val, sizeof(val));
  490. if (val < cutoff)
  491. return val % max;
  492. }
  493. }
  494. /**
  495. * Return a pseudorandom integer, chosen uniformly from the values i such
  496. * that min <= i < max.
  497. *
  498. * <b>min</b> MUST be in range [0, <b>max</b>).
  499. * <b>max</b> MUST be in range (min, INT_MAX].
  500. **/
  501. int
  502. crypto_rand_int_range(unsigned int min, unsigned int max)
  503. {
  504. tor_assert(min < max);
  505. tor_assert(max <= INT_MAX);
  506. /* The overflow is avoided here because crypto_rand_int() returns a value
  507. * between 0 and (max - min) inclusive. */
  508. return min + crypto_rand_int(max - min);
  509. }
  510. /**
  511. * As crypto_rand_int_range, but supports uint64_t.
  512. **/
  513. uint64_t
  514. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  515. {
  516. tor_assert(min < max);
  517. return min + crypto_rand_uint64(max - min);
  518. }
  519. /**
  520. * As crypto_rand_int_range, but supports time_t.
  521. **/
  522. time_t
  523. crypto_rand_time_range(time_t min, time_t max)
  524. {
  525. tor_assert(min < max);
  526. return min + (time_t)crypto_rand_uint64(max - min);
  527. }
  528. /**
  529. * Return a pseudorandom 64-bit integer, chosen uniformly from the values
  530. * between 0 and <b>max</b>-1 inclusive.
  531. **/
  532. uint64_t
  533. crypto_rand_uint64(uint64_t max)
  534. {
  535. uint64_t val;
  536. uint64_t cutoff;
  537. tor_assert(max < UINT64_MAX);
  538. tor_assert(max > 0); /* don't div by 0 */
  539. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  540. * distribution with clipping at the upper end of unsigned int's
  541. * range.
  542. */
  543. cutoff = UINT64_MAX - (UINT64_MAX%max);
  544. while (1) {
  545. crypto_rand((char*)&val, sizeof(val));
  546. if (val < cutoff)
  547. return val % max;
  548. }
  549. }
  550. /**
  551. * Return a pseudorandom double d, chosen uniformly from the range
  552. * 0.0 <= d < 1.0.
  553. **/
  554. double
  555. crypto_rand_double(void)
  556. {
  557. /* We just use an unsigned int here; we don't really care about getting
  558. * more than 32 bits of resolution */
  559. unsigned int u;
  560. crypto_rand((char*)&u, sizeof(u));
  561. #if SIZEOF_INT == 4
  562. #define UINT_MAX_AS_DOUBLE 4294967296.0
  563. #elif SIZEOF_INT == 8
  564. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  565. #else
  566. #error SIZEOF_INT is neither 4 nor 8
  567. #endif /* SIZEOF_INT == 4 || ... */
  568. return ((double)u) / UINT_MAX_AS_DOUBLE;
  569. }
  570. /**
  571. * Generate and return a new random hostname starting with <b>prefix</b>,
  572. * ending with <b>suffix</b>, and containing no fewer than
  573. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  574. * characters. Does not check for failure.
  575. *
  576. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  577. **/
  578. char *
  579. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  580. const char *suffix)
  581. {
  582. char *result, *rand_bytes;
  583. int randlen, rand_bytes_len;
  584. size_t resultlen, prefixlen;
  585. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  586. max_rand_len = MAX_DNS_LABEL_SIZE;
  587. if (min_rand_len > max_rand_len)
  588. min_rand_len = max_rand_len;
  589. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  590. prefixlen = strlen(prefix);
  591. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  592. rand_bytes_len = ((randlen*5)+7)/8;
  593. if (rand_bytes_len % 5)
  594. rand_bytes_len += 5 - (rand_bytes_len%5);
  595. rand_bytes = tor_malloc(rand_bytes_len);
  596. crypto_rand(rand_bytes, rand_bytes_len);
  597. result = tor_malloc(resultlen);
  598. memcpy(result, prefix, prefixlen);
  599. base32_encode(result+prefixlen, resultlen-prefixlen,
  600. rand_bytes, rand_bytes_len);
  601. tor_free(rand_bytes);
  602. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  603. return result;
  604. }
  605. /**
  606. * Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  607. * is empty.
  608. **/
  609. void *
  610. smartlist_choose(const smartlist_t *sl)
  611. {
  612. int len = smartlist_len(sl);
  613. if (len)
  614. return smartlist_get(sl,crypto_rand_int(len));
  615. return NULL; /* no elements to choose from */
  616. }
  617. /**
  618. * Scramble the elements of <b>sl</b> into a random order.
  619. **/
  620. void
  621. smartlist_shuffle(smartlist_t *sl)
  622. {
  623. int i;
  624. /* From the end of the list to the front, choose at random from the
  625. positions we haven't looked at yet, and swap that position into the
  626. current position. Remember to give "no swap" the same probability as
  627. any other swap. */
  628. for (i = smartlist_len(sl)-1; i > 0; --i) {
  629. int j = crypto_rand_int(i+1);
  630. smartlist_swap(sl, i, j);
  631. }
  632. }
  633. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  634. * adjust it; 0 otherwise. */
  635. int
  636. crypto_force_rand_ssleay(void)
  637. {
  638. #ifdef ENABLE_OPENSSL
  639. RAND_METHOD *default_method;
  640. default_method = RAND_OpenSSL();
  641. if (RAND_get_rand_method() != default_method) {
  642. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  643. "a replacement the OpenSSL RNG. Resetting it to the default "
  644. "implementation.");
  645. RAND_set_rand_method(default_method);
  646. return 1;
  647. }
  648. #endif
  649. return 0;
  650. }
  651. #endif /* !defined(CRYPTO_RAND_PRIVATE) */