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