Raven Core  3.0.0
P2P Digital Currency
random.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "random.h"
8 
9 #include "crypto/sha512.h"
10 #include "support/cleanse.h"
11 #ifdef WIN32
12 #include "compat.h" // for Windows API
13 #include <wincrypt.h>
14 #endif
15 #include "util.h" // for LogPrint()
16 #include "utilstrencodings.h" // for GetTime()
17 
18 #include <stdlib.h>
19 #include <limits>
20 #include <chrono>
21 #include <thread>
22 
23 #ifndef WIN32
24 #include <sys/time.h>
25 #endif
26 
27 #ifdef HAVE_SYS_GETRANDOM
28 #include <sys/syscall.h>
29 #include <linux/random.h>
30 #endif
31 #if defined(HAVE_GETENTROPY) || (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX))
32 #include <unistd.h>
33 #endif
34 #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
35 #include <sys/random.h>
36 #endif
37 #ifdef HAVE_SYSCTL_ARND
38 #include <sys/sysctl.h>
39 #endif
40 
41 #include <mutex>
42 
43 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
44 #include <cpuid.h>
45 #endif
46 
47 #include <openssl/err.h>
48 #include <openssl/rand.h>
49 
50 [[noreturn]] static void RandFailure()
51 {
52  LogPrintf("Failed to read randomness, aborting\n");
53  std::abort();
54 }
55 
56 static inline int64_t GetPerformanceCounter()
57 {
58  // Read the hardware time stamp counter when available.
59  // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information.
60 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
61  return __rdtsc();
62 #elif !defined(_MSC_VER) && defined(__i386__)
63  uint64_t r = 0;
64  __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair.
65  return r;
66 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__))
67  uint64_t r1 = 0, r2 = 0;
68  __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx.
69  return (r2 << 32) | r1;
70 #else
71  // Fall back to using C++11 clock (usually microsecond or nanosecond precision)
72  return std::chrono::high_resolution_clock::now().time_since_epoch().count();
73 #endif
74 }
75 
76 
77 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
78 static std::atomic<bool> hwrand_initialized{false};
79 static bool rdrand_supported = false;
80 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
81 static void RDRandInit()
82 {
83  uint32_t eax, ebx, ecx, edx;
84  if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx & CPUID_F1_ECX_RDRAND)) {
85  LogPrintf("Using RdRand as an additional entropy source\n");
86  rdrand_supported = true;
87  }
88  hwrand_initialized.store(true);
89 }
90 #else
91 static void RDRandInit() {}
92 #endif
93 
94 static bool GetHWRand(unsigned char* ent32) {
95 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
96  assert(hwrand_initialized.load(std::memory_order_relaxed));
97  if (rdrand_supported) {
98  uint8_t ok;
99  // Not all assemblers support the rdrand instruction, write it in hex.
100 #ifdef __i386__
101  for (int iter = 0; iter < 4; ++iter) {
102  uint32_t r1, r2;
103  __asm__ volatile (".byte 0x0f, 0xc7, 0xf0;" // rdrand %eax
104  ".byte 0x0f, 0xc7, 0xf2;" // rdrand %edx
105  "setc %2" :
106  "=a"(r1), "=d"(r2), "=q"(ok) :: "cc");
107  if (!ok) return false;
108  WriteLE32(ent32 + 8 * iter, r1);
109  WriteLE32(ent32 + 8 * iter + 4, r2);
110  }
111 #else
112  uint64_t r1, r2, r3, r4;
113  __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf0, " // rdrand %rax
114  "0x48, 0x0f, 0xc7, 0xf3, " // rdrand %rbx
115  "0x48, 0x0f, 0xc7, 0xf1, " // rdrand %rcx
116  "0x48, 0x0f, 0xc7, 0xf2; " // rdrand %rdx
117  "setc %4" :
118  "=a"(r1), "=b"(r2), "=c"(r3), "=d"(r4), "=q"(ok) :: "cc");
119  if (!ok) return false;
120  WriteLE64(ent32, r1);
121  WriteLE64(ent32 + 8, r2);
122  WriteLE64(ent32 + 16, r3);
123  WriteLE64(ent32 + 24, r4);
124 #endif
125  return true;
126  }
127 #endif
128  return false;
129 }
130 
132 {
133  // Seed with CPU performance counter
134  int64_t nCounter = GetPerformanceCounter();
135  RAND_add(&nCounter, sizeof(nCounter), 1.5);
136  memory_cleanse((void*)&nCounter, sizeof(nCounter));
137 }
138 
139 static void RandAddSeedPerfmon()
140 {
141  RandAddSeed();
142 
143 #ifdef WIN32
144  // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
145  // Seed with the entire set of perfmon data
146 
147  // This can take up to 2 seconds, so only do it every 10 minutes
148  static int64_t nLastPerfmon;
149  if (GetTime() < nLastPerfmon + 10 * 60)
150  return;
151  nLastPerfmon = GetTime();
152 
153  std::vector<unsigned char> vData(250000, 0);
154  long ret = 0;
155  unsigned long nSize = 0;
156  const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data
157  while (true) {
158  nSize = vData.size();
159  ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, vData.data(), &nSize);
160  if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
161  break;
162  vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially
163  }
164  RegCloseKey(HKEY_PERFORMANCE_DATA);
165  if (ret == ERROR_SUCCESS) {
166  RAND_add(vData.data(), nSize, nSize / 100.0);
167  memory_cleanse(vData.data(), nSize);
168  LogPrint(BCLog::RAND, "%s: %lu bytes\n", __func__, nSize);
169  } else {
170  static bool warned = false; // Warn only once
171  if (!warned) {
172  LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret);
173  warned = true;
174  }
175  }
176 #endif
177 }
178 
179 #ifndef WIN32
180 
183 void GetDevURandom(unsigned char *ent32)
184 {
185  int f = open("/dev/urandom", O_RDONLY);
186  if (f == -1) {
187  RandFailure();
188  }
189  int have = 0;
190  do {
191  ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
192  if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
193  close(f);
194  RandFailure();
195  }
196  have += n;
197  } while (have < NUM_OS_RANDOM_BYTES);
198  close(f);
199 }
200 #endif
201 
203 void GetOSRand(unsigned char *ent32)
204 {
205 #if defined(WIN32)
206  HCRYPTPROV hProvider;
207  int ret = CryptAcquireContextW(&hProvider, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
208  if (!ret) {
209  RandFailure();
210  }
211  ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
212  if (!ret) {
213  RandFailure();
214  }
215  CryptReleaseContext(hProvider, 0);
216 #elif defined(HAVE_SYS_GETRANDOM)
217  /* Linux. From the getrandom(2) man page:
218  * "If the urandom source has been initialized, reads of up to 256 bytes
219  * will always return as many bytes as requested and will not be
220  * interrupted by signals."
221  */
222  int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
223  if (rv != NUM_OS_RANDOM_BYTES) {
224  if (rv < 0 && errno == ENOSYS) {
225  /* Fallback for kernel <3.17: the return value will be -1 and errno
226  * ENOSYS if the syscall is not available, in that case fall back
227  * to /dev/urandom.
228  */
229  GetDevURandom(ent32);
230  } else {
231  RandFailure();
232  }
233  }
234 #elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__)
235  /* On OpenBSD this can return up to 256 bytes of entropy, will return an
236  * error if more are requested.
237  * The call cannot return less than the requested number of bytes.
238  getentropy is explicitly limited to openbsd here, as a similar (but not
239  the same) function may exist on other platforms via glibc.
240  */
241  if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
242  RandFailure();
243  }
244 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
245  // We need a fallback for OSX < 10.12
246  if (&getentropy != nullptr) {
247  if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
248  RandFailure();
249  }
250  } else {
251  GetDevURandom(ent32);
252  }
253 #elif defined(HAVE_SYSCTL_ARND)
254  /* FreeBSD and similar. It is possible for the call to return less
255  * bytes than requested, so need to read in a loop.
256  */
257  static const int name[2] = {CTL_KERN, KERN_ARND};
258  int have = 0;
259  do {
260  size_t len = NUM_OS_RANDOM_BYTES - have;
261  if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, nullptr, 0) != 0) {
262  RandFailure();
263  }
264  have += len;
265  } while (have < NUM_OS_RANDOM_BYTES);
266 #else
267  /* Fall back to /dev/urandom if there is no specific method implemented to
268  * get system entropy for this OS.
269  */
270  GetDevURandom(ent32);
271 #endif
272 }
273 
274 void GetRandBytes(unsigned char* buf, int num)
275 {
276  if (RAND_bytes(buf, num) != 1) {
277  RandFailure();
278  }
279 }
280 
281 static void AddDataToRng(void* data, size_t len);
282 
284 {
285  int64_t nPerfCounter1 = GetPerformanceCounter();
286  std::this_thread::sleep_for(std::chrono::milliseconds(1));
287  int64_t nPerfCounter2 = GetPerformanceCounter();
288 
289  // Combine with and update state
290  AddDataToRng(&nPerfCounter1, sizeof(nPerfCounter1));
291  AddDataToRng(&nPerfCounter2, sizeof(nPerfCounter2));
292 
293  memory_cleanse(&nPerfCounter1, sizeof(nPerfCounter1));
294  memory_cleanse(&nPerfCounter2, sizeof(nPerfCounter2));
295 }
296 
297 
298 static std::mutex cs_rng_state;
299 static unsigned char rng_state[32] = {0};
300 static uint64_t rng_counter = 0;
301 
302 static void AddDataToRng(void* data, size_t len) {
303  CSHA512 hasher;
304  hasher.Write((const unsigned char*)&len, sizeof(len));
305  hasher.Write((const unsigned char*)data, len);
306  unsigned char buf[64];
307  {
308  std::unique_lock<std::mutex> lock(cs_rng_state);
309  hasher.Write(rng_state, sizeof(rng_state));
310  hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
311  ++rng_counter;
312  hasher.Finalize(buf);
313  memcpy(rng_state, buf + 32, 32);
314  }
315  memory_cleanse(buf, 64);
316 }
317 
318 void GetStrongRandBytes(unsigned char* out, int num)
319 {
320  assert(num <= 32);
321  CSHA512 hasher;
322  unsigned char buf[64];
323 
324  // First source: OpenSSL's RNG
325  RandAddSeedPerfmon();
326  GetRandBytes(buf, 32);
327  hasher.Write(buf, 32);
328 
329  // Second source: OS RNG
330  GetOSRand(buf);
331  hasher.Write(buf, 32);
332 
333  // Third source: HW RNG, if available.
334  if (GetHWRand(buf)) {
335  hasher.Write(buf, 32);
336  }
337 
338  // Combine with and update state
339  {
340  std::unique_lock<std::mutex> lock(cs_rng_state);
341  hasher.Write(rng_state, sizeof(rng_state));
342  hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
343  ++rng_counter;
344  hasher.Finalize(buf);
345  memcpy(rng_state, buf + 32, 32);
346  }
347 
348  // Produce output
349  memcpy(out, buf, num);
350  memory_cleanse(buf, 64);
351 }
352 
353 uint64_t GetRand(uint64_t nMax)
354 {
355  if (nMax == 0)
356  return 0;
357 
358  // The range of the random source must be a multiple of the modulus
359  // to give every possible output value an equal possibility
360  uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
361  uint64_t nRand = 0;
362  do {
363  GetRandBytes((unsigned char*)&nRand, sizeof(nRand));
364  } while (nRand >= nRange);
365  return (nRand % nMax);
366 }
367 
368 int GetRandInt(int nMax)
369 {
370  return GetRand(nMax);
371 }
372 
374 {
375  uint256 hash;
376  GetRandBytes((unsigned char*)&hash, sizeof(hash));
377  return hash;
378 }
379 
381 {
382  uint256 seed = GetRandHash();
383  rng.SetKey(seed.begin(), 32);
384  requires_seed = false;
385 }
386 
388 {
389  if (bytebuf_size < 32) {
390  FillByteBuffer();
391  }
392  uint256 ret;
393  memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32);
394  bytebuf_size -= 32;
395  return ret;
396 }
397 
398 std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
399 {
400  std::vector<unsigned char> ret(len);
401  if (len > 0) {
402  rng.Output(&ret[0], len);
403  }
404  return ret;
405 }
406 
408 {
409  rng.SetKey(seed.begin(), 32);
410 }
411 
413 {
414  uint64_t start = GetPerformanceCounter();
415 
416  /* This does not measure the quality of randomness, but it does test that
417  * OSRandom() overwrites all 32 bytes of the output given a maximum
418  * number of tries.
419  */
420  static const ssize_t MAX_TRIES = 1024;
421  uint8_t data[NUM_OS_RANDOM_BYTES];
422  bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */
423  int num_overwritten;
424  int tries = 0;
425  /* Loop until all bytes have been overwritten at least once, or max number tries reached */
426  do {
427  memset(data, 0, NUM_OS_RANDOM_BYTES);
428  GetOSRand(data);
429  for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
430  overwritten[x] |= (data[x] != 0);
431  }
432 
433  num_overwritten = 0;
434  for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
435  if (overwritten[x]) {
436  num_overwritten += 1;
437  }
438  }
439 
440  tries += 1;
441  } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
442  if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */
443 
444  // Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep.
445  std::this_thread::sleep_for(std::chrono::milliseconds(1));
446  uint64_t stop = GetPerformanceCounter();
447  if (stop == start) return false;
448 
449  // We called GetPerformanceCounter. Use it as entropy.
450  RAND_add((const unsigned char*)&start, sizeof(start), 1);
451  RAND_add((const unsigned char*)&stop, sizeof(stop), 1);
452 
453  return true;
454 }
455 
456 FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0)
457 {
458  if (!fDeterministic) {
459  return;
460  }
461  uint256 seed;
462  rng.SetKey(seed.begin(), 32);
463 }
464 
466 {
467  RDRandInit();
468 }
void GetDevURandom(unsigned char *ent32)
Fallback: get 32 bytes of system entropy from /dev/urandom.
Definition: random.cpp:183
void RandomInit()
Initialize the RNG.
Definition: random.cpp:465
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
Definition: random.cpp:203
void Output(unsigned char *output, size_t bytes)
Definition: chacha20.cpp:75
void RandAddSeedSleep()
Add a little bit of randomness to the output of GetStrongRangBytes.
Definition: random.cpp:283
uint256 GetRandHash()
Definition: random.cpp:373
FastRandomContext(bool fDeterministic=false)
Definition: random.cpp:456
int GetRandInt(int nMax)
Definition: random.cpp:368
unsigned char bytebuf[64]
Definition: random.h:50
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those source fail to pr...
Definition: random.cpp:318
unsigned char * begin()
Definition: uint256.h:57
void FillByteBuffer()
Definition: random.h:58
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha512.cpp:186
void memory_cleanse(void *ptr, size_t len)
Definition: cleanse.cpp:28
#define LogPrintf(...)
Definition: util.h:149
uint256 rand256()
generate a random uint256.
Definition: random.cpp:387
void RandomSeed()
Definition: random.cpp:380
int bytebuf_size
Definition: random.h:51
#define LogPrint(category,...)
Definition: util.h:160
bool requires_seed
Definition: random.h:47
256-bit opaque blob.
Definition: uint256.h:123
#define ARRAYLEN(array)
void * memcpy(void *a, const void *b, size_t c)
CSHA512 & Write(const unsigned char *data, size_t len)
Definition: sha512.cpp:160
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:274
void RandAddSeed()
Definition: random.cpp:131
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
A hasher class for SHA-512.
Definition: sha512.h:13
ChaCha20 rng
Definition: random.h:48
void SetKey(const unsigned char *key, size_t keylen)
Definition: chacha20.cpp:25
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:412
std::vector< unsigned char > randbytes(size_t len)
Generate random bytes.
Definition: random.cpp:398
UniValue stop(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:236
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:353