123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741 |
- #ifndef CRYPTO_RAND_PRIVATE
- #define CRYPTO_RAND_PRIVATE
- #include "lib/crypt_ops/crypto_rand.h"
- #ifdef _WIN32
- #include <windows.h>
- #include <wincrypt.h>
- #endif
- #include "lib/container/smartlist.h"
- #include "lib/crypt_ops/compat_openssl.h"
- #include "lib/crypt_ops/crypto_util.h"
- #include "lib/encoding/binascii.h"
- #include "lib/intmath/weakrng.h"
- #include "lib/log/log.h"
- #include "lib/log/util_bug.h"
- #include "lib/malloc/malloc.h"
- #include "lib/sandbox/sandbox.h"
- #include "lib/string/compat_string.h"
- #include "lib/string/util_string.h"
- #include "lib/testsupport/testsupport.h"
- #include "lib/fs/files.h"
- #include "lib/defs/digest_sizes.h"
- #include "lib/crypt_ops/crypto_digest.h"
- #ifdef ENABLE_NSS
- #include "lib/crypt_ops/crypto_nss_mgt.h"
- #endif
- #ifdef ENABLE_OPENSSL
- DISABLE_GCC_WARNING(redundant-decls)
- #include <openssl/rand.h>
- ENABLE_GCC_WARNING(redundant-decls)
- #endif
- #ifdef ENABLE_NSS
- #include <pk11pub.h>
- #include <secerr.h>
- #include <prerror.h>
- #endif
- #if __GNUC__ && GCC_VERSION >= 402
- #if GCC_VERSION >= 406
- #pragma GCC diagnostic pop
- #else
- #pragma GCC diagnostic warning "-Wredundant-decls"
- #endif
- #endif
- #ifdef HAVE_FCNTL_H
- #include <fcntl.h>
- #endif
- #ifdef HAVE_SYS_FCNTL_H
- #include <sys/fcntl.h>
- #endif
- #ifdef HAVE_SYS_STAT_H
- #include <sys/stat.h>
- #endif
- #ifdef HAVE_UNISTD_H
- #include <unistd.h>
- #endif
- #ifdef HAVE_SYS_SYSCALL_H
- #include <sys/syscall.h>
- #endif
- #ifdef HAVE_SYS_RANDOM_H
- #include <sys/random.h>
- #endif
- #include <string.h>
- #include <errno.h>
- #define ADD_ENTROPY 32
- #define MAX_DNS_LABEL_SIZE 63
- #define MAX_STRONGEST_RAND_SIZE 256
- void
- crypto_seed_weak_rng(tor_weak_rng_t *rng)
- {
- unsigned seed;
- crypto_rand((void*)&seed, sizeof(seed));
- tor_init_weak_random(rng, seed);
- }
- #ifdef TOR_UNIT_TESTS
- int break_strongest_rng_syscall = 0;
- int break_strongest_rng_fallback = 0;
- #endif
- static int
- crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
- {
- tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
-
- #ifdef TOR_UNIT_TESTS
- if (break_strongest_rng_syscall)
- return -1;
- #endif
- #if defined(_WIN32)
- static int provider_set = 0;
- static HCRYPTPROV provider;
- if (!provider_set) {
- if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
- CRYPT_VERIFYCONTEXT)) {
- log_notice(LD_CRYPTO, "Unable to set Windows CryptoAPI provider [1].");
- return -1;
- }
- provider_set = 1;
- }
- if (!CryptGenRandom(provider, out_len, out)) {
- log_notice(LD_CRYPTO, "Unable get entropy from the Windows CryptoAPI.");
- return -1;
- }
- return 0;
- #elif defined(__linux__) && defined(SYS_getrandom)
- static int getrandom_works = 1;
-
- if (PREDICT_LIKELY(getrandom_works)) {
- long ret;
-
- const unsigned int flags = 0;
- do {
- ret = syscall(SYS_getrandom, out, out_len, flags);
- } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
- if (PREDICT_UNLIKELY(ret == -1)) {
-
- tor_assert(errno != EAGAIN);
- tor_assert(errno != EINTR);
-
- if (errno == ENOSYS) {
- log_notice(LD_CRYPTO, "Can't get entropy from getrandom()."
- " You are running a version of Tor built to support"
- " getrandom(), but the kernel doesn't implement this"
- " function--probably because it is too old?"
- " Trying fallback method instead.");
- } else {
- log_notice(LD_CRYPTO, "Can't get entropy from getrandom(): %s."
- " Trying fallback method instead.",
- strerror(errno));
- }
- getrandom_works = 0;
- return -1;
-
- }
- tor_assert(ret == (long)out_len);
- return 0;
- }
- return -1;
- #elif defined(HAVE_GETENTROPY)
-
- return getentropy(out, out_len);
- #else
- (void) out;
- #endif
-
- return -1;
- }
- static int
- crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
- {
- #ifdef TOR_UNIT_TESTS
- if (break_strongest_rng_fallback)
- return -1;
- #endif
- #ifdef _WIN32
-
- (void)out;
- (void)out_len;
- return -1;
- #else
- static const char *filenames[] = {
- "/dev/srandom", "/dev/urandom", "/dev/random", NULL
- };
- int fd, i;
- size_t n;
- for (i = 0; filenames[i]; ++i) {
- log_debug(LD_FS, "Considering %s as entropy source", filenames[i]);
- fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
- if (fd<0) continue;
- log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
- n = read_all_from_fd(fd, (char*)out, out_len);
- close(fd);
- if (n != out_len) {
-
- log_notice(LD_CRYPTO,
- "Error reading from entropy source %s (read only %lu bytes).",
- filenames[i],
- (unsigned long)n);
- return -1;
-
- }
- return 0;
- }
- return -1;
- #endif
- }
- STATIC int
- crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
- {
- static const size_t sanity_min_size = 16;
- static const int max_attempts = 3;
- tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
-
- memwipe(out, 0, out_len);
- for (int i = 0; i < max_attempts; i++) {
-
- if (crypto_strongest_rand_syscall(out, out_len) != 0) {
-
- if (crypto_strongest_rand_fallback(out, out_len) != 0) {
-
- log_warn(LD_CRYPTO,
- "Cannot get strong entropy: no entropy source found.");
- return -1;
- }
- }
- if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
- return 0;
- }
-
- log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
- return -1;
-
- }
- void
- crypto_strongest_rand(uint8_t *out, size_t out_len)
- {
- crypto_strongest_rand_(out, out_len);
- }
- MOCK_IMPL(void,
- crypto_strongest_rand_,(uint8_t *out, size_t out_len))
- {
- #define DLEN DIGEST512_LEN
-
- uint8_t inp[DLEN*3];
- uint8_t tmp[DLEN];
- tor_assert(out);
- while (out_len) {
- memset(inp, 0, sizeof(inp));
- #ifdef ENABLE_OPENSSL
- RAND_bytes(inp, DLEN);
- #endif
- #ifdef ENABLE_NSS
- PK11_GenerateRandom(inp+DLEN, DLEN);
- #endif
- if (crypto_strongest_rand_raw(inp+DLEN*2, DLEN) < 0) {
-
- log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
- "important key. Exiting.");
-
- tor_assert(0);
-
- }
- if (out_len >= DLEN) {
- crypto_digest512((char*)out, (char*)inp, sizeof(inp), DIGEST_SHA512);
- out += DLEN;
- out_len -= DLEN;
- } else {
- crypto_digest512((char*)tmp, (char*)inp, sizeof(inp), DIGEST_SHA512);
- memcpy(out, tmp, out_len);
- break;
- }
- }
- memwipe(tmp, 0, sizeof(tmp));
- memwipe(inp, 0, sizeof(inp));
- #undef DLEN
- }
- #ifdef ENABLE_OPENSSL
- static int
- crypto_seed_openssl_rng(void)
- {
- int rand_poll_ok = 0, load_entropy_ok = 0;
- uint8_t buf[ADD_ENTROPY];
-
- rand_poll_ok = RAND_poll();
- if (rand_poll_ok == 0)
- log_warn(LD_CRYPTO, "RAND_poll() failed.");
- load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
- if (load_entropy_ok) {
- RAND_seed(buf, sizeof(buf));
- }
- memwipe(buf, 0, sizeof(buf));
- if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
- return 0;
- else
- return -1;
- }
- #endif
- #ifdef ENABLE_NSS
- static int
- crypto_seed_nss_rng(void)
- {
- uint8_t buf[ADD_ENTROPY];
- int load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
- if (load_entropy_ok) {
- if (PK11_RandomUpdate(buf, sizeof(buf)) != SECSuccess) {
- load_entropy_ok = 0;
- }
- }
- memwipe(buf, 0, sizeof(buf));
- return load_entropy_ok ? 0 : -1;
- }
- #endif
- int
- crypto_seed_rng(void)
- {
- int seeded = 0;
- #ifdef ENABLE_NSS
- if (crypto_seed_nss_rng() < 0)
- return -1;
- ++seeded;
- #endif
- #ifdef ENABLE_OPENSSL
- if (crypto_seed_openssl_rng() < 0)
- return -1;
- ++seeded;
- #endif
- tor_assert(seeded);
- return 0;
- }
- MOCK_IMPL(void,
- crypto_rand, (char *to, size_t n))
- {
- crypto_rand_unmocked(to, n);
- }
- void
- crypto_rand_unmocked(char *to, size_t n)
- {
- if (n == 0)
- return;
- tor_assert(n < INT_MAX);
- tor_assert(to);
- #ifdef ENABLE_NSS
- SECStatus s = PK11_GenerateRandom((unsigned char*)to, (int)n);
- if (s != SECSuccess) {
-
-
- #define BUFLEN 512
- tor_assert(PR_GetError() == SEC_ERROR_INVALID_ARGS && n > BUFLEN);
- unsigned char buf[BUFLEN];
- s = PK11_GenerateRandom(buf, BUFLEN);
- tor_assert(s == SECSuccess);
- crypto_xof_t *xof = crypto_xof_new();
- crypto_xof_add_bytes(xof, buf, BUFLEN);
- crypto_xof_squeeze_bytes(xof, (unsigned char *)to, n);
- crypto_xof_free(xof);
- memwipe(buf, 0, BUFLEN);
- #undef BUFLEN
- }
- #else
- int r = RAND_bytes((unsigned char*)to, (int)n);
-
- tor_assert(r >= 0);
- #endif
- }
- uint32_t
- crypto_rand_u32(void)
- {
- uint32_t rand;
- crypto_rand((void*)&rand, sizeof(rand));
- return rand;
- }
- int
- crypto_rand_int(unsigned int max)
- {
- unsigned int val;
- unsigned int cutoff;
- tor_assert(max <= ((unsigned int)INT_MAX)+1);
- tor_assert(max > 0);
-
- cutoff = UINT_MAX - (UINT_MAX%max);
- while (1) {
- crypto_rand((char*)&val, sizeof(val));
- if (val < cutoff)
- return val % max;
- }
- }
- int
- crypto_rand_int_range(unsigned int min, unsigned int max)
- {
- tor_assert(min < max);
- tor_assert(max <= INT_MAX);
-
- return min + crypto_rand_int(max - min);
- }
- uint64_t
- crypto_rand_uint64_range(uint64_t min, uint64_t max)
- {
- tor_assert(min < max);
- return min + crypto_rand_uint64(max - min);
- }
- time_t
- crypto_rand_time_range(time_t min, time_t max)
- {
- tor_assert(min < max);
- return min + (time_t)crypto_rand_uint64(max - min);
- }
- uint64_t
- crypto_rand_uint64(uint64_t max)
- {
- uint64_t val;
- uint64_t cutoff;
- tor_assert(max < UINT64_MAX);
- tor_assert(max > 0);
-
- cutoff = UINT64_MAX - (UINT64_MAX%max);
- while (1) {
- crypto_rand((char*)&val, sizeof(val));
- if (val < cutoff)
- return val % max;
- }
- }
- double
- crypto_rand_double(void)
- {
-
- unsigned int u;
- crypto_rand((char*)&u, sizeof(u));
- #if SIZEOF_INT == 4
- #define UINT_MAX_AS_DOUBLE 4294967296.0
- #elif SIZEOF_INT == 8
- #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
- #else
- #error SIZEOF_INT is neither 4 nor 8
- #endif
- return ((double)u) / UINT_MAX_AS_DOUBLE;
- }
- char *
- crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
- const char *suffix)
- {
- char *result, *rand_bytes;
- int randlen, rand_bytes_len;
- size_t resultlen, prefixlen;
- if (max_rand_len > MAX_DNS_LABEL_SIZE)
- max_rand_len = MAX_DNS_LABEL_SIZE;
- if (min_rand_len > max_rand_len)
- min_rand_len = max_rand_len;
- randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
- prefixlen = strlen(prefix);
- resultlen = prefixlen + strlen(suffix) + randlen + 16;
- rand_bytes_len = ((randlen*5)+7)/8;
- if (rand_bytes_len % 5)
- rand_bytes_len += 5 - (rand_bytes_len%5);
- rand_bytes = tor_malloc(rand_bytes_len);
- crypto_rand(rand_bytes, rand_bytes_len);
- result = tor_malloc(resultlen);
- memcpy(result, prefix, prefixlen);
- base32_encode(result+prefixlen, resultlen-prefixlen,
- rand_bytes, rand_bytes_len);
- tor_free(rand_bytes);
- strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
- return result;
- }
- void *
- smartlist_choose(const smartlist_t *sl)
- {
- int len = smartlist_len(sl);
- if (len)
- return smartlist_get(sl,crypto_rand_int(len));
- return NULL;
- }
- void
- smartlist_shuffle(smartlist_t *sl)
- {
- int i;
-
- for (i = smartlist_len(sl)-1; i > 0; --i) {
- int j = crypto_rand_int(i+1);
- smartlist_swap(sl, i, j);
- }
- }
- int
- crypto_force_rand_ssleay(void)
- {
- #ifdef ENABLE_OPENSSL
- RAND_METHOD *default_method;
- default_method = RAND_OpenSSL();
- if (RAND_get_rand_method() != default_method) {
- log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
- "a replacement the OpenSSL RNG. Resetting it to the default "
- "implementation.");
- RAND_set_rand_method(default_method);
- return 1;
- }
- #endif
- return 0;
- }
- #endif
|