2 * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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>
19 #include "internal/rand_int.h"
21 #include "internal/dso.h"
23 # include <asm/unistd.h>
26 # include <sys/utsname.h>
28 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
29 # include <sys/types.h>
30 # include <sys/sysctl.h>
31 # include <sys/param.h>
33 #if defined(__OpenBSD__) || defined(__NetBSD__)
34 # include <sys/param.h>
37 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
38 # include <sys/types.h>
39 # include <sys/stat.h>
42 # include <sys/time.h>
44 static uint64_t get_time_stamp(void);
45 static uint64_t get_timer_bits(void);
47 /* Macro to convert two thirty two bit values into a sixty four bit one */
48 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
51 * Check for the existence and support of POSIX timers. The standard
52 * says that the _POSIX_TIMERS macro will have a positive value if they
55 * However, we want an additional constraint: that the timer support does
56 * not require an extra library dependency. Early versions of glibc
57 * require -lrt to be specified on the link line to access the timers,
58 * so this needs to be checked for.
60 * It is worse because some libraries define __GLIBC__ but don't
61 * support the version testing macro (e.g. uClibc). This means
62 * an extra check is needed.
64 * The final condition is:
65 * "have posix timers and either not glibc or glibc without -lrt"
67 * The nested #if sequences are required to avoid using a parameterised
68 * macro that might be undefined.
70 # undef OSSL_POSIX_TIMER_OKAY
71 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
72 # if defined(__GLIBC__)
73 # if defined(__GLIBC_PREREQ)
74 # if __GLIBC_PREREQ(2, 17)
75 # define OSSL_POSIX_TIMER_OKAY
79 # define OSSL_POSIX_TIMER_OKAY
82 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
84 #if defined(OPENSSL_RAND_SEED_NONE)
85 /* none means none. this simplifies the following logic */
86 # undef OPENSSL_RAND_SEED_OS
87 # undef OPENSSL_RAND_SEED_GETRANDOM
88 # undef OPENSSL_RAND_SEED_LIBRANDOM
89 # undef OPENSSL_RAND_SEED_DEVRANDOM
90 # undef OPENSSL_RAND_SEED_RDTSC
91 # undef OPENSSL_RAND_SEED_RDCPU
92 # undef OPENSSL_RAND_SEED_EGD
95 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
96 !defined(OPENSSL_RAND_SEED_NONE)
97 # error "UEFI and VXWorks only support seeding NONE"
100 #if defined(OPENSSL_SYS_VXWORKS)
101 /* empty implementation */
102 int rand_pool_init(void)
107 void rand_pool_cleanup(void)
111 void rand_pool_keep_random_devices_open(int keep)
115 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
117 return rand_pool_entropy_available(pool);
121 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
122 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
123 || defined(OPENSSL_SYS_UEFI))
125 # if defined(OPENSSL_SYS_VOS)
127 # ifndef OPENSSL_RAND_SEED_OS
128 # error "Unsupported seeding method configured; must be os"
131 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
132 # error "Unsupported HP-PA and IA32 at the same time."
134 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
135 # error "Must have one of HP-PA or IA32"
139 * The following algorithm repeatedly samples the real-time clock (RTC) to
140 * generate a sequence of unpredictable data. The algorithm relies upon the
141 * uneven execution speed of the code (due to factors such as cache misses,
142 * interrupts, bus activity, and scheduling) and upon the rather large
143 * relative difference between the speed of the clock and the rate at which
144 * it can be read. If it is ported to an environment where execution speed
145 * is more constant or where the RTC ticks at a much slower rate, or the
146 * clock can be read with fewer instructions, it is likely that the results
147 * would be far more predictable. This should only be used for legacy
150 * As a precaution, we assume only 2 bits of entropy per byte.
152 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
159 # ifdef OPENSSL_SYS_VOS_HPPA
161 extern void s$sleep(long *_duration, short int *_code);
164 extern void s$sleep2(long long *_duration, short int *_code);
167 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
169 for (i = 0; i < bytes_needed; i++) {
171 * burn some cpu; hope for interrupts, cache collisions, bus
174 for (k = 0; k < 99; k++)
175 ts.tv_nsec = random();
177 # ifdef OPENSSL_SYS_VOS_HPPA
178 /* sleep for 1/1024 of a second (976 us). */
180 s$sleep(&duration, &code);
182 /* sleep for 1/65536 of a second (15 us). */
184 s$sleep2(&duration, &code);
187 /* Get wall clock time, take 8 bits. */
188 clock_gettime(CLOCK_REALTIME, &ts);
189 v = (unsigned char)(ts.tv_nsec & 0xFF);
190 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
192 return rand_pool_entropy_available(pool);
195 void rand_pool_cleanup(void)
199 void rand_pool_keep_random_devices_open(int keep)
205 # if defined(OPENSSL_RAND_SEED_EGD) && \
206 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
207 # error "Seeding uses EGD but EGD is turned off or no device given"
210 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
211 # error "Seeding uses urandom but DEVRANDOM is not configured"
214 # if defined(OPENSSL_RAND_SEED_OS)
215 # if !defined(DEVRANDOM)
216 # error "OS seeding requires DEVRANDOM to be configured"
218 # define OPENSSL_RAND_SEED_GETRANDOM
219 # define OPENSSL_RAND_SEED_DEVRANDOM
222 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
223 # error "librandom not (yet) supported"
226 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
228 * sysctl_random(): Use sysctl() to read a random number from the kernel
229 * Returns the number of bytes returned in buf on success, -1 on failure.
231 static ssize_t sysctl_random(char *buf, size_t buflen)
238 * Note: sign conversion between size_t and ssize_t is safe even
239 * without a range check, see comment in syscall_random()
243 * On FreeBSD old implementations returned longs, newer versions support
244 * variable sizes up to 256 byte. The code below would not work properly
245 * when the sysctl returns long and we want to request something not a
246 * multiple of longs, which should never be the case.
248 if (!ossl_assert(buflen % sizeof(long) == 0)) {
254 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
255 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
256 * it returns a variable number of bytes with the current version supporting
258 * Just return an error on older NetBSD versions.
260 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
270 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
271 return done > 0 ? done : -1;
275 } while (buflen > 0);
281 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
283 # if defined(__linux) && !defined(__NR_getrandom)
284 # if defined(__arm__) && defined(__NR_SYSCALL_BASE)
285 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
286 # elif defined(__i386__)
287 # define __NR_getrandom 355
288 # elif defined(__x86_64__) && !defined(__ILP32__)
289 # define __NR_getrandom 318
294 * syscall_random(): Try to get random data using a system call
295 * returns the number of bytes returned in buf, or < 0 on error.
297 static ssize_t syscall_random(void *buf, size_t buflen)
300 * Note: 'buflen' equals the size of the buffer which is used by the
301 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
303 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
305 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
306 * between size_t and ssize_t is safe even without a range check.
310 * Do runtime detection to find getentropy().
312 * Known OSs that should support this:
313 * - Darwin since 16 (OSX 10.12, IOS 10.0).
314 * - Solaris since 11.3
315 * - OpenBSD since 5.6
316 * - Linux since 3.17 with glibc 2.25
317 * - FreeBSD since 12.0 (1200061)
319 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
320 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
322 if (getentropy != NULL)
323 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
327 int (*f)(void *buffer, size_t length);
331 * We could cache the result of the lookup, but we normally don't
332 * call this function often.
335 p_getentropy.p = DSO_global_lookup("getentropy");
337 if (p_getentropy.p != NULL)
338 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
341 /* Linux supports this since version 3.17 */
342 # if defined(__linux) && defined(__NR_getrandom)
343 return syscall(__NR_getrandom, buf, buflen, 0);
344 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
345 return sysctl_random(buf, buflen);
351 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
353 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
354 static const char *random_device_paths[] = { DEVRANDOM };
355 static struct random_device {
361 } random_devices[OSSL_NELEM(random_device_paths)];
362 static int keep_random_devices_open = 1;
364 # if defined(__linux) && defined(DEVRANDOM_WAIT)
365 static void *shm_addr;
367 static void cleanup_shm(void)
373 * Ensure that the system randomness source has been adequately seeded.
374 * This is done by having the first start of libcrypto, wait until the device
375 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
376 * of the library and later reseedings do not need to do this.
378 static int wait_random_seeded(void)
380 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
381 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
389 /* See if anything has created the global seeded indication */
390 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
392 * Check the kernel's version and fail if it is too recent.
394 * Linux kernels from 4.8 onwards do not guarantee that
395 * /dev/urandom is properly seeded when /dev/random becomes
396 * readable. However, such kernels support the getentropy(2)
397 * system call and this should always succeed which renders
398 * this alternative but essentially identical source moot.
400 if (uname(&un) == 0) {
401 kernel[0] = atoi(un.release);
402 p = strchr(un.release, '.');
403 kernel[1] = p == NULL ? 0 : atoi(p + 1);
404 if (kernel[0] > kernel_version[0]
405 || (kernel[0] == kernel_version[0]
406 && kernel[1] >= kernel_version[1])) {
410 /* Open /dev/random and wait for it to be readable */
411 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
412 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
415 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
418 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
423 /* Create the shared memory indicator */
424 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
425 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
432 * Map the shared memory to prevent its premature destruction.
433 * If this call fails, it isn't a big problem.
435 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
436 if (shm_addr != (void *)-1)
437 OPENSSL_atexit(&cleanup_shm);
442 # else /* defined __linux */
443 static int wait_random_seeded(void)
450 * Verify that the file descriptor associated with the random source is
451 * still valid. The rationale for doing this is the fact that it is not
452 * uncommon for daemons to close all open file handles when daemonizing.
453 * So the handle might have been closed or even reused for opening
456 static int check_random_device(struct random_device * rd)
461 && fstat(rd->fd, &st) != -1
462 && rd->dev == st.st_dev
463 && rd->ino == st.st_ino
464 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
465 && rd->rdev == st.st_rdev;
469 * Open a random device if required and return its file descriptor or -1 on error
471 static int get_random_device(size_t n)
474 struct random_device * rd = &random_devices[n];
476 /* reuse existing file descriptor if it is (still) valid */
477 if (check_random_device(rd))
480 /* open the random device ... */
481 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
484 /* ... and cache its relevant stat(2) data */
485 if (fstat(rd->fd, &st) != -1) {
488 rd->mode = st.st_mode;
489 rd->rdev = st.st_rdev;
499 * Close a random device making sure it is a random device
501 static void close_random_device(size_t n)
503 struct random_device * rd = &random_devices[n];
505 if (check_random_device(rd))
510 int rand_pool_init(void)
514 for (i = 0; i < OSSL_NELEM(random_devices); i++)
515 random_devices[i].fd = -1;
520 void rand_pool_cleanup(void)
524 for (i = 0; i < OSSL_NELEM(random_devices); i++)
525 close_random_device(i);
528 void rand_pool_keep_random_devices_open(int keep)
533 keep_random_devices_open = keep;
536 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
538 int rand_pool_init(void)
543 void rand_pool_cleanup(void)
547 void rand_pool_keep_random_devices_open(int keep)
551 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
554 * Try the various seeding methods in turn, exit when successful.
556 * TODO(DRBG): If more than one entropy source is available, is it
557 * preferable to stop as soon as enough entropy has been collected
558 * (as favored by @rsalz) or should one rather be defensive and add
559 * more entropy than requested and/or from different sources?
561 * Currently, the user can select multiple entropy sources in the
562 * configure step, yet in practice only the first available source
563 * will be used. A more flexible solution has been requested, but
564 * currently it is not clear how this can be achieved without
565 * overengineering the problem. There are many parameters which
566 * could be taken into account when selecting the order and amount
567 * of input from the different entropy sources (trust, quality,
568 * possibility of blocking).
570 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
572 # if defined(OPENSSL_RAND_SEED_NONE)
573 return rand_pool_entropy_available(pool);
576 size_t entropy_available = 0;
577 unsigned char *buffer;
579 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
582 /* Maximum allowed number of consecutive unsuccessful attempts */
585 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
586 while (bytes_needed != 0 && attempts-- > 0) {
587 buffer = rand_pool_add_begin(pool, bytes_needed);
588 bytes = syscall_random(buffer, bytes_needed);
590 rand_pool_add_end(pool, bytes, 8 * bytes);
591 bytes_needed -= bytes;
592 attempts = 3; /* reset counter after successful attempt */
593 } else if (bytes < 0 && errno != EINTR) {
598 entropy_available = rand_pool_entropy_available(pool);
599 if (entropy_available > 0)
600 return entropy_available;
603 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
605 /* Not yet implemented. */
609 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
610 if (wait_random_seeded()) {
613 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
614 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
617 /* Maximum number of consecutive unsuccessful attempts */
619 const int fd = get_random_device(i);
624 while (bytes_needed != 0 && attempts-- > 0) {
625 buffer = rand_pool_add_begin(pool, bytes_needed);
626 bytes = read(fd, buffer, bytes_needed);
629 rand_pool_add_end(pool, bytes, 8 * bytes);
630 bytes_needed -= bytes;
631 attempts = 3; /* reset counter on successful attempt */
632 } else if (bytes < 0 && errno != EINTR) {
636 if (bytes < 0 || !keep_random_devices_open)
637 close_random_device(i);
639 bytes_needed = rand_pool_bytes_needed(pool, 1);
641 entropy_available = rand_pool_entropy_available(pool);
642 if (entropy_available > 0)
643 return entropy_available;
647 # if defined(OPENSSL_RAND_SEED_RDTSC)
648 entropy_available = rand_acquire_entropy_from_tsc(pool);
649 if (entropy_available > 0)
650 return entropy_available;
653 # if defined(OPENSSL_RAND_SEED_RDCPU)
654 entropy_available = rand_acquire_entropy_from_cpu(pool);
655 if (entropy_available > 0)
656 return entropy_available;
659 # if defined(OPENSSL_RAND_SEED_EGD)
660 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
661 if (bytes_needed > 0) {
662 static const char *paths[] = { DEVRANDOM_EGD, NULL };
665 for (i = 0; paths[i] != NULL; i++) {
666 buffer = rand_pool_add_begin(pool, bytes_needed);
667 if (buffer != NULL) {
669 int num = RAND_query_egd_bytes(paths[i],
670 buffer, (int)bytes_needed);
671 if (num == (int)bytes_needed)
672 bytes = bytes_needed;
674 rand_pool_add_end(pool, bytes, 8 * bytes);
675 entropy_available = rand_pool_entropy_available(pool);
677 if (entropy_available > 0)
678 return entropy_available;
683 return rand_pool_entropy_available(pool);
689 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
690 int rand_pool_add_nonce_data(RAND_POOL *pool)
694 CRYPTO_THREAD_ID tid;
699 * Add process id, thread id, and a high resolution timestamp to
700 * ensure that the nonce is unique with high probability for
701 * different process instances.
704 data.tid = CRYPTO_THREAD_get_current_id();
705 data.time = get_time_stamp();
707 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
710 int rand_pool_add_additional_data(RAND_POOL *pool)
713 CRYPTO_THREAD_ID tid;
718 * Add some noise from the thread id and a high resolution timer.
719 * The thread id adds a little randomness if the drbg is accessed
720 * concurrently (which is the case for the <master> drbg).
722 data.tid = CRYPTO_THREAD_get_current_id();
723 data.time = get_timer_bits();
725 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
730 * Get the current time with the highest possible resolution
732 * The time stamp is added to the nonce, so it is optimized for not repeating.
733 * The current time is ideal for this purpose, provided the computer's clock
736 static uint64_t get_time_stamp(void)
738 # if defined(OSSL_POSIX_TIMER_OKAY)
742 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
743 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
746 # if defined(__unix__) \
747 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
751 if (gettimeofday(&tv, NULL) == 0)
752 return TWO32TO64(tv.tv_sec, tv.tv_usec);
759 * Get an arbitrary timer value of the highest possible resolution
761 * The timer value is added as random noise to the additional data,
762 * which is not considered a trusted entropy sourec, so any result
765 static uint64_t get_timer_bits(void)
767 uint64_t res = OPENSSL_rdtsc();
772 # if defined(__sun) || defined(__hpux)
778 read_wall_time(&t, TIMEBASE_SZ);
779 return TWO32TO64(t.tb_high, t.tb_low);
781 # elif defined(OSSL_POSIX_TIMER_OKAY)
785 # ifdef CLOCK_BOOTTIME
786 # define CLOCK_TYPE CLOCK_BOOTTIME
787 # elif defined(_POSIX_MONOTONIC_CLOCK)
788 # define CLOCK_TYPE CLOCK_MONOTONIC
790 # define CLOCK_TYPE CLOCK_REALTIME
793 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
794 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
797 # if defined(__unix__) \
798 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
802 if (gettimeofday(&tv, NULL) == 0)
803 return TWO32TO64(tv.tv_sec, tv.tv_usec);
808 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */