081ffca908bd486145cabffa64f3caa5f794c97a
[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(__NetBSD__)) && !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__)
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   defined(__FreeBSD__)
231     if (!ossl_assert(buflen % sizeof(long) == 0)) {
232         errno = EINVAL;
233         return -1;
234     }
235 #endif
236
237     /*
238      * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
239      * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
240      * it returns a variable number of bytes with the current version supporting
241      * up to 256 bytes.
242      * Just return an error on older NetBSD versions.
243      */
244 #if   defined(__NetBSD__) && __NetBSD_Version__ < 400000000
245     errno = ENOSYS;
246     return -1;
247 #endif
248
249     mib[0] = CTL_KERN;
250     mib[1] = KERN_ARND;
251
252     do {
253         len = buflen > 256 ? 256 : buflen;
254         if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
255             return done > 0 ? done : -1;
256         done += len;
257         buf += len;
258         buflen -= len;
259     } while (buflen > 0);
260
261     return done;
262 }
263 #  endif
264
265 #  if defined(OPENSSL_RAND_SEED_GETRANDOM)
266
267 #   if defined(__linux) && !defined(__NR_getrandom)
268 #    if defined(__arm__)
269 #     define __NR_getrandom    (__NR_SYSCALL_BASE+384)
270 #    elif defined(__i386__)
271 #     define __NR_getrandom    355
272 #    elif defined(__x86_64__)
273 #     if defined(__ILP32__)
274 #      define __NR_getrandom   (__X32_SYSCALL_BIT + 318)
275 #     else
276 #      define __NR_getrandom   318
277 #     endif
278 #    elif defined(__xtensa__)
279 #     define __NR_getrandom    338
280 #    elif defined(__s390__) || defined(__s390x__)
281 #     define __NR_getrandom    349
282 #    elif defined(__bfin__)
283 #     define __NR_getrandom    389
284 #    elif defined(__powerpc__)
285 #     define __NR_getrandom    359
286 #    elif defined(__mips__) || defined(__mips64)
287 #     if _MIPS_SIM == _MIPS_SIM_ABI32
288 #      define __NR_getrandom   (__NR_Linux + 353)
289 #     elif _MIPS_SIM == _MIPS_SIM_ABI64
290 #      define __NR_getrandom   (__NR_Linux + 313)
291 #     elif _MIPS_SIM == _MIPS_SIM_NABI32
292 #      define __NR_getrandom   (__NR_Linux + 317)
293 #     endif
294 #    elif defined(__hppa__)
295 #     define __NR_getrandom    (__NR_Linux + 339)
296 #    elif defined(__sparc__)
297 #     define __NR_getrandom    347
298 #    elif defined(__ia64__)
299 #     define __NR_getrandom    1339
300 #    elif defined(__alpha__)
301 #     define __NR_getrandom    511
302 #    elif defined(__sh__)
303 #     if defined(__SH5__)
304 #      define __NR_getrandom   373
305 #     else
306 #      define __NR_getrandom   384
307 #     endif
308 #    elif defined(__avr32__)
309 #     define __NR_getrandom    317
310 #    elif defined(__microblaze__)
311 #     define __NR_getrandom    385
312 #    elif defined(__m68k__)
313 #     define __NR_getrandom    352
314 #    elif defined(__cris__)
315 #     define __NR_getrandom    356
316 #    elif defined(__aarch64__)
317 #     define __NR_getrandom    278
318 #    else /* generic */
319 #     define __NR_getrandom    278
320 #    endif
321 #   endif
322
323 /*
324  * syscall_random(): Try to get random data using a system call
325  * returns the number of bytes returned in buf, or < 0 on error.
326  */
327 static ssize_t syscall_random(void *buf, size_t buflen)
328 {
329     /*
330      * Note: 'buflen' equals the size of the buffer which is used by the
331      * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
332      *
333      *   2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
334      *
335      * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
336      * between size_t and ssize_t is safe even without a range check.
337      */
338
339     /*
340      * Do runtime detection to find getentropy().
341      *
342      * Known OSs that should support this:
343      * - Darwin since 16 (OSX 10.12, IOS 10.0).
344      * - Solaris since 11.3
345      * - OpenBSD since 5.6
346      * - Linux since 3.17 with glibc 2.25
347      * - FreeBSD since 12.0 (1200061)
348      */
349 #  if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
350     extern int getentropy(void *buffer, size_t length) __attribute__((weak));
351
352     if (getentropy != NULL)
353         return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
354 #  elif !defined(FIPS_MODULE)
355     union {
356         void *p;
357         int (*f)(void *buffer, size_t length);
358     } p_getentropy;
359
360     /*
361      * We could cache the result of the lookup, but we normally don't
362      * call this function often.
363      */
364     ERR_set_mark();
365     p_getentropy.p = DSO_global_lookup("getentropy");
366     ERR_pop_to_mark();
367     if (p_getentropy.p != NULL)
368         return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
369 #  endif
370
371     /* Linux supports this since version 3.17 */
372 #  if defined(__linux) && defined(__NR_getrandom)
373     return syscall(__NR_getrandom, buf, buflen, 0);
374 #  elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
375     return sysctl_random(buf, buflen);
376 #  else
377     errno = ENOSYS;
378     return -1;
379 #  endif
380 }
381 #  endif    /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
382
383 #  if defined(OPENSSL_RAND_SEED_DEVRANDOM)
384 static const char *random_device_paths[] = { DEVRANDOM };
385 static struct random_device {
386     int fd;
387     dev_t dev;
388     ino_t ino;
389     mode_t mode;
390     dev_t rdev;
391 } random_devices[OSSL_NELEM(random_device_paths)];
392 static int keep_random_devices_open = 1;
393
394 #   if defined(__linux) && defined(DEVRANDOM_WAIT)
395 static void *shm_addr;
396
397 #    if !defined(FIPS_MODULE)
398 static void cleanup_shm(void)
399 {
400     shmdt(shm_addr);
401 }
402 #    endif
403
404 /*
405  * Ensure that the system randomness source has been adequately seeded.
406  * This is done by having the first start of libcrypto, wait until the device
407  * /dev/random becomes able to supply a byte of entropy.  Subsequent starts
408  * of the library and later reseedings do not need to do this.
409  */
410 static int wait_random_seeded(void)
411 {
412     static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
413     static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
414     int kernel[2];
415     int shm_id, fd, r;
416     char c, *p;
417     struct utsname un;
418     fd_set fds;
419
420     if (!seeded) {
421         /* See if anything has created the global seeded indication */
422         if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
423             /*
424              * Check the kernel's version and fail if it is too recent.
425              *
426              * Linux kernels from 4.8 onwards do not guarantee that
427              * /dev/urandom is properly seeded when /dev/random becomes
428              * readable.  However, such kernels support the getentropy(2)
429              * system call and this should always succeed which renders
430              * this alternative but essentially identical source moot.
431              */
432             if (uname(&un) == 0) {
433                 kernel[0] = atoi(un.release);
434                 p = strchr(un.release, '.');
435                 kernel[1] = p == NULL ? 0 : atoi(p + 1);
436                 if (kernel[0] > kernel_version[0]
437                     || (kernel[0] == kernel_version[0]
438                         && kernel[1] >= kernel_version[1])) {
439                     return 0;
440                 }
441             }
442             /* Open /dev/random and wait for it to be readable */
443             if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
444                 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
445                     FD_ZERO(&fds);
446                     FD_SET(fd, &fds);
447                     while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
448                            && errno == EINTR);
449                 } else {
450                     while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
451                 }
452                 close(fd);
453                 if (r == 1) {
454                     seeded = 1;
455                     /* Create the shared memory indicator */
456                     shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
457                                     IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
458                 }
459             }
460         }
461         if (shm_id != -1) {
462             seeded = 1;
463             /*
464              * Map the shared memory to prevent its premature destruction.
465              * If this call fails, it isn't a big problem.
466              */
467             shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
468 #    ifndef FIPS_MODULE
469             /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
470             if (shm_addr != (void *)-1)
471                 OPENSSL_atexit(&cleanup_shm);
472 #    endif
473         }
474     }
475     return seeded;
476 }
477 #   else /* defined __linux */
478 static int wait_random_seeded(void)
479 {
480     return 1;
481 }
482 #   endif
483
484 /*
485  * Verify that the file descriptor associated with the random source is
486  * still valid. The rationale for doing this is the fact that it is not
487  * uncommon for daemons to close all open file handles when daemonizing.
488  * So the handle might have been closed or even reused for opening
489  * another file.
490  */
491 static int check_random_device(struct random_device * rd)
492 {
493     struct stat st;
494
495     return rd->fd != -1
496            && fstat(rd->fd, &st) != -1
497            && rd->dev == st.st_dev
498            && rd->ino == st.st_ino
499            && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
500            && rd->rdev == st.st_rdev;
501 }
502
503 /*
504  * Open a random device if required and return its file descriptor or -1 on error
505  */
506 static int get_random_device(size_t n)
507 {
508     struct stat st;
509     struct random_device * rd = &random_devices[n];
510
511     /* reuse existing file descriptor if it is (still) valid */
512     if (check_random_device(rd))
513         return rd->fd;
514
515     /* open the random device ... */
516     if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
517         return rd->fd;
518
519     /* ... and cache its relevant stat(2) data */
520     if (fstat(rd->fd, &st) != -1) {
521         rd->dev = st.st_dev;
522         rd->ino = st.st_ino;
523         rd->mode = st.st_mode;
524         rd->rdev = st.st_rdev;
525     } else {
526         close(rd->fd);
527         rd->fd = -1;
528     }
529
530     return rd->fd;
531 }
532
533 /*
534  * Close a random device making sure it is a random device
535  */
536 static void close_random_device(size_t n)
537 {
538     struct random_device * rd = &random_devices[n];
539
540     if (check_random_device(rd))
541         close(rd->fd);
542     rd->fd = -1;
543 }
544
545 int rand_pool_init(void)
546 {
547     size_t i;
548
549     for (i = 0; i < OSSL_NELEM(random_devices); i++)
550         random_devices[i].fd = -1;
551
552     return 1;
553 }
554
555 void rand_pool_cleanup(void)
556 {
557     size_t i;
558
559     for (i = 0; i < OSSL_NELEM(random_devices); i++)
560         close_random_device(i);
561 }
562
563 void rand_pool_keep_random_devices_open(int keep)
564 {
565     if (!keep)
566         rand_pool_cleanup();
567
568     keep_random_devices_open = keep;
569 }
570
571 #  else     /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
572
573 int rand_pool_init(void)
574 {
575     return 1;
576 }
577
578 void rand_pool_cleanup(void)
579 {
580 }
581
582 void rand_pool_keep_random_devices_open(int keep)
583 {
584 }
585
586 #  endif    /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
587
588 /*
589  * Try the various seeding methods in turn, exit when successful.
590  *
591  * TODO(DRBG): If more than one entropy source is available, is it
592  * preferable to stop as soon as enough entropy has been collected
593  * (as favored by @rsalz) or should one rather be defensive and add
594  * more entropy than requested and/or from different sources?
595  *
596  * Currently, the user can select multiple entropy sources in the
597  * configure step, yet in practice only the first available source
598  * will be used. A more flexible solution has been requested, but
599  * currently it is not clear how this can be achieved without
600  * overengineering the problem. There are many parameters which
601  * could be taken into account when selecting the order and amount
602  * of input from the different entropy sources (trust, quality,
603  * possibility of blocking).
604  */
605 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
606 {
607 #  if defined(OPENSSL_RAND_SEED_NONE)
608     return rand_pool_entropy_available(pool);
609 #  else
610     size_t entropy_available;
611
612 #   if defined(OPENSSL_RAND_SEED_GETRANDOM)
613     {
614         size_t bytes_needed;
615         unsigned char *buffer;
616         ssize_t bytes;
617         /* Maximum allowed number of consecutive unsuccessful attempts */
618         int attempts = 3;
619
620         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
621         while (bytes_needed != 0 && attempts-- > 0) {
622             buffer = rand_pool_add_begin(pool, bytes_needed);
623             bytes = syscall_random(buffer, bytes_needed);
624             if (bytes > 0) {
625                 rand_pool_add_end(pool, bytes, 8 * bytes);
626                 bytes_needed -= bytes;
627                 attempts = 3; /* reset counter after successful attempt */
628             } else if (bytes < 0 && errno != EINTR) {
629                 break;
630             }
631         }
632     }
633     entropy_available = rand_pool_entropy_available(pool);
634     if (entropy_available > 0)
635         return entropy_available;
636 #   endif
637
638 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
639     {
640         /* Not yet implemented. */
641     }
642 #   endif
643
644 #   if defined(OPENSSL_RAND_SEED_DEVRANDOM)
645     if (wait_random_seeded()) {
646         size_t bytes_needed;
647         unsigned char *buffer;
648         size_t i;
649
650         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
651         for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
652              i++) {
653             ssize_t bytes = 0;
654             /* Maximum number of consecutive unsuccessful attempts */
655             int attempts = 3;
656             const int fd = get_random_device(i);
657
658             if (fd == -1)
659                 continue;
660
661             while (bytes_needed != 0 && attempts-- > 0) {
662                 buffer = rand_pool_add_begin(pool, bytes_needed);
663                 bytes = read(fd, buffer, bytes_needed);
664
665                 if (bytes > 0) {
666                     rand_pool_add_end(pool, bytes, 8 * bytes);
667                     bytes_needed -= bytes;
668                     attempts = 3; /* reset counter on successful attempt */
669                 } else if (bytes < 0 && errno != EINTR) {
670                     break;
671                 }
672             }
673             if (bytes < 0 || !keep_random_devices_open)
674                 close_random_device(i);
675
676             bytes_needed = rand_pool_bytes_needed(pool, 1);
677         }
678         entropy_available = rand_pool_entropy_available(pool);
679         if (entropy_available > 0)
680             return entropy_available;
681     }
682 #   endif
683
684 #   if defined(OPENSSL_RAND_SEED_RDTSC)
685     entropy_available = rand_acquire_entropy_from_tsc(pool);
686     if (entropy_available > 0)
687         return entropy_available;
688 #   endif
689
690 #   if defined(OPENSSL_RAND_SEED_RDCPU)
691     entropy_available = rand_acquire_entropy_from_cpu(pool);
692     if (entropy_available > 0)
693         return entropy_available;
694 #   endif
695
696 #   if defined(OPENSSL_RAND_SEED_EGD)
697     {
698         static const char *paths[] = { DEVRANDOM_EGD, NULL };
699         size_t bytes_needed;
700         unsigned char *buffer;
701         int i;
702
703         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
704         for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
705             size_t bytes = 0;
706             int num;
707
708             buffer = rand_pool_add_begin(pool, bytes_needed);
709             num = RAND_query_egd_bytes(paths[i],
710                                        buffer, (int)bytes_needed);
711             if (num == (int)bytes_needed)
712                 bytes = bytes_needed;
713
714             rand_pool_add_end(pool, bytes, 8 * bytes);
715             bytes_needed = rand_pool_bytes_needed(pool, 1);
716         }
717         entropy_available = rand_pool_entropy_available(pool);
718         if (entropy_available > 0)
719             return entropy_available;
720     }
721 #   endif
722
723     return rand_pool_entropy_available(pool);
724 #  endif
725 }
726 # endif
727 #endif
728
729 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
730      || defined(__DJGPP__)
731 int rand_pool_add_nonce_data(RAND_POOL *pool)
732 {
733     struct {
734         pid_t pid;
735         CRYPTO_THREAD_ID tid;
736         uint64_t time;
737     } data;
738
739     /* Erase the entire structure including any padding */
740     memset(&data, 0, sizeof(data));
741
742     /*
743      * Add process id, thread id, and a high resolution timestamp to
744      * ensure that the nonce is unique with high probability for
745      * different process instances.
746      */
747     data.pid = getpid();
748     data.tid = CRYPTO_THREAD_get_current_id();
749     data.time = get_time_stamp();
750
751     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
752 }
753
754 int rand_pool_add_additional_data(RAND_POOL *pool)
755 {
756     struct {
757         int fork_id;
758         CRYPTO_THREAD_ID tid;
759         uint64_t time;
760     } data;
761
762     /* Erase the entire structure including any padding */
763     memset(&data, 0, sizeof(data));
764
765     /*
766      * Add some noise from the thread id and a high resolution timer.
767      * The fork_id adds some extra fork-safety.
768      * The thread id adds a little randomness if the drbg is accessed
769      * concurrently (which is the case for the <master> drbg).
770      */
771     data.fork_id = openssl_get_fork_id();
772     data.tid = CRYPTO_THREAD_get_current_id();
773     data.time = get_timer_bits();
774
775     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
776 }
777
778
779 /*
780  * Get the current time with the highest possible resolution
781  *
782  * The time stamp is added to the nonce, so it is optimized for not repeating.
783  * The current time is ideal for this purpose, provided the computer's clock
784  * is synchronized.
785  */
786 static uint64_t get_time_stamp(void)
787 {
788 # if defined(OSSL_POSIX_TIMER_OKAY)
789     {
790         struct timespec ts;
791
792         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
793             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
794     }
795 # endif
796 # if defined(__unix__) \
797      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
798     {
799         struct timeval tv;
800
801         if (gettimeofday(&tv, NULL) == 0)
802             return TWO32TO64(tv.tv_sec, tv.tv_usec);
803     }
804 # endif
805     return time(NULL);
806 }
807
808 /*
809  * Get an arbitrary timer value of the highest possible resolution
810  *
811  * The timer value is added as random noise to the additional data,
812  * which is not considered a trusted entropy sourec, so any result
813  * is acceptable.
814  */
815 static uint64_t get_timer_bits(void)
816 {
817     uint64_t res = OPENSSL_rdtsc();
818
819     if (res != 0)
820         return res;
821
822 # if defined(__sun) || defined(__hpux)
823     return gethrtime();
824 # elif defined(_AIX)
825     {
826         timebasestruct_t t;
827
828         read_wall_time(&t, TIMEBASE_SZ);
829         return TWO32TO64(t.tb_high, t.tb_low);
830     }
831 # elif defined(OSSL_POSIX_TIMER_OKAY)
832     {
833         struct timespec ts;
834
835 #  ifdef CLOCK_BOOTTIME
836 #   define CLOCK_TYPE CLOCK_BOOTTIME
837 #  elif defined(_POSIX_MONOTONIC_CLOCK)
838 #   define CLOCK_TYPE CLOCK_MONOTONIC
839 #  else
840 #   define CLOCK_TYPE CLOCK_REALTIME
841 #  endif
842
843         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
844             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
845     }
846 # endif
847 # if defined(__unix__) \
848      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
849     {
850         struct timeval tv;
851
852         if (gettimeofday(&tv, NULL) == 0)
853             return TWO32TO64(tv.tv_sec, tv.tv_usec);
854     }
855 # endif
856     return time(NULL);
857 }
858 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
859           || defined(__DJGPP__) */