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>
18 #include "internal/rand_int.h"
20 #include "internal/dso.h"
22 # include <asm/unistd.h>
24 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
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 # if defined(__linux) && !defined(__NR_getrandom)
280 # if defined(__arm__) && defined(__NR_SYSCALL_BASE)
281 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
282 # elif defined(__i386__)
283 # define __NR_getrandom 355
284 # elif defined(__x86_64__) && !defined(__ILP32__)
285 # define __NR_getrandom 318
290 * syscall_random(): Try to get random data using a system call
291 * returns the number of bytes returned in buf, or < 0 on error.
293 static ssize_t syscall_random(void *buf, size_t buflen)
296 * Note: 'buflen' equals the size of the buffer which is used by the
297 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
299 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
301 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
302 * between size_t and ssize_t is safe even without a range check.
306 * Do runtime detection to find getentropy().
308 * Known OSs that should support this:
309 * - Darwin since 16 (OSX 10.12, IOS 10.0).
310 * - Solaris since 11.3
311 * - OpenBSD since 5.6
312 * - Linux since 3.17 with glibc 2.25
313 * - FreeBSD since 12.0 (1200061)
315 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
316 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
318 if (getentropy != NULL)
319 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
323 int (*f)(void *buffer, size_t length);
327 * We could cache the result of the lookup, but we normally don't
328 * call this function often.
331 p_getentropy.p = DSO_global_lookup("getentropy");
333 if (p_getentropy.p != NULL)
334 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
337 /* Linux supports this since version 3.17 */
338 # if defined(__linux) && defined(__NR_getrandom)
339 return syscall(__NR_getrandom, buf, buflen, 0);
340 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
341 return sysctl_random(buf, buflen);
347 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
349 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
350 static const char *random_device_paths[] = { DEVRANDOM };
351 static struct random_device {
357 } random_devices[OSSL_NELEM(random_device_paths)];
358 static int keep_random_devices_open = 1;
361 * Verify that the file descriptor associated with the random source is
362 * still valid. The rationale for doing this is the fact that it is not
363 * uncommon for daemons to close all open file handles when daemonizing.
364 * So the handle might have been closed or even reused for opening
367 static int check_random_device(struct random_device * rd)
372 && fstat(rd->fd, &st) != -1
373 && rd->dev == st.st_dev
374 && rd->ino == st.st_ino
375 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
376 && rd->rdev == st.st_rdev;
380 * Open a random device if required and return its file descriptor or -1 on error
382 static int get_random_device(size_t n)
385 struct random_device * rd = &random_devices[n];
387 /* reuse existing file descriptor if it is (still) valid */
388 if (check_random_device(rd))
391 /* open the random device ... */
392 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
395 /* ... and cache its relevant stat(2) data */
396 if (fstat(rd->fd, &st) != -1) {
399 rd->mode = st.st_mode;
400 rd->rdev = st.st_rdev;
410 * Close a random device making sure it is a random device
412 static void close_random_device(size_t n)
414 struct random_device * rd = &random_devices[n];
416 if (check_random_device(rd))
421 int rand_pool_init(void)
425 for (i = 0; i < OSSL_NELEM(random_devices); i++)
426 random_devices[i].fd = -1;
431 void rand_pool_cleanup(void)
435 for (i = 0; i < OSSL_NELEM(random_devices); i++)
436 close_random_device(i);
439 void rand_pool_keep_random_devices_open(int keep)
444 keep_random_devices_open = keep;
447 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
449 int rand_pool_init(void)
454 void rand_pool_cleanup(void)
458 void rand_pool_keep_random_devices_open(int keep)
462 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
465 * Try the various seeding methods in turn, exit when successful.
467 * TODO(DRBG): If more than one entropy source is available, is it
468 * preferable to stop as soon as enough entropy has been collected
469 * (as favored by @rsalz) or should one rather be defensive and add
470 * more entropy than requested and/or from different sources?
472 * Currently, the user can select multiple entropy sources in the
473 * configure step, yet in practice only the first available source
474 * will be used. A more flexible solution has been requested, but
475 * currently it is not clear how this can be achieved without
476 * overengineering the problem. There are many parameters which
477 * could be taken into account when selecting the order and amount
478 * of input from the different entropy sources (trust, quality,
479 * possibility of blocking).
481 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
483 # if defined(OPENSSL_RAND_SEED_NONE)
484 return rand_pool_entropy_available(pool);
487 size_t entropy_available = 0;
488 unsigned char *buffer;
490 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
493 /* Maximum allowed number of consecutive unsuccessful attempts */
496 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
497 while (bytes_needed != 0 && attempts-- > 0) {
498 buffer = rand_pool_add_begin(pool, bytes_needed);
499 bytes = syscall_random(buffer, bytes_needed);
501 rand_pool_add_end(pool, bytes, 8 * bytes);
502 bytes_needed -= bytes;
503 attempts = 3; /* reset counter after successful attempt */
504 } else if (bytes < 0 && errno != EINTR) {
509 entropy_available = rand_pool_entropy_available(pool);
510 if (entropy_available > 0)
511 return entropy_available;
514 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
516 /* Not yet implemented. */
520 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
521 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
525 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); i++) {
527 /* Maximum allowed number of consecutive unsuccessful attempts */
529 const int fd = get_random_device(i);
534 while (bytes_needed != 0 && attempts-- > 0) {
535 buffer = rand_pool_add_begin(pool, bytes_needed);
536 bytes = read(fd, buffer, bytes_needed);
539 rand_pool_add_end(pool, bytes, 8 * bytes);
540 bytes_needed -= bytes;
541 attempts = 3; /* reset counter after successful attempt */
542 } else if (bytes < 0 && errno != EINTR) {
546 if (bytes < 0 || !keep_random_devices_open)
547 close_random_device(i);
549 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
551 entropy_available = rand_pool_entropy_available(pool);
552 if (entropy_available > 0)
553 return entropy_available;
557 # if defined(OPENSSL_RAND_SEED_RDTSC)
558 entropy_available = rand_acquire_entropy_from_tsc(pool);
559 if (entropy_available > 0)
560 return entropy_available;
563 # if defined(OPENSSL_RAND_SEED_RDCPU)
564 entropy_available = rand_acquire_entropy_from_cpu(pool);
565 if (entropy_available > 0)
566 return entropy_available;
569 # if defined(OPENSSL_RAND_SEED_EGD)
570 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
571 if (bytes_needed > 0) {
572 static const char *paths[] = { DEVRANDOM_EGD, NULL };
575 for (i = 0; paths[i] != NULL; i++) {
576 buffer = rand_pool_add_begin(pool, bytes_needed);
577 if (buffer != NULL) {
579 int num = RAND_query_egd_bytes(paths[i],
580 buffer, (int)bytes_needed);
581 if (num == (int)bytes_needed)
582 bytes = bytes_needed;
584 rand_pool_add_end(pool, bytes, 8 * bytes);
585 entropy_available = rand_pool_entropy_available(pool);
587 if (entropy_available > 0)
588 return entropy_available;
593 return rand_pool_entropy_available(pool);
599 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
600 int rand_pool_add_nonce_data(RAND_POOL *pool)
604 CRYPTO_THREAD_ID tid;
609 * Add process id, thread id, and a high resolution timestamp to
610 * ensure that the nonce is unique with high probability for
611 * different process instances.
614 data.tid = CRYPTO_THREAD_get_current_id();
615 data.time = get_time_stamp();
617 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
620 int rand_pool_add_additional_data(RAND_POOL *pool)
623 CRYPTO_THREAD_ID tid;
628 * Add some noise from the thread id and a high resolution timer.
629 * The thread id adds a little randomness if the drbg is accessed
630 * concurrently (which is the case for the <master> drbg).
632 data.tid = CRYPTO_THREAD_get_current_id();
633 data.time = get_timer_bits();
635 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
640 * Get the current time with the highest possible resolution
642 * The time stamp is added to the nonce, so it is optimized for not repeating.
643 * The current time is ideal for this purpose, provided the computer's clock
646 static uint64_t get_time_stamp(void)
648 # if defined(OSSL_POSIX_TIMER_OKAY)
652 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
653 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
656 # if defined(__unix__) \
657 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
661 if (gettimeofday(&tv, NULL) == 0)
662 return TWO32TO64(tv.tv_sec, tv.tv_usec);
669 * Get an arbitrary timer value of the highest possible resolution
671 * The timer value is added as random noise to the additional data,
672 * which is not considered a trusted entropy sourec, so any result
675 static uint64_t get_timer_bits(void)
677 uint64_t res = OPENSSL_rdtsc();
682 # if defined(__sun) || defined(__hpux)
688 read_wall_time(&t, TIMEBASE_SZ);
689 return TWO32TO64(t.tb_high, t.tb_low);
691 # elif defined(OSSL_POSIX_TIMER_OKAY)
695 # ifdef CLOCK_BOOTTIME
696 # define CLOCK_TYPE CLOCK_BOOTTIME
697 # elif defined(_POSIX_MONOTONIC_CLOCK)
698 # define CLOCK_TYPE CLOCK_MONOTONIC
700 # define CLOCK_TYPE CLOCK_REALTIME
703 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
704 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
707 # if defined(__unix__) \
708 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
712 if (gettimeofday(&tv, NULL) == 0)
713 return TWO32TO64(tv.tv_sec, tv.tv_usec);
718 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */