869c2d04ddab5858b46effc0477f8bb1494623f2
[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        && defined(OPENSSL_RAND_SEED_GETRANDOM)
396 static void *shm_addr;
397
398 #    if !defined(FIPS_MODULE)
399 static void cleanup_shm(void)
400 {
401     shmdt(shm_addr);
402 }
403 #    endif
404
405 /*
406  * Ensure that the system randomness source has been adequately seeded.
407  * This is done by having the first start of libcrypto, wait until the device
408  * /dev/random becomes able to supply a byte of entropy.  Subsequent starts
409  * of the library and later reseedings do not need to do this.
410  */
411 static int wait_random_seeded(void)
412 {
413     static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
414     static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
415     int kernel[2];
416     int shm_id, fd, r;
417     char c, *p;
418     struct utsname un;
419     fd_set fds;
420
421     if (!seeded) {
422         /* See if anything has created the global seeded indication */
423         if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
424             /*
425              * Check the kernel's version and fail if it is too recent.
426              *
427              * Linux kernels from 4.8 onwards do not guarantee that
428              * /dev/urandom is properly seeded when /dev/random becomes
429              * readable.  However, such kernels support the getentropy(2)
430              * system call and this should always succeed which renders
431              * this alternative but essentially identical source moot.
432              */
433             if (uname(&un) == 0) {
434                 kernel[0] = atoi(un.release);
435                 p = strchr(un.release, '.');
436                 kernel[1] = p == NULL ? 0 : atoi(p + 1);
437                 if (kernel[0] > kernel_version[0]
438                     || (kernel[0] == kernel_version[0]
439                         && kernel[1] >= kernel_version[1])) {
440                     return 0;
441                 }
442             }
443             /* Open /dev/random and wait for it to be readable */
444             if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
445                 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
446                     FD_ZERO(&fds);
447                     FD_SET(fd, &fds);
448                     while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
449                            && errno == EINTR);
450                 } else {
451                     while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
452                 }
453                 close(fd);
454                 if (r == 1) {
455                     seeded = 1;
456                     /* Create the shared memory indicator */
457                     shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
458                                     IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
459                 }
460             }
461         }
462         if (shm_id != -1) {
463             seeded = 1;
464             /*
465              * Map the shared memory to prevent its premature destruction.
466              * If this call fails, it isn't a big problem.
467              */
468             shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
469 #    ifndef FIPS_MODULE
470             /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
471             if (shm_addr != (void *)-1)
472                 OPENSSL_atexit(&cleanup_shm);
473 #    endif
474         }
475     }
476     return seeded;
477 }
478 #   else /* defined __linux && DEVRANDOM_WAIT && OPENSSL_RAND_SEED_GETRANDOM */
479 static int wait_random_seeded(void)
480 {
481     return 1;
482 }
483 #   endif
484
485 /*
486  * Verify that the file descriptor associated with the random source is
487  * still valid. The rationale for doing this is the fact that it is not
488  * uncommon for daemons to close all open file handles when daemonizing.
489  * So the handle might have been closed or even reused for opening
490  * another file.
491  */
492 static int check_random_device(struct random_device * rd)
493 {
494     struct stat st;
495
496     return rd->fd != -1
497            && fstat(rd->fd, &st) != -1
498            && rd->dev == st.st_dev
499            && rd->ino == st.st_ino
500            && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
501            && rd->rdev == st.st_rdev;
502 }
503
504 /*
505  * Open a random device if required and return its file descriptor or -1 on error
506  */
507 static int get_random_device(size_t n)
508 {
509     struct stat st;
510     struct random_device * rd = &random_devices[n];
511
512     /* reuse existing file descriptor if it is (still) valid */
513     if (check_random_device(rd))
514         return rd->fd;
515
516     /* open the random device ... */
517     if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
518         return rd->fd;
519
520     /* ... and cache its relevant stat(2) data */
521     if (fstat(rd->fd, &st) != -1) {
522         rd->dev = st.st_dev;
523         rd->ino = st.st_ino;
524         rd->mode = st.st_mode;
525         rd->rdev = st.st_rdev;
526     } else {
527         close(rd->fd);
528         rd->fd = -1;
529     }
530
531     return rd->fd;
532 }
533
534 /*
535  * Close a random device making sure it is a random device
536  */
537 static void close_random_device(size_t n)
538 {
539     struct random_device * rd = &random_devices[n];
540
541     if (check_random_device(rd))
542         close(rd->fd);
543     rd->fd = -1;
544 }
545
546 int rand_pool_init(void)
547 {
548     size_t i;
549
550     for (i = 0; i < OSSL_NELEM(random_devices); i++)
551         random_devices[i].fd = -1;
552
553     return 1;
554 }
555
556 void rand_pool_cleanup(void)
557 {
558     size_t i;
559
560     for (i = 0; i < OSSL_NELEM(random_devices); i++)
561         close_random_device(i);
562 }
563
564 void rand_pool_keep_random_devices_open(int keep)
565 {
566     if (!keep)
567         rand_pool_cleanup();
568
569     keep_random_devices_open = keep;
570 }
571
572 #  else     /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
573
574 int rand_pool_init(void)
575 {
576     return 1;
577 }
578
579 void rand_pool_cleanup(void)
580 {
581 }
582
583 void rand_pool_keep_random_devices_open(int keep)
584 {
585 }
586
587 #  endif    /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
588
589 /*
590  * Try the various seeding methods in turn, exit when successful.
591  *
592  * TODO(DRBG): If more than one entropy source is available, is it
593  * preferable to stop as soon as enough entropy has been collected
594  * (as favored by @rsalz) or should one rather be defensive and add
595  * more entropy than requested and/or from different sources?
596  *
597  * Currently, the user can select multiple entropy sources in the
598  * configure step, yet in practice only the first available source
599  * will be used. A more flexible solution has been requested, but
600  * currently it is not clear how this can be achieved without
601  * overengineering the problem. There are many parameters which
602  * could be taken into account when selecting the order and amount
603  * of input from the different entropy sources (trust, quality,
604  * possibility of blocking).
605  */
606 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
607 {
608 #  if defined(OPENSSL_RAND_SEED_NONE)
609     return rand_pool_entropy_available(pool);
610 #  else
611     size_t entropy_available;
612
613 #   if defined(OPENSSL_RAND_SEED_GETRANDOM)
614     {
615         size_t bytes_needed;
616         unsigned char *buffer;
617         ssize_t bytes;
618         /* Maximum allowed number of consecutive unsuccessful attempts */
619         int attempts = 3;
620
621         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
622         while (bytes_needed != 0 && attempts-- > 0) {
623             buffer = rand_pool_add_begin(pool, bytes_needed);
624             bytes = syscall_random(buffer, bytes_needed);
625             if (bytes > 0) {
626                 rand_pool_add_end(pool, bytes, 8 * bytes);
627                 bytes_needed -= bytes;
628                 attempts = 3; /* reset counter after successful attempt */
629             } else if (bytes < 0 && errno != EINTR) {
630                 break;
631             }
632         }
633     }
634     entropy_available = rand_pool_entropy_available(pool);
635     if (entropy_available > 0)
636         return entropy_available;
637 #   endif
638
639 #   if defined(OPENSSL_RAND_SEED_LIBRANDOM)
640     {
641         /* Not yet implemented. */
642     }
643 #   endif
644
645 #   if defined(OPENSSL_RAND_SEED_DEVRANDOM)
646     if (wait_random_seeded()) {
647         size_t bytes_needed;
648         unsigned char *buffer;
649         size_t i;
650
651         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
652         for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
653              i++) {
654             ssize_t bytes = 0;
655             /* Maximum number of consecutive unsuccessful attempts */
656             int attempts = 3;
657             const int fd = get_random_device(i);
658
659             if (fd == -1)
660                 continue;
661
662             while (bytes_needed != 0 && attempts-- > 0) {
663                 buffer = rand_pool_add_begin(pool, bytes_needed);
664                 bytes = read(fd, buffer, bytes_needed);
665
666                 if (bytes > 0) {
667                     rand_pool_add_end(pool, bytes, 8 * bytes);
668                     bytes_needed -= bytes;
669                     attempts = 3; /* reset counter on successful attempt */
670                 } else if (bytes < 0 && errno != EINTR) {
671                     break;
672                 }
673             }
674             if (bytes < 0 || !keep_random_devices_open)
675                 close_random_device(i);
676
677             bytes_needed = rand_pool_bytes_needed(pool, 1);
678         }
679         entropy_available = rand_pool_entropy_available(pool);
680         if (entropy_available > 0)
681             return entropy_available;
682     }
683 #   endif
684
685 #   if defined(OPENSSL_RAND_SEED_RDTSC)
686     entropy_available = rand_acquire_entropy_from_tsc(pool);
687     if (entropy_available > 0)
688         return entropy_available;
689 #   endif
690
691 #   if defined(OPENSSL_RAND_SEED_RDCPU)
692     entropy_available = rand_acquire_entropy_from_cpu(pool);
693     if (entropy_available > 0)
694         return entropy_available;
695 #   endif
696
697 #   if defined(OPENSSL_RAND_SEED_EGD)
698     {
699         static const char *paths[] = { DEVRANDOM_EGD, NULL };
700         size_t bytes_needed;
701         unsigned char *buffer;
702         int i;
703
704         bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
705         for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
706             size_t bytes = 0;
707             int num;
708
709             buffer = rand_pool_add_begin(pool, bytes_needed);
710             num = RAND_query_egd_bytes(paths[i],
711                                        buffer, (int)bytes_needed);
712             if (num == (int)bytes_needed)
713                 bytes = bytes_needed;
714
715             rand_pool_add_end(pool, bytes, 8 * bytes);
716             bytes_needed = rand_pool_bytes_needed(pool, 1);
717         }
718         entropy_available = rand_pool_entropy_available(pool);
719         if (entropy_available > 0)
720             return entropy_available;
721     }
722 #   endif
723
724     return rand_pool_entropy_available(pool);
725 #  endif
726 }
727 # endif
728 #endif
729
730 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
731      || defined(__DJGPP__)
732 int rand_pool_add_nonce_data(RAND_POOL *pool)
733 {
734     struct {
735         pid_t pid;
736         CRYPTO_THREAD_ID tid;
737         uint64_t time;
738     } data;
739
740     /* Erase the entire structure including any padding */
741     memset(&data, 0, sizeof(data));
742
743     /*
744      * Add process id, thread id, and a high resolution timestamp to
745      * ensure that the nonce is unique with high probability for
746      * different process instances.
747      */
748     data.pid = getpid();
749     data.tid = CRYPTO_THREAD_get_current_id();
750     data.time = get_time_stamp();
751
752     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
753 }
754
755 int rand_pool_add_additional_data(RAND_POOL *pool)
756 {
757     struct {
758         int fork_id;
759         CRYPTO_THREAD_ID tid;
760         uint64_t time;
761     } data;
762
763     /* Erase the entire structure including any padding */
764     memset(&data, 0, sizeof(data));
765
766     /*
767      * Add some noise from the thread id and a high resolution timer.
768      * The fork_id adds some extra fork-safety.
769      * The thread id adds a little randomness if the drbg is accessed
770      * concurrently (which is the case for the <master> drbg).
771      */
772     data.fork_id = openssl_get_fork_id();
773     data.tid = CRYPTO_THREAD_get_current_id();
774     data.time = get_timer_bits();
775
776     return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
777 }
778
779
780 /*
781  * Get the current time with the highest possible resolution
782  *
783  * The time stamp is added to the nonce, so it is optimized for not repeating.
784  * The current time is ideal for this purpose, provided the computer's clock
785  * is synchronized.
786  */
787 static uint64_t get_time_stamp(void)
788 {
789 # if defined(OSSL_POSIX_TIMER_OKAY)
790     {
791         struct timespec ts;
792
793         if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
794             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
795     }
796 # endif
797 # if defined(__unix__) \
798      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
799     {
800         struct timeval tv;
801
802         if (gettimeofday(&tv, NULL) == 0)
803             return TWO32TO64(tv.tv_sec, tv.tv_usec);
804     }
805 # endif
806     return time(NULL);
807 }
808
809 /*
810  * Get an arbitrary timer value of the highest possible resolution
811  *
812  * The timer value is added as random noise to the additional data,
813  * which is not considered a trusted entropy sourec, so any result
814  * is acceptable.
815  */
816 static uint64_t get_timer_bits(void)
817 {
818     uint64_t res = OPENSSL_rdtsc();
819
820     if (res != 0)
821         return res;
822
823 # if defined(__sun) || defined(__hpux)
824     return gethrtime();
825 # elif defined(_AIX)
826     {
827         timebasestruct_t t;
828
829         read_wall_time(&t, TIMEBASE_SZ);
830         return TWO32TO64(t.tb_high, t.tb_low);
831     }
832 # elif defined(OSSL_POSIX_TIMER_OKAY)
833     {
834         struct timespec ts;
835
836 #  ifdef CLOCK_BOOTTIME
837 #   define CLOCK_TYPE CLOCK_BOOTTIME
838 #  elif defined(_POSIX_MONOTONIC_CLOCK)
839 #   define CLOCK_TYPE CLOCK_MONOTONIC
840 #  else
841 #   define CLOCK_TYPE CLOCK_REALTIME
842 #  endif
843
844         if (clock_gettime(CLOCK_TYPE, &ts) == 0)
845             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
846     }
847 # endif
848 # if defined(__unix__) \
849      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
850     {
851         struct timeval tv;
852
853         if (gettimeofday(&tv, NULL) == 0)
854             return TWO32TO64(tv.tv_sec, tv.tv_usec);
855     }
856 # endif
857     return time(NULL);
858 }
859 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
860           || defined(__DJGPP__) */