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