tor  0.4.1.0-alpha-dev
crypto_rand.c
Go to the documentation of this file.
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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
14 #define CRYPTO_RAND_PRIVATE
15 
17 
18 #ifdef _WIN32
19 #include <windows.h>
20 #include <wincrypt.h>
21 #endif /* defined(_WIN32) */
22 
24 #include "lib/crypt_ops/compat_openssl.h"
26 #include "lib/encoding/binascii.h"
27 #include "lib/intmath/weakrng.h"
28 #include "lib/log/log.h"
29 #include "lib/log/util_bug.h"
30 #include "lib/malloc/malloc.h"
31 #include "lib/sandbox/sandbox.h"
33 #include "lib/string/util_string.h"
35 #include "lib/fs/files.h"
36 
37 #include "lib/defs/digest_sizes.h"
39 
40 #ifdef ENABLE_NSS
42 #endif
43 
44 #ifdef ENABLE_OPENSSL
45 DISABLE_GCC_WARNING(redundant-decls)
46 #include <openssl/rand.h>
47 #include <openssl/sha.h>
48 ENABLE_GCC_WARNING(redundant-decls)
49 #endif
50 
51 #ifdef ENABLE_NSS
52 #include <pk11pub.h>
53 #include <secerr.h>
54 #include <prerror.h>
55 #endif
56 
57 #if __GNUC__ && GCC_VERSION >= 402
58 #if GCC_VERSION >= 406
59 #pragma GCC diagnostic pop
60 #else
61 #pragma GCC diagnostic warning "-Wredundant-decls"
62 #endif
63 #endif /* __GNUC__ && GCC_VERSION >= 402 */
64 
65 #ifdef HAVE_FCNTL_H
66 #include <fcntl.h>
67 #endif
68 #ifdef HAVE_SYS_FCNTL_H
69 #include <sys/fcntl.h>
70 #endif
71 #ifdef HAVE_SYS_STAT_H
72 #include <sys/stat.h>
73 #endif
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77 #ifdef HAVE_SYS_SYSCALL_H
78 #include <sys/syscall.h>
79 #endif
80 #ifdef HAVE_SYS_RANDOM_H
81 #include <sys/random.h>
82 #endif
83 
84 #include <string.h>
85 #include <errno.h>
86 
93 #define ADD_ENTROPY 32
94 
98 #define MAX_DNS_LABEL_SIZE 63
99 
103 #define MAX_STRONGEST_RAND_SIZE 256
104 
108 void
110 {
111  unsigned seed;
112  crypto_rand((void*)&seed, sizeof(seed));
113  tor_init_weak_random(rng, seed);
114 }
115 
116 #ifdef TOR_UNIT_TESTS
117 int break_strongest_rng_syscall = 0;
118 int break_strongest_rng_fallback = 0;
119 #endif
120 
126 static int
127 crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
128 {
130 
131  /* We only log at notice-level here because in the case that this function
132  * fails the crypto_strongest_rand_raw() caller will log with a warning-level
133  * message and let crypto_strongest_rand() error out and finally terminating
134  * Tor with an assertion error.
135  */
136 
137 #ifdef TOR_UNIT_TESTS
138  if (break_strongest_rng_syscall)
139  return -1;
140 #endif
141 
142 #if defined(_WIN32)
143  static int provider_set = 0;
144  static HCRYPTPROV provider;
145 
146  if (!provider_set) {
147  if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
148  CRYPT_VERIFYCONTEXT)) {
149  log_notice(LD_CRYPTO, "Unable to set Windows CryptoAPI provider [1].");
150  return -1;
151  }
152  provider_set = 1;
153  }
154  if (!CryptGenRandom(provider, out_len, out)) {
155  log_notice(LD_CRYPTO, "Unable get entropy from the Windows CryptoAPI.");
156  return -1;
157  }
158 
159  return 0;
160 #elif defined(__linux__) && defined(SYS_getrandom)
161  static int getrandom_works = 1; /* Be optimistic about our chances... */
162 
163  /* getrandom() isn't as straightforward as getentropy(), and has
164  * no glibc wrapper.
165  *
166  * As far as I can tell from getrandom(2) and the source code, the
167  * requests we issue will always succeed (though it will block on the
168  * call if /dev/urandom isn't seeded yet), since we are NOT specifying
169  * GRND_NONBLOCK and the request is <= 256 bytes.
170  *
171  * The manpage is unclear on what happens if a signal interrupts the call
172  * while the request is blocked due to lack of entropy....
173  *
174  * We optimistically assume that getrandom() is available and functional
175  * because it is the way of the future, and 2 branch mispredicts pale in
176  * comparison to the overheads involved with failing to open
177  * /dev/srandom followed by opening and reading from /dev/urandom.
178  */
179  if (PREDICT_LIKELY(getrandom_works)) {
180  long ret;
181  /* A flag of '0' here means to read from '/dev/urandom', and to
182  * block if insufficient entropy is available to service the
183  * request.
184  */
185  const unsigned int flags = 0;
186  do {
187  ret = syscall(SYS_getrandom, out, out_len, flags);
188  } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
189 
190  if (PREDICT_UNLIKELY(ret == -1)) {
191  /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
192  tor_assert(errno != EAGAIN);
193  tor_assert(errno != EINTR);
194 
195  /* Useful log message for errno. */
196  if (errno == ENOSYS) {
197  log_notice(LD_CRYPTO, "Can't get entropy from getrandom()."
198  " You are running a version of Tor built to support"
199  " getrandom(), but the kernel doesn't implement this"
200  " function--probably because it is too old?"
201  " Trying fallback method instead.");
202  } else {
203  log_notice(LD_CRYPTO, "Can't get entropy from getrandom(): %s."
204  " Trying fallback method instead.",
205  strerror(errno));
206  }
207 
208  getrandom_works = 0; /* Don't bother trying again. */
209  return -1;
210  /* LCOV_EXCL_STOP */
211  }
212 
213  tor_assert(ret == (long)out_len);
214  return 0;
215  }
216 
217  return -1; /* getrandom() previously failed unexpectedly. */
218 #elif defined(HAVE_GETENTROPY)
219  /* getentropy() is what Linux's getrandom() wants to be when it grows up.
220  * the only gotcha is that requests are limited to 256 bytes.
221  */
222  return getentropy(out, out_len);
223 #else
224  (void) out;
225 #endif /* defined(_WIN32) || ... */
226 
227  /* This platform doesn't have a supported syscall based random. */
228  return -1;
229 }
230 
237 static int
238 crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
239 {
240 #ifdef TOR_UNIT_TESTS
241  if (break_strongest_rng_fallback)
242  return -1;
243 #endif
244 
245 #ifdef _WIN32
246  /* Windows exclusively uses crypto_strongest_rand_syscall(). */
247  (void)out;
248  (void)out_len;
249  return -1;
250 #else /* !(defined(_WIN32)) */
251  static const char *filenames[] = {
252  "/dev/srandom", "/dev/urandom", "/dev/random", NULL
253  };
254  int fd, i;
255  size_t n;
256 
257  for (i = 0; filenames[i]; ++i) {
258  log_debug(LD_FS, "Considering %s as entropy source", filenames[i]);
259  fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
260  if (fd<0) continue;
261  log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
262  n = read_all_from_fd(fd, (char*)out, out_len);
263  close(fd);
264  if (n != out_len) {
265  /* LCOV_EXCL_START
266  * We can't make /dev/foorandom actually fail. */
267  log_notice(LD_CRYPTO,
268  "Error reading from entropy source %s (read only %lu bytes).",
269  filenames[i],
270  (unsigned long)n);
271  return -1;
272  /* LCOV_EXCL_STOP */
273  }
274 
275  return 0;
276  }
277 
278  return -1;
279 #endif /* defined(_WIN32) */
280 }
281 
287 STATIC int
288 crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
289 {
290  static const size_t sanity_min_size = 16;
291  static const int max_attempts = 3;
293 
294  /* For buffers >= 16 bytes (128 bits), we sanity check the output by
295  * zero filling the buffer and ensuring that it actually was at least
296  * partially modified.
297  *
298  * Checking that any individual byte is non-zero seems like it would
299  * fail too often (p = out_len * 1/256) for comfort, but this is an
300  * "adjust according to taste" sort of check.
301  */
302  memwipe(out, 0, out_len);
303  for (int i = 0; i < max_attempts; i++) {
304  /* Try to use the syscall/OS favored mechanism to get strong entropy. */
305  if (crypto_strongest_rand_syscall(out, out_len) != 0) {
306  /* Try to use the less-favored mechanism to get strong entropy. */
307  if (crypto_strongest_rand_fallback(out, out_len) != 0) {
308  /* Welp, we tried. Hopefully the calling code terminates the process
309  * since we're basically boned without good entropy.
310  */
311  log_warn(LD_CRYPTO,
312  "Cannot get strong entropy: no entropy source found.");
313  return -1;
314  }
315  }
316 
317  if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
318  return 0;
319  }
320 
321  /* LCOV_EXCL_START
322  *
323  * We tried max_attempts times to fill a buffer >= 128 bits long,
324  * and each time it returned all '0's. Either the system entropy
325  * source is busted, or the user should go out and buy a ticket to
326  * every lottery on the planet.
327  */
328  log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
329 
330  return -1;
331  /* LCOV_EXCL_STOP */
332 }
333 
338 void
339 crypto_strongest_rand(uint8_t *out, size_t out_len)
340 {
341  crypto_strongest_rand_(out, out_len);
342 }
343 
349 crypto_strongest_rand_,(uint8_t *out, size_t out_len))
350 {
351 #define DLEN DIGEST512_LEN
352 
353  /* We're going to hash DLEN bytes from the system RNG together with some
354  * bytes from the PRNGs from our crypto librar(y/ies), in order to yield
355  * DLEN bytes.
356  */
357  uint8_t inp[DLEN*3];
358  uint8_t tmp[DLEN];
359  tor_assert(out);
360  while (out_len) {
361  memset(inp, 0, sizeof(inp));
362 #ifdef ENABLE_OPENSSL
363  RAND_bytes(inp, DLEN);
364 #endif
365 #ifdef ENABLE_NSS
366  PK11_GenerateRandom(inp+DLEN, DLEN);
367 #endif
368  if (crypto_strongest_rand_raw(inp+DLEN*2, DLEN) < 0) {
369  // LCOV_EXCL_START
370  log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
371  "important key. Exiting.");
372  /* Die with an assertion so we get a stack trace. */
373  tor_assert(0);
374  // LCOV_EXCL_STOP
375  }
376  if (out_len >= DLEN) {
377  crypto_digest512((char*)out, (char*)inp, sizeof(inp), DIGEST_SHA512);
378  out += DLEN;
379  out_len -= DLEN;
380  } else {
381  crypto_digest512((char*)tmp, (char*)inp, sizeof(inp), DIGEST_SHA512);
382  memcpy(out, tmp, out_len);
383  break;
384  }
385  }
386  memwipe(tmp, 0, sizeof(tmp));
387  memwipe(inp, 0, sizeof(inp));
388 #undef DLEN
389 }
390 
391 #ifdef ENABLE_OPENSSL
392 
396 static int
397 crypto_seed_openssl_rng(void)
398 {
399  int rand_poll_ok = 0, load_entropy_ok = 0;
400  uint8_t buf[ADD_ENTROPY];
401 
402  /* OpenSSL has a RAND_poll function that knows about more kinds of
403  * entropy than we do. We'll try calling that, *and* calling our own entropy
404  * functions. If one succeeds, we'll accept the RNG as seeded. */
405  rand_poll_ok = RAND_poll();
406  if (rand_poll_ok == 0)
407  log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
408 
409  load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
410  if (load_entropy_ok) {
411  RAND_seed(buf, sizeof(buf));
412  }
413 
414  memwipe(buf, 0, sizeof(buf));
415 
416  if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
417  return 0;
418  else
419  return -1;
420 }
421 #endif
422 
423 #ifdef ENABLE_NSS
424 
428 static int
429 crypto_seed_nss_rng(void)
430 {
431  uint8_t buf[ADD_ENTROPY];
432 
433  int load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
434  if (load_entropy_ok) {
435  if (PK11_RandomUpdate(buf, sizeof(buf)) != SECSuccess) {
436  load_entropy_ok = 0;
437  }
438  }
439 
440  memwipe(buf, 0, sizeof(buf));
441 
442  return load_entropy_ok ? 0 : -1;
443 }
444 #endif
445 
450 int
452 {
453  int seeded = 0;
454 #ifdef ENABLE_NSS
455  if (crypto_seed_nss_rng() < 0)
456  return -1;
457  ++seeded;
458 #endif
459 #ifdef ENABLE_OPENSSL
460  if (crypto_seed_openssl_rng() < 0)
461  return -1;
462  ++seeded;
463 #endif
464  tor_assert(seeded);
465  return 0;
466 }
467 
476 crypto_rand, (char *to, size_t n))
477 {
478  crypto_rand_unmocked(to, n);
479 }
480 
488 void
489 crypto_rand_unmocked(char *to, size_t n)
490 {
491  if (n == 0)
492  return;
493 
494  tor_assert(n < INT_MAX);
495  tor_assert(to);
496 
497 #ifdef ENABLE_NSS
498  SECStatus s = PK11_GenerateRandom((unsigned char*)to, (int)n);
499  if (s != SECSuccess) {
500  /* NSS rather sensibly might refuse to generate huge amounts of random
501  * data at once. Unfortunately, our unit test do this in a couple of
502  * places. To solve this issue, we use our XOF to stretch a shorter
503  * output when a longer one is needed.
504  *
505  * Yes, this is secure. */
506 
507  /* This is longer than it needs to be; 1600 bits == 200 bytes is the
508  * state-size of SHA3. */
509 #define BUFLEN 512
510  tor_assert(PR_GetError() == SEC_ERROR_INVALID_ARGS && n > BUFLEN);
511  unsigned char buf[BUFLEN];
512  s = PK11_GenerateRandom(buf, BUFLEN);
513  tor_assert(s == SECSuccess);
514  crypto_xof_t *xof = crypto_xof_new();
515  crypto_xof_add_bytes(xof, buf, BUFLEN);
516  crypto_xof_squeeze_bytes(xof, (unsigned char *)to, n);
517  crypto_xof_free(xof);
518  memwipe(buf, 0, BUFLEN);
519 
520 #undef BUFLEN
521  }
522 #else
523  int r = RAND_bytes((unsigned char*)to, (int)n);
524  /* We consider a PRNG failure non-survivable. Let's assert so that we get a
525  * stack trace about where it happened.
526  */
527  tor_assert(r >= 0);
528 #endif
529 }
530 
534 uint32_t
536 {
537  uint32_t rand;
538  crypto_rand((void*)&rand, sizeof(rand));
539  return rand;
540 }
541 
550 char *
551 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
552  const char *suffix)
553 {
554  char *result, *rand_bytes;
555  int randlen, rand_bytes_len;
556  size_t resultlen, prefixlen;
557 
558  if (max_rand_len > MAX_DNS_LABEL_SIZE)
559  max_rand_len = MAX_DNS_LABEL_SIZE;
560  if (min_rand_len > max_rand_len)
561  min_rand_len = max_rand_len;
562 
563  randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
564 
565  prefixlen = strlen(prefix);
566  resultlen = prefixlen + strlen(suffix) + randlen + 16;
567 
568  rand_bytes_len = ((randlen*5)+7)/8;
569  if (rand_bytes_len % 5)
570  rand_bytes_len += 5 - (rand_bytes_len%5);
571  rand_bytes = tor_malloc(rand_bytes_len);
572  crypto_rand(rand_bytes, rand_bytes_len);
573 
574  result = tor_malloc(resultlen);
575  memcpy(result, prefix, prefixlen);
576  base32_encode(result+prefixlen, resultlen-prefixlen,
577  rand_bytes, rand_bytes_len);
578  tor_free(rand_bytes);
579  strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
580 
581  return result;
582 }
583 
588 void *
590 {
591  int len = smartlist_len(sl);
592  if (len)
593  return smartlist_get(sl,crypto_rand_int(len));
594  return NULL; /* no elements to choose from */
595 }
596 
600 void
602 {
603  int i;
604  /* From the end of the list to the front, choose at random from the
605  positions we haven't looked at yet, and swap that position into the
606  current position. Remember to give "no swap" the same probability as
607  any other swap. */
608  for (i = smartlist_len(sl)-1; i > 0; --i) {
609  int j = crypto_rand_int(i+1);
610  smartlist_swap(sl, i, j);
611  }
612 }
613 
616 int
618 {
619 #ifdef ENABLE_OPENSSL
620  RAND_METHOD *default_method;
621  default_method = RAND_OpenSSL();
622  if (RAND_get_rand_method() != default_method) {
623  log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
624  "a replacement the OpenSSL RNG. Resetting it to the default "
625  "implementation.");
626  RAND_set_rand_method(default_method);
627  return 1;
628  }
629 #endif
630  return 0;
631 }
static int crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
Definition: crypto_rand.c:238
uint32_t crypto_rand_u32(void)
Definition: crypto_rand.c:535
Common functions for using (pseudo-)random number generators.
Header for smartlist.c.
MOCK_IMPL(void, crypto_strongest_rand_,(uint8_t *out, size_t out_len))
Definition: crypto_rand.c:348
void crypto_seed_weak_rng(tor_weak_rng_t *rng)
Definition: crypto_rand.c:109
int crypto_force_rand_ssleay(void)
Definition: crypto_rand.c:617
#define MAX_DNS_LABEL_SIZE
Definition: crypto_rand.c:98
int tor_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:74
void crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
int crypto_digest512(char *digest, const char *m, size_t len, digest_algorithm_t algorithm)
void base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:60
int crypto_rand_int_range(unsigned int min, unsigned int max)
void crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
#define tor_free(p)
Definition: malloc.h:52
Header for util_string.c.
#define ADD_ENTROPY
Definition: crypto_rand.c:93
Headers for util_malloc.c.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
#define sandbox_intern_string(s)
Definition: sandbox.h:112
void smartlist_shuffle(smartlist_t *sl)
Definition: crypto_rand.c:601
void crypto_rand_unmocked(char *to, size_t n)
Definition: crypto_rand.c:489
Common functions for cryptographic routines.
tor_assert(buffer)
static void smartlist_swap(smartlist_t *sl, int idx1, int idx2)
STATIC int crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
Definition: crypto_rand.c:288
Header file for sandbox.c.
int crypto_rand_int(unsigned int max)
Header for binascii.c.
Header for weakrng.c.
#define LD_FS
Definition: log.h:66
Headers for crypto_digest.c.
ssize_t read_all_from_fd(int fd, char *buf, size_t count)
Definition: files.c:181
void crypto_strongest_rand(uint8_t *out, size_t out_len)
Definition: crypto_rand.c:339
Macros to implement mocking and selective exposure for the test code.
Header for compat_string.c.
Wrappers for reading and writing data to files on disk.
Definitions for common sizes of cryptographic digests.
static int crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
Definition: crypto_rand.c:127
#define MAX_STRONGEST_RAND_SIZE
Definition: crypto_rand.c:103
int crypto_seed_rng(void)
Definition: crypto_rand.c:451
Headers for log.c.
void tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
Definition: weakrng.c:22
#define LD_CRYPTO
Definition: log.h:60
Macros to manage assertions, fatal and non-fatal.
crypto_xof_t * crypto_xof_new(void)
char * crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix, const char *suffix)
Definition: crypto_rand.c:551
Headers for crypto_nss_mgt.c.
void * smartlist_choose(const smartlist_t *sl)
Definition: crypto_rand.c:589