2 * Copyright 1995-2018 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>
18 #include "internal/rand_int.h"
20 #include "internal/dso.h"
22 # include <sys/syscall.h>
24 #if defined(__FreeBSD__)
25 # include <sys/types.h>
26 # include <sys/sysctl.h>
27 # include <sys/param.h>
29 #if defined(__OpenBSD__) || defined(__NetBSD__)
30 # include <sys/param.h>
33 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
34 # include <sys/types.h>
35 # include <sys/stat.h>
38 # include <sys/time.h>
40 static uint64_t get_time_stamp(void);
41 static uint64_t get_timer_bits(void);
43 /* Macro to convert two thirty two bit values into a sixty four bit one */
44 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
47 * Check for the existence and support of POSIX timers. The standard
48 * says that the _POSIX_TIMERS macro will have a positive value if they
51 * However, we want an additional constraint: that the timer support does
52 * not require an extra library dependency. Early versions of glibc
53 * require -lrt to be specified on the link line to access the timers,
54 * so this needs to be checked for.
56 * It is worse because some libraries define __GLIBC__ but don't
57 * support the version testing macro (e.g. uClibc). This means
58 * an extra check is needed.
60 * The final condition is:
61 * "have posix timers and either not glibc or glibc without -lrt"
63 * The nested #if sequences are required to avoid using a parameterised
64 * macro that might be undefined.
66 # undef OSSL_POSIX_TIMER_OKAY
67 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
68 # if defined(__GLIBC__)
69 # if defined(__GLIBC_PREREQ)
70 # if __GLIBC_PREREQ(2, 17)
71 # define OSSL_POSIX_TIMER_OKAY
75 # define OSSL_POSIX_TIMER_OKAY
78 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
80 #if defined(OPENSSL_RAND_SEED_NONE)
81 /* none means none. this simplifies the following logic */
82 # undef OPENSSL_RAND_SEED_OS
83 # undef OPENSSL_RAND_SEED_GETRANDOM
84 # undef OPENSSL_RAND_SEED_LIBRANDOM
85 # undef OPENSSL_RAND_SEED_DEVRANDOM
86 # undef OPENSSL_RAND_SEED_RDTSC
87 # undef OPENSSL_RAND_SEED_RDCPU
88 # undef OPENSSL_RAND_SEED_EGD
91 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
92 !defined(OPENSSL_RAND_SEED_NONE)
93 # error "UEFI and VXWorks only support seeding NONE"
96 #if defined(OPENSSL_SYS_VXWORKS)
97 /* empty implementation */
98 int rand_pool_init(void)
103 void rand_pool_cleanup(void)
107 void rand_pool_keep_random_devices_open(int keep)
111 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
113 return rand_pool_entropy_available(pool);
117 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
118 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
119 || defined(OPENSSL_SYS_UEFI))
121 # if defined(OPENSSL_SYS_VOS)
123 # ifndef OPENSSL_RAND_SEED_OS
124 # error "Unsupported seeding method configured; must be os"
127 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
128 # error "Unsupported HP-PA and IA32 at the same time."
130 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
131 # error "Must have one of HP-PA or IA32"
135 * The following algorithm repeatedly samples the real-time clock (RTC) to
136 * generate a sequence of unpredictable data. The algorithm relies upon the
137 * uneven execution speed of the code (due to factors such as cache misses,
138 * interrupts, bus activity, and scheduling) and upon the rather large
139 * relative difference between the speed of the clock and the rate at which
140 * it can be read. If it is ported to an environment where execution speed
141 * is more constant or where the RTC ticks at a much slower rate, or the
142 * clock can be read with fewer instructions, it is likely that the results
143 * would be far more predictable. This should only be used for legacy
146 * As a precaution, we assume only 2 bits of entropy per byte.
148 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
155 # ifdef OPENSSL_SYS_VOS_HPPA
157 extern void s$sleep(long *_duration, short int *_code);
160 extern void s$sleep2(long long *_duration, short int *_code);
163 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
165 for (i = 0; i < bytes_needed; i++) {
167 * burn some cpu; hope for interrupts, cache collisions, bus
170 for (k = 0; k < 99; k++)
171 ts.tv_nsec = random();
173 # ifdef OPENSSL_SYS_VOS_HPPA
174 /* sleep for 1/1024 of a second (976 us). */
176 s$sleep(&duration, &code);
178 /* sleep for 1/65536 of a second (15 us). */
180 s$sleep2(&duration, &code);
183 /* Get wall clock time, take 8 bits. */
184 clock_gettime(CLOCK_REALTIME, &ts);
185 v = (unsigned char)(ts.tv_nsec & 0xFF);
186 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
188 return rand_pool_entropy_available(pool);
191 void rand_pool_cleanup(void)
195 void rand_pool_keep_random_devices_open(int keep)
201 # if defined(OPENSSL_RAND_SEED_EGD) && \
202 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
203 # error "Seeding uses EGD but EGD is turned off or no device given"
206 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
207 # error "Seeding uses urandom but DEVRANDOM is not configured"
210 # if defined(OPENSSL_RAND_SEED_OS)
211 # if !defined(DEVRANDOM)
212 # error "OS seeding requires DEVRANDOM to be configured"
214 # define OPENSSL_RAND_SEED_GETRANDOM
215 # define OPENSSL_RAND_SEED_DEVRANDOM
218 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
219 # error "librandom not (yet) supported"
222 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
224 * sysctl_random(): Use sysctl() to read a random number from the kernel
225 * Returns the number of bytes returned in buf on success, -1 on failure.
227 static ssize_t sysctl_random(char *buf, size_t buflen)
234 * Note: sign conversion between size_t and ssize_t is safe even
235 * without a range check, see comment in syscall_random()
239 * On FreeBSD old implementations returned longs, newer versions support
240 * variable sizes up to 256 byte. The code below would not work properly
241 * when the sysctl returns long and we want to request something not a
242 * multiple of longs, which should never be the case.
244 if (!ossl_assert(buflen % sizeof(long) == 0)) {
250 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
251 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
252 * it returns a variable number of bytes with the current version supporting
254 * Just return an error on older NetBSD versions.
256 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
266 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
267 return done > 0 ? done : -1;
271 } while (buflen > 0);
277 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
279 * syscall_random(): Try to get random data using a system call
280 * returns the number of bytes returned in buf, or < 0 on error.
282 static ssize_t syscall_random(void *buf, size_t buflen)
285 * Note: 'buflen' equals the size of the buffer which is used by the
286 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
288 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
290 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
291 * between size_t and ssize_t is safe even without a range check.
295 * Do runtime detection to find getentropy().
297 * Known OSs that should support this:
298 * - Darwin since 16 (OSX 10.12, IOS 10.0).
299 * - Solaris since 11.3
300 * - OpenBSD since 5.6
301 * - Linux since 3.17 with glibc 2.25
302 * - FreeBSD since 12.0 (1200061)
304 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
305 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
307 if (getentropy != NULL)
308 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
312 int (*f)(void *buffer, size_t length);
316 * We could cache the result of the lookup, but we normally don't
317 * call this function often.
320 p_getentropy.p = DSO_global_lookup("getentropy");
322 if (p_getentropy.p != NULL)
323 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
326 /* Linux supports this since version 3.17 */
327 # if defined(__linux) && defined(SYS_getrandom)
328 return syscall(SYS_getrandom, buf, buflen, 0);
329 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
330 return sysctl_random(buf, buflen);
336 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
338 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
339 static const char *random_device_paths[] = { DEVRANDOM };
340 static struct random_device {
346 } random_devices[OSSL_NELEM(random_device_paths)];
347 static int keep_random_devices_open = 1;
350 * Verify that the file descriptor associated with the random source is
351 * still valid. The rationale for doing this is the fact that it is not
352 * uncommon for daemons to close all open file handles when daemonizing.
353 * So the handle might have been closed or even reused for opening
356 static int check_random_device(struct random_device * rd)
361 && fstat(rd->fd, &st) != -1
362 && rd->dev == st.st_dev
363 && rd->ino == st.st_ino
364 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
365 && rd->rdev == st.st_rdev;
369 * Open a random device if required and return its file descriptor or -1 on error
371 static int get_random_device(size_t n)
374 struct random_device * rd = &random_devices[n];
376 /* reuse existing file descriptor if it is (still) valid */
377 if (check_random_device(rd))
380 /* open the random device ... */
381 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
384 /* ... and cache its relevant stat(2) data */
385 if (fstat(rd->fd, &st) != -1) {
388 rd->mode = st.st_mode;
389 rd->rdev = st.st_rdev;
399 * Close a random device making sure it is a random device
401 static void close_random_device(size_t n)
403 struct random_device * rd = &random_devices[n];
405 if (check_random_device(rd))
410 int rand_pool_init(void)
414 for (i = 0; i < OSSL_NELEM(random_devices); i++)
415 random_devices[i].fd = -1;
420 void rand_pool_cleanup(void)
424 for (i = 0; i < OSSL_NELEM(random_devices); i++)
425 close_random_device(i);
428 void rand_pool_keep_random_devices_open(int keep)
433 keep_random_devices_open = keep;
436 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
438 int rand_pool_init(void)
443 void rand_pool_cleanup(void)
447 void rand_pool_keep_random_devices_open(int keep)
451 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
454 * Try the various seeding methods in turn, exit when successful.
456 * TODO(DRBG): If more than one entropy source is available, is it
457 * preferable to stop as soon as enough entropy has been collected
458 * (as favored by @rsalz) or should one rather be defensive and add
459 * more entropy than requested and/or from different sources?
461 * Currently, the user can select multiple entropy sources in the
462 * configure step, yet in practice only the first available source
463 * will be used. A more flexible solution has been requested, but
464 * currently it is not clear how this can be achieved without
465 * overengineering the problem. There are many parameters which
466 * could be taken into account when selecting the order and amount
467 * of input from the different entropy sources (trust, quality,
468 * possibility of blocking).
470 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
472 # if defined(OPENSSL_RAND_SEED_NONE)
473 return rand_pool_entropy_available(pool);
476 size_t entropy_available = 0;
477 unsigned char *buffer;
479 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
482 /* Maximum allowed number of consecutive unsuccessful attempts */
485 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
486 while (bytes_needed != 0 && attempts-- > 0) {
487 buffer = rand_pool_add_begin(pool, bytes_needed);
488 bytes = syscall_random(buffer, bytes_needed);
490 rand_pool_add_end(pool, bytes, 8 * bytes);
491 bytes_needed -= bytes;
492 attempts = 3; /* reset counter after successful attempt */
493 } else if (bytes < 0 && errno != EINTR) {
498 entropy_available = rand_pool_entropy_available(pool);
499 if (entropy_available > 0)
500 return entropy_available;
503 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
505 /* Not yet implemented. */
509 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
510 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
514 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); i++) {
516 /* Maximum allowed number of consecutive unsuccessful attempts */
518 const int fd = get_random_device(i);
523 while (bytes_needed != 0 && attempts-- > 0) {
524 buffer = rand_pool_add_begin(pool, bytes_needed);
525 bytes = read(fd, buffer, bytes_needed);
528 rand_pool_add_end(pool, bytes, 8 * bytes);
529 bytes_needed -= bytes;
530 attempts = 3; /* reset counter after successful attempt */
531 } else if (bytes < 0 && errno != EINTR) {
535 if (bytes < 0 || !keep_random_devices_open)
536 close_random_device(i);
538 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
540 entropy_available = rand_pool_entropy_available(pool);
541 if (entropy_available > 0)
542 return entropy_available;
546 # if defined(OPENSSL_RAND_SEED_RDTSC)
547 entropy_available = rand_acquire_entropy_from_tsc(pool);
548 if (entropy_available > 0)
549 return entropy_available;
552 # if defined(OPENSSL_RAND_SEED_RDCPU)
553 entropy_available = rand_acquire_entropy_from_cpu(pool);
554 if (entropy_available > 0)
555 return entropy_available;
558 # if defined(OPENSSL_RAND_SEED_EGD)
559 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
560 if (bytes_needed > 0) {
561 static const char *paths[] = { DEVRANDOM_EGD, NULL };
564 for (i = 0; paths[i] != NULL; i++) {
565 buffer = rand_pool_add_begin(pool, bytes_needed);
566 if (buffer != NULL) {
568 int num = RAND_query_egd_bytes(paths[i],
569 buffer, (int)bytes_needed);
570 if (num == (int)bytes_needed)
571 bytes = bytes_needed;
573 rand_pool_add_end(pool, bytes, 8 * bytes);
574 entropy_available = rand_pool_entropy_available(pool);
576 if (entropy_available > 0)
577 return entropy_available;
582 return rand_pool_entropy_available(pool);
588 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
589 int rand_pool_add_nonce_data(RAND_POOL *pool)
593 CRYPTO_THREAD_ID tid;
598 * Add process id, thread id, and a high resolution timestamp to
599 * ensure that the nonce is unique with high probability for
600 * different process instances.
603 data.tid = CRYPTO_THREAD_get_current_id();
604 data.time = get_time_stamp();
606 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
609 int rand_pool_add_additional_data(RAND_POOL *pool)
612 CRYPTO_THREAD_ID tid;
617 * Add some noise from the thread id and a high resolution timer.
618 * The thread id adds a little randomness if the drbg is accessed
619 * concurrently (which is the case for the <master> drbg).
621 data.tid = CRYPTO_THREAD_get_current_id();
622 data.time = get_timer_bits();
624 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
629 * Get the current time with the highest possible resolution
631 * The time stamp is added to the nonce, so it is optimized for not repeating.
632 * The current time is ideal for this purpose, provided the computer's clock
635 static uint64_t get_time_stamp(void)
637 # if defined(OSSL_POSIX_TIMER_OKAY)
641 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
642 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
645 # if defined(__unix__) \
646 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
650 if (gettimeofday(&tv, NULL) == 0)
651 return TWO32TO64(tv.tv_sec, tv.tv_usec);
658 * Get an arbitrary timer value of the highest possible resolution
660 * The timer value is added as random noise to the additional data,
661 * which is not considered a trusted entropy sourec, so any result
664 static uint64_t get_timer_bits(void)
666 uint64_t res = OPENSSL_rdtsc();
671 # if defined(__sun) || defined(__hpux)
677 read_wall_time(&t, TIMEBASE_SZ);
678 return TWO32TO64(t.tb_high, t.tb_low);
680 # elif defined(OSSL_POSIX_TIMER_OKAY)
684 # ifdef CLOCK_BOOTTIME
685 # define CLOCK_TYPE CLOCK_BOOTTIME
686 # elif defined(_POSIX_MONOTONIC_CLOCK)
687 # define CLOCK_TYPE CLOCK_MONOTONIC
689 # define CLOCK_TYPE CLOCK_REALTIME
692 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
693 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
696 # if defined(__unix__) \
697 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
701 if (gettimeofday(&tv, NULL) == 0)
702 return TWO32TO64(tv.tv_sec, tv.tv_usec);
707 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */