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