crypto_rand.c 20 KB

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