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