2 * Copyright 1995-2018 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"
23 # include <sys/syscall.h>
24 # ifdef DEVRANDOM_WAIT
26 # include <sys/utsname.h>
29 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
30 # include <sys/types.h>
31 # include <sys/sysctl.h>
32 # include <sys/param.h>
34 #if defined(__OpenBSD__) || defined(__NetBSD__)
35 # include <sys/param.h>
38 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
40 # include <sys/types.h>
41 # include <sys/stat.h>
44 # include <sys/time.h>
46 static uint64_t get_time_stamp(void);
47 static uint64_t get_timer_bits(void);
49 /* Macro to convert two thirty two bit values into a sixty four bit one */
50 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
53 * Check for the existence and support of POSIX timers. The standard
54 * says that the _POSIX_TIMERS macro will have a positive value if they
57 * However, we want an additional constraint: that the timer support does
58 * not require an extra library dependency. Early versions of glibc
59 * require -lrt to be specified on the link line to access the timers,
60 * so this needs to be checked for.
62 * It is worse because some libraries define __GLIBC__ but don't
63 * support the version testing macro (e.g. uClibc). This means
64 * an extra check is needed.
66 * The final condition is:
67 * "have posix timers and either not glibc or glibc without -lrt"
69 * The nested #if sequences are required to avoid using a parameterised
70 * macro that might be undefined.
72 # undef OSSL_POSIX_TIMER_OKAY
73 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
74 # if defined(__GLIBC__)
75 # if defined(__GLIBC_PREREQ)
76 # if __GLIBC_PREREQ(2, 17)
77 # define OSSL_POSIX_TIMER_OKAY
81 # define OSSL_POSIX_TIMER_OKAY
84 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
86 #if defined(OPENSSL_RAND_SEED_NONE)
87 /* none means none. this simplifies the following logic */
88 # undef OPENSSL_RAND_SEED_OS
89 # undef OPENSSL_RAND_SEED_GETRANDOM
90 # undef OPENSSL_RAND_SEED_LIBRANDOM
91 # undef OPENSSL_RAND_SEED_DEVRANDOM
92 # undef OPENSSL_RAND_SEED_RDTSC
93 # undef OPENSSL_RAND_SEED_RDCPU
94 # undef OPENSSL_RAND_SEED_EGD
97 #if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
98 # error "UEFI only supports seeding NONE"
101 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
102 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
103 || defined(OPENSSL_SYS_UEFI))
105 # if defined(OPENSSL_SYS_VOS)
107 # ifndef OPENSSL_RAND_SEED_OS
108 # error "Unsupported seeding method configured; must be os"
111 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
112 # error "Unsupported HP-PA and IA32 at the same time."
114 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
115 # error "Must have one of HP-PA or IA32"
119 * The following algorithm repeatedly samples the real-time clock (RTC) to
120 * generate a sequence of unpredictable data. The algorithm relies upon the
121 * uneven execution speed of the code (due to factors such as cache misses,
122 * interrupts, bus activity, and scheduling) and upon the rather large
123 * relative difference between the speed of the clock and the rate at which
124 * it can be read. If it is ported to an environment where execution speed
125 * is more constant or where the RTC ticks at a much slower rate, or the
126 * clock can be read with fewer instructions, it is likely that the results
127 * would be far more predictable. This should only be used for legacy
130 * As a precaution, we assume only 2 bits of entropy per byte.
132 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
139 # ifdef OPENSSL_SYS_VOS_HPPA
141 extern void s$sleep(long *_duration, short int *_code);
144 extern void s$sleep2(long long *_duration, short int *_code);
147 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
149 for (i = 0; i < bytes_needed; i++) {
151 * burn some cpu; hope for interrupts, cache collisions, bus
154 for (k = 0; k < 99; k++)
155 ts.tv_nsec = random();
157 # ifdef OPENSSL_SYS_VOS_HPPA
158 /* sleep for 1/1024 of a second (976 us). */
160 s$sleep(&duration, &code);
162 /* sleep for 1/65536 of a second (15 us). */
164 s$sleep2(&duration, &code);
167 /* Get wall clock time, take 8 bits. */
168 clock_gettime(CLOCK_REALTIME, &ts);
169 v = (unsigned char)(ts.tv_nsec & 0xFF);
170 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
172 return rand_pool_entropy_available(pool);
175 void rand_pool_cleanup(void)
179 void rand_pool_keep_random_devices_open(int keep)
185 # if defined(OPENSSL_RAND_SEED_EGD) && \
186 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
187 # error "Seeding uses EGD but EGD is turned off or no device given"
190 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
191 # error "Seeding uses urandom but DEVRANDOM is not configured"
194 # if defined(OPENSSL_RAND_SEED_OS)
195 # if !defined(DEVRANDOM)
196 # error "OS seeding requires DEVRANDOM to be configured"
198 # define OPENSSL_RAND_SEED_GETRANDOM
199 # define OPENSSL_RAND_SEED_DEVRANDOM
202 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
203 # error "librandom not (yet) supported"
206 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
208 * sysctl_random(): Use sysctl() to read a random number from the kernel
209 * Returns the number of bytes returned in buf on success, -1 on failure.
211 static ssize_t sysctl_random(char *buf, size_t buflen)
218 * Note: sign conversion between size_t and ssize_t is safe even
219 * without a range check, see comment in syscall_random()
223 * On FreeBSD old implementations returned longs, newer versions support
224 * variable sizes up to 256 byte. The code below would not work properly
225 * when the sysctl returns long and we want to request something not a
226 * multiple of longs, which should never be the case.
228 if (!ossl_assert(buflen % sizeof(long) == 0)) {
234 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
235 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
236 * it returns a variable number of bytes with the current version supporting
238 * Just return an error on older NetBSD versions.
240 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
250 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
251 return done > 0 ? done : -1;
255 } while (buflen > 0);
261 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
263 # if defined(__linux) && !defined(__NR_getrandom)
264 # if defined(__arm__)
265 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
266 # elif defined(__i386__)
267 # define __NR_getrandom 355
268 # elif defined(__x86_64__)
269 # if defined(__ILP32__)
270 # define __NR_getrandom (__X32_SYSCALL_BIT + 318)
272 # define __NR_getrandom 318
274 # elif defined(__xtensa__)
275 # define __NR_getrandom 338
276 # elif defined(__s390__) || defined(__s390x__)
277 # define __NR_getrandom 349
278 # elif defined(__bfin__)
279 # define __NR_getrandom 389
280 # elif defined(__powerpc__)
281 # define __NR_getrandom 359
282 # elif defined(__mips__) || defined(__mips64)
283 # if _MIPS_SIM == _MIPS_SIM_ABI32
284 # define __NR_getrandom (__NR_Linux + 353)
285 # elif _MIPS_SIM == _MIPS_SIM_ABI64
286 # define __NR_getrandom (__NR_Linux + 313)
287 # elif _MIPS_SIM == _MIPS_SIM_NABI32
288 # define __NR_getrandom (__NR_Linux + 317)
290 # elif defined(__hppa__)
291 # define __NR_getrandom (__NR_Linux + 339)
292 # elif defined(__sparc__)
293 # define __NR_getrandom 347
294 # elif defined(__ia64__)
295 # define __NR_getrandom 1339
296 # elif defined(__alpha__)
297 # define __NR_getrandom 511
298 # elif defined(__sh__)
299 # if defined(__SH5__)
300 # define __NR_getrandom 373
302 # define __NR_getrandom 384
304 # elif defined(__avr32__)
305 # define __NR_getrandom 317
306 # elif defined(__microblaze__)
307 # define __NR_getrandom 385
308 # elif defined(__m68k__)
309 # define __NR_getrandom 352
310 # elif defined(__cris__)
311 # define __NR_getrandom 356
312 # elif defined(__aarch64__)
313 # define __NR_getrandom 278
315 # define __NR_getrandom 278
320 * syscall_random(): Try to get random data using a system call
321 * returns the number of bytes returned in buf, or < 0 on error.
323 static ssize_t syscall_random(void *buf, size_t buflen)
326 * Note: 'buflen' equals the size of the buffer which is used by the
327 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
329 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
331 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
332 * between size_t and ssize_t is safe even without a range check.
336 * Do runtime detection to find getentropy().
338 * Known OSs that should support this:
339 * - Darwin since 16 (OSX 10.12, IOS 10.0).
340 * - Solaris since 11.3
341 * - OpenBSD since 5.6
342 * - Linux since 3.17 with glibc 2.25
343 * - FreeBSD since 12.0 (1200061)
345 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
346 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
348 if (getentropy != NULL)
349 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
350 # elif !defined(FIPS_MODE)
353 int (*f)(void *buffer, size_t length);
357 * We could cache the result of the lookup, but we normally don't
358 * call this function often.
361 p_getentropy.p = DSO_global_lookup("getentropy");
363 if (p_getentropy.p != NULL)
364 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
367 /* Linux supports this since version 3.17 */
368 # if defined(__linux) && defined(__NR_getrandom)
369 return syscall(__NR_getrandom, buf, buflen, 0);
370 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
371 return sysctl_random(buf, buflen);
377 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
379 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
380 static const char *random_device_paths[] = { DEVRANDOM };
381 static struct random_device {
387 } random_devices[OSSL_NELEM(random_device_paths)];
388 static int keep_random_devices_open = 1;
390 # if defined(__linux) && defined(DEVRANDOM_WAIT)
391 static void *shm_addr;
393 # if !defined(FIPS_MODE)
394 static void cleanup_shm(void)
401 * Ensure that the system randomness source has been adequately seeded.
402 * This is done by having the first start of libcrypto, wait until the device
403 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
404 * of the library and later reseedings do not need to do this.
406 static int wait_random_seeded(void)
408 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
409 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
417 /* See if anything has created the global seeded indication */
418 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
420 * Check the kernel's version and fail if it is too recent.
422 * Linux kernels from 4.8 onwards do not guarantee that
423 * /dev/urandom is properly seeded when /dev/random becomes
424 * readable. However, such kernels support the getentropy(2)
425 * system call and this should always succeed which renders
426 * this alternative but essentially identical source moot.
428 if (uname(&un) == 0) {
429 kernel[0] = atoi(un.release);
430 p = strchr(un.release, '.');
431 kernel[1] = p == NULL ? 0 : atoi(p + 1);
432 if (kernel[0] > kernel_version[0]
433 || (kernel[0] == kernel_version[0]
434 && kernel[1] >= kernel_version[1])) {
438 /* Open /dev/random and wait for it to be readable */
439 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
440 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
443 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
446 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
451 /* Create the shared memory indicator */
452 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
453 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
460 * Map the shared memory to prevent its premature destruction.
461 * If this call fails, it isn't a big problem.
463 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
465 /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
466 if (shm_addr != (void *)-1)
467 OPENSSL_atexit(&cleanup_shm);
473 # else /* defined __linux */
474 static int wait_random_seeded(void)
481 * Verify that the file descriptor associated with the random source is
482 * still valid. The rationale for doing this is the fact that it is not
483 * uncommon for daemons to close all open file handles when daemonizing.
484 * So the handle might have been closed or even reused for opening
487 static int check_random_device(struct random_device * rd)
492 && fstat(rd->fd, &st) != -1
493 && rd->dev == st.st_dev
494 && rd->ino == st.st_ino
495 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
496 && rd->rdev == st.st_rdev;
500 * Open a random device if required and return its file descriptor or -1 on error
502 static int get_random_device(size_t n)
505 struct random_device * rd = &random_devices[n];
507 /* reuse existing file descriptor if it is (still) valid */
508 if (check_random_device(rd))
511 /* open the random device ... */
512 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
515 /* ... and cache its relevant stat(2) data */
516 if (fstat(rd->fd, &st) != -1) {
519 rd->mode = st.st_mode;
520 rd->rdev = st.st_rdev;
530 * Close a random device making sure it is a random device
532 static void close_random_device(size_t n)
534 struct random_device * rd = &random_devices[n];
536 if (check_random_device(rd))
541 int rand_pool_init(void)
545 for (i = 0; i < OSSL_NELEM(random_devices); i++)
546 random_devices[i].fd = -1;
551 void rand_pool_cleanup(void)
555 for (i = 0; i < OSSL_NELEM(random_devices); i++)
556 close_random_device(i);
559 void rand_pool_keep_random_devices_open(int keep)
564 keep_random_devices_open = keep;
567 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
569 int rand_pool_init(void)
574 void rand_pool_cleanup(void)
578 void rand_pool_keep_random_devices_open(int keep)
582 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
585 * Try the various seeding methods in turn, exit when successful.
587 * TODO(DRBG): If more than one entropy source is available, is it
588 * preferable to stop as soon as enough entropy has been collected
589 * (as favored by @rsalz) or should one rather be defensive and add
590 * more entropy than requested and/or from different sources?
592 * Currently, the user can select multiple entropy sources in the
593 * configure step, yet in practice only the first available source
594 * will be used. A more flexible solution has been requested, but
595 * currently it is not clear how this can be achieved without
596 * overengineering the problem. There are many parameters which
597 * could be taken into account when selecting the order and amount
598 * of input from the different entropy sources (trust, quality,
599 * possibility of blocking).
601 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
603 # if defined(OPENSSL_RAND_SEED_NONE)
604 return rand_pool_entropy_available(pool);
606 size_t entropy_available;
608 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
611 unsigned char *buffer;
613 /* Maximum allowed number of consecutive unsuccessful attempts */
616 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
617 while (bytes_needed != 0 && attempts-- > 0) {
618 buffer = rand_pool_add_begin(pool, bytes_needed);
619 bytes = syscall_random(buffer, bytes_needed);
621 rand_pool_add_end(pool, bytes, 8 * bytes);
622 bytes_needed -= bytes;
623 attempts = 3; /* reset counter after successful attempt */
624 } else if (bytes < 0 && errno != EINTR) {
629 entropy_available = rand_pool_entropy_available(pool);
630 if (entropy_available > 0)
631 return entropy_available;
634 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
636 /* Not yet implemented. */
640 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
641 if (wait_random_seeded()) {
643 unsigned char *buffer;
646 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
647 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
650 /* Maximum number of consecutive unsuccessful attempts */
652 const int fd = get_random_device(i);
657 while (bytes_needed != 0 && attempts-- > 0) {
658 buffer = rand_pool_add_begin(pool, bytes_needed);
659 bytes = read(fd, buffer, bytes_needed);
662 rand_pool_add_end(pool, bytes, 8 * bytes);
663 bytes_needed -= bytes;
664 attempts = 3; /* reset counter on successful attempt */
665 } else if (bytes < 0 && errno != EINTR) {
669 if (bytes < 0 || !keep_random_devices_open)
670 close_random_device(i);
672 bytes_needed = rand_pool_bytes_needed(pool, 1);
674 entropy_available = rand_pool_entropy_available(pool);
675 if (entropy_available > 0)
676 return entropy_available;
680 # if defined(OPENSSL_RAND_SEED_RDTSC)
681 entropy_available = rand_acquire_entropy_from_tsc(pool);
682 if (entropy_available > 0)
683 return entropy_available;
686 # if defined(OPENSSL_RAND_SEED_RDCPU)
687 entropy_available = rand_acquire_entropy_from_cpu(pool);
688 if (entropy_available > 0)
689 return entropy_available;
692 # if defined(OPENSSL_RAND_SEED_EGD)
694 static const char *paths[] = { DEVRANDOM_EGD, NULL };
696 unsigned char *buffer;
699 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
700 for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
704 buffer = rand_pool_add_begin(pool, bytes_needed);
705 num = RAND_query_egd_bytes(paths[i],
706 buffer, (int)bytes_needed);
707 if (num == (int)bytes_needed)
708 bytes = bytes_needed;
710 rand_pool_add_end(pool, bytes, 8 * bytes);
711 bytes_needed = rand_pool_bytes_needed(pool, 1);
713 entropy_available = rand_pool_entropy_available(pool);
714 if (entropy_available > 0)
715 return entropy_available;
719 return rand_pool_entropy_available(pool);
725 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
726 || defined(__DJGPP__)
727 int rand_pool_add_nonce_data(RAND_POOL *pool)
731 CRYPTO_THREAD_ID tid;
735 /* Erase the entire structure including any padding */
736 memset(&data, 0, sizeof(data));
739 * Add process id, thread id, and a high resolution timestamp to
740 * ensure that the nonce is unique with high probability for
741 * different process instances.
744 data.tid = CRYPTO_THREAD_get_current_id();
745 data.time = get_time_stamp();
747 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
750 int rand_pool_add_additional_data(RAND_POOL *pool)
754 CRYPTO_THREAD_ID tid;
758 /* Erase the entire structure including any padding */
759 memset(&data, 0, sizeof(data));
762 * Add some noise from the thread id and a high resolution timer.
763 * The fork_id adds some extra fork-safety.
764 * The thread id adds a little randomness if the drbg is accessed
765 * concurrently (which is the case for the <master> drbg).
767 data.fork_id = openssl_get_fork_id();
768 data.tid = CRYPTO_THREAD_get_current_id();
769 data.time = get_timer_bits();
771 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
776 * Get the current time with the highest possible resolution
778 * The time stamp is added to the nonce, so it is optimized for not repeating.
779 * The current time is ideal for this purpose, provided the computer's clock
782 static uint64_t get_time_stamp(void)
784 # if defined(OSSL_POSIX_TIMER_OKAY)
788 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
789 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
792 # if defined(__unix__) \
793 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
797 if (gettimeofday(&tv, NULL) == 0)
798 return TWO32TO64(tv.tv_sec, tv.tv_usec);
805 * Get an arbitrary timer value of the highest possible resolution
807 * The timer value is added as random noise to the additional data,
808 * which is not considered a trusted entropy sourec, so any result
811 static uint64_t get_timer_bits(void)
813 uint64_t res = OPENSSL_rdtsc();
818 # if defined(__sun) || defined(__hpux)
824 read_wall_time(&t, TIMEBASE_SZ);
825 return TWO32TO64(t.tb_high, t.tb_low);
827 # elif defined(OSSL_POSIX_TIMER_OKAY)
831 # ifdef CLOCK_BOOTTIME
832 # define CLOCK_TYPE CLOCK_BOOTTIME
833 # elif defined(_POSIX_MONOTONIC_CLOCK)
834 # define CLOCK_TYPE CLOCK_MONOTONIC
836 # define CLOCK_TYPE CLOCK_REALTIME
839 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
840 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
843 # if defined(__unix__) \
844 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
848 if (gettimeofday(&tv, NULL) == 0)
849 return TWO32TO64(tv.tv_sec, tv.tv_usec);
854 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */