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