Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2021 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 : #if defined(HAVE_CONFIG_H)
7 : #include <config/bitcoin-config.h>
8 : #endif
9 :
10 : #include <randomenv.h>
11 :
12 : #include <clientversion.h>
13 : #include <compat/cpuid.h>
14 : #include <crypto/sha512.h>
15 : #include <span.h>
16 : #include <support/cleanse.h>
17 : #include <util/time.h>
18 :
19 : #include <algorithm>
20 : #include <atomic>
21 : #include <cstdint>
22 : #include <cstring>
23 : #include <chrono>
24 : #include <climits>
25 : #include <thread>
26 : #include <vector>
27 :
28 : #include <sys/types.h> // must go before a number of other headers
29 :
30 : #ifdef WIN32
31 : #include <windows.h>
32 : #include <winreg.h>
33 : #else
34 : #include <fcntl.h>
35 : #include <netinet/in.h>
36 : #include <sys/resource.h>
37 : #include <sys/socket.h>
38 : #include <sys/stat.h>
39 : #include <sys/time.h>
40 : #include <sys/utsname.h>
41 : #include <unistd.h>
42 : #endif
43 : #if HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS
44 : #include <ifaddrs.h>
45 : #endif
46 : #if HAVE_SYSCTL
47 : #include <sys/sysctl.h>
48 : #if HAVE_VM_VM_PARAM_H
49 : #include <vm/vm_param.h>
50 : #endif
51 : #if HAVE_SYS_RESOURCES_H
52 : #include <sys/resources.h>
53 : #endif
54 : #if HAVE_SYS_VMMETER_H
55 : #include <sys/vmmeter.h>
56 : #endif
57 : #endif
58 : #if defined(HAVE_STRONG_GETAUXVAL)
59 : #include <sys/auxv.h>
60 : #endif
61 :
62 : #ifndef _MSC_VER
63 : //! Necessary on some platforms
64 : extern char** environ; // NOLINT(readability-redundant-declaration): Necessary on some platforms
65 : #endif
66 :
67 : namespace {
68 :
69 8844 : void RandAddSeedPerfmon(CSHA512& hasher)
70 : {
71 : #ifdef WIN32
72 : // Seed with the entire set of perfmon data
73 :
74 : // This can take up to 2 seconds, so only do it every 10 minutes.
75 : // Initialize last_perfmon to 0 seconds, we don't skip the first call.
76 : static std::atomic<SteadyClock::time_point> last_perfmon{SteadyClock::time_point{0s}};
77 : auto last_time = last_perfmon.load();
78 : auto current_time = SteadyClock::now();
79 : if (current_time < last_time + 10min) return;
80 : last_perfmon = current_time;
81 :
82 : std::vector<unsigned char> vData(250000, 0);
83 : long ret = 0;
84 : unsigned long nSize = 0;
85 : const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data
86 : while (true) {
87 : nSize = vData.size();
88 : ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, vData.data(), &nSize);
89 : if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
90 : break;
91 : vData.resize(std::min((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially
92 : }
93 : RegCloseKey(HKEY_PERFORMANCE_DATA);
94 : if (ret == ERROR_SUCCESS) {
95 : hasher.Write(vData.data(), nSize);
96 : memory_cleanse(vData.data(), nSize);
97 : } else {
98 : // Performance data is only a best-effort attempt at improving the
99 : // situation when the OS randomness (and other sources) aren't
100 : // adequate. As a result, failure to read it is isn't considered critical,
101 : // so we don't call RandFailure().
102 : // TODO: Add logging when the logger is made functional before global
103 : // constructors have been invoked.
104 : }
105 : #endif
106 8844 : }
107 :
108 : /** Helper to easily feed data into a CSHA512.
109 : *
110 : * Note that this does not serialize the passed object (like stream.h's << operators do).
111 : * Its raw memory representation is used directly.
112 : */
113 : template<typename T>
114 333015 : CSHA512& operator<<(CSHA512& hasher, const T& data) {
115 : static_assert(!std::is_same<typename std::decay<T>::type, char*>::value, "Calling operator<<(CSHA512, char*) is probably not what you want");
116 : static_assert(!std::is_same<typename std::decay<T>::type, unsigned char*>::value, "Calling operator<<(CSHA512, unsigned char*) is probably not what you want");
117 : static_assert(!std::is_same<typename std::decay<T>::type, const char*>::value, "Calling operator<<(CSHA512, const char*) is probably not what you want");
118 : static_assert(!std::is_same<typename std::decay<T>::type, const unsigned char*>::value, "Calling operator<<(CSHA512, const unsigned char*) is probably not what you want");
119 333015 : hasher.Write((const unsigned char*)&data, sizeof(data));
120 333015 : return hasher;
121 : }
122 :
123 : #ifndef WIN32
124 425703 : void AddSockaddr(CSHA512& hasher, const struct sockaddr *addr)
125 : {
126 425703 : if (addr == nullptr) return;
127 231887 : switch (addr->sa_family) {
128 : case AF_INET:
129 31149 : hasher.Write((const unsigned char*)addr, sizeof(sockaddr_in));
130 31149 : break;
131 : case AF_INET6:
132 86525 : hasher.Write((const unsigned char*)addr, sizeof(sockaddr_in6));
133 86525 : break;
134 : default:
135 114213 : hasher.Write((const unsigned char*)&addr->sa_family, sizeof(addr->sa_family));
136 114213 : }
137 425703 : }
138 :
139 20766 : void AddFile(CSHA512& hasher, const char *path)
140 : {
141 20766 : struct stat sb = {};
142 20766 : int f = open(path, O_RDONLY);
143 20766 : size_t total = 0;
144 20766 : if (f != -1) {
145 : unsigned char fbuf[4096];
146 : int n;
147 17305 : hasher.Write((const unsigned char*)&f, sizeof(f));
148 17305 : if (fstat(f, &sb) == 0) hasher << sb;
149 17305 : do {
150 24227 : n = read(f, fbuf, sizeof(fbuf));
151 24227 : if (n > 0) hasher.Write(fbuf, n);
152 24227 : total += n;
153 : /* not bothering with EINTR handling. */
154 24227 : } while (n == sizeof(fbuf) && total < 1048576); // Read only the first 1 Mbyte
155 17305 : close(f);
156 17305 : }
157 20766 : }
158 :
159 17305 : void AddPath(CSHA512& hasher, const char *path)
160 : {
161 17305 : struct stat sb = {};
162 17305 : if (stat(path, &sb) == 0) {
163 13844 : hasher.Write((const unsigned char*)path, strlen(path) + 1);
164 13844 : hasher << sb;
165 13844 : }
166 17305 : }
167 : #endif
168 :
169 : #if HAVE_SYSCTL
170 : template<int... S>
171 104596 : void AddSysctl(CSHA512& hasher)
172 : {
173 104596 : int CTL[sizeof...(S)] = {S...};
174 : unsigned char buffer[65536];
175 104596 : size_t siz = 65536;
176 104596 : int ret = sysctl(CTL, sizeof...(S), buffer, &siz, nullptr, 0);
177 104596 : if (ret == 0 || (ret == -1 && errno == ENOMEM)) {
178 69603 : hasher << sizeof(CTL);
179 69603 : hasher.Write((const unsigned char*)CTL, sizeof(CTL));
180 69603 : if (siz > sizeof(buffer)) siz = sizeof(buffer);
181 69603 : hasher << siz;
182 69603 : hasher.Write(buffer, siz);
183 69603 : }
184 104596 : }
185 : #endif
186 :
187 : #ifdef HAVE_GETCPUID
188 : void inline AddCPUID(CSHA512& hasher, uint32_t leaf, uint32_t subleaf, uint32_t& ax, uint32_t& bx, uint32_t& cx, uint32_t& dx)
189 : {
190 : GetCPUID(leaf, subleaf, ax, bx, cx, dx);
191 : hasher << leaf << subleaf << ax << bx << cx << dx;
192 : }
193 :
194 : void AddAllCPUID(CSHA512& hasher)
195 : {
196 : uint32_t ax, bx, cx, dx;
197 : // Iterate over all standard leaves
198 : AddCPUID(hasher, 0, 0, ax, bx, cx, dx); // Returns max leaf in ax
199 : uint32_t max = ax;
200 : for (uint32_t leaf = 1; leaf <= max && leaf <= 0xFF; ++leaf) {
201 : uint32_t maxsub = 0;
202 : for (uint32_t subleaf = 0; subleaf <= 0xFF; ++subleaf) {
203 : AddCPUID(hasher, leaf, subleaf, ax, bx, cx, dx);
204 : // Iterate subleafs for leaf values 4, 7, 11, 13
205 : if (leaf == 4) {
206 : if ((ax & 0x1f) == 0) break;
207 : } else if (leaf == 7) {
208 : if (subleaf == 0) maxsub = ax;
209 : if (subleaf == maxsub) break;
210 : } else if (leaf == 11) {
211 : if ((cx & 0xff00) == 0) break;
212 : } else if (leaf == 13) {
213 : if (ax == 0 && bx == 0 && cx == 0 && dx == 0) break;
214 : } else {
215 : // For any other leaf, stop after subleaf 0.
216 : break;
217 : }
218 : }
219 : }
220 : // Iterate over all extended leaves
221 : AddCPUID(hasher, 0x80000000, 0, ax, bx, cx, dx); // Returns max extended leaf in ax
222 : uint32_t ext_max = ax;
223 : for (uint32_t leaf = 0x80000001; leaf <= ext_max && leaf <= 0x800000FF; ++leaf) {
224 : AddCPUID(hasher, leaf, 0, ax, bx, cx, dx);
225 : }
226 : }
227 : #endif
228 : } // namespace
229 :
230 8844 : void RandAddDynamicEnv(CSHA512& hasher)
231 : {
232 8844 : RandAddSeedPerfmon(hasher);
233 :
234 : // Various clocks
235 : #ifdef WIN32
236 : FILETIME ftime;
237 : GetSystemTimeAsFileTime(&ftime);
238 : hasher << ftime;
239 : #else
240 8844 : struct timespec ts = {};
241 : # ifdef CLOCK_MONOTONIC
242 8844 : clock_gettime(CLOCK_MONOTONIC, &ts);
243 8844 : hasher << ts;
244 : # endif
245 : # ifdef CLOCK_REALTIME
246 8844 : clock_gettime(CLOCK_REALTIME, &ts);
247 8844 : hasher << ts;
248 : # endif
249 : # ifdef CLOCK_BOOTTIME
250 : clock_gettime(CLOCK_BOOTTIME, &ts);
251 : hasher << ts;
252 : # endif
253 : // gettimeofday is available on all UNIX systems, but only has microsecond precision.
254 8844 : struct timeval tv = {};
255 8844 : gettimeofday(&tv, nullptr);
256 8844 : hasher << tv;
257 : #endif
258 : // Probably redundant, but also use all the standard library clocks:
259 8844 : hasher << std::chrono::system_clock::now().time_since_epoch().count();
260 8844 : hasher << std::chrono::steady_clock::now().time_since_epoch().count();
261 8844 : hasher << std::chrono::high_resolution_clock::now().time_since_epoch().count();
262 :
263 : #ifndef WIN32
264 : // Current resource usage.
265 8844 : struct rusage usage = {};
266 8844 : if (getrusage(RUSAGE_SELF, &usage) == 0) hasher << usage;
267 : #endif
268 :
269 : #ifdef __linux__
270 : AddFile(hasher, "/proc/diskstats");
271 : AddFile(hasher, "/proc/vmstat");
272 : AddFile(hasher, "/proc/schedstat");
273 : AddFile(hasher, "/proc/zoneinfo");
274 : AddFile(hasher, "/proc/meminfo");
275 : AddFile(hasher, "/proc/softirqs");
276 : AddFile(hasher, "/proc/stat");
277 : AddFile(hasher, "/proc/self/schedstat");
278 : AddFile(hasher, "/proc/self/status");
279 : #endif
280 :
281 : #if HAVE_SYSCTL
282 : # ifdef CTL_KERN
283 : # if defined(KERN_PROC) && defined(KERN_PROC_ALL)
284 8844 : AddSysctl<CTL_KERN, KERN_PROC, KERN_PROC_ALL>(hasher);
285 : # endif
286 : # endif
287 : # ifdef CTL_HW
288 : # ifdef HW_DISKSTATS
289 8844 : AddSysctl<CTL_HW, HW_DISKSTATS>(hasher);
290 : # endif
291 : # endif
292 : # ifdef CTL_VM
293 : # ifdef VM_LOADAVG
294 8844 : AddSysctl<CTL_VM, VM_LOADAVG>(hasher);
295 : # endif
296 : # ifdef VM_TOTAL
297 : AddSysctl<CTL_VM, VM_TOTAL>(hasher);
298 : # endif
299 : # ifdef VM_METER
300 8844 : AddSysctl<CTL_VM, VM_METER>(hasher);
301 : # endif
302 : # endif
303 : #endif
304 :
305 : // Stack and heap location
306 8844 : void* addr = malloc(4097);
307 8844 : hasher << &addr << addr;
308 8844 : free(addr);
309 8844 : }
310 :
311 3461 : void RandAddStaticEnv(CSHA512& hasher)
312 : {
313 : // Some compile-time static properties
314 3461 : hasher << (CHAR_MIN < 0) << sizeof(void*) << sizeof(long) << sizeof(int);
315 : #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__)
316 3461 : hasher << __GNUC__ << __GNUC_MINOR__ << __GNUC_PATCHLEVEL__;
317 : #endif
318 : #ifdef _MSC_VER
319 : hasher << _MSC_VER;
320 : #endif
321 3461 : hasher << __cplusplus;
322 : #ifdef _XOPEN_VERSION
323 3461 : hasher << _XOPEN_VERSION;
324 : #endif
325 : #ifdef __VERSION__
326 3461 : const char* COMPILER_VERSION = __VERSION__;
327 3461 : hasher.Write((const unsigned char*)COMPILER_VERSION, strlen(COMPILER_VERSION) + 1);
328 : #endif
329 :
330 : // Bitcoin client version
331 3461 : hasher << CLIENT_VERSION;
332 :
333 : #if defined(HAVE_STRONG_GETAUXVAL)
334 : // Information available through getauxval()
335 : # ifdef AT_HWCAP
336 : hasher << getauxval(AT_HWCAP);
337 : # endif
338 : # ifdef AT_HWCAP2
339 : hasher << getauxval(AT_HWCAP2);
340 : # endif
341 : # ifdef AT_RANDOM
342 : const unsigned char* random_aux = (const unsigned char*)getauxval(AT_RANDOM);
343 : if (random_aux) hasher.Write(random_aux, 16);
344 : # endif
345 : # ifdef AT_PLATFORM
346 : const char* platform_str = (const char*)getauxval(AT_PLATFORM);
347 : if (platform_str) hasher.Write((const unsigned char*)platform_str, strlen(platform_str) + 1);
348 : # endif
349 : # ifdef AT_EXECFN
350 : const char* exec_str = (const char*)getauxval(AT_EXECFN);
351 : if (exec_str) hasher.Write((const unsigned char*)exec_str, strlen(exec_str) + 1);
352 : # endif
353 : #endif // HAVE_STRONG_GETAUXVAL
354 :
355 : #ifdef HAVE_GETCPUID
356 : AddAllCPUID(hasher);
357 : #endif
358 :
359 : // Memory locations
360 3461 : hasher << &hasher << &RandAddStaticEnv << &malloc << &errno << &environ;
361 :
362 : // Hostname
363 : #ifdef WIN32
364 : constexpr DWORD max_size = MAX_COMPUTERNAME_LENGTH + 1;
365 : char hname[max_size];
366 : DWORD size = max_size;
367 : if (GetComputerNameA(hname, &size) != 0) {
368 : hasher.Write(UCharCast(hname), size);
369 : }
370 : #else
371 : char hname[256];
372 3461 : if (gethostname(hname, 256) == 0) {
373 3461 : hasher.Write((const unsigned char*)hname, strnlen(hname, 256));
374 3461 : }
375 : #endif
376 :
377 : #if HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS
378 : // Network interfaces
379 3461 : struct ifaddrs *ifad = nullptr;
380 3461 : getifaddrs(&ifad);
381 3461 : struct ifaddrs *ifit = ifad;
382 145362 : while (ifit != nullptr) {
383 141901 : hasher.Write((const unsigned char*)&ifit, sizeof(ifit));
384 141901 : hasher.Write((const unsigned char*)ifit->ifa_name, strlen(ifit->ifa_name) + 1);
385 141901 : hasher.Write((const unsigned char*)&ifit->ifa_flags, sizeof(ifit->ifa_flags));
386 141901 : AddSockaddr(hasher, ifit->ifa_addr);
387 141901 : AddSockaddr(hasher, ifit->ifa_netmask);
388 141901 : AddSockaddr(hasher, ifit->ifa_dstaddr);
389 141901 : ifit = ifit->ifa_next;
390 : }
391 3461 : freeifaddrs(ifad);
392 : #endif
393 :
394 : #ifndef WIN32
395 : // UNIX kernel information
396 : struct utsname name;
397 3461 : if (uname(&name) != -1) {
398 3461 : hasher.Write((const unsigned char*)&name.sysname, strlen(name.sysname) + 1);
399 3461 : hasher.Write((const unsigned char*)&name.nodename, strlen(name.nodename) + 1);
400 3461 : hasher.Write((const unsigned char*)&name.release, strlen(name.release) + 1);
401 3461 : hasher.Write((const unsigned char*)&name.version, strlen(name.version) + 1);
402 3461 : hasher.Write((const unsigned char*)&name.machine, strlen(name.machine) + 1);
403 3461 : }
404 :
405 : /* Path and filesystem provided data */
406 3461 : AddPath(hasher, "/");
407 3461 : AddPath(hasher, ".");
408 3461 : AddPath(hasher, "/tmp");
409 3461 : AddPath(hasher, "/home");
410 3461 : AddPath(hasher, "/proc");
411 : #ifdef __linux__
412 : AddFile(hasher, "/proc/cmdline");
413 : AddFile(hasher, "/proc/cpuinfo");
414 : AddFile(hasher, "/proc/version");
415 : #endif
416 3461 : AddFile(hasher, "/etc/passwd");
417 3461 : AddFile(hasher, "/etc/group");
418 3461 : AddFile(hasher, "/etc/hosts");
419 3461 : AddFile(hasher, "/etc/resolv.conf");
420 3461 : AddFile(hasher, "/etc/timezone");
421 3461 : AddFile(hasher, "/etc/localtime");
422 : #endif
423 :
424 : // For MacOS/BSDs, gather data through sysctl instead of /proc. Not all of these
425 : // will exist on every system.
426 : #if HAVE_SYSCTL
427 : # ifdef CTL_HW
428 : # ifdef HW_MACHINE
429 3461 : AddSysctl<CTL_HW, HW_MACHINE>(hasher);
430 : # endif
431 : # ifdef HW_MODEL
432 3461 : AddSysctl<CTL_HW, HW_MODEL>(hasher);
433 : # endif
434 : # ifdef HW_NCPU
435 3461 : AddSysctl<CTL_HW, HW_NCPU>(hasher);
436 : # endif
437 : # ifdef HW_PHYSMEM
438 3461 : AddSysctl<CTL_HW, HW_PHYSMEM>(hasher);
439 : # endif
440 : # ifdef HW_USERMEM
441 3461 : AddSysctl<CTL_HW, HW_USERMEM>(hasher);
442 : # endif
443 : # ifdef HW_MACHINE_ARCH
444 3461 : AddSysctl<CTL_HW, HW_MACHINE_ARCH>(hasher);
445 : # endif
446 : # ifdef HW_REALMEM
447 : AddSysctl<CTL_HW, HW_REALMEM>(hasher);
448 : # endif
449 : # ifdef HW_CPU_FREQ
450 3461 : AddSysctl<CTL_HW, HW_CPU_FREQ>(hasher);
451 : # endif
452 : # ifdef HW_BUS_FREQ
453 3461 : AddSysctl<CTL_HW, HW_BUS_FREQ>(hasher);
454 : # endif
455 : # ifdef HW_CACHELINE
456 3461 : AddSysctl<CTL_HW, HW_CACHELINE>(hasher);
457 : # endif
458 : # endif
459 : # ifdef CTL_KERN
460 : # ifdef KERN_BOOTFILE
461 3461 : AddSysctl<CTL_KERN, KERN_BOOTFILE>(hasher);
462 : # endif
463 : # ifdef KERN_BOOTTIME
464 3461 : AddSysctl<CTL_KERN, KERN_BOOTTIME>(hasher);
465 : # endif
466 : # ifdef KERN_CLOCKRATE
467 3461 : AddSysctl<CTL_KERN, KERN_CLOCKRATE>(hasher);
468 : # endif
469 : # ifdef KERN_HOSTID
470 3461 : AddSysctl<CTL_KERN, KERN_HOSTID>(hasher);
471 : # endif
472 : # ifdef KERN_HOSTUUID
473 : AddSysctl<CTL_KERN, KERN_HOSTUUID>(hasher);
474 : # endif
475 : # ifdef KERN_HOSTNAME
476 3461 : AddSysctl<CTL_KERN, KERN_HOSTNAME>(hasher);
477 : # endif
478 : # ifdef KERN_OSRELDATE
479 3461 : AddSysctl<CTL_KERN, KERN_OSRELDATE>(hasher);
480 : # endif
481 : # ifdef KERN_OSRELEASE
482 3461 : AddSysctl<CTL_KERN, KERN_OSRELEASE>(hasher);
483 : # endif
484 : # ifdef KERN_OSREV
485 3461 : AddSysctl<CTL_KERN, KERN_OSREV>(hasher);
486 : # endif
487 : # ifdef KERN_OSTYPE
488 3461 : AddSysctl<CTL_KERN, KERN_OSTYPE>(hasher);
489 : # endif
490 : # ifdef KERN_POSIX1
491 3461 : AddSysctl<CTL_KERN, KERN_OSREV>(hasher);
492 : # endif
493 : # ifdef KERN_VERSION
494 3461 : AddSysctl<CTL_KERN, KERN_VERSION>(hasher);
495 : # endif
496 : # endif
497 : #endif
498 :
499 : // Env variables
500 3461 : if (environ) {
501 97947 : for (size_t i = 0; environ[i]; ++i) {
502 94486 : hasher.Write((const unsigned char*)environ[i], strlen(environ[i]));
503 94486 : }
504 3461 : }
505 :
506 : // Process, thread, user, session, group, ... ids.
507 : #ifdef WIN32
508 : hasher << GetCurrentProcessId() << GetCurrentThreadId();
509 : #else
510 3461 : hasher << getpid() << getppid() << getsid(0) << getpgid(0) << getuid() << geteuid() << getgid() << getegid();
511 : #endif
512 3461 : hasher << std::this_thread::get_id();
513 3461 : }
|