crypto_rand.c 17 KB

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