0142d8401937c849a828f624f24e829d444b845b
[openssl.git] / crypto / rand / rand_unix.c
1 /*
2  * Copyright 1995-2018 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 /*
24  * Defines related to seed sources
25  */
26 #ifndef DEVRANDOM
27 /*
28  * set this to a comma-separated list of 'random' device files to try out. By
29  * default, we will try to read at least one of these files
30  */
31 # define DEVRANDOM "/dev/urandom", "/dev/random", "/dev/hwrng", "/dev/srandom"
32 # if defined(__linux) && !defined(__ANDROID__)
33 #  ifndef DEVRANDOM_WAIT
34 #   define DEVRANDOM_WAIT   "/dev/random"
35 #  endif
36 /*
37  * Linux kernels 4.8 and later changes how their random device works and there
38  * is no reliable way to tell that /dev/urandom has been seeded -- getentropy(2)
39  * should be used instead.
40  */
41 #  ifndef DEVRANDOM_SAFE_KERNEL
42 #   define DEVRANDOM_SAFE_KERNEL        4, 8
43 #  endif
44 /*
45  * Some operating systems do not permit select(2) on their random devices,
46  * defining this to zero will force the use of read(2) to extract one byte
47  * from /dev/random.
48  */
49 #  ifndef DEVRANDM_WAIT_USE_SELECT
50 #   define DEVRANDM_WAIT_USE_SELECT     1
51 #  endif
52 /*
53  * Define the shared memory identifier used to indicate if the operating
54  * system has properly seeded the DEVRANDOM source.
55  */
56 #  ifndef OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID
57 #   define OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID 114
58 #  endif
59
60 # endif
61 #endif
62
63 #if !defined(OPENSSL_NO_EGD) && !defined(DEVRANDOM_EGD)
64 /*
65  * set this to a comma-separated list of 'egd' sockets to try out. These
66  * sockets will be tried in the order listed in case accessing the device
67  * files listed in DEVRANDOM did not return enough randomness.
68  */
69 # define DEVRANDOM_EGD "/var/run/egd-pool", "/dev/egd-pool", "/etc/egd-pool", "/etc/entropy"
70 #endif
71
72 #ifdef __linux
73 # include <sys/syscall.h>
74 # ifdef DEVRANDOM_WAIT
75 #  include <sys/shm.h>
76 #  include <sys/utsname.h>
77 # endif
78 #endif
79 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
80 # include <sys/types.h>
81 # include <sys/sysctl.h>
82 # include <sys/param.h>
83 #endif
84 #if defined(__OpenBSD__) || defined(__NetBSD__)
85 # include <sys/param.h>
86 #endif
87
88 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
89      || defined(__DJGPP__)
90 # include <sys/types.h>
91 # include <sys/stat.h>
92 # include <fcntl.h>
93 # include <unistd.h>
94 # include <sys/time.h>
95
96 static uint64_t get_time_stamp(void);
97 static uint64_t get_timer_bits(void);
98
99 /* Macro to convert two thirty two bit values into a sixty four bit one */
100 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
101
102 /*
103  * Check for the existence and support of POSIX timers.  The standard
104  * says that the _POSIX_TIMERS macro will have a positive value if they
105  * are available.
106  *
107  * However, we want an additional constraint: that the timer support does
108  * not require an extra library dependency.  Early versions of glibc
109  * require -lrt to be specified on the link line to access the timers,
110  * so this needs to be checked for.
111  *
112  * It is worse because some libraries define __GLIBC__ but don't
113  * support the version testing macro (e.g. uClibc).  This means
114  * an extra check is needed.
115  *
116  * The final condition is:
117  *      "have posix timers and either not glibc or glibc without -lrt"
118  *
119  * The nested #if sequences are required to avoid using a parameterised
120  * macro that might be undefined.
121  */
122 # undef OSSL_POSIX_TIMER_OKAY
123 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
124 #  if defined(__GLIBC__)
125 #   if defined(__GLIBC_PREREQ)
126 #    if __GLIBC_PREREQ(2, 17)
127 #     define OSSL_POSIX_TIMER_OKAY
128 #    endif
129 #   endif
130 #  else
131 #   define OSSL_POSIX_TIMER_OKAY
132 #  endif
133 # endif
134 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
135           || defined(__DJGPP__) */
136
137 #if defined(OPENSSL_RAND_SEED_NONE)
138 /* none means none. this simplifies the following logic */
139 # undef OPENSSL_RAND_SEED_OS
140 # undef OPENSSL_RAND_SEED_GETRANDOM
141 # undef OPENSSL_RAND_SEED_LIBRANDOM
142 # undef OPENSSL_RAND_SEED_DEVRANDOM
143 # undef OPENSSL_RAND_SEED_RDTSC
144 # undef OPENSSL_RAND_SEED_RDCPU
145 # undef OPENSSL_RAND_SEED_EGD
146 #endif
147
148 #if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
149 # error "UEFI only supports seeding NONE"
150 #endif
151
152 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
153     || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
154     || defined(OPENSSL_SYS_UEFI))
155
156 # if defined(OPENSSL_SYS_VOS)
157
158 #  ifndef OPENSSL_RAND_SEED_OS
159 #   error "Unsupported seeding method configured; must be os"
160 #  endif
161
162 #  if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
163 #   error "Unsupported HP-PA and IA32 at the same time."
164 #  endif
165 #  if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
166 #   error "Must have one of HP-PA or IA32"
167 #  endif
168
169 /*
170  * The following algorithm repeatedly samples the real-time clock (RTC) to
171  * generate a sequence of unpredictable data.  The algorithm relies upon the
172  * uneven execution speed of the code (due to factors such as cache misses,
173  * interrupts, bus activity, and scheduling) and upon the rather large
174  * relative difference between the speed of the clock and the rate at which
175  * it can be read.  If it is ported to an environment where execution speed
176  * is more constant or where the RTC ticks at a much slower rate, or the
177  * clock can be read with fewer instructions, it is likely that the results
178  * would be far more predictable.  This should only be used for legacy
179  * platforms.
180  *
181  * As a precaution, we assume only 2 bits of entropy per byte.
182  */
183 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
184 {
185     short int code;
186     int i, k;
187     size_t bytes_needed;
188     struct timespec ts;
189     unsigned char v;
190 #  ifdef OPENSSL_SYS_VOS_HPPA
191     long duration;
192     extern void s$sleep(long *_duration, short int *_code);
193 #  else
194     long long duration;
195     extern void s$sleep2(long long *_duration, short int *_code);
196 #  endif
197
198     bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
199
200     for (i = 0; i < bytes_needed; i++) {
201         /*
202          * burn some cpu; hope for interrupts, cache collisions, bus
203          * interference, etc.
204          */
205         for (k = 0; k < 99; k++)
206             ts.tv_nsec = random();
207
208 #  ifdef OPENSSL_SYS_VOS_HPPA
209         /* sleep for 1/1024 of a second (976 us).  */
210         duration = 1;
211         s$sleep(&duration, &code);
212 #  else
213         /* sleep for 1/65536 of a second (15 us).  */
214         duration = 1;
215         s$sleep2(&duration, &code);
216 #  endif
217
218         /* Get wall clock time, take 8 bits. */
219         clock_gettime(CLOCK_REALTIME, &ts);
220         v = (unsigned char)(ts.tv_nsec & 0xFF);
221         rand_pool_add(pool, arg, &v, sizeof(v) , 2);
222     }
223     return rand_pool_entropy_available(pool);
224 }
225
226 void rand_pool_cleanup(void)
227 {
228 }
229
230 void rand_pool_keep_random_devices_open(int keep)
231 {
232 }
233
234 # else
235
236 #  if defined(OPENSSL_RAND_SEED_EGD) && \
237         (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
238 #   error "Seeding uses EGD but EGD is turned off or no device given"
239 #  endif
240
241 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
242 #   error "Seeding uses urandom but DEVRANDOM is not configured"
243 #  endif
244
245 #  if defined(OPENSSL_RAND_SEED_OS)
246 #   if !defined(DEVRANDOM)
247 #    error "OS seeding requires DEVRANDOM to be configured"
248 #   endif
249 #   define OPENSSL_RAND_SEED_GETRANDOM
250 #   define OPENSSL_RAND_SEED_DEVRANDOM
251 #  endif
252
253 #  if defined(OPENSSL_RAND_SEED_LIBRANDOM)
254 #   error "librandom not (yet) supported"
255 #  endif
256
257 #  if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
258 /*
259  * sysctl_random(): Use sysctl() to read a random number from the kernel
260  * Returns the number of bytes returned in buf on success, -1 on failure.
261  */
262 static ssize_t sysctl_random(char *buf, size_t buflen)
263 {
264     int mib[2];
265     size_t done = 0;
266     size_t len;
267
268     /*
269      * Note: sign conversion between size_t and ssize_t is safe even
270      * without a range check, see comment in syscall_random()
271      */
272
273     /*
274      * On FreeBSD old implementations returned longs, newer versions support
275      * variable sizes up to 256 byte. The code below would not work properly
276      * when the sysctl returns long and we want to request something not a
277      * multiple of longs, which should never be the case.
278      */
279     if (!ossl_assert(buflen % sizeof(long) == 0)) {
280         errno = EINVAL;
281         return -1;
282     }
283
284     /*
285      * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
286      * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
287      * it returns a variable number of bytes with the current version supporting
288      * up to 256 bytes.
289      * Just return an error on older NetBSD versions.
290      */
291 #if   defined(__NetBSD__) && __NetBSD_Version__ < 400000000
292     errno = ENOSYS;
293     return -1;
294 #endif
295
296     mib[0] = CTL_KERN;
297     mib[1] = KERN_ARND;
298
299     do {
300         len = buflen;
301         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
302             return done > 0 ? done : -1;
303         done += len;
304         buf += len;
305         buflen -= len;
306     } while (buflen > 0);
307
308     return done;
309 }
310 #  endif
311
312 #  if defined(OPENSSL_RAND_SEED_GETRANDOM)
313
314 #   if defined(__linux) && !defined(__NR_getrandom)
315 #    if defined(__arm__)
316 #     define __NR_getrandom    (__NR_SYSCALL_BASE+384)
317 #    elif defined(__i386__)
318 #     define __NR_getrandom    355
319 #    elif defined(__x86_64__)
320 #     if defined(__ILP32__)
321 #      define __NR_getrandom   (__X32_SYSCALL_BIT + 318)
322 #     else
323 #      define __NR_getrandom   318
324 #     endif
325 #    elif defined(__xtensa__)
326 #     define __NR_getrandom    338
327 #    elif defined(__s390__) || defined(__s390x__)
328 #     define __NR_getrandom    349
329 #    elif defined(__bfin__)
330 #     define __NR_getrandom    389
331 #    elif defined(__powerpc__)
332 #     define __NR_getrandom    359
333 #    elif defined(__mips__) || defined(__mips64)
334 #     if _MIPS_SIM == _MIPS_SIM_ABI32
335 #      define __NR_getrandom   (__NR_Linux + 353)
336 #     elif _MIPS_SIM == _MIPS_SIM_ABI64
337 #      define __NR_getrandom   (__NR_Linux + 313)
338 #     elif _MIPS_SIM == _MIPS_SIM_NABI32
339 #      define __NR_getrandom   (__NR_Linux + 317)
340 #     endif
341 #    elif defined(__hppa__)
342 #     define __NR_getrandom    (__NR_Linux + 339)
343 #    elif defined(__sparc__)
344 #     define __NR_getrandom    347
345 #    elif defined(__ia64__)
346 #     define __NR_getrandom    1339
347 #    elif defined(__alpha__)
348 #     define __NR_getrandom    511
349 #    elif defined(__sh__)
350 #     if defined(__SH5__)
351 #      define __NR_getrandom   373
352 #     else
353 #      define __NR_getrandom   384
354 #     endif
355 #    elif defined(__avr32__)
356 #     define __NR_getrandom    317
357 #    elif defined(__microblaze__)
358 #     define __NR_getrandom    385
359 #    elif defined(__m68k__)
360 #     define __NR_getrandom    352
361 #    elif defined(__cris__)
362 #     define __NR_getrandom    356
363 #    elif defined(__aarch64__)
364 #     define __NR_getrandom    278
365 #    else /* generic */
366 #     define __NR_getrandom    278
367 #    endif
368 #   endif
369
370 /*
371  * syscall_random(): Try to get random data using a system call
372  * returns the number of bytes returned in buf, or < 0 on error.
373  */
374 static ssize_t syscall_random(void *buf, size_t buflen)
375 {
376     /*
377      * Note: 'buflen' equals the size of the buffer which is used by the
378      * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
379      *
380      *   2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
381      *
382      * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
383      * between size_t and ssize_t is safe even without a range check.
384      */
385
386     /*
387      * Do runtime detection to find getentropy().
388      *
389      * Known OSs that should support this:
390      * - Darwin since 16 (OSX 10.12, IOS 10.0).
391      * - Solaris since 11.3
392      * - OpenBSD since 5.6
393      * - Linux since 3.17 with glibc 2.25
394      * - FreeBSD since 12.0 (1200061)
395      */
396 #  if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
397     extern int getentropy(void *buffer, size_t length) __attribute__((weak));
398
399     if (getentropy != NULL)
400         return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
401 #  elif !defined(FIPS_MODE)
402     union {
403         void *p;
404         int (*f)(void *buffer, size_t length);
405     } p_getentropy;
406
407     /*
408      * We could cache the result of the lookup, but we normally don't
409      * call this function often.
410      */
411     ERR_set_mark();
412     p_getentropy.p = DSO_global_lookup("getentropy");
413     ERR_pop_to_mark();
414     if (p_getentropy.p != NULL)
415         return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
416 #  endif
417
418     /* Linux supports this since version 3.17 */
419 #  if defined(__linux) && defined(__NR_getrandom)
420     return syscall(__NR_getrandom, buf, buflen, 0);
421 #  elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
422     return sysctl_random(buf, buflen);
423 #  else
424     errno = ENOSYS;
425     return -1;
426 #  endif
427 }
428 #  endif    /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
429
430 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM)
431 static const char *random_device_paths[] = { DEVRANDOM };
432 static struct random_device {
433     int fd;
434     dev_t dev;
435     ino_t ino;
436     mode_t mode;
437     dev_t rdev;
438 } random_devices[OSSL_NELEM(random_device_paths)];
439 static int keep_random_devices_open = 1;
440
441 #   if defined(__linux) && defined(DEVRANDOM_WAIT)
442 static void *shm_addr;
443
444 #    if !defined(FIPS_MODE)
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_MODE
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 */
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 rand_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;
658
659 #   if defined(OPENSSL_RAND_SEED_GETRANDOM)
660     {
661         size_t bytes_needed;
662         unsigned char *buffer;
663         ssize_t bytes;
664         /* Maximum allowed number of consecutive unsuccessful attempts */
665         int attempts = 3;
666
667         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
668         while (bytes_needed != 0 && attempts-- > 0) {
669             buffer = rand_pool_add_begin(pool, bytes_needed);
670             bytes = syscall_random(buffer, bytes_needed);
671             if (bytes > 0) {
672                 rand_pool_add_end(pool, bytes, 8 * bytes);
673                 bytes_needed -= bytes;
674                 attempts = 3; /* reset counter after successful attempt */
675             } else if (bytes < 0 && errno != EINTR) {
676                 break;
677             }
678         }
679     }
680     entropy_available = rand_pool_entropy_available(pool);
681     if (entropy_available > 0)
682         return entropy_available;
683 #   endif
684
685 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
686     {
687         /* Not yet implemented. */
688     }
689 #   endif
690
691 #   if defined(OPENSSL_RAND_SEED_DEVRANDOM)
692     if (wait_random_seeded()) {
693         size_t bytes_needed;
694         unsigned char *buffer;
695         size_t i;
696
697         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
698         for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
699              i++) {
700             ssize_t bytes = 0;
701             /* Maximum number of consecutive unsuccessful attempts */
702             int attempts = 3;
703             const int fd = get_random_device(i);
704
705             if (fd == -1)
706                 continue;
707
708             while (bytes_needed != 0 && attempts-- > 0) {
709                 buffer = rand_pool_add_begin(pool, bytes_needed);
710                 bytes = read(fd, buffer, bytes_needed);
711
712                 if (bytes > 0) {
713                     rand_pool_add_end(pool, bytes, 8 * bytes);
714                     bytes_needed -= bytes;
715                     attempts = 3; /* reset counter on successful attempt */
716                 } else if (bytes < 0 && errno != EINTR) {
717                     break;
718                 }
719             }
720             if (bytes < 0 || !keep_random_devices_open)
721                 close_random_device(i);
722
723             bytes_needed = rand_pool_bytes_needed(pool, 1);
724         }
725         entropy_available = rand_pool_entropy_available(pool);
726         if (entropy_available > 0)
727             return entropy_available;
728     }
729 #   endif
730
731 #   if defined(OPENSSL_RAND_SEED_RDTSC)
732     entropy_available = rand_acquire_entropy_from_tsc(pool);
733     if (entropy_available > 0)
734         return entropy_available;
735 #   endif
736
737 #   if defined(OPENSSL_RAND_SEED_RDCPU)
738     entropy_available = rand_acquire_entropy_from_cpu(pool);
739     if (entropy_available > 0)
740         return entropy_available;
741 #   endif
742
743 #   if defined(OPENSSL_RAND_SEED_EGD)
744     {
745         static const char *paths[] = { DEVRANDOM_EGD, NULL };
746         size_t bytes_needed;
747         unsigned char *buffer;
748         int i;
749
750         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
751         for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
752             size_t bytes = 0;
753             int num;
754
755             buffer = rand_pool_add_begin(pool, bytes_needed);
756             num = RAND_query_egd_bytes(paths[i],
757                                        buffer, (int)bytes_needed);
758             if (num == (int)bytes_needed)
759                 bytes = bytes_needed;
760
761             rand_pool_add_end(pool, bytes, 8 * bytes);
762             bytes_needed = rand_pool_bytes_needed(pool, 1);
763         }
764         entropy_available = rand_pool_entropy_available(pool);
765         if (entropy_available > 0)
766             return entropy_available;
767     }
768 #   endif
769
770     return rand_pool_entropy_available(pool);
771 #  endif
772 }
773 # endif
774 #endif
775
776 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
777      || defined(__DJGPP__)
778 int rand_pool_add_nonce_data(RAND_POOL *pool)
779 {
780     struct {
781         pid_t pid;
782         CRYPTO_THREAD_ID tid;
783         uint64_t time;
784     } data;
785
786     /* Erase the entire structure including any padding */
787     memset(&data, 0, sizeof(data));
788
789     /*
790      * Add process id, thread id, and a high resolution timestamp to
791      * ensure that the nonce is unique with high probability for
792      * different process instances.
793      */
794     data.pid = getpid();
795     data.tid = CRYPTO_THREAD_get_current_id();
796     data.time = get_time_stamp();
797
798     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
799 }
800
801 int rand_pool_add_additional_data(RAND_POOL *pool)
802 {
803     struct {
804         int fork_id;
805         CRYPTO_THREAD_ID tid;
806         uint64_t time;
807     } data;
808
809     /* Erase the entire structure including any padding */
810     memset(&data, 0, sizeof(data));
811
812     /*
813      * Add some noise from the thread id and a high resolution timer.
814      * The fork_id adds some extra fork-safety.
815      * The thread id adds a little randomness if the drbg is accessed
816      * concurrently (which is the case for the <master> drbg).
817      */
818     data.fork_id = openssl_get_fork_id();
819     data.tid = CRYPTO_THREAD_get_current_id();
820     data.time = get_timer_bits();
821
822     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
823 }
824
825
826 /*
827  * Get the current time with the highest possible resolution
828  *
829  * The time stamp is added to the nonce, so it is optimized for not repeating.
830  * The current time is ideal for this purpose, provided the computer's clock
831  * is synchronized.
832  */
833 static uint64_t get_time_stamp(void)
834 {
835 # if defined(OSSL_POSIX_TIMER_OKAY)
836     {
837         struct timespec ts;
838
839         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
840             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
841     }
842 # endif
843 # if defined(__unix__) \
844      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
845     {
846         struct timeval tv;
847
848         if (gettimeofday(&tv, NULL) == 0)
849             return TWO32TO64(tv.tv_sec, tv.tv_usec);
850     }
851 # endif
852     return time(NULL);
853 }
854
855 /*
856  * Get an arbitrary timer value of the highest possible resolution
857  *
858  * The timer value is added as random noise to the additional data,
859  * which is not considered a trusted entropy sourec, so any result
860  * is acceptable.
861  */
862 static uint64_t get_timer_bits(void)
863 {
864     uint64_t res = OPENSSL_rdtsc();
865
866     if (res != 0)
867         return res;
868
869 # if defined(__sun) || defined(__hpux)
870     return gethrtime();
871 # elif defined(_AIX)
872     {
873         timebasestruct_t t;
874
875         read_wall_time(&t, TIMEBASE_SZ);
876         return TWO32TO64(t.tb_high, t.tb_low);
877     }
878 # elif defined(OSSL_POSIX_TIMER_OKAY)
879     {
880         struct timespec ts;
881
882 #  ifdef CLOCK_BOOTTIME
883 #   define CLOCK_TYPE CLOCK_BOOTTIME
884 #  elif defined(_POSIX_MONOTONIC_CLOCK)
885 #   define CLOCK_TYPE CLOCK_MONOTONIC
886 #  else
887 #   define CLOCK_TYPE CLOCK_REALTIME
888 #  endif
889
890         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
891             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
892     }
893 # endif
894 # if defined(__unix__) \
895      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
896     {
897         struct timeval tv;
898
899         if (gettimeofday(&tv, NULL) == 0)
900             return TWO32TO64(tv.tv_sec, tv.tv_usec);
901     }
902 # endif
903     return time(NULL);
904 }
905 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
906           || defined(__DJGPP__) */