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