Update copyright year
[openssl.git] / crypto / rand / rand_unix.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #ifndef _GNU_SOURCE
11 # define _GNU_SOURCE
12 #endif
13 #include "e_os.h"
14 #include <stdio.h>
15 #include "internal/cryptlib.h"
16 #include <openssl/rand.h>
17 #include <openssl/crypto.h>
18 #include "rand_local.h"
19 #include "crypto/rand.h"
20 #include <stdio.h>
21 #include "internal/dso.h"
22
23 #ifdef __linux
24 # include <sys/syscall.h>
25 # ifdef DEVRANDOM_WAIT
26 #  include <sys/shm.h>
27 #  include <sys/utsname.h>
28 # endif
29 #endif
30 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
31 # include <sys/types.h>
32 # include <sys/sysctl.h>
33 # include <sys/param.h>
34 #endif
35 #if defined(__OpenBSD__) || defined(__NetBSD__)
36 # include <sys/param.h>
37 #endif
38
39 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
40      || defined(__DJGPP__)
41 # include <sys/types.h>
42 # include <sys/stat.h>
43 # include <fcntl.h>
44 # include <unistd.h>
45 # include <sys/time.h>
46
47 static uint64_t get_time_stamp(void);
48 static uint64_t get_timer_bits(void);
49
50 /* Macro to convert two thirty two bit values into a sixty four bit one */
51 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
52
53 /*
54  * Check for the existence and support of POSIX timers.  The standard
55  * says that the _POSIX_TIMERS macro will have a positive value if they
56  * are available.
57  *
58  * However, we want an additional constraint: that the timer support does
59  * not require an extra library dependency.  Early versions of glibc
60  * require -lrt to be specified on the link line to access the timers,
61  * so this needs to be checked for.
62  *
63  * It is worse because some libraries define __GLIBC__ but don't
64  * support the version testing macro (e.g. uClibc).  This means
65  * an extra check is needed.
66  *
67  * The final condition is:
68  *      "have posix timers and either not glibc or glibc without -lrt"
69  *
70  * The nested #if sequences are required to avoid using a parameterised
71  * macro that might be undefined.
72  */
73 # undef OSSL_POSIX_TIMER_OKAY
74 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
75 #  if defined(__GLIBC__)
76 #   if defined(__GLIBC_PREREQ)
77 #    if __GLIBC_PREREQ(2, 17)
78 #     define OSSL_POSIX_TIMER_OKAY
79 #    endif
80 #   endif
81 #  else
82 #   define OSSL_POSIX_TIMER_OKAY
83 #  endif
84 # endif
85 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
86           || defined(__DJGPP__) */
87
88 #if defined(OPENSSL_RAND_SEED_NONE)
89 /* none means none. this simplifies the following logic */
90 # undef OPENSSL_RAND_SEED_OS
91 # undef OPENSSL_RAND_SEED_GETRANDOM
92 # undef OPENSSL_RAND_SEED_LIBRANDOM
93 # undef OPENSSL_RAND_SEED_DEVRANDOM
94 # undef OPENSSL_RAND_SEED_RDTSC
95 # undef OPENSSL_RAND_SEED_RDCPU
96 # undef OPENSSL_RAND_SEED_EGD
97 #endif
98
99 #if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
100 # error "UEFI only supports seeding NONE"
101 #endif
102
103 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
104     || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
105     || defined(OPENSSL_SYS_UEFI))
106
107 # if defined(OPENSSL_SYS_VOS)
108
109 #  ifndef OPENSSL_RAND_SEED_OS
110 #   error "Unsupported seeding method configured; must be os"
111 #  endif
112
113 #  if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
114 #   error "Unsupported HP-PA and IA32 at the same time."
115 #  endif
116 #  if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
117 #   error "Must have one of HP-PA or IA32"
118 #  endif
119
120 /*
121  * The following algorithm repeatedly samples the real-time clock (RTC) to
122  * generate a sequence of unpredictable data.  The algorithm relies upon the
123  * uneven execution speed of the code (due to factors such as cache misses,
124  * interrupts, bus activity, and scheduling) and upon the rather large
125  * relative difference between the speed of the clock and the rate at which
126  * it can be read.  If it is ported to an environment where execution speed
127  * is more constant or where the RTC ticks at a much slower rate, or the
128  * clock can be read with fewer instructions, it is likely that the results
129  * would be far more predictable.  This should only be used for legacy
130  * platforms.
131  *
132  * As a precaution, we assume only 2 bits of entropy per byte.
133  */
134 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
135 {
136     short int code;
137     int i, k;
138     size_t bytes_needed;
139     struct timespec ts;
140     unsigned char v;
141 #  ifdef OPENSSL_SYS_VOS_HPPA
142     long duration;
143     extern void s$sleep(long *_duration, short int *_code);
144 #  else
145     long long duration;
146     extern void s$sleep2(long long *_duration, short int *_code);
147 #  endif
148
149     bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
150
151     for (i = 0; i < bytes_needed; i++) {
152         /*
153          * burn some cpu; hope for interrupts, cache collisions, bus
154          * interference, etc.
155          */
156         for (k = 0; k < 99; k++)
157             ts.tv_nsec = random();
158
159 #  ifdef OPENSSL_SYS_VOS_HPPA
160         /* sleep for 1/1024 of a second (976 us).  */
161         duration = 1;
162         s$sleep(&duration, &code);
163 #  else
164         /* sleep for 1/65536 of a second (15 us).  */
165         duration = 1;
166         s$sleep2(&duration, &code);
167 #  endif
168
169         /* Get wall clock time, take 8 bits. */
170         clock_gettime(CLOCK_REALTIME, &ts);
171         v = (unsigned char)(ts.tv_nsec & 0xFF);
172         rand_pool_add(pool, arg, &v, sizeof(v) , 2);
173     }
174     return rand_pool_entropy_available(pool);
175 }
176
177 void rand_pool_cleanup(void)
178 {
179 }
180
181 void rand_pool_keep_random_devices_open(int keep)
182 {
183 }
184
185 # else
186
187 #  if defined(OPENSSL_RAND_SEED_EGD) && \
188         (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
189 #   error "Seeding uses EGD but EGD is turned off or no device given"
190 #  endif
191
192 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
193 #   error "Seeding uses urandom but DEVRANDOM is not configured"
194 #  endif
195
196 #  if defined(OPENSSL_RAND_SEED_OS)
197 #   if !defined(DEVRANDOM)
198 #    error "OS seeding requires DEVRANDOM to be configured"
199 #   endif
200 #   define OPENSSL_RAND_SEED_GETRANDOM
201 #   define OPENSSL_RAND_SEED_DEVRANDOM
202 #  endif
203
204 #  if defined(OPENSSL_RAND_SEED_LIBRANDOM)
205 #   error "librandom not (yet) supported"
206 #  endif
207
208 #  if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
209 /*
210  * sysctl_random(): Use sysctl() to read a random number from the kernel
211  * Returns the number of bytes returned in buf on success, -1 on failure.
212  */
213 static ssize_t sysctl_random(char *buf, size_t buflen)
214 {
215     int mib[2];
216     size_t done = 0;
217     size_t len;
218
219     /*
220      * Note: sign conversion between size_t and ssize_t is safe even
221      * without a range check, see comment in syscall_random()
222      */
223
224     /*
225      * On FreeBSD old implementations returned longs, newer versions support
226      * variable sizes up to 256 byte. The code below would not work properly
227      * when the sysctl returns long and we want to request something not a
228      * multiple of longs, which should never be the case.
229      */
230     if (!ossl_assert(buflen % sizeof(long) == 0)) {
231         errno = EINVAL;
232         return -1;
233     }
234
235     /*
236      * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
237      * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
238      * it returns a variable number of bytes with the current version supporting
239      * up to 256 bytes.
240      * Just return an error on older NetBSD versions.
241      */
242 #if   defined(__NetBSD__) && __NetBSD_Version__ < 400000000
243     errno = ENOSYS;
244     return -1;
245 #endif
246
247     mib[0] = CTL_KERN;
248     mib[1] = KERN_ARND;
249
250     do {
251         len = buflen;
252         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
253             return done > 0 ? done : -1;
254         done += len;
255         buf += len;
256         buflen -= len;
257     } while (buflen > 0);
258
259     return done;
260 }
261 #  endif
262
263 #  if defined(OPENSSL_RAND_SEED_GETRANDOM)
264
265 #   if defined(__linux) && !defined(__NR_getrandom)
266 #    if defined(__arm__)
267 #     define __NR_getrandom    (__NR_SYSCALL_BASE+384)
268 #    elif defined(__i386__)
269 #     define __NR_getrandom    355
270 #    elif defined(__x86_64__)
271 #     if defined(__ILP32__)
272 #      define __NR_getrandom   (__X32_SYSCALL_BIT + 318)
273 #     else
274 #      define __NR_getrandom   318
275 #     endif
276 #    elif defined(__xtensa__)
277 #     define __NR_getrandom    338
278 #    elif defined(__s390__) || defined(__s390x__)
279 #     define __NR_getrandom    349
280 #    elif defined(__bfin__)
281 #     define __NR_getrandom    389
282 #    elif defined(__powerpc__)
283 #     define __NR_getrandom    359
284 #    elif defined(__mips__) || defined(__mips64)
285 #     if _MIPS_SIM == _MIPS_SIM_ABI32
286 #      define __NR_getrandom   (__NR_Linux + 353)
287 #     elif _MIPS_SIM == _MIPS_SIM_ABI64
288 #      define __NR_getrandom   (__NR_Linux + 313)
289 #     elif _MIPS_SIM == _MIPS_SIM_NABI32
290 #      define __NR_getrandom   (__NR_Linux + 317)
291 #     endif
292 #    elif defined(__hppa__)
293 #     define __NR_getrandom    (__NR_Linux + 339)
294 #    elif defined(__sparc__)
295 #     define __NR_getrandom    347
296 #    elif defined(__ia64__)
297 #     define __NR_getrandom    1339
298 #    elif defined(__alpha__)
299 #     define __NR_getrandom    511
300 #    elif defined(__sh__)
301 #     if defined(__SH5__)
302 #      define __NR_getrandom   373
303 #     else
304 #      define __NR_getrandom   384
305 #     endif
306 #    elif defined(__avr32__)
307 #     define __NR_getrandom    317
308 #    elif defined(__microblaze__)
309 #     define __NR_getrandom    385
310 #    elif defined(__m68k__)
311 #     define __NR_getrandom    352
312 #    elif defined(__cris__)
313 #     define __NR_getrandom    356
314 #    elif defined(__aarch64__)
315 #     define __NR_getrandom    278
316 #    else /* generic */
317 #     define __NR_getrandom    278
318 #    endif
319 #   endif
320
321 /*
322  * syscall_random(): Try to get random data using a system call
323  * returns the number of bytes returned in buf, or < 0 on error.
324  */
325 static ssize_t syscall_random(void *buf, size_t buflen)
326 {
327     /*
328      * Note: 'buflen' equals the size of the buffer which is used by the
329      * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
330      *
331      *   2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
332      *
333      * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
334      * between size_t and ssize_t is safe even without a range check.
335      */
336
337     /*
338      * Do runtime detection to find getentropy().
339      *
340      * Known OSs that should support this:
341      * - Darwin since 16 (OSX 10.12, IOS 10.0).
342      * - Solaris since 11.3
343      * - OpenBSD since 5.6
344      * - Linux since 3.17 with glibc 2.25
345      * - FreeBSD since 12.0 (1200061)
346      */
347 #  if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
348     extern int getentropy(void *buffer, size_t length) __attribute__((weak));
349
350     if (getentropy != NULL)
351         return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
352 #  elif !defined(FIPS_MODE)
353     union {
354         void *p;
355         int (*f)(void *buffer, size_t length);
356     } p_getentropy;
357
358     /*
359      * We could cache the result of the lookup, but we normally don't
360      * call this function often.
361      */
362     ERR_set_mark();
363     p_getentropy.p = DSO_global_lookup("getentropy");
364     ERR_pop_to_mark();
365     if (p_getentropy.p != NULL)
366         return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
367 #  endif
368
369     /* Linux supports this since version 3.17 */
370 #  if defined(__linux) && defined(__NR_getrandom)
371     return syscall(__NR_getrandom, buf, buflen, 0);
372 #  elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
373     return sysctl_random(buf, buflen);
374 #  else
375     errno = ENOSYS;
376     return -1;
377 #  endif
378 }
379 #  endif    /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
380
381 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM)
382 static const char *random_device_paths[] = { DEVRANDOM };
383 static struct random_device {
384     int fd;
385     dev_t dev;
386     ino_t ino;
387     mode_t mode;
388     dev_t rdev;
389 } random_devices[OSSL_NELEM(random_device_paths)];
390 static int keep_random_devices_open = 1;
391
392 #   if defined(__linux) && defined(DEVRANDOM_WAIT)
393 static void *shm_addr;
394
395 #    if !defined(FIPS_MODE)
396 static void cleanup_shm(void)
397 {
398     shmdt(shm_addr);
399 }
400 #    endif
401
402 /*
403  * Ensure that the system randomness source has been adequately seeded.
404  * This is done by having the first start of libcrypto, wait until the device
405  * /dev/random becomes able to supply a byte of entropy.  Subsequent starts
406  * of the library and later reseedings do not need to do this.
407  */
408 static int wait_random_seeded(void)
409 {
410     static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
411     static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
412     int kernel[2];
413     int shm_id, fd, r;
414     char c, *p;
415     struct utsname un;
416     fd_set fds;
417
418     if (!seeded) {
419         /* See if anything has created the global seeded indication */
420         if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
421             /*
422              * Check the kernel's version and fail if it is too recent.
423              *
424              * Linux kernels from 4.8 onwards do not guarantee that
425              * /dev/urandom is properly seeded when /dev/random becomes
426              * readable.  However, such kernels support the getentropy(2)
427              * system call and this should always succeed which renders
428              * this alternative but essentially identical source moot.
429              */
430             if (uname(&un) == 0) {
431                 kernel[0] = atoi(un.release);
432                 p = strchr(un.release, '.');
433                 kernel[1] = p == NULL ? 0 : atoi(p + 1);
434                 if (kernel[0] > kernel_version[0]
435                     || (kernel[0] == kernel_version[0]
436                         && kernel[1] >= kernel_version[1])) {
437                     return 0;
438                 }
439             }
440             /* Open /dev/random and wait for it to be readable */
441             if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
442                 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
443                     FD_ZERO(&fds);
444                     FD_SET(fd, &fds);
445                     while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
446                            && errno == EINTR);
447                 } else {
448                     while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
449                 }
450                 close(fd);
451                 if (r == 1) {
452                     seeded = 1;
453                     /* Create the shared memory indicator */
454                     shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
455                                     IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
456                 }
457             }
458         }
459         if (shm_id != -1) {
460             seeded = 1;
461             /*
462              * Map the shared memory to prevent its premature destruction.
463              * If this call fails, it isn't a big problem.
464              */
465             shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
466 #    ifndef FIPS_MODE
467             /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
468             if (shm_addr != (void *)-1)
469                 OPENSSL_atexit(&cleanup_shm);
470 #    endif
471         }
472     }
473     return seeded;
474 }
475 #   else /* defined __linux */
476 static int wait_random_seeded(void)
477 {
478     return 1;
479 }
480 #   endif
481
482 /*
483  * Verify that the file descriptor associated with the random source is
484  * still valid. The rationale for doing this is the fact that it is not
485  * uncommon for daemons to close all open file handles when daemonizing.
486  * So the handle might have been closed or even reused for opening
487  * another file.
488  */
489 static int check_random_device(struct random_device * rd)
490 {
491     struct stat st;
492
493     return rd->fd != -1
494            && fstat(rd->fd, &st) != -1
495            && rd->dev == st.st_dev
496            && rd->ino == st.st_ino
497            && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
498            && rd->rdev == st.st_rdev;
499 }
500
501 /*
502  * Open a random device if required and return its file descriptor or -1 on error
503  */
504 static int get_random_device(size_t n)
505 {
506     struct stat st;
507     struct random_device * rd = &random_devices[n];
508
509     /* reuse existing file descriptor if it is (still) valid */
510     if (check_random_device(rd))
511         return rd->fd;
512
513     /* open the random device ... */
514     if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
515         return rd->fd;
516
517     /* ... and cache its relevant stat(2) data */
518     if (fstat(rd->fd, &st) != -1) {
519         rd->dev = st.st_dev;
520         rd->ino = st.st_ino;
521         rd->mode = st.st_mode;
522         rd->rdev = st.st_rdev;
523     } else {
524         close(rd->fd);
525         rd->fd = -1;
526     }
527
528     return rd->fd;
529 }
530
531 /*
532  * Close a random device making sure it is a random device
533  */
534 static void close_random_device(size_t n)
535 {
536     struct random_device * rd = &random_devices[n];
537
538     if (check_random_device(rd))
539         close(rd->fd);
540     rd->fd = -1;
541 }
542
543 int rand_pool_init(void)
544 {
545     size_t i;
546
547     for (i = 0; i < OSSL_NELEM(random_devices); i++)
548         random_devices[i].fd = -1;
549
550     return 1;
551 }
552
553 void rand_pool_cleanup(void)
554 {
555     size_t i;
556
557     for (i = 0; i < OSSL_NELEM(random_devices); i++)
558         close_random_device(i);
559 }
560
561 void rand_pool_keep_random_devices_open(int keep)
562 {
563     if (!keep)
564         rand_pool_cleanup();
565
566     keep_random_devices_open = keep;
567 }
568
569 #  else     /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
570
571 int rand_pool_init(void)
572 {
573     return 1;
574 }
575
576 void rand_pool_cleanup(void)
577 {
578 }
579
580 void rand_pool_keep_random_devices_open(int keep)
581 {
582 }
583
584 #  endif    /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
585
586 /*
587  * Try the various seeding methods in turn, exit when successful.
588  *
589  * TODO(DRBG): If more than one entropy source is available, is it
590  * preferable to stop as soon as enough entropy has been collected
591  * (as favored by @rsalz) or should one rather be defensive and add
592  * more entropy than requested and/or from different sources?
593  *
594  * Currently, the user can select multiple entropy sources in the
595  * configure step, yet in practice only the first available source
596  * will be used. A more flexible solution has been requested, but
597  * currently it is not clear how this can be achieved without
598  * overengineering the problem. There are many parameters which
599  * could be taken into account when selecting the order and amount
600  * of input from the different entropy sources (trust, quality,
601  * possibility of blocking).
602  */
603 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
604 {
605 #  if defined(OPENSSL_RAND_SEED_NONE)
606     return rand_pool_entropy_available(pool);
607 #  else
608     size_t entropy_available;
609
610 #   if defined(OPENSSL_RAND_SEED_GETRANDOM)
611     {
612         size_t bytes_needed;
613         unsigned char *buffer;
614         ssize_t bytes;
615         /* Maximum allowed number of consecutive unsuccessful attempts */
616         int attempts = 3;
617
618         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
619         while (bytes_needed != 0 && attempts-- > 0) {
620             buffer = rand_pool_add_begin(pool, bytes_needed);
621             bytes = syscall_random(buffer, bytes_needed);
622             if (bytes > 0) {
623                 rand_pool_add_end(pool, bytes, 8 * bytes);
624                 bytes_needed -= bytes;
625                 attempts = 3; /* reset counter after successful attempt */
626             } else if (bytes < 0 && errno != EINTR) {
627                 break;
628             }
629         }
630     }
631     entropy_available = rand_pool_entropy_available(pool);
632     if (entropy_available > 0)
633         return entropy_available;
634 #   endif
635
636 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
637     {
638         /* Not yet implemented. */
639     }
640 #   endif
641
642 #   if defined(OPENSSL_RAND_SEED_DEVRANDOM)
643     if (wait_random_seeded()) {
644         size_t bytes_needed;
645         unsigned char *buffer;
646         size_t i;
647
648         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
649         for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
650              i++) {
651             ssize_t bytes = 0;
652             /* Maximum number of consecutive unsuccessful attempts */
653             int attempts = 3;
654             const int fd = get_random_device(i);
655
656             if (fd == -1)
657                 continue;
658
659             while (bytes_needed != 0 && attempts-- > 0) {
660                 buffer = rand_pool_add_begin(pool, bytes_needed);
661                 bytes = read(fd, buffer, bytes_needed);
662
663                 if (bytes > 0) {
664                     rand_pool_add_end(pool, bytes, 8 * bytes);
665                     bytes_needed -= bytes;
666                     attempts = 3; /* reset counter on successful attempt */
667                 } else if (bytes < 0 && errno != EINTR) {
668                     break;
669                 }
670             }
671             if (bytes < 0 || !keep_random_devices_open)
672                 close_random_device(i);
673
674             bytes_needed = rand_pool_bytes_needed(pool, 1);
675         }
676         entropy_available = rand_pool_entropy_available(pool);
677         if (entropy_available > 0)
678             return entropy_available;
679     }
680 #   endif
681
682 #   if defined(OPENSSL_RAND_SEED_RDTSC)
683     entropy_available = rand_acquire_entropy_from_tsc(pool);
684     if (entropy_available > 0)
685         return entropy_available;
686 #   endif
687
688 #   if defined(OPENSSL_RAND_SEED_RDCPU)
689     entropy_available = rand_acquire_entropy_from_cpu(pool);
690     if (entropy_available > 0)
691         return entropy_available;
692 #   endif
693
694 #   if defined(OPENSSL_RAND_SEED_EGD)
695     {
696         static const char *paths[] = { DEVRANDOM_EGD, NULL };
697         size_t bytes_needed;
698         unsigned char *buffer;
699         int i;
700
701         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
702         for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
703             size_t bytes = 0;
704             int num;
705
706             buffer = rand_pool_add_begin(pool, bytes_needed);
707             num = RAND_query_egd_bytes(paths[i],
708                                        buffer, (int)bytes_needed);
709             if (num == (int)bytes_needed)
710                 bytes = bytes_needed;
711
712             rand_pool_add_end(pool, bytes, 8 * bytes);
713             bytes_needed = rand_pool_bytes_needed(pool, 1);
714         }
715         entropy_available = rand_pool_entropy_available(pool);
716         if (entropy_available > 0)
717             return entropy_available;
718     }
719 #   endif
720
721     return rand_pool_entropy_available(pool);
722 #  endif
723 }
724 # endif
725 #endif
726
727 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
728      || defined(__DJGPP__)
729 int rand_pool_add_nonce_data(RAND_POOL *pool)
730 {
731     struct {
732         pid_t pid;
733         CRYPTO_THREAD_ID tid;
734         uint64_t time;
735     } data;
736
737     /* Erase the entire structure including any padding */
738     memset(&data, 0, sizeof(data));
739
740     /*
741      * Add process id, thread id, and a high resolution timestamp to
742      * ensure that the nonce is unique with high probability for
743      * different process instances.
744      */
745     data.pid = getpid();
746     data.tid = CRYPTO_THREAD_get_current_id();
747     data.time = get_time_stamp();
748
749     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
750 }
751
752 int rand_pool_add_additional_data(RAND_POOL *pool)
753 {
754     struct {
755         int fork_id;
756         CRYPTO_THREAD_ID tid;
757         uint64_t time;
758     } data;
759
760     /* Erase the entire structure including any padding */
761     memset(&data, 0, sizeof(data));
762
763     /*
764      * Add some noise from the thread id and a high resolution timer.
765      * The fork_id adds some extra fork-safety.
766      * The thread id adds a little randomness if the drbg is accessed
767      * concurrently (which is the case for the <master> drbg).
768      */
769     data.fork_id = openssl_get_fork_id();
770     data.tid = CRYPTO_THREAD_get_current_id();
771     data.time = get_timer_bits();
772
773     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
774 }
775
776
777 /*
778  * Get the current time with the highest possible resolution
779  *
780  * The time stamp is added to the nonce, so it is optimized for not repeating.
781  * The current time is ideal for this purpose, provided the computer's clock
782  * is synchronized.
783  */
784 static uint64_t get_time_stamp(void)
785 {
786 # if defined(OSSL_POSIX_TIMER_OKAY)
787     {
788         struct timespec ts;
789
790         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
791             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
792     }
793 # endif
794 # if defined(__unix__) \
795      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
796     {
797         struct timeval tv;
798
799         if (gettimeofday(&tv, NULL) == 0)
800             return TWO32TO64(tv.tv_sec, tv.tv_usec);
801     }
802 # endif
803     return time(NULL);
804 }
805
806 /*
807  * Get an arbitrary timer value of the highest possible resolution
808  *
809  * The timer value is added as random noise to the additional data,
810  * which is not considered a trusted entropy sourec, so any result
811  * is acceptable.
812  */
813 static uint64_t get_timer_bits(void)
814 {
815     uint64_t res = OPENSSL_rdtsc();
816
817     if (res != 0)
818         return res;
819
820 # if defined(__sun) || defined(__hpux)
821     return gethrtime();
822 # elif defined(_AIX)
823     {
824         timebasestruct_t t;
825
826         read_wall_time(&t, TIMEBASE_SZ);
827         return TWO32TO64(t.tb_high, t.tb_low);
828     }
829 # elif defined(OSSL_POSIX_TIMER_OKAY)
830     {
831         struct timespec ts;
832
833 #  ifdef CLOCK_BOOTTIME
834 #   define CLOCK_TYPE CLOCK_BOOTTIME
835 #  elif defined(_POSIX_MONOTONIC_CLOCK)
836 #   define CLOCK_TYPE CLOCK_MONOTONIC
837 #  else
838 #   define CLOCK_TYPE CLOCK_REALTIME
839 #  endif
840
841         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
842             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
843     }
844 # endif
845 # if defined(__unix__) \
846      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
847     {
848         struct timeval tv;
849
850         if (gettimeofday(&tv, NULL) == 0)
851             return TWO32TO64(tv.tv_sec, tv.tv_usec);
852     }
853 # endif
854     return time(NULL);
855 }
856 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
857           || defined(__DJGPP__) */