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