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