crypto_rand.c 19 KB

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