crypto_rand.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. #define DLEN DIGEST512_LEN
  301. /* We're going to hash DLEN bytes from the system RNG together with some
  302. * bytes from the PRNGs from our crypto librar(y/ies), in order to yield
  303. * DLEN bytes.
  304. */
  305. uint8_t inp[DLEN*3];
  306. uint8_t tmp[DLEN];
  307. tor_assert(out);
  308. while (out_len) {
  309. memset(inp, 0, sizeof(inp));
  310. #ifdef ENABLE_OPENSSL
  311. RAND_bytes(inp, DLEN);
  312. #endif
  313. #ifdef ENABLE_NSS
  314. PK11_GenerateRandom(inp+DLEN, DLEN);
  315. #endif
  316. if (crypto_strongest_rand_raw(inp+DLEN*2, DLEN) < 0) {
  317. // LCOV_EXCL_START
  318. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  319. "important key. Exiting.");
  320. /* Die with an assertion so we get a stack trace. */
  321. tor_assert(0);
  322. // LCOV_EXCL_STOP
  323. }
  324. if (out_len >= DLEN) {
  325. crypto_digest512((char*)out, (char*)inp, sizeof(inp), DIGEST_SHA512);
  326. out += DLEN;
  327. out_len -= DLEN;
  328. } else {
  329. crypto_digest512((char*)tmp, (char*)inp, sizeof(inp), DIGEST_SHA512);
  330. memcpy(out, tmp, out_len);
  331. break;
  332. }
  333. }
  334. memwipe(tmp, 0, sizeof(tmp));
  335. memwipe(inp, 0, sizeof(inp));
  336. #undef DLEN
  337. }
  338. #ifdef ENABLE_OPENSSL
  339. /**
  340. * Seed OpenSSL's random number generator with bytes from the operating
  341. * system. Return 0 on success, -1 on failure.
  342. **/
  343. static int
  344. crypto_seed_openssl_rng(void)
  345. {
  346. int rand_poll_ok = 0, load_entropy_ok = 0;
  347. uint8_t buf[ADD_ENTROPY];
  348. /* OpenSSL has a RAND_poll function that knows about more kinds of
  349. * entropy than we do. We'll try calling that, *and* calling our own entropy
  350. * functions. If one succeeds, we'll accept the RNG as seeded. */
  351. rand_poll_ok = RAND_poll();
  352. if (rand_poll_ok == 0)
  353. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  354. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  355. if (load_entropy_ok) {
  356. RAND_seed(buf, sizeof(buf));
  357. }
  358. memwipe(buf, 0, sizeof(buf));
  359. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  360. return 0;
  361. else
  362. return -1;
  363. }
  364. #endif
  365. #ifdef ENABLE_NSS
  366. /**
  367. * Seed OpenSSL's random number generator with bytes from the operating
  368. * system. Return 0 on success, -1 on failure.
  369. **/
  370. static int
  371. crypto_seed_nss_rng(void)
  372. {
  373. uint8_t buf[ADD_ENTROPY];
  374. int load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  375. if (load_entropy_ok) {
  376. if (PK11_RandomUpdate(buf, sizeof(buf)) != SECSuccess) {
  377. load_entropy_ok = 0;
  378. }
  379. }
  380. memwipe(buf, 0, sizeof(buf));
  381. return load_entropy_ok ? 0 : -1;
  382. }
  383. #endif
  384. /**
  385. * Seed the RNG for any and all crypto libraries that we're using with bytes
  386. * from the operating system. Return 0 on success, -1 on failure.
  387. */
  388. int
  389. crypto_seed_rng(void)
  390. {
  391. int seeded = 0;
  392. #ifdef ENABLE_NSS
  393. if (crypto_seed_nss_rng() < 0)
  394. return -1;
  395. ++seeded;
  396. #endif
  397. #ifdef ENABLE_OPENSSL
  398. if (crypto_seed_openssl_rng() < 0)
  399. return -1;
  400. ++seeded;
  401. #endif
  402. tor_assert(seeded);
  403. return 0;
  404. }
  405. /**
  406. * Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  407. * for unit tests.
  408. *
  409. * This function is not allowed to fail; if it would fail to generate strong
  410. * entropy, it must terminate the process instead.
  411. **/
  412. MOCK_IMPL(void,
  413. crypto_rand, (char *to, size_t n))
  414. {
  415. crypto_rand_unmocked(to, n);
  416. }
  417. /**
  418. * Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  419. * will want crypto_rand instead.
  420. *
  421. * This function is not allowed to fail; if it would fail to generate strong
  422. * entropy, it must terminate the process instead.
  423. **/
  424. void
  425. crypto_rand_unmocked(char *to, size_t n)
  426. {
  427. if (n == 0)
  428. return;
  429. tor_assert(n < INT_MAX);
  430. tor_assert(to);
  431. #ifdef ENABLE_NSS
  432. SECStatus s = PK11_GenerateRandom((unsigned char*)to, (int)n);
  433. if (s != SECSuccess) {
  434. /* NSS rather sensibly might refuse to generate huge amounts of random
  435. * data at once. Unfortunately, our unit test do this in a couple of
  436. * places. To solve this issue, we use our XOF to stretch a shorter
  437. * output when a longer one is needed.
  438. *
  439. * Yes, this is secure. */
  440. /* This is longer than it needs to be; 1600 bits == 200 bytes is the
  441. * state-size of SHA3. */
  442. #define BUFLEN 512
  443. tor_assert(PR_GetError() == SEC_ERROR_INVALID_ARGS && n > BUFLEN);
  444. unsigned char buf[BUFLEN];
  445. s = PK11_GenerateRandom(buf, BUFLEN);
  446. tor_assert(s == SECSuccess);
  447. crypto_xof_t *xof = crypto_xof_new();
  448. crypto_xof_add_bytes(xof, buf, BUFLEN);
  449. crypto_xof_squeeze_bytes(xof, (unsigned char *)to, n);
  450. crypto_xof_free(xof);
  451. memwipe(buf, 0, BUFLEN);
  452. #undef BUFLEN
  453. }
  454. #else
  455. int r = RAND_bytes((unsigned char*)to, (int)n);
  456. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  457. * stack trace about where it happened.
  458. */
  459. tor_assert(r >= 0);
  460. #endif
  461. }
  462. /**
  463. * Return a pseudorandom integer, chosen uniformly from the values
  464. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  465. * INT_MAX+1, inclusive.
  466. */
  467. int
  468. crypto_rand_int(unsigned int max)
  469. {
  470. unsigned int val;
  471. unsigned int cutoff;
  472. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  473. tor_assert(max > 0); /* don't div by 0 */
  474. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  475. * distribution with clipping at the upper end of unsigned int's
  476. * range.
  477. */
  478. cutoff = UINT_MAX - (UINT_MAX%max);
  479. while (1) {
  480. crypto_rand((char*)&val, sizeof(val));
  481. if (val < cutoff)
  482. return val % max;
  483. }
  484. }
  485. /**
  486. * Return a pseudorandom integer, chosen uniformly from the values i such
  487. * that min <= i < max.
  488. *
  489. * <b>min</b> MUST be in range [0, <b>max</b>).
  490. * <b>max</b> MUST be in range (min, INT_MAX].
  491. **/
  492. int
  493. crypto_rand_int_range(unsigned int min, unsigned int max)
  494. {
  495. tor_assert(min < max);
  496. tor_assert(max <= INT_MAX);
  497. /* The overflow is avoided here because crypto_rand_int() returns a value
  498. * between 0 and (max - min) inclusive. */
  499. return min + crypto_rand_int(max - min);
  500. }
  501. /**
  502. * As crypto_rand_int_range, but supports uint64_t.
  503. **/
  504. uint64_t
  505. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  506. {
  507. tor_assert(min < max);
  508. return min + crypto_rand_uint64(max - min);
  509. }
  510. /**
  511. * As crypto_rand_int_range, but supports time_t.
  512. **/
  513. time_t
  514. crypto_rand_time_range(time_t min, time_t max)
  515. {
  516. tor_assert(min < max);
  517. return min + (time_t)crypto_rand_uint64(max - min);
  518. }
  519. /**
  520. * Return a pseudorandom 64-bit integer, chosen uniformly from the values
  521. * between 0 and <b>max</b>-1 inclusive.
  522. **/
  523. uint64_t
  524. crypto_rand_uint64(uint64_t max)
  525. {
  526. uint64_t val;
  527. uint64_t cutoff;
  528. tor_assert(max < UINT64_MAX);
  529. tor_assert(max > 0); /* don't div by 0 */
  530. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  531. * distribution with clipping at the upper end of unsigned int's
  532. * range.
  533. */
  534. cutoff = UINT64_MAX - (UINT64_MAX%max);
  535. while (1) {
  536. crypto_rand((char*)&val, sizeof(val));
  537. if (val < cutoff)
  538. return val % max;
  539. }
  540. }
  541. /**
  542. * Return a pseudorandom double d, chosen uniformly from the range
  543. * 0.0 <= d < 1.0.
  544. **/
  545. double
  546. crypto_rand_double(void)
  547. {
  548. /* We just use an unsigned int here; we don't really care about getting
  549. * more than 32 bits of resolution */
  550. unsigned int u;
  551. crypto_rand((char*)&u, sizeof(u));
  552. #if SIZEOF_INT == 4
  553. #define UINT_MAX_AS_DOUBLE 4294967296.0
  554. #elif SIZEOF_INT == 8
  555. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  556. #else
  557. #error SIZEOF_INT is neither 4 nor 8
  558. #endif /* SIZEOF_INT == 4 || ... */
  559. return ((double)u) / UINT_MAX_AS_DOUBLE;
  560. }
  561. /**
  562. * Generate and return a new random hostname starting with <b>prefix</b>,
  563. * ending with <b>suffix</b>, and containing no fewer than
  564. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  565. * characters. Does not check for failure.
  566. *
  567. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  568. **/
  569. char *
  570. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  571. const char *suffix)
  572. {
  573. char *result, *rand_bytes;
  574. int randlen, rand_bytes_len;
  575. size_t resultlen, prefixlen;
  576. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  577. max_rand_len = MAX_DNS_LABEL_SIZE;
  578. if (min_rand_len > max_rand_len)
  579. min_rand_len = max_rand_len;
  580. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  581. prefixlen = strlen(prefix);
  582. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  583. rand_bytes_len = ((randlen*5)+7)/8;
  584. if (rand_bytes_len % 5)
  585. rand_bytes_len += 5 - (rand_bytes_len%5);
  586. rand_bytes = tor_malloc(rand_bytes_len);
  587. crypto_rand(rand_bytes, rand_bytes_len);
  588. result = tor_malloc(resultlen);
  589. memcpy(result, prefix, prefixlen);
  590. base32_encode(result+prefixlen, resultlen-prefixlen,
  591. rand_bytes, rand_bytes_len);
  592. tor_free(rand_bytes);
  593. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  594. return result;
  595. }
  596. /**
  597. * Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  598. * is empty.
  599. **/
  600. void *
  601. smartlist_choose(const smartlist_t *sl)
  602. {
  603. int len = smartlist_len(sl);
  604. if (len)
  605. return smartlist_get(sl,crypto_rand_int(len));
  606. return NULL; /* no elements to choose from */
  607. }
  608. /**
  609. * Scramble the elements of <b>sl</b> into a random order.
  610. **/
  611. void
  612. smartlist_shuffle(smartlist_t *sl)
  613. {
  614. int i;
  615. /* From the end of the list to the front, choose at random from the
  616. positions we haven't looked at yet, and swap that position into the
  617. current position. Remember to give "no swap" the same probability as
  618. any other swap. */
  619. for (i = smartlist_len(sl)-1; i > 0; --i) {
  620. int j = crypto_rand_int(i+1);
  621. smartlist_swap(sl, i, j);
  622. }
  623. }
  624. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  625. * adjust it; 0 otherwise. */
  626. int
  627. crypto_force_rand_ssleay(void)
  628. {
  629. #ifdef ENABLE_OPENSSL
  630. RAND_METHOD *default_method;
  631. default_method = RAND_OpenSSL();
  632. if (RAND_get_rand_method() != default_method) {
  633. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  634. "a replacement the OpenSSL RNG. Resetting it to the default "
  635. "implementation.");
  636. RAND_set_rand_method(default_method);
  637. return 1;
  638. }
  639. #endif
  640. return 0;
  641. }
  642. #endif /* !defined(CRYPTO_RAND_PRIVATE) */