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 <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(__DJGPP__)
39 # include <sys/types.h>
40 # include <sys/stat.h>
43 # include <sys/time.h>
45 static uint64_t get_time_stamp(void);
46 static uint64_t get_timer_bits(void);
48 /* Macro to convert two thirty two bit values into a sixty four bit one */
49 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
52 * Check for the existence and support of POSIX timers. The standard
53 * says that the _POSIX_TIMERS macro will have a positive value if they
56 * However, we want an additional constraint: that the timer support does
57 * not require an extra library dependency. Early versions of glibc
58 * require -lrt to be specified on the link line to access the timers,
59 * so this needs to be checked for.
61 * It is worse because some libraries define __GLIBC__ but don't
62 * support the version testing macro (e.g. uClibc). This means
63 * an extra check is needed.
65 * The final condition is:
66 * "have posix timers and either not glibc or glibc without -lrt"
68 * The nested #if sequences are required to avoid using a parameterised
69 * macro that might be undefined.
71 # undef OSSL_POSIX_TIMER_OKAY
72 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
73 # if defined(__GLIBC__)
74 # if defined(__GLIBC_PREREQ)
75 # if __GLIBC_PREREQ(2, 17)
76 # define OSSL_POSIX_TIMER_OKAY
80 # define OSSL_POSIX_TIMER_OKAY
83 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
85 #if defined(OPENSSL_RAND_SEED_NONE)
86 /* none means none. this simplifies the following logic */
87 # undef OPENSSL_RAND_SEED_OS
88 # undef OPENSSL_RAND_SEED_GETRANDOM
89 # undef OPENSSL_RAND_SEED_LIBRANDOM
90 # undef OPENSSL_RAND_SEED_DEVRANDOM
91 # undef OPENSSL_RAND_SEED_RDTSC
92 # undef OPENSSL_RAND_SEED_RDCPU
93 # undef OPENSSL_RAND_SEED_EGD
96 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
97 !defined(OPENSSL_RAND_SEED_NONE)
98 # error "UEFI and VXWorks only support seeding NONE"
101 #if defined(OPENSSL_SYS_VXWORKS)
102 /* empty implementation */
103 int rand_pool_init(void)
108 void rand_pool_cleanup(void)
112 void rand_pool_keep_random_devices_open(int keep)
116 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
118 return rand_pool_entropy_available(pool);
122 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
123 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
124 || defined(OPENSSL_SYS_UEFI))
126 # if defined(OPENSSL_SYS_VOS)
128 # ifndef OPENSSL_RAND_SEED_OS
129 # error "Unsupported seeding method configured; must be os"
132 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
133 # error "Unsupported HP-PA and IA32 at the same time."
135 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
136 # error "Must have one of HP-PA or IA32"
140 * The following algorithm repeatedly samples the real-time clock (RTC) to
141 * generate a sequence of unpredictable data. The algorithm relies upon the
142 * uneven execution speed of the code (due to factors such as cache misses,
143 * interrupts, bus activity, and scheduling) and upon the rather large
144 * relative difference between the speed of the clock and the rate at which
145 * it can be read. If it is ported to an environment where execution speed
146 * is more constant or where the RTC ticks at a much slower rate, or the
147 * clock can be read with fewer instructions, it is likely that the results
148 * would be far more predictable. This should only be used for legacy
151 * As a precaution, we assume only 2 bits of entropy per byte.
153 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
160 # ifdef OPENSSL_SYS_VOS_HPPA
162 extern void s$sleep(long *_duration, short int *_code);
165 extern void s$sleep2(long long *_duration, short int *_code);
168 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
170 for (i = 0; i < bytes_needed; i++) {
172 * burn some cpu; hope for interrupts, cache collisions, bus
175 for (k = 0; k < 99; k++)
176 ts.tv_nsec = random();
178 # ifdef OPENSSL_SYS_VOS_HPPA
179 /* sleep for 1/1024 of a second (976 us). */
181 s$sleep(&duration, &code);
183 /* sleep for 1/65536 of a second (15 us). */
185 s$sleep2(&duration, &code);
188 /* Get wall clock time, take 8 bits. */
189 clock_gettime(CLOCK_REALTIME, &ts);
190 v = (unsigned char)(ts.tv_nsec & 0xFF);
191 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
193 return rand_pool_entropy_available(pool);
196 void rand_pool_cleanup(void)
200 void rand_pool_keep_random_devices_open(int keep)
206 # if defined(OPENSSL_RAND_SEED_EGD) && \
207 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
208 # error "Seeding uses EGD but EGD is turned off or no device given"
211 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
212 # error "Seeding uses urandom but DEVRANDOM is not configured"
215 # if defined(OPENSSL_RAND_SEED_OS)
216 # if !defined(DEVRANDOM)
217 # error "OS seeding requires DEVRANDOM to be configured"
219 # define OPENSSL_RAND_SEED_GETRANDOM
220 # define OPENSSL_RAND_SEED_DEVRANDOM
223 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
224 # error "librandom not (yet) supported"
227 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
229 * sysctl_random(): Use sysctl() to read a random number from the kernel
230 * Returns the number of bytes returned in buf on success, -1 on failure.
232 static ssize_t sysctl_random(char *buf, size_t buflen)
239 * Note: sign conversion between size_t and ssize_t is safe even
240 * without a range check, see comment in syscall_random()
244 * On FreeBSD old implementations returned longs, newer versions support
245 * variable sizes up to 256 byte. The code below would not work properly
246 * when the sysctl returns long and we want to request something not a
247 * multiple of longs, which should never be the case.
249 if (!ossl_assert(buflen % sizeof(long) == 0)) {
255 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
256 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
257 * it returns a variable number of bytes with the current version supporting
259 * Just return an error on older NetBSD versions.
261 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
271 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
272 return done > 0 ? done : -1;
276 } while (buflen > 0);
282 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
284 # if defined(__linux) && !defined(__NR_getrandom)
285 # if defined(__arm__) && defined(__NR_SYSCALL_BASE)
286 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
287 # elif defined(__i386__)
288 # define __NR_getrandom 355
289 # elif defined(__x86_64__) && !defined(__ILP32__)
290 # define __NR_getrandom 318
295 * syscall_random(): Try to get random data using a system call
296 * returns the number of bytes returned in buf, or < 0 on error.
298 static ssize_t syscall_random(void *buf, size_t buflen)
301 * Note: 'buflen' equals the size of the buffer which is used by the
302 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
304 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
306 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
307 * between size_t and ssize_t is safe even without a range check.
311 * Do runtime detection to find getentropy().
313 * Known OSs that should support this:
314 * - Darwin since 16 (OSX 10.12, IOS 10.0).
315 * - Solaris since 11.3
316 * - OpenBSD since 5.6
317 * - Linux since 3.17 with glibc 2.25
318 * - FreeBSD since 12.0 (1200061)
320 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
321 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
323 if (getentropy != NULL)
324 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
328 int (*f)(void *buffer, size_t length);
332 * We could cache the result of the lookup, but we normally don't
333 * call this function often.
336 p_getentropy.p = DSO_global_lookup("getentropy");
338 if (p_getentropy.p != NULL)
339 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
342 /* Linux supports this since version 3.17 */
343 # if defined(__linux) && defined(__NR_getrandom)
344 return syscall(__NR_getrandom, buf, buflen, 0);
345 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
346 return sysctl_random(buf, buflen);
352 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
354 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
355 static const char *random_device_paths[] = { DEVRANDOM };
356 static struct random_device {
362 } random_devices[OSSL_NELEM(random_device_paths)];
363 static int keep_random_devices_open = 1;
365 # if defined(__linux) && defined(DEVRANDOM_WAIT)
366 static void *shm_addr;
368 static void cleanup_shm(void)
374 * Ensure that the system randomness source has been adequately seeded.
375 * This is done by having the first start of libcrypto, wait until the device
376 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
377 * of the library and later reseedings do not need to do this.
379 static int wait_random_seeded(void)
381 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
382 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
390 /* See if anything has created the global seeded indication */
391 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
393 * Check the kernel's version and fail if it is too recent.
395 * Linux kernels from 4.8 onwards do not guarantee that
396 * /dev/urandom is properly seeded when /dev/random becomes
397 * readable. However, such kernels support the getentropy(2)
398 * system call and this should always succeed which renders
399 * this alternative but essentially identical source moot.
401 if (uname(&un) == 0) {
402 kernel[0] = atoi(un.release);
403 p = strchr(un.release, '.');
404 kernel[1] = p == NULL ? 0 : atoi(p + 1);
405 if (kernel[0] > kernel_version[0]
406 || (kernel[0] == kernel_version[0]
407 && kernel[1] >= kernel_version[1])) {
411 /* Open /dev/random and wait for it to be readable */
412 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
413 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
416 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
419 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
424 /* Create the shared memory indicator */
425 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
426 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
433 * Map the shared memory to prevent its premature destruction.
434 * If this call fails, it isn't a big problem.
436 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
437 if (shm_addr != (void *)-1)
438 OPENSSL_atexit(&cleanup_shm);
443 # else /* defined __linux */
444 static int wait_random_seeded(void)
451 * Verify that the file descriptor associated with the random source is
452 * still valid. The rationale for doing this is the fact that it is not
453 * uncommon for daemons to close all open file handles when daemonizing.
454 * So the handle might have been closed or even reused for opening
457 static int check_random_device(struct random_device * rd)
462 && fstat(rd->fd, &st) != -1
463 && rd->dev == st.st_dev
464 && rd->ino == st.st_ino
465 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
466 && rd->rdev == st.st_rdev;
470 * Open a random device if required and return its file descriptor or -1 on error
472 static int get_random_device(size_t n)
475 struct random_device * rd = &random_devices[n];
477 /* reuse existing file descriptor if it is (still) valid */
478 if (check_random_device(rd))
481 /* open the random device ... */
482 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
485 /* ... and cache its relevant stat(2) data */
486 if (fstat(rd->fd, &st) != -1) {
489 rd->mode = st.st_mode;
490 rd->rdev = st.st_rdev;
500 * Close a random device making sure it is a random device
502 static void close_random_device(size_t n)
504 struct random_device * rd = &random_devices[n];
506 if (check_random_device(rd))
511 int rand_pool_init(void)
515 for (i = 0; i < OSSL_NELEM(random_devices); i++)
516 random_devices[i].fd = -1;
521 void rand_pool_cleanup(void)
525 for (i = 0; i < OSSL_NELEM(random_devices); i++)
526 close_random_device(i);
529 void rand_pool_keep_random_devices_open(int keep)
534 keep_random_devices_open = keep;
537 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
539 int rand_pool_init(void)
544 void rand_pool_cleanup(void)
548 void rand_pool_keep_random_devices_open(int keep)
552 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
555 * Try the various seeding methods in turn, exit when successful.
557 * TODO(DRBG): If more than one entropy source is available, is it
558 * preferable to stop as soon as enough entropy has been collected
559 * (as favored by @rsalz) or should one rather be defensive and add
560 * more entropy than requested and/or from different sources?
562 * Currently, the user can select multiple entropy sources in the
563 * configure step, yet in practice only the first available source
564 * will be used. A more flexible solution has been requested, but
565 * currently it is not clear how this can be achieved without
566 * overengineering the problem. There are many parameters which
567 * could be taken into account when selecting the order and amount
568 * of input from the different entropy sources (trust, quality,
569 * possibility of blocking).
571 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
573 # if defined(OPENSSL_RAND_SEED_NONE)
574 return rand_pool_entropy_available(pool);
576 size_t entropy_available;
578 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
581 unsigned char *buffer;
583 /* Maximum allowed number of consecutive unsuccessful attempts */
586 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
587 while (bytes_needed != 0 && attempts-- > 0) {
588 buffer = rand_pool_add_begin(pool, bytes_needed);
589 bytes = syscall_random(buffer, bytes_needed);
591 rand_pool_add_end(pool, bytes, 8 * bytes);
592 bytes_needed -= bytes;
593 attempts = 3; /* reset counter after successful attempt */
594 } else if (bytes < 0 && errno != EINTR) {
599 entropy_available = rand_pool_entropy_available(pool);
600 if (entropy_available > 0)
601 return entropy_available;
604 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
606 /* Not yet implemented. */
610 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
611 if (wait_random_seeded()) {
613 unsigned char *buffer;
616 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
617 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
620 /* Maximum number of consecutive unsuccessful attempts */
622 const int fd = get_random_device(i);
627 while (bytes_needed != 0 && attempts-- > 0) {
628 buffer = rand_pool_add_begin(pool, bytes_needed);
629 bytes = read(fd, buffer, bytes_needed);
632 rand_pool_add_end(pool, bytes, 8 * bytes);
633 bytes_needed -= bytes;
634 attempts = 3; /* reset counter on successful attempt */
635 } else if (bytes < 0 && errno != EINTR) {
639 if (bytes < 0 || !keep_random_devices_open)
640 close_random_device(i);
642 bytes_needed = rand_pool_bytes_needed(pool, 1);
644 entropy_available = rand_pool_entropy_available(pool);
645 if (entropy_available > 0)
646 return entropy_available;
650 # if defined(OPENSSL_RAND_SEED_RDTSC)
651 entropy_available = rand_acquire_entropy_from_tsc(pool);
652 if (entropy_available > 0)
653 return entropy_available;
656 # if defined(OPENSSL_RAND_SEED_RDCPU)
657 entropy_available = rand_acquire_entropy_from_cpu(pool);
658 if (entropy_available > 0)
659 return entropy_available;
662 # if defined(OPENSSL_RAND_SEED_EGD)
664 static const char *paths[] = { DEVRANDOM_EGD, NULL };
666 unsigned char *buffer;
669 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
670 for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
674 buffer = rand_pool_add_begin(pool, bytes_needed);
675 num = RAND_query_egd_bytes(paths[i],
676 buffer, (int)bytes_needed);
677 if (num == (int)bytes_needed)
678 bytes = bytes_needed;
680 rand_pool_add_end(pool, bytes, 8 * bytes);
681 bytes_needed = rand_pool_bytes_needed(pool, 1);
683 entropy_available = rand_pool_entropy_available(pool);
684 if (entropy_available > 0)
685 return entropy_available;
689 return rand_pool_entropy_available(pool);
695 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
696 int rand_pool_add_nonce_data(RAND_POOL *pool)
700 CRYPTO_THREAD_ID tid;
705 * Add process id, thread id, and a high resolution timestamp to
706 * ensure that the nonce is unique with high probability for
707 * different process instances.
710 data.tid = CRYPTO_THREAD_get_current_id();
711 data.time = get_time_stamp();
713 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
716 int rand_pool_add_additional_data(RAND_POOL *pool)
720 CRYPTO_THREAD_ID tid;
725 * Add some noise from the thread id and a high resolution timer.
726 * The fork_id adds some extra fork-safety.
727 * The thread id adds a little randomness if the drbg is accessed
728 * concurrently (which is the case for the <master> drbg).
730 data.fork_id = openssl_get_fork_id();
731 data.tid = CRYPTO_THREAD_get_current_id();
732 data.time = get_timer_bits();
734 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
739 * Get the current time with the highest possible resolution
741 * The time stamp is added to the nonce, so it is optimized for not repeating.
742 * The current time is ideal for this purpose, provided the computer's clock
745 static uint64_t get_time_stamp(void)
747 # if defined(OSSL_POSIX_TIMER_OKAY)
751 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
752 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
755 # if defined(__unix__) \
756 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
760 if (gettimeofday(&tv, NULL) == 0)
761 return TWO32TO64(tv.tv_sec, tv.tv_usec);
768 * Get an arbitrary timer value of the highest possible resolution
770 * The timer value is added as random noise to the additional data,
771 * which is not considered a trusted entropy sourec, so any result
774 static uint64_t get_timer_bits(void)
776 uint64_t res = OPENSSL_rdtsc();
781 # if defined(__sun) || defined(__hpux)
787 read_wall_time(&t, TIMEBASE_SZ);
788 return TWO32TO64(t.tb_high, t.tb_low);
790 # elif defined(OSSL_POSIX_TIMER_OKAY)
794 # ifdef CLOCK_BOOTTIME
795 # define CLOCK_TYPE CLOCK_BOOTTIME
796 # elif defined(_POSIX_MONOTONIC_CLOCK)
797 # define CLOCK_TYPE CLOCK_MONOTONIC
799 # define CLOCK_TYPE CLOCK_REALTIME
802 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
803 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
806 # if defined(__unix__) \
807 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
811 if (gettimeofday(&tv, NULL) == 0)
812 return TWO32TO64(tv.tv_sec, tv.tv_usec);
817 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */