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(OPENSSL_SYS_VXWORKS))
85 || defined(__DJGPP__) */
87 #if defined(OPENSSL_RAND_SEED_NONE)
88 /* none means none. this simplifies the following logic */
89 # undef OPENSSL_RAND_SEED_OS
90 # undef OPENSSL_RAND_SEED_GETRANDOM
91 # undef OPENSSL_RAND_SEED_LIBRANDOM
92 # undef OPENSSL_RAND_SEED_DEVRANDOM
93 # undef OPENSSL_RAND_SEED_RDTSC
94 # undef OPENSSL_RAND_SEED_RDCPU
95 # undef OPENSSL_RAND_SEED_EGD
98 #if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
99 # error "UEFI only supports seeding NONE"
102 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
103 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
104 || defined(OPENSSL_SYS_UEFI))
106 # if defined(OPENSSL_SYS_VOS)
108 # ifndef OPENSSL_RAND_SEED_OS
109 # error "Unsupported seeding method configured; must be os"
112 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
113 # error "Unsupported HP-PA and IA32 at the same time."
115 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
116 # error "Must have one of HP-PA or IA32"
120 * The following algorithm repeatedly samples the real-time clock (RTC) to
121 * generate a sequence of unpredictable data. The algorithm relies upon the
122 * uneven execution speed of the code (due to factors such as cache misses,
123 * interrupts, bus activity, and scheduling) and upon the rather large
124 * relative difference between the speed of the clock and the rate at which
125 * it can be read. If it is ported to an environment where execution speed
126 * is more constant or where the RTC ticks at a much slower rate, or the
127 * clock can be read with fewer instructions, it is likely that the results
128 * would be far more predictable. This should only be used for legacy
131 * As a precaution, we assume only 2 bits of entropy per byte.
133 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
140 # ifdef OPENSSL_SYS_VOS_HPPA
142 extern void s$sleep(long *_duration, short int *_code);
145 extern void s$sleep2(long long *_duration, short int *_code);
148 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
150 for (i = 0; i < bytes_needed; i++) {
152 * burn some cpu; hope for interrupts, cache collisions, bus
155 for (k = 0; k < 99; k++)
156 ts.tv_nsec = random();
158 # ifdef OPENSSL_SYS_VOS_HPPA
159 /* sleep for 1/1024 of a second (976 us). */
161 s$sleep(&duration, &code);
163 /* sleep for 1/65536 of a second (15 us). */
165 s$sleep2(&duration, &code);
168 /* Get wall clock time, take 8 bits. */
169 clock_gettime(CLOCK_REALTIME, &ts);
170 v = (unsigned char)(ts.tv_nsec & 0xFF);
171 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
173 return rand_pool_entropy_available(pool);
176 void rand_pool_cleanup(void)
180 void rand_pool_keep_random_devices_open(int keep)
186 # if defined(OPENSSL_RAND_SEED_EGD) && \
187 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
188 # error "Seeding uses EGD but EGD is turned off or no device given"
191 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
192 # error "Seeding uses urandom but DEVRANDOM is not configured"
195 # if defined(OPENSSL_RAND_SEED_OS)
196 # if !defined(DEVRANDOM)
197 # error "OS seeding requires DEVRANDOM to be configured"
199 # define OPENSSL_RAND_SEED_GETRANDOM
200 # define OPENSSL_RAND_SEED_DEVRANDOM
203 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
204 # error "librandom not (yet) supported"
207 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
209 * sysctl_random(): Use sysctl() to read a random number from the kernel
210 * Returns the number of bytes returned in buf on success, -1 on failure.
212 static ssize_t sysctl_random(char *buf, size_t buflen)
219 * Note: sign conversion between size_t and ssize_t is safe even
220 * without a range check, see comment in syscall_random()
224 * On FreeBSD old implementations returned longs, newer versions support
225 * variable sizes up to 256 byte. The code below would not work properly
226 * when the sysctl returns long and we want to request something not a
227 * multiple of longs, which should never be the case.
229 if (!ossl_assert(buflen % sizeof(long) == 0)) {
235 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
236 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
237 * it returns a variable number of bytes with the current version supporting
239 * Just return an error on older NetBSD versions.
241 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
251 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
252 return done > 0 ? done : -1;
256 } while (buflen > 0);
262 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
264 # if defined(__linux) && !defined(__NR_getrandom)
265 # if defined(__arm__)
266 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
267 # elif defined(__i386__)
268 # define __NR_getrandom 355
269 # elif defined(__x86_64__)
270 # if defined(__ILP32__)
271 # define __NR_getrandom (__X32_SYSCALL_BIT + 318)
273 # define __NR_getrandom 318
275 # elif defined(__xtensa__)
276 # define __NR_getrandom 338
277 # elif defined(__s390__) || defined(__s390x__)
278 # define __NR_getrandom 349
279 # elif defined(__bfin__)
280 # define __NR_getrandom 389
281 # elif defined(__powerpc__)
282 # define __NR_getrandom 359
283 # elif defined(__mips__) || defined(__mips64)
284 # if _MIPS_SIM == _MIPS_SIM_ABI32
285 # define __NR_getrandom (__NR_Linux + 353)
286 # elif _MIPS_SIM == _MIPS_SIM_ABI64
287 # define __NR_getrandom (__NR_Linux + 313)
288 # elif _MIPS_SIM == _MIPS_SIM_NABI32
289 # define __NR_getrandom (__NR_Linux + 317)
291 # elif defined(__hppa__)
292 # define __NR_getrandom (__NR_Linux + 339)
293 # elif defined(__sparc__)
294 # define __NR_getrandom 347
295 # elif defined(__ia64__)
296 # define __NR_getrandom 1339
297 # elif defined(__alpha__)
298 # define __NR_getrandom 511
299 # elif defined(__sh__)
300 # if defined(__SH5__)
301 # define __NR_getrandom 373
303 # define __NR_getrandom 384
305 # elif defined(__avr32__)
306 # define __NR_getrandom 317
307 # elif defined(__microblaze__)
308 # define __NR_getrandom 385
309 # elif defined(__m68k__)
310 # define __NR_getrandom 352
311 # elif defined(__cris__)
312 # define __NR_getrandom 356
313 # elif defined(__aarch64__)
314 # define __NR_getrandom 278
316 # define __NR_getrandom 278
321 * syscall_random(): Try to get random data using a system call
322 * returns the number of bytes returned in buf, or < 0 on error.
324 static ssize_t syscall_random(void *buf, size_t buflen)
327 * Note: 'buflen' equals the size of the buffer which is used by the
328 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
330 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
332 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
333 * between size_t and ssize_t is safe even without a range check.
337 * Do runtime detection to find getentropy().
339 * Known OSs that should support this:
340 * - Darwin since 16 (OSX 10.12, IOS 10.0).
341 * - Solaris since 11.3
342 * - OpenBSD since 5.6
343 * - Linux since 3.17 with glibc 2.25
344 * - FreeBSD since 12.0 (1200061)
346 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
347 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
349 if (getentropy != NULL)
350 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
351 # elif !defined(FIPS_MODE)
354 int (*f)(void *buffer, size_t length);
358 * We could cache the result of the lookup, but we normally don't
359 * call this function often.
362 p_getentropy.p = DSO_global_lookup("getentropy");
364 if (p_getentropy.p != NULL)
365 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
368 /* Linux supports this since version 3.17 */
369 # if defined(__linux) && defined(__NR_getrandom)
370 return syscall(__NR_getrandom, buf, buflen, 0);
371 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
372 return sysctl_random(buf, buflen);
378 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
380 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
381 static const char *random_device_paths[] = { DEVRANDOM };
382 static struct random_device {
388 } random_devices[OSSL_NELEM(random_device_paths)];
389 static int keep_random_devices_open = 1;
391 # if defined(__linux) && defined(DEVRANDOM_WAIT)
392 static void *shm_addr;
394 # if !defined(FIPS_MODE)
395 static void cleanup_shm(void)
402 * Ensure that the system randomness source has been adequately seeded.
403 * This is done by having the first start of libcrypto, wait until the device
404 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
405 * of the library and later reseedings do not need to do this.
407 static int wait_random_seeded(void)
409 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
410 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
418 /* See if anything has created the global seeded indication */
419 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
421 * Check the kernel's version and fail if it is too recent.
423 * Linux kernels from 4.8 onwards do not guarantee that
424 * /dev/urandom is properly seeded when /dev/random becomes
425 * readable. However, such kernels support the getentropy(2)
426 * system call and this should always succeed which renders
427 * this alternative but essentially identical source moot.
429 if (uname(&un) == 0) {
430 kernel[0] = atoi(un.release);
431 p = strchr(un.release, '.');
432 kernel[1] = p == NULL ? 0 : atoi(p + 1);
433 if (kernel[0] > kernel_version[0]
434 || (kernel[0] == kernel_version[0]
435 && kernel[1] >= kernel_version[1])) {
439 /* Open /dev/random and wait for it to be readable */
440 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
441 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
444 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
447 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
452 /* Create the shared memory indicator */
453 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
454 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
461 * Map the shared memory to prevent its premature destruction.
462 * If this call fails, it isn't a big problem.
464 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
466 /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
467 if (shm_addr != (void *)-1)
468 OPENSSL_atexit(&cleanup_shm);
474 # else /* defined __linux */
475 static int wait_random_seeded(void)
482 * Verify that the file descriptor associated with the random source is
483 * still valid. The rationale for doing this is the fact that it is not
484 * uncommon for daemons to close all open file handles when daemonizing.
485 * So the handle might have been closed or even reused for opening
488 static int check_random_device(struct random_device * rd)
493 && fstat(rd->fd, &st) != -1
494 && rd->dev == st.st_dev
495 && rd->ino == st.st_ino
496 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
497 && rd->rdev == st.st_rdev;
501 * Open a random device if required and return its file descriptor or -1 on error
503 static int get_random_device(size_t n)
506 struct random_device * rd = &random_devices[n];
508 /* reuse existing file descriptor if it is (still) valid */
509 if (check_random_device(rd))
512 /* open the random device ... */
513 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
516 /* ... and cache its relevant stat(2) data */
517 if (fstat(rd->fd, &st) != -1) {
520 rd->mode = st.st_mode;
521 rd->rdev = st.st_rdev;
531 * Close a random device making sure it is a random device
533 static void close_random_device(size_t n)
535 struct random_device * rd = &random_devices[n];
537 if (check_random_device(rd))
542 int rand_pool_init(void)
546 for (i = 0; i < OSSL_NELEM(random_devices); i++)
547 random_devices[i].fd = -1;
552 void rand_pool_cleanup(void)
556 for (i = 0; i < OSSL_NELEM(random_devices); i++)
557 close_random_device(i);
560 void rand_pool_keep_random_devices_open(int keep)
565 keep_random_devices_open = keep;
568 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
570 int rand_pool_init(void)
575 void rand_pool_cleanup(void)
579 void rand_pool_keep_random_devices_open(int keep)
583 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
586 * Try the various seeding methods in turn, exit when successful.
588 * TODO(DRBG): If more than one entropy source is available, is it
589 * preferable to stop as soon as enough entropy has been collected
590 * (as favored by @rsalz) or should one rather be defensive and add
591 * more entropy than requested and/or from different sources?
593 * Currently, the user can select multiple entropy sources in the
594 * configure step, yet in practice only the first available source
595 * will be used. A more flexible solution has been requested, but
596 * currently it is not clear how this can be achieved without
597 * overengineering the problem. There are many parameters which
598 * could be taken into account when selecting the order and amount
599 * of input from the different entropy sources (trust, quality,
600 * possibility of blocking).
602 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
604 # if defined(OPENSSL_RAND_SEED_NONE)
605 return rand_pool_entropy_available(pool);
607 size_t entropy_available;
609 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
612 unsigned char *buffer;
614 /* Maximum allowed number of consecutive unsuccessful attempts */
617 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
618 while (bytes_needed != 0 && attempts-- > 0) {
619 buffer = rand_pool_add_begin(pool, bytes_needed);
620 bytes = syscall_random(buffer, bytes_needed);
622 rand_pool_add_end(pool, bytes, 8 * bytes);
623 bytes_needed -= bytes;
624 attempts = 3; /* reset counter after successful attempt */
625 } else if (bytes < 0 && errno != EINTR) {
630 entropy_available = rand_pool_entropy_available(pool);
631 if (entropy_available > 0)
632 return entropy_available;
635 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
637 /* Not yet implemented. */
641 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
642 if (wait_random_seeded()) {
644 unsigned char *buffer;
647 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
648 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
651 /* Maximum number of consecutive unsuccessful attempts */
653 const int fd = get_random_device(i);
658 while (bytes_needed != 0 && attempts-- > 0) {
659 buffer = rand_pool_add_begin(pool, bytes_needed);
660 bytes = read(fd, buffer, bytes_needed);
663 rand_pool_add_end(pool, bytes, 8 * bytes);
664 bytes_needed -= bytes;
665 attempts = 3; /* reset counter on successful attempt */
666 } else if (bytes < 0 && errno != EINTR) {
670 if (bytes < 0 || !keep_random_devices_open)
671 close_random_device(i);
673 bytes_needed = rand_pool_bytes_needed(pool, 1);
675 entropy_available = rand_pool_entropy_available(pool);
676 if (entropy_available > 0)
677 return entropy_available;
681 # if defined(OPENSSL_RAND_SEED_RDTSC)
682 entropy_available = rand_acquire_entropy_from_tsc(pool);
683 if (entropy_available > 0)
684 return entropy_available;
687 # if defined(OPENSSL_RAND_SEED_RDCPU)
688 entropy_available = rand_acquire_entropy_from_cpu(pool);
689 if (entropy_available > 0)
690 return entropy_available;
693 # if defined(OPENSSL_RAND_SEED_EGD)
695 static const char *paths[] = { DEVRANDOM_EGD, NULL };
697 unsigned char *buffer;
700 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
701 for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
705 buffer = rand_pool_add_begin(pool, bytes_needed);
706 num = RAND_query_egd_bytes(paths[i],
707 buffer, (int)bytes_needed);
708 if (num == (int)bytes_needed)
709 bytes = bytes_needed;
711 rand_pool_add_end(pool, bytes, 8 * bytes);
712 bytes_needed = rand_pool_bytes_needed(pool, 1);
714 entropy_available = rand_pool_entropy_available(pool);
715 if (entropy_available > 0)
716 return entropy_available;
720 return rand_pool_entropy_available(pool);
726 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
727 || defined(__DJGPP__)
728 int rand_pool_add_nonce_data(RAND_POOL *pool)
732 CRYPTO_THREAD_ID tid;
736 /* Erase the entire structure including any padding */
737 memset(&data, 0, sizeof(data));
740 * Add process id, thread id, and a high resolution timestamp to
741 * ensure that the nonce is unique with high probability for
742 * different process instances.
745 data.tid = CRYPTO_THREAD_get_current_id();
746 data.time = get_time_stamp();
748 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
751 int rand_pool_add_additional_data(RAND_POOL *pool)
755 CRYPTO_THREAD_ID tid;
759 /* Erase the entire structure including any padding */
760 memset(&data, 0, sizeof(data));
763 * Add some noise from the thread id and a high resolution timer.
764 * The fork_id adds some extra fork-safety.
765 * The thread id adds a little randomness if the drbg is accessed
766 * concurrently (which is the case for the <master> drbg).
768 data.fork_id = openssl_get_fork_id();
769 data.tid = CRYPTO_THREAD_get_current_id();
770 data.time = get_timer_bits();
772 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
777 * Get the current time with the highest possible resolution
779 * The time stamp is added to the nonce, so it is optimized for not repeating.
780 * The current time is ideal for this purpose, provided the computer's clock
783 static uint64_t get_time_stamp(void)
785 # if defined(OSSL_POSIX_TIMER_OKAY)
789 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
790 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
793 # if defined(__unix__) \
794 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
798 if (gettimeofday(&tv, NULL) == 0)
799 return TWO32TO64(tv.tv_sec, tv.tv_usec);
806 * Get an arbitrary timer value of the highest possible resolution
808 * The timer value is added as random noise to the additional data,
809 * which is not considered a trusted entropy sourec, so any result
812 static uint64_t get_timer_bits(void)
814 uint64_t res = OPENSSL_rdtsc();
819 # if defined(__sun) || defined(__hpux)
825 read_wall_time(&t, TIMEBASE_SZ);
826 return TWO32TO64(t.tb_high, t.tb_low);
828 # elif defined(OSSL_POSIX_TIMER_OKAY)
832 # ifdef CLOCK_BOOTTIME
833 # define CLOCK_TYPE CLOCK_BOOTTIME
834 # elif defined(_POSIX_MONOTONIC_CLOCK)
835 # define CLOCK_TYPE CLOCK_MONOTONIC
837 # define CLOCK_TYPE CLOCK_REALTIME
840 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
841 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
844 # if defined(__unix__) \
845 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
849 if (gettimeofday(&tv, NULL) == 0)
850 return TWO32TO64(tv.tv_sec, tv.tv_usec);
855 #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
856 || defined(__DJGPP__) */