2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
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
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"
21 #include "internal/dso.h"
24 # include <sys/syscall.h>
25 # ifdef DEVRANDOM_WAIT
27 # include <sys/utsname.h>
30 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
31 # include <sys/types.h>
32 # include <sys/sysctl.h>
33 # include <sys/param.h>
35 #if defined(__OpenBSD__) || defined(__NetBSD__)
36 # include <sys/param.h>
39 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
41 # include <sys/types.h>
42 # include <sys/stat.h>
45 # include <sys/time.h>
47 static uint64_t get_time_stamp(void);
48 static uint64_t get_timer_bits(void);
50 /* Macro to convert two thirty two bit values into a sixty four bit one */
51 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
54 * Check for the existence and support of POSIX timers. The standard
55 * says that the _POSIX_TIMERS macro will have a positive value if they
58 * However, we want an additional constraint: that the timer support does
59 * not require an extra library dependency. Early versions of glibc
60 * require -lrt to be specified on the link line to access the timers,
61 * so this needs to be checked for.
63 * It is worse because some libraries define __GLIBC__ but don't
64 * support the version testing macro (e.g. uClibc). This means
65 * an extra check is needed.
67 * The final condition is:
68 * "have posix timers and either not glibc or glibc without -lrt"
70 * The nested #if sequences are required to avoid using a parameterised
71 * macro that might be undefined.
73 # undef OSSL_POSIX_TIMER_OKAY
74 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
75 # if defined(__GLIBC__)
76 # if defined(__GLIBC_PREREQ)
77 # if __GLIBC_PREREQ(2, 17)
78 # define OSSL_POSIX_TIMER_OKAY
82 # define OSSL_POSIX_TIMER_OKAY
85 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
86 || defined(__DJGPP__) */
88 #if defined(OPENSSL_RAND_SEED_NONE)
89 /* none means none. this simplifies the following logic */
90 # undef OPENSSL_RAND_SEED_OS
91 # undef OPENSSL_RAND_SEED_GETRANDOM
92 # undef OPENSSL_RAND_SEED_LIBRANDOM
93 # undef OPENSSL_RAND_SEED_DEVRANDOM
94 # undef OPENSSL_RAND_SEED_RDTSC
95 # undef OPENSSL_RAND_SEED_RDCPU
96 # undef OPENSSL_RAND_SEED_EGD
99 #if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
100 # error "UEFI only supports seeding NONE"
103 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
104 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
105 || defined(OPENSSL_SYS_UEFI))
107 # if defined(OPENSSL_SYS_VOS)
109 # ifndef OPENSSL_RAND_SEED_OS
110 # error "Unsupported seeding method configured; must be os"
113 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
114 # error "Unsupported HP-PA and IA32 at the same time."
116 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
117 # error "Must have one of HP-PA or IA32"
121 * The following algorithm repeatedly samples the real-time clock (RTC) to
122 * generate a sequence of unpredictable data. The algorithm relies upon the
123 * uneven execution speed of the code (due to factors such as cache misses,
124 * interrupts, bus activity, and scheduling) and upon the rather large
125 * relative difference between the speed of the clock and the rate at which
126 * it can be read. If it is ported to an environment where execution speed
127 * is more constant or where the RTC ticks at a much slower rate, or the
128 * clock can be read with fewer instructions, it is likely that the results
129 * would be far more predictable. This should only be used for legacy
132 * As a precaution, we assume only 2 bits of entropy per byte.
134 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
141 # ifdef OPENSSL_SYS_VOS_HPPA
143 extern void s$sleep(long *_duration, short int *_code);
146 extern void s$sleep2(long long *_duration, short int *_code);
149 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
151 for (i = 0; i < bytes_needed; i++) {
153 * burn some cpu; hope for interrupts, cache collisions, bus
156 for (k = 0; k < 99; k++)
157 ts.tv_nsec = random();
159 # ifdef OPENSSL_SYS_VOS_HPPA
160 /* sleep for 1/1024 of a second (976 us). */
162 s$sleep(&duration, &code);
164 /* sleep for 1/65536 of a second (15 us). */
166 s$sleep2(&duration, &code);
169 /* Get wall clock time, take 8 bits. */
170 clock_gettime(CLOCK_REALTIME, &ts);
171 v = (unsigned char)(ts.tv_nsec & 0xFF);
172 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
174 return rand_pool_entropy_available(pool);
177 void rand_pool_cleanup(void)
181 void rand_pool_keep_random_devices_open(int keep)
187 # if defined(OPENSSL_RAND_SEED_EGD) && \
188 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
189 # error "Seeding uses EGD but EGD is turned off or no device given"
192 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
193 # error "Seeding uses urandom but DEVRANDOM is not configured"
196 # if defined(OPENSSL_RAND_SEED_OS)
197 # if !defined(DEVRANDOM)
198 # error "OS seeding requires DEVRANDOM to be configured"
200 # define OPENSSL_RAND_SEED_GETRANDOM
201 # define OPENSSL_RAND_SEED_DEVRANDOM
204 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
205 # error "librandom not (yet) supported"
208 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
210 * sysctl_random(): Use sysctl() to read a random number from the kernel
211 * Returns the number of bytes returned in buf on success, -1 on failure.
213 static ssize_t sysctl_random(char *buf, size_t buflen)
220 * Note: sign conversion between size_t and ssize_t is safe even
221 * without a range check, see comment in syscall_random()
225 * On FreeBSD old implementations returned longs, newer versions support
226 * variable sizes up to 256 byte. The code below would not work properly
227 * when the sysctl returns long and we want to request something not a
228 * multiple of longs, which should never be the case.
230 if (!ossl_assert(buflen % sizeof(long) == 0)) {
236 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
237 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
238 * it returns a variable number of bytes with the current version supporting
240 * Just return an error on older NetBSD versions.
242 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
252 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
253 return done > 0 ? done : -1;
257 } while (buflen > 0);
263 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
265 # if defined(__linux) && !defined(__NR_getrandom)
266 # if defined(__arm__)
267 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
268 # elif defined(__i386__)
269 # define __NR_getrandom 355
270 # elif defined(__x86_64__)
271 # if defined(__ILP32__)
272 # define __NR_getrandom (__X32_SYSCALL_BIT + 318)
274 # define __NR_getrandom 318
276 # elif defined(__xtensa__)
277 # define __NR_getrandom 338
278 # elif defined(__s390__) || defined(__s390x__)
279 # define __NR_getrandom 349
280 # elif defined(__bfin__)
281 # define __NR_getrandom 389
282 # elif defined(__powerpc__)
283 # define __NR_getrandom 359
284 # elif defined(__mips__) || defined(__mips64)
285 # if _MIPS_SIM == _MIPS_SIM_ABI32
286 # define __NR_getrandom (__NR_Linux + 353)
287 # elif _MIPS_SIM == _MIPS_SIM_ABI64
288 # define __NR_getrandom (__NR_Linux + 313)
289 # elif _MIPS_SIM == _MIPS_SIM_NABI32
290 # define __NR_getrandom (__NR_Linux + 317)
292 # elif defined(__hppa__)
293 # define __NR_getrandom (__NR_Linux + 339)
294 # elif defined(__sparc__)
295 # define __NR_getrandom 347
296 # elif defined(__ia64__)
297 # define __NR_getrandom 1339
298 # elif defined(__alpha__)
299 # define __NR_getrandom 511
300 # elif defined(__sh__)
301 # if defined(__SH5__)
302 # define __NR_getrandom 373
304 # define __NR_getrandom 384
306 # elif defined(__avr32__)
307 # define __NR_getrandom 317
308 # elif defined(__microblaze__)
309 # define __NR_getrandom 385
310 # elif defined(__m68k__)
311 # define __NR_getrandom 352
312 # elif defined(__cris__)
313 # define __NR_getrandom 356
314 # elif defined(__aarch64__)
315 # define __NR_getrandom 278
317 # define __NR_getrandom 278
322 * syscall_random(): Try to get random data using a system call
323 * returns the number of bytes returned in buf, or < 0 on error.
325 static ssize_t syscall_random(void *buf, size_t buflen)
328 * Note: 'buflen' equals the size of the buffer which is used by the
329 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
331 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
333 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
334 * between size_t and ssize_t is safe even without a range check.
338 * Do runtime detection to find getentropy().
340 * Known OSs that should support this:
341 * - Darwin since 16 (OSX 10.12, IOS 10.0).
342 * - Solaris since 11.3
343 * - OpenBSD since 5.6
344 * - Linux since 3.17 with glibc 2.25
345 * - FreeBSD since 12.0 (1200061)
347 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
348 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
350 if (getentropy != NULL)
351 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
352 # elif !defined(FIPS_MODULE)
355 int (*f)(void *buffer, size_t length);
359 * We could cache the result of the lookup, but we normally don't
360 * call this function often.
363 p_getentropy.p = DSO_global_lookup("getentropy");
365 if (p_getentropy.p != NULL)
366 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
369 /* Linux supports this since version 3.17 */
370 # if defined(__linux) && defined(__NR_getrandom)
371 return syscall(__NR_getrandom, buf, buflen, 0);
372 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
373 return sysctl_random(buf, buflen);
379 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
381 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
382 static const char *random_device_paths[] = { DEVRANDOM };
383 static struct random_device {
389 } random_devices[OSSL_NELEM(random_device_paths)];
390 static int keep_random_devices_open = 1;
392 # if defined(__linux) && defined(DEVRANDOM_WAIT)
393 static void *shm_addr;
395 # if !defined(FIPS_MODULE)
396 static void cleanup_shm(void)
403 * Ensure that the system randomness source has been adequately seeded.
404 * This is done by having the first start of libcrypto, wait until the device
405 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
406 * of the library and later reseedings do not need to do this.
408 static int wait_random_seeded(void)
410 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
411 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
419 /* See if anything has created the global seeded indication */
420 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
422 * Check the kernel's version and fail if it is too recent.
424 * Linux kernels from 4.8 onwards do not guarantee that
425 * /dev/urandom is properly seeded when /dev/random becomes
426 * readable. However, such kernels support the getentropy(2)
427 * system call and this should always succeed which renders
428 * this alternative but essentially identical source moot.
430 if (uname(&un) == 0) {
431 kernel[0] = atoi(un.release);
432 p = strchr(un.release, '.');
433 kernel[1] = p == NULL ? 0 : atoi(p + 1);
434 if (kernel[0] > kernel_version[0]
435 || (kernel[0] == kernel_version[0]
436 && kernel[1] >= kernel_version[1])) {
440 /* Open /dev/random and wait for it to be readable */
441 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
442 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
445 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
448 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
453 /* Create the shared memory indicator */
454 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
455 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
462 * Map the shared memory to prevent its premature destruction.
463 * If this call fails, it isn't a big problem.
465 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
467 /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
468 if (shm_addr != (void *)-1)
469 OPENSSL_atexit(&cleanup_shm);
475 # else /* defined __linux */
476 static int wait_random_seeded(void)
483 * Verify that the file descriptor associated with the random source is
484 * still valid. The rationale for doing this is the fact that it is not
485 * uncommon for daemons to close all open file handles when daemonizing.
486 * So the handle might have been closed or even reused for opening
489 static int check_random_device(struct random_device * rd)
494 && fstat(rd->fd, &st) != -1
495 && rd->dev == st.st_dev
496 && rd->ino == st.st_ino
497 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
498 && rd->rdev == st.st_rdev;
502 * Open a random device if required and return its file descriptor or -1 on error
504 static int get_random_device(size_t n)
507 struct random_device * rd = &random_devices[n];
509 /* reuse existing file descriptor if it is (still) valid */
510 if (check_random_device(rd))
513 /* open the random device ... */
514 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
517 /* ... and cache its relevant stat(2) data */
518 if (fstat(rd->fd, &st) != -1) {
521 rd->mode = st.st_mode;
522 rd->rdev = st.st_rdev;
532 * Close a random device making sure it is a random device
534 static void close_random_device(size_t n)
536 struct random_device * rd = &random_devices[n];
538 if (check_random_device(rd))
543 int rand_pool_init(void)
547 for (i = 0; i < OSSL_NELEM(random_devices); i++)
548 random_devices[i].fd = -1;
553 void rand_pool_cleanup(void)
557 for (i = 0; i < OSSL_NELEM(random_devices); i++)
558 close_random_device(i);
561 void rand_pool_keep_random_devices_open(int keep)
566 keep_random_devices_open = keep;
569 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
571 int rand_pool_init(void)
576 void rand_pool_cleanup(void)
580 void rand_pool_keep_random_devices_open(int keep)
584 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
587 * Try the various seeding methods in turn, exit when successful.
589 * TODO(DRBG): If more than one entropy source is available, is it
590 * preferable to stop as soon as enough entropy has been collected
591 * (as favored by @rsalz) or should one rather be defensive and add
592 * more entropy than requested and/or from different sources?
594 * Currently, the user can select multiple entropy sources in the
595 * configure step, yet in practice only the first available source
596 * will be used. A more flexible solution has been requested, but
597 * currently it is not clear how this can be achieved without
598 * overengineering the problem. There are many parameters which
599 * could be taken into account when selecting the order and amount
600 * of input from the different entropy sources (trust, quality,
601 * possibility of blocking).
603 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
605 # if defined(OPENSSL_RAND_SEED_NONE)
606 return rand_pool_entropy_available(pool);
608 size_t entropy_available;
610 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
613 unsigned char *buffer;
615 /* Maximum allowed number of consecutive unsuccessful attempts */
618 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
619 while (bytes_needed != 0 && attempts-- > 0) {
620 buffer = rand_pool_add_begin(pool, bytes_needed);
621 bytes = syscall_random(buffer, bytes_needed);
623 rand_pool_add_end(pool, bytes, 8 * bytes);
624 bytes_needed -= bytes;
625 attempts = 3; /* reset counter after successful attempt */
626 } else if (bytes < 0 && errno != EINTR) {
631 entropy_available = rand_pool_entropy_available(pool);
632 if (entropy_available > 0)
633 return entropy_available;
636 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
638 /* Not yet implemented. */
642 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
643 if (wait_random_seeded()) {
645 unsigned char *buffer;
648 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
649 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
652 /* Maximum number of consecutive unsuccessful attempts */
654 const int fd = get_random_device(i);
659 while (bytes_needed != 0 && attempts-- > 0) {
660 buffer = rand_pool_add_begin(pool, bytes_needed);
661 bytes = read(fd, buffer, bytes_needed);
664 rand_pool_add_end(pool, bytes, 8 * bytes);
665 bytes_needed -= bytes;
666 attempts = 3; /* reset counter on successful attempt */
667 } else if (bytes < 0 && errno != EINTR) {
671 if (bytes < 0 || !keep_random_devices_open)
672 close_random_device(i);
674 bytes_needed = rand_pool_bytes_needed(pool, 1);
676 entropy_available = rand_pool_entropy_available(pool);
677 if (entropy_available > 0)
678 return entropy_available;
682 # if defined(OPENSSL_RAND_SEED_RDTSC)
683 entropy_available = rand_acquire_entropy_from_tsc(pool);
684 if (entropy_available > 0)
685 return entropy_available;
688 # if defined(OPENSSL_RAND_SEED_RDCPU)
689 entropy_available = rand_acquire_entropy_from_cpu(pool);
690 if (entropy_available > 0)
691 return entropy_available;
694 # if defined(OPENSSL_RAND_SEED_EGD)
696 static const char *paths[] = { DEVRANDOM_EGD, NULL };
698 unsigned char *buffer;
701 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
702 for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
706 buffer = rand_pool_add_begin(pool, bytes_needed);
707 num = RAND_query_egd_bytes(paths[i],
708 buffer, (int)bytes_needed);
709 if (num == (int)bytes_needed)
710 bytes = bytes_needed;
712 rand_pool_add_end(pool, bytes, 8 * bytes);
713 bytes_needed = rand_pool_bytes_needed(pool, 1);
715 entropy_available = rand_pool_entropy_available(pool);
716 if (entropy_available > 0)
717 return entropy_available;
721 return rand_pool_entropy_available(pool);
727 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
728 || defined(__DJGPP__)
729 int rand_pool_add_nonce_data(RAND_POOL *pool)
733 CRYPTO_THREAD_ID tid;
737 /* Erase the entire structure including any padding */
738 memset(&data, 0, sizeof(data));
741 * Add process id, thread id, and a high resolution timestamp to
742 * ensure that the nonce is unique with high probability for
743 * different process instances.
746 data.tid = CRYPTO_THREAD_get_current_id();
747 data.time = get_time_stamp();
749 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
752 int rand_pool_add_additional_data(RAND_POOL *pool)
756 CRYPTO_THREAD_ID tid;
760 /* Erase the entire structure including any padding */
761 memset(&data, 0, sizeof(data));
764 * Add some noise from the thread id and a high resolution timer.
765 * The fork_id adds some extra fork-safety.
766 * The thread id adds a little randomness if the drbg is accessed
767 * concurrently (which is the case for the <master> drbg).
769 data.fork_id = openssl_get_fork_id();
770 data.tid = CRYPTO_THREAD_get_current_id();
771 data.time = get_timer_bits();
773 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
778 * Get the current time with the highest possible resolution
780 * The time stamp is added to the nonce, so it is optimized for not repeating.
781 * The current time is ideal for this purpose, provided the computer's clock
784 static uint64_t get_time_stamp(void)
786 # if defined(OSSL_POSIX_TIMER_OKAY)
790 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
791 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
794 # if defined(__unix__) \
795 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
799 if (gettimeofday(&tv, NULL) == 0)
800 return TWO32TO64(tv.tv_sec, tv.tv_usec);
807 * Get an arbitrary timer value of the highest possible resolution
809 * The timer value is added as random noise to the additional data,
810 * which is not considered a trusted entropy sourec, so any result
813 static uint64_t get_timer_bits(void)
815 uint64_t res = OPENSSL_rdtsc();
820 # if defined(__sun) || defined(__hpux)
826 read_wall_time(&t, TIMEBASE_SZ);
827 return TWO32TO64(t.tb_high, t.tb_low);
829 # elif defined(OSSL_POSIX_TIMER_OKAY)
833 # ifdef CLOCK_BOOTTIME
834 # define CLOCK_TYPE CLOCK_BOOTTIME
835 # elif defined(_POSIX_MONOTONIC_CLOCK)
836 # define CLOCK_TYPE CLOCK_MONOTONIC
838 # define CLOCK_TYPE CLOCK_REALTIME
841 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
842 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
845 # if defined(__unix__) \
846 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
850 if (gettimeofday(&tv, NULL) == 0)
851 return TWO32TO64(tv.tv_sec, tv.tv_usec);
856 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
857 || defined(__DJGPP__) */