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