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(__NetBSD__)) && !defined(OPENSSL_SYS_UEFI)
31 # include <sys/types.h>
32 # include <sys/sysctl.h>
33 # include <sys/param.h>
35 #if defined(__OpenBSD__)
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 defined(__FreeBSD__)
231 if (!ossl_assert(buflen % sizeof(long) == 0)) {
238 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
239 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
240 * it returns a variable number of bytes with the current version supporting
242 * Just return an error on older NetBSD versions.
244 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
254 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
255 return done > 0 ? done : -1;
259 } while (buflen > 0);
265 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
267 # if defined(__linux) && !defined(__NR_getrandom)
268 # if defined(__arm__)
269 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
270 # elif defined(__i386__)
271 # define __NR_getrandom 355
272 # elif defined(__x86_64__)
273 # if defined(__ILP32__)
274 # define __NR_getrandom (__X32_SYSCALL_BIT + 318)
276 # define __NR_getrandom 318
278 # elif defined(__xtensa__)
279 # define __NR_getrandom 338
280 # elif defined(__s390__) || defined(__s390x__)
281 # define __NR_getrandom 349
282 # elif defined(__bfin__)
283 # define __NR_getrandom 389
284 # elif defined(__powerpc__)
285 # define __NR_getrandom 359
286 # elif defined(__mips__) || defined(__mips64)
287 # if _MIPS_SIM == _MIPS_SIM_ABI32
288 # define __NR_getrandom (__NR_Linux + 353)
289 # elif _MIPS_SIM == _MIPS_SIM_ABI64
290 # define __NR_getrandom (__NR_Linux + 313)
291 # elif _MIPS_SIM == _MIPS_SIM_NABI32
292 # define __NR_getrandom (__NR_Linux + 317)
294 # elif defined(__hppa__)
295 # define __NR_getrandom (__NR_Linux + 339)
296 # elif defined(__sparc__)
297 # define __NR_getrandom 347
298 # elif defined(__ia64__)
299 # define __NR_getrandom 1339
300 # elif defined(__alpha__)
301 # define __NR_getrandom 511
302 # elif defined(__sh__)
303 # if defined(__SH5__)
304 # define __NR_getrandom 373
306 # define __NR_getrandom 384
308 # elif defined(__avr32__)
309 # define __NR_getrandom 317
310 # elif defined(__microblaze__)
311 # define __NR_getrandom 385
312 # elif defined(__m68k__)
313 # define __NR_getrandom 352
314 # elif defined(__cris__)
315 # define __NR_getrandom 356
316 # elif defined(__aarch64__)
317 # define __NR_getrandom 278
319 # define __NR_getrandom 278
324 * syscall_random(): Try to get random data using a system call
325 * returns the number of bytes returned in buf, or < 0 on error.
327 static ssize_t syscall_random(void *buf, size_t buflen)
330 * Note: 'buflen' equals the size of the buffer which is used by the
331 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
333 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
335 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
336 * between size_t and ssize_t is safe even without a range check.
340 * Do runtime detection to find getentropy().
342 * Known OSs that should support this:
343 * - Darwin since 16 (OSX 10.12, IOS 10.0).
344 * - Solaris since 11.3
345 * - OpenBSD since 5.6
346 * - Linux since 3.17 with glibc 2.25
347 * - FreeBSD since 12.0 (1200061)
349 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
350 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
352 if (getentropy != NULL)
353 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
354 # elif !defined(FIPS_MODULE)
357 int (*f)(void *buffer, size_t length);
361 * We could cache the result of the lookup, but we normally don't
362 * call this function often.
365 p_getentropy.p = DSO_global_lookup("getentropy");
367 if (p_getentropy.p != NULL)
368 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
371 /* Linux supports this since version 3.17 */
372 # if defined(__linux) && defined(__NR_getrandom)
373 return syscall(__NR_getrandom, buf, buflen, 0);
374 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
375 return sysctl_random(buf, buflen);
381 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
383 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
384 static const char *random_device_paths[] = { DEVRANDOM };
385 static struct random_device {
391 } random_devices[OSSL_NELEM(random_device_paths)];
392 static int keep_random_devices_open = 1;
394 # if defined(__linux) && defined(DEVRANDOM_WAIT)
395 static void *shm_addr;
397 # if !defined(FIPS_MODULE)
398 static void cleanup_shm(void)
405 * Ensure that the system randomness source has been adequately seeded.
406 * This is done by having the first start of libcrypto, wait until the device
407 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
408 * of the library and later reseedings do not need to do this.
410 static int wait_random_seeded(void)
412 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
413 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
421 /* See if anything has created the global seeded indication */
422 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
424 * Check the kernel's version and fail if it is too recent.
426 * Linux kernels from 4.8 onwards do not guarantee that
427 * /dev/urandom is properly seeded when /dev/random becomes
428 * readable. However, such kernels support the getentropy(2)
429 * system call and this should always succeed which renders
430 * this alternative but essentially identical source moot.
432 if (uname(&un) == 0) {
433 kernel[0] = atoi(un.release);
434 p = strchr(un.release, '.');
435 kernel[1] = p == NULL ? 0 : atoi(p + 1);
436 if (kernel[0] > kernel_version[0]
437 || (kernel[0] == kernel_version[0]
438 && kernel[1] >= kernel_version[1])) {
442 /* Open /dev/random and wait for it to be readable */
443 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
444 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
447 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
450 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
455 /* Create the shared memory indicator */
456 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
457 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
464 * Map the shared memory to prevent its premature destruction.
465 * If this call fails, it isn't a big problem.
467 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
469 /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
470 if (shm_addr != (void *)-1)
471 OPENSSL_atexit(&cleanup_shm);
477 # else /* defined __linux */
478 static int wait_random_seeded(void)
485 * Verify that the file descriptor associated with the random source is
486 * still valid. The rationale for doing this is the fact that it is not
487 * uncommon for daemons to close all open file handles when daemonizing.
488 * So the handle might have been closed or even reused for opening
491 static int check_random_device(struct random_device * rd)
496 && fstat(rd->fd, &st) != -1
497 && rd->dev == st.st_dev
498 && rd->ino == st.st_ino
499 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
500 && rd->rdev == st.st_rdev;
504 * Open a random device if required and return its file descriptor or -1 on error
506 static int get_random_device(size_t n)
509 struct random_device * rd = &random_devices[n];
511 /* reuse existing file descriptor if it is (still) valid */
512 if (check_random_device(rd))
515 /* open the random device ... */
516 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
519 /* ... and cache its relevant stat(2) data */
520 if (fstat(rd->fd, &st) != -1) {
523 rd->mode = st.st_mode;
524 rd->rdev = st.st_rdev;
534 * Close a random device making sure it is a random device
536 static void close_random_device(size_t n)
538 struct random_device * rd = &random_devices[n];
540 if (check_random_device(rd))
545 int rand_pool_init(void)
549 for (i = 0; i < OSSL_NELEM(random_devices); i++)
550 random_devices[i].fd = -1;
555 void rand_pool_cleanup(void)
559 for (i = 0; i < OSSL_NELEM(random_devices); i++)
560 close_random_device(i);
563 void rand_pool_keep_random_devices_open(int keep)
568 keep_random_devices_open = keep;
571 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
573 int rand_pool_init(void)
578 void rand_pool_cleanup(void)
582 void rand_pool_keep_random_devices_open(int keep)
586 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
589 * Try the various seeding methods in turn, exit when successful.
591 * TODO(DRBG): If more than one entropy source is available, is it
592 * preferable to stop as soon as enough entropy has been collected
593 * (as favored by @rsalz) or should one rather be defensive and add
594 * more entropy than requested and/or from different sources?
596 * Currently, the user can select multiple entropy sources in the
597 * configure step, yet in practice only the first available source
598 * will be used. A more flexible solution has been requested, but
599 * currently it is not clear how this can be achieved without
600 * overengineering the problem. There are many parameters which
601 * could be taken into account when selecting the order and amount
602 * of input from the different entropy sources (trust, quality,
603 * possibility of blocking).
605 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
607 # if defined(OPENSSL_RAND_SEED_NONE)
608 return rand_pool_entropy_available(pool);
610 size_t entropy_available;
612 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
615 unsigned char *buffer;
617 /* Maximum allowed number of consecutive unsuccessful attempts */
620 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
621 while (bytes_needed != 0 && attempts-- > 0) {
622 buffer = rand_pool_add_begin(pool, bytes_needed);
623 bytes = syscall_random(buffer, bytes_needed);
625 rand_pool_add_end(pool, bytes, 8 * bytes);
626 bytes_needed -= bytes;
627 attempts = 3; /* reset counter after successful attempt */
628 } else if (bytes < 0 && errno != EINTR) {
633 entropy_available = rand_pool_entropy_available(pool);
634 if (entropy_available > 0)
635 return entropy_available;
638 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
640 /* Not yet implemented. */
644 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
645 if (wait_random_seeded()) {
647 unsigned char *buffer;
650 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
651 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
654 /* Maximum number of consecutive unsuccessful attempts */
656 const int fd = get_random_device(i);
661 while (bytes_needed != 0 && attempts-- > 0) {
662 buffer = rand_pool_add_begin(pool, bytes_needed);
663 bytes = read(fd, buffer, bytes_needed);
666 rand_pool_add_end(pool, bytes, 8 * bytes);
667 bytes_needed -= bytes;
668 attempts = 3; /* reset counter on successful attempt */
669 } else if (bytes < 0 && errno != EINTR) {
673 if (bytes < 0 || !keep_random_devices_open)
674 close_random_device(i);
676 bytes_needed = rand_pool_bytes_needed(pool, 1);
678 entropy_available = rand_pool_entropy_available(pool);
679 if (entropy_available > 0)
680 return entropy_available;
684 # if defined(OPENSSL_RAND_SEED_RDTSC)
685 entropy_available = rand_acquire_entropy_from_tsc(pool);
686 if (entropy_available > 0)
687 return entropy_available;
690 # if defined(OPENSSL_RAND_SEED_RDCPU)
691 entropy_available = rand_acquire_entropy_from_cpu(pool);
692 if (entropy_available > 0)
693 return entropy_available;
696 # if defined(OPENSSL_RAND_SEED_EGD)
698 static const char *paths[] = { DEVRANDOM_EGD, NULL };
700 unsigned char *buffer;
703 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
704 for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
708 buffer = rand_pool_add_begin(pool, bytes_needed);
709 num = RAND_query_egd_bytes(paths[i],
710 buffer, (int)bytes_needed);
711 if (num == (int)bytes_needed)
712 bytes = bytes_needed;
714 rand_pool_add_end(pool, bytes, 8 * bytes);
715 bytes_needed = rand_pool_bytes_needed(pool, 1);
717 entropy_available = rand_pool_entropy_available(pool);
718 if (entropy_available > 0)
719 return entropy_available;
723 return rand_pool_entropy_available(pool);
729 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
730 || defined(__DJGPP__)
731 int rand_pool_add_nonce_data(RAND_POOL *pool)
735 CRYPTO_THREAD_ID tid;
739 /* Erase the entire structure including any padding */
740 memset(&data, 0, sizeof(data));
743 * Add process id, thread id, and a high resolution timestamp to
744 * ensure that the nonce is unique with high probability for
745 * different process instances.
748 data.tid = CRYPTO_THREAD_get_current_id();
749 data.time = get_time_stamp();
751 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
754 int rand_pool_add_additional_data(RAND_POOL *pool)
758 CRYPTO_THREAD_ID tid;
762 /* Erase the entire structure including any padding */
763 memset(&data, 0, sizeof(data));
766 * Add some noise from the thread id and a high resolution timer.
767 * The fork_id adds some extra fork-safety.
768 * The thread id adds a little randomness if the drbg is accessed
769 * concurrently (which is the case for the <master> drbg).
771 data.fork_id = openssl_get_fork_id();
772 data.tid = CRYPTO_THREAD_get_current_id();
773 data.time = get_timer_bits();
775 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
780 * Get the current time with the highest possible resolution
782 * The time stamp is added to the nonce, so it is optimized for not repeating.
783 * The current time is ideal for this purpose, provided the computer's clock
786 static uint64_t get_time_stamp(void)
788 # if defined(OSSL_POSIX_TIMER_OKAY)
792 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
793 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
796 # if defined(__unix__) \
797 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
801 if (gettimeofday(&tv, NULL) == 0)
802 return TWO32TO64(tv.tv_sec, tv.tv_usec);
809 * Get an arbitrary timer value of the highest possible resolution
811 * The timer value is added as random noise to the additional data,
812 * which is not considered a trusted entropy sourec, so any result
815 static uint64_t get_timer_bits(void)
817 uint64_t res = OPENSSL_rdtsc();
822 # if defined(__sun) || defined(__hpux)
828 read_wall_time(&t, TIMEBASE_SZ);
829 return TWO32TO64(t.tb_high, t.tb_low);
831 # elif defined(OSSL_POSIX_TIMER_OKAY)
835 # ifdef CLOCK_BOOTTIME
836 # define CLOCK_TYPE CLOCK_BOOTTIME
837 # elif defined(_POSIX_MONOTONIC_CLOCK)
838 # define CLOCK_TYPE CLOCK_MONOTONIC
840 # define CLOCK_TYPE CLOCK_REALTIME
843 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
844 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
847 # if defined(__unix__) \
848 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
852 if (gettimeofday(&tv, NULL) == 0)
853 return TWO32TO64(tv.tv_sec, tv.tv_usec);
858 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
859 || defined(__DJGPP__) */