crypto_rand.c 17 KB

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