crypto_rand.c 17 KB

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