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