Use rdrand as entropy source on supported platforms
[bitcoinplatinum.git] / src / random.cpp
blobfb7160c8ccb045aab8ce1e5134adf5480859437c
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "random.h"
8 #include "crypto/sha512.h"
9 #include "support/cleanse.h"
10 #ifdef WIN32
11 #include "compat.h" // for Windows API
12 #include <wincrypt.h>
13 #endif
14 #include "util.h" // for LogPrint()
15 #include "utilstrencodings.h" // for GetTime()
17 #include <stdlib.h>
18 #include <limits>
19 #include <chrono>
20 #include <thread>
22 #ifndef WIN32
23 #include <sys/time.h>
24 #endif
26 #ifdef HAVE_SYS_GETRANDOM
27 #include <sys/syscall.h>
28 #include <linux/random.h>
29 #endif
30 #ifdef HAVE_GETENTROPY
31 #include <unistd.h>
32 #endif
33 #ifdef HAVE_SYSCTL_ARND
34 #include <sys/sysctl.h>
35 #endif
37 #include <mutex>
39 #include <openssl/err.h>
40 #include <openssl/rand.h>
42 static void RandFailure()
44 LogPrintf("Failed to read randomness, aborting\n");
45 abort();
48 static inline int64_t GetPerformanceCounter()
50 // Read the hardware time stamp counter when available.
51 // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information.
52 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
53 return __rdtsc();
54 #elif !defined(_MSC_VER) && defined(__i386__)
55 uint64_t r = 0;
56 __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair.
57 return r;
58 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__))
59 uint64_t r1 = 0, r2 = 0;
60 __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx.
61 return (r2 << 32) | r1;
62 #else
63 // Fall back to using C++11 clock (usually microsecond or nanosecond precision)
64 return std::chrono::high_resolution_clock::now().time_since_epoch().count();
65 #endif
69 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
70 static std::atomic<bool> hwrand_initialized{false};
71 static bool rdrand_supported = false;
72 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
73 static void RDRandInit()
75 //! When calling cpuid function #1, ecx register will have this set if RDRAND is available.
76 // Avoid clobbering ebx, as that is used for PIC on x86.
77 uint32_t eax, tmp, ecx, edx;
78 __asm__ ("mov %%ebx, %1; cpuid; mov %1, %%ebx": "=a"(eax), "=g"(tmp), "=c"(ecx), "=d"(edx) : "a"(1));
79 if (ecx & CPUID_F1_ECX_RDRAND) {
80 LogPrintf("Using RdRand as entropy source\n");
81 rdrand_supported = true;
83 hwrand_initialized.store(true);
85 #else
86 static void RDRandInit() {}
87 #endif
89 static bool GetHWRand(unsigned char* ent32) {
90 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
91 assert(hwrand_initialized.load(std::memory_order_relaxed));
92 if (rdrand_supported) {
93 uint8_t ok;
94 // Not all assemblers support the rdrand instruction, write it in hex.
95 #ifdef __i386__
96 for (int iter = 0; iter < 4; ++iter) {
97 uint32_t r1, r2;
98 __asm__ volatile (".byte 0x0f, 0xc7, 0xf0;" // rdrand %eax
99 ".byte 0x0f, 0xc7, 0xf2;" // rdrand %edx
100 "setc %2" :
101 "=a"(r1), "=d"(r2), "=q"(ok) :: "cc");
102 if (!ok) return false;
103 WriteLE32(ent32 + 8 * iter, r1);
104 WriteLE32(ent32 + 8 * iter + 4, r2);
106 #else
107 uint64_t r1, r2, r3, r4;
108 __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf0, " // rdrand %rax
109 "0x48, 0x0f, 0xc7, 0xf3, " // rdrand %rbx
110 "0x48, 0x0f, 0xc7, 0xf1, " // rdrand %rcx
111 "0x48, 0x0f, 0xc7, 0xf2; " // rdrand %rdx
112 "setc %4" :
113 "=a"(r1), "=b"(r2), "=c"(r3), "=d"(r4), "=q"(ok) :: "cc");
114 if (!ok) return false;
115 WriteLE64(ent32, r1);
116 WriteLE64(ent32 + 8, r2);
117 WriteLE64(ent32 + 16, r3);
118 WriteLE64(ent32 + 24, r4);
119 #endif
120 return true;
122 #endif
123 return false;
126 void RandAddSeed()
128 // Seed with CPU performance counter
129 int64_t nCounter = GetPerformanceCounter();
130 RAND_add(&nCounter, sizeof(nCounter), 1.5);
131 memory_cleanse((void*)&nCounter, sizeof(nCounter));
134 static void RandAddSeedPerfmon()
136 RandAddSeed();
138 #ifdef WIN32
139 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
140 // Seed with the entire set of perfmon data
142 // This can take up to 2 seconds, so only do it every 10 minutes
143 static int64_t nLastPerfmon;
144 if (GetTime() < nLastPerfmon + 10 * 60)
145 return;
146 nLastPerfmon = GetTime();
148 std::vector<unsigned char> vData(250000, 0);
149 long ret = 0;
150 unsigned long nSize = 0;
151 const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data
152 while (true) {
153 nSize = vData.size();
154 ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, vData.data(), &nSize);
155 if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
156 break;
157 vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially
159 RegCloseKey(HKEY_PERFORMANCE_DATA);
160 if (ret == ERROR_SUCCESS) {
161 RAND_add(vData.data(), nSize, nSize / 100.0);
162 memory_cleanse(vData.data(), nSize);
163 LogPrint(BCLog::RAND, "%s: %lu bytes\n", __func__, nSize);
164 } else {
165 static bool warned = false; // Warn only once
166 if (!warned) {
167 LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret);
168 warned = true;
171 #endif
174 #ifndef WIN32
175 /** Fallback: get 32 bytes of system entropy from /dev/urandom. The most
176 * compatible way to get cryptographic randomness on UNIX-ish platforms.
178 void GetDevURandom(unsigned char *ent32)
180 int f = open("/dev/urandom", O_RDONLY);
181 if (f == -1) {
182 RandFailure();
184 int have = 0;
185 do {
186 ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
187 if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
188 RandFailure();
190 have += n;
191 } while (have < NUM_OS_RANDOM_BYTES);
192 close(f);
194 #endif
196 /** Get 32 bytes of system entropy. */
197 void GetOSRand(unsigned char *ent32)
199 #if defined(WIN32)
200 HCRYPTPROV hProvider;
201 int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
202 if (!ret) {
203 RandFailure();
205 ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
206 if (!ret) {
207 RandFailure();
209 CryptReleaseContext(hProvider, 0);
210 #elif defined(HAVE_SYS_GETRANDOM)
211 /* Linux. From the getrandom(2) man page:
212 * "If the urandom source has been initialized, reads of up to 256 bytes
213 * will always return as many bytes as requested and will not be
214 * interrupted by signals."
216 int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
217 if (rv != NUM_OS_RANDOM_BYTES) {
218 if (rv < 0 && errno == ENOSYS) {
219 /* Fallback for kernel <3.17: the return value will be -1 and errno
220 * ENOSYS if the syscall is not available, in that case fall back
221 * to /dev/urandom.
223 GetDevURandom(ent32);
224 } else {
225 RandFailure();
228 #elif defined(HAVE_GETENTROPY)
229 /* On OpenBSD this can return up to 256 bytes of entropy, will return an
230 * error if more are requested.
231 * The call cannot return less than the requested number of bytes.
233 if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
234 RandFailure();
236 #elif defined(HAVE_SYSCTL_ARND)
237 /* FreeBSD and similar. It is possible for the call to return less
238 * bytes than requested, so need to read in a loop.
240 static const int name[2] = {CTL_KERN, KERN_ARND};
241 int have = 0;
242 do {
243 size_t len = NUM_OS_RANDOM_BYTES - have;
244 if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, NULL, 0) != 0) {
245 RandFailure();
247 have += len;
248 } while (have < NUM_OS_RANDOM_BYTES);
249 #else
250 /* Fall back to /dev/urandom if there is no specific method implemented to
251 * get system entropy for this OS.
253 GetDevURandom(ent32);
254 #endif
257 void GetRandBytes(unsigned char* buf, int num)
259 if (RAND_bytes(buf, num) != 1) {
260 RandFailure();
264 static void AddDataToRng(void* data, size_t len);
266 void RandAddSeedSleep()
268 int64_t nPerfCounter1 = GetPerformanceCounter();
269 std::this_thread::sleep_for(std::chrono::milliseconds(1));
270 int64_t nPerfCounter2 = GetPerformanceCounter();
272 // Combine with and update state
273 AddDataToRng(&nPerfCounter1, sizeof(nPerfCounter1));
274 AddDataToRng(&nPerfCounter2, sizeof(nPerfCounter2));
276 memory_cleanse(&nPerfCounter1, sizeof(nPerfCounter1));
277 memory_cleanse(&nPerfCounter2, sizeof(nPerfCounter2));
281 static std::mutex cs_rng_state;
282 static unsigned char rng_state[32] = {0};
283 static uint64_t rng_counter = 0;
285 static void AddDataToRng(void* data, size_t len) {
286 CSHA512 hasher;
287 hasher.Write((const unsigned char*)&len, sizeof(len));
288 hasher.Write((const unsigned char*)data, len);
289 unsigned char buf[64];
291 std::unique_lock<std::mutex> lock(cs_rng_state);
292 hasher.Write(rng_state, sizeof(rng_state));
293 hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
294 ++rng_counter;
295 hasher.Finalize(buf);
296 memcpy(rng_state, buf + 32, 32);
298 memory_cleanse(buf, 64);
301 void GetStrongRandBytes(unsigned char* out, int num)
303 assert(num <= 32);
304 CSHA512 hasher;
305 unsigned char buf[64];
307 // First source: OpenSSL's RNG
308 RandAddSeedPerfmon();
309 GetRandBytes(buf, 32);
310 hasher.Write(buf, 32);
312 // Second source: OS RNG
313 GetOSRand(buf);
314 hasher.Write(buf, 32);
316 // Third source: HW RNG, if available.
317 if (GetHWRand(buf)) {
318 hasher.Write(buf, 32);
321 // Combine with and update state
323 std::unique_lock<std::mutex> lock(cs_rng_state);
324 hasher.Write(rng_state, sizeof(rng_state));
325 hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
326 ++rng_counter;
327 hasher.Finalize(buf);
328 memcpy(rng_state, buf + 32, 32);
331 // Produce output
332 memcpy(out, buf, num);
333 memory_cleanse(buf, 64);
336 uint64_t GetRand(uint64_t nMax)
338 if (nMax == 0)
339 return 0;
341 // The range of the random source must be a multiple of the modulus
342 // to give every possible output value an equal possibility
343 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
344 uint64_t nRand = 0;
345 do {
346 GetRandBytes((unsigned char*)&nRand, sizeof(nRand));
347 } while (nRand >= nRange);
348 return (nRand % nMax);
351 int GetRandInt(int nMax)
353 return GetRand(nMax);
356 uint256 GetRandHash()
358 uint256 hash;
359 GetRandBytes((unsigned char*)&hash, sizeof(hash));
360 return hash;
363 void FastRandomContext::RandomSeed()
365 uint256 seed = GetRandHash();
366 rng.SetKey(seed.begin(), 32);
367 requires_seed = false;
370 FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
372 rng.SetKey(seed.begin(), 32);
375 bool Random_SanityCheck()
377 uint64_t start = GetPerformanceCounter();
379 /* This does not measure the quality of randomness, but it does test that
380 * OSRandom() overwrites all 32 bytes of the output given a maximum
381 * number of tries.
383 static const ssize_t MAX_TRIES = 1024;
384 uint8_t data[NUM_OS_RANDOM_BYTES];
385 bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */
386 int num_overwritten;
387 int tries = 0;
388 /* Loop until all bytes have been overwritten at least once, or max number tries reached */
389 do {
390 memset(data, 0, NUM_OS_RANDOM_BYTES);
391 GetOSRand(data);
392 for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
393 overwritten[x] |= (data[x] != 0);
396 num_overwritten = 0;
397 for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
398 if (overwritten[x]) {
399 num_overwritten += 1;
403 tries += 1;
404 } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
405 if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */
407 // Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep.
408 std::this_thread::sleep_for(std::chrono::milliseconds(1));
409 uint64_t stop = GetPerformanceCounter();
410 if (stop == start) return false;
412 // We called GetPerformanceCounter. Use it as entropy.
413 RAND_add((const unsigned char*)&start, sizeof(start), 1);
414 RAND_add((const unsigned char*)&stop, sizeof(stop), 1);
416 return true;
419 FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0)
421 if (!fDeterministic) {
422 return;
424 uint256 seed;
425 rng.SetKey(seed.begin(), 32);
428 void RandomInit()
430 RDRandInit();