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_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
81 !defined(OPENSSL_RAND_SEED_NONE)
82 # error "UEFI and VXWorks only support seeding NONE"
85 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
86 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
87 || defined(OPENSSL_SYS_UEFI))
89 static ssize_t syscall_random(void *buf, size_t buflen);
91 # if defined(OPENSSL_SYS_VOS)
93 # ifndef OPENSSL_RAND_SEED_OS
94 # error "Unsupported seeding method configured; must be os"
97 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
98 # error "Unsupported HP-PA and IA32 at the same time."
100 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
101 # error "Must have one of HP-PA or IA32"
105 * The following algorithm repeatedly samples the real-time clock (RTC) to
106 * generate a sequence of unpredictable data. The algorithm relies upon the
107 * uneven execution speed of the code (due to factors such as cache misses,
108 * interrupts, bus activity, and scheduling) and upon the rather large
109 * relative difference between the speed of the clock and the rate at which
110 * it can be read. If it is ported to an environment where execution speed
111 * is more constant or where the RTC ticks at a much slower rate, or the
112 * clock can be read with fewer instructions, it is likely that the results
113 * would be far more predictable. This should only be used for legacy
116 * As a precaution, we assume only 2 bits of entropy per byte.
118 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
125 # ifdef OPENSSL_SYS_VOS_HPPA
127 extern void s$sleep(long *_duration, short int *_code);
130 extern void s$sleep2(long long *_duration, short int *_code);
133 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
135 for (i = 0; i < bytes_needed; i++) {
137 * burn some cpu; hope for interrupts, cache collisions, bus
140 for (k = 0; k < 99; k++)
141 ts.tv_nsec = random();
143 # ifdef OPENSSL_SYS_VOS_HPPA
144 /* sleep for 1/1024 of a second (976 us). */
146 s$sleep(&duration, &code);
148 /* sleep for 1/65536 of a second (15 us). */
150 s$sleep2(&duration, &code);
153 /* Get wall clock time, take 8 bits. */
154 clock_gettime(CLOCK_REALTIME, &ts);
155 v = (unsigned char)(ts.tv_nsec & 0xFF);
156 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
158 return rand_pool_entropy_available(pool);
161 void rand_pool_cleanup(void)
165 void rand_pool_keep_random_devices_open(int keep)
171 # if defined(OPENSSL_RAND_SEED_EGD) && \
172 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
173 # error "Seeding uses EGD but EGD is turned off or no device given"
176 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
177 # error "Seeding uses urandom but DEVRANDOM is not configured"
180 # if defined(OPENSSL_RAND_SEED_OS)
181 # if !defined(DEVRANDOM)
182 # error "OS seeding requires DEVRANDOM to be configured"
184 # define OPENSSL_RAND_SEED_GETRANDOM
185 # define OPENSSL_RAND_SEED_DEVRANDOM
188 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
189 # error "librandom not (yet) supported"
192 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
194 * sysctl_random(): Use sysctl() to read a random number from the kernel
195 * Returns the number of bytes returned in buf on success, -1 on failure.
197 static ssize_t sysctl_random(char *buf, size_t buflen)
204 * Note: sign conversion between size_t and ssize_t is safe even
205 * without a range check, see comment in syscall_random()
209 * On FreeBSD old implementations returned longs, newer versions support
210 * variable sizes up to 256 byte. The code below would not work properly
211 * when the sysctl returns long and we want to request something not a
212 * multiple of longs, which should never be the case.
214 if (!ossl_assert(buflen % sizeof(long) == 0)) {
220 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
221 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
222 * it returns a variable number of bytes with the current version supporting
224 * Just return an error on older NetBSD versions.
226 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
236 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
237 return done > 0 ? done : -1;
241 } while (buflen > 0);
248 * syscall_random(): Try to get random data using a system call
249 * returns the number of bytes returned in buf, or < 0 on error.
251 static ssize_t syscall_random(void *buf, size_t buflen)
254 * Note: 'buflen' equals the size of the buffer which is used by the
255 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
257 * 2 * DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^13
259 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
260 * between size_t and ssize_t is safe even without a range check.
264 * Do runtime detection to find getentropy().
266 * Known OSs that should support this:
267 * - Darwin since 16 (OSX 10.12, IOS 10.0).
268 * - Solaris since 11.3
269 * - OpenBSD since 5.6
270 * - Linux since 3.17 with glibc 2.25
271 * - FreeBSD since 12.0 (1200061)
273 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
274 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
276 if (getentropy != NULL)
277 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
281 int (*f)(void *buffer, size_t length);
285 * We could cache the result of the lookup, but we normally don't
286 * call this function often.
289 p_getentropy.p = DSO_global_lookup("getentropy");
291 if (p_getentropy.p != NULL)
292 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
295 /* Linux supports this since version 3.17 */
296 # if defined(__linux) && defined(SYS_getrandom)
297 return syscall(SYS_getrandom, buf, buflen, 0);
298 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
299 return sysctl_random(buf, buflen);
306 #if !defined(OPENSSL_RAND_SEED_NONE) && defined(OPENSSL_RAND_SEED_DEVRANDOM)
307 static const char *random_device_paths[] = { DEVRANDOM };
308 static struct random_device {
314 } random_devices[OSSL_NELEM(random_device_paths)];
315 static int keep_random_devices_open = 1;
318 * Verify that the file descriptor associated with the random source is
319 * still valid. The rationale for doing this is the fact that it is not
320 * uncommon for daemons to close all open file handles when daemonizing.
321 * So the handle might have been closed or even reused for opening
324 static int check_random_device(struct random_device * rd)
329 && fstat(rd->fd, &st) != -1
330 && rd->dev == st.st_dev
331 && rd->ino == st.st_ino
332 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
333 && rd->rdev == st.st_rdev;
337 * Open a random device if required and return its file descriptor or -1 on error
339 static int get_random_device(size_t n)
342 struct random_device * rd = &random_devices[n];
344 /* reuse existing file descriptor if it is (still) valid */
345 if (check_random_device(rd))
348 /* open the random device ... */
349 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
352 /* ... and cache its relevant stat(2) data */
353 if (fstat(rd->fd, &st) != -1) {
356 rd->mode = st.st_mode;
357 rd->rdev = st.st_rdev;
367 * Close a random device making sure it is a random device
369 static void close_random_device(size_t n)
371 struct random_device * rd = &random_devices[n];
373 if (check_random_device(rd))
378 static void open_random_devices(void)
382 for (i = 0; i < OSSL_NELEM(random_devices); i++)
383 (void)get_random_device(i);
386 int rand_pool_init(void)
390 for (i = 0; i < OSSL_NELEM(random_devices); i++)
391 random_devices[i].fd = -1;
392 open_random_devices();
396 void rand_pool_cleanup(void)
400 for (i = 0; i < OSSL_NELEM(random_devices); i++)
401 close_random_device(i);
404 void rand_pool_keep_random_devices_open(int keep)
407 open_random_devices();
410 keep_random_devices_open = keep;
413 # else /* defined(OPENSSL_RAND_SEED_NONE)
414 * || !defined(OPENSSL_RAND_SEED_DEVRANDOM)
417 int rand_pool_init(void)
422 void rand_pool_cleanup(void)
426 void rand_pool_keep_random_devices_open(int keep)
430 # endif /* !defined(OPENSSL_RAND_SEED_NONE)
431 * && defined(OPENSSL_RAND_SEED_DEVRANDOM)
435 * Try the various seeding methods in turn, exit when successful.
437 * TODO(DRBG): If more than one entropy source is available, is it
438 * preferable to stop as soon as enough entropy has been collected
439 * (as favored by @rsalz) or should one rather be defensive and add
440 * more entropy than requested and/or from different sources?
442 * Currently, the user can select multiple entropy sources in the
443 * configure step, yet in practice only the first available source
444 * will be used. A more flexible solution has been requested, but
445 * currently it is not clear how this can be achieved without
446 * overengineering the problem. There are many parameters which
447 * could be taken into account when selecting the order and amount
448 * of input from the different entropy sources (trust, quality,
449 * possibility of blocking).
451 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
453 # ifdef OPENSSL_RAND_SEED_NONE
454 return rand_pool_entropy_available(pool);
457 size_t entropy_available = 0;
458 unsigned char *buffer;
460 # ifdef OPENSSL_RAND_SEED_GETRANDOM
463 /* Maximum allowed number of consecutive unsuccessful attempts */
466 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
467 while (bytes_needed != 0 && attempts-- > 0) {
468 buffer = rand_pool_add_begin(pool, bytes_needed);
469 bytes = syscall_random(buffer, bytes_needed);
471 rand_pool_add_end(pool, bytes, 8 * bytes);
472 bytes_needed -= bytes;
473 attempts = 3; /* reset counter after successful attempt */
474 } else if (bytes < 0 && errno != EINTR) {
479 entropy_available = rand_pool_entropy_available(pool);
480 if (entropy_available > 0)
481 return entropy_available;
484 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
486 /* Not yet implemented. */
490 # ifdef OPENSSL_RAND_SEED_DEVRANDOM
491 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
495 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); i++) {
497 /* Maximum allowed number of consecutive unsuccessful attempts */
499 const int fd = get_random_device(i);
504 while (bytes_needed != 0 && attempts-- > 0) {
505 buffer = rand_pool_add_begin(pool, bytes_needed);
506 bytes = read(fd, buffer, bytes_needed);
509 rand_pool_add_end(pool, bytes, 8 * bytes);
510 bytes_needed -= bytes;
511 attempts = 3; /* reset counter after successful attempt */
512 } else if (bytes < 0 && errno != EINTR) {
516 if (bytes < 0 || !keep_random_devices_open)
517 close_random_device(i);
519 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
521 entropy_available = rand_pool_entropy_available(pool);
522 if (entropy_available > 0)
523 return entropy_available;
527 # ifdef OPENSSL_RAND_SEED_RDTSC
528 entropy_available = rand_acquire_entropy_from_tsc(pool);
529 if (entropy_available > 0)
530 return entropy_available;
533 # ifdef OPENSSL_RAND_SEED_RDCPU
534 entropy_available = rand_acquire_entropy_from_cpu(pool);
535 if (entropy_available > 0)
536 return entropy_available;
539 # ifdef OPENSSL_RAND_SEED_EGD
540 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
541 if (bytes_needed > 0) {
542 static const char *paths[] = { DEVRANDOM_EGD, NULL };
545 for (i = 0; paths[i] != NULL; i++) {
546 buffer = rand_pool_add_begin(pool, bytes_needed);
547 if (buffer != NULL) {
549 int num = RAND_query_egd_bytes(paths[i],
550 buffer, (int)bytes_needed);
551 if (num == (int)bytes_needed)
552 bytes = bytes_needed;
554 rand_pool_add_end(pool, bytes, 8 * bytes);
555 entropy_available = rand_pool_entropy_available(pool);
557 if (entropy_available > 0)
558 return entropy_available;
563 return rand_pool_entropy_available(pool);
569 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
570 int rand_pool_add_nonce_data(RAND_POOL *pool)
574 CRYPTO_THREAD_ID tid;
579 * Add process id, thread id, and a high resolution timestamp to
580 * ensure that the nonce is unique with high probability for
581 * different process instances.
584 data.tid = CRYPTO_THREAD_get_current_id();
585 data.time = get_time_stamp();
587 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
590 int rand_pool_add_additional_data(RAND_POOL *pool)
593 CRYPTO_THREAD_ID tid;
598 * Add some noise from the thread id and a high resolution timer.
599 * The thread id adds a little randomness if the drbg is accessed
600 * concurrently (which is the case for the <master> drbg).
602 data.tid = CRYPTO_THREAD_get_current_id();
603 data.time = get_timer_bits();
605 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
610 * Get the current time with the highest possible resolution
612 * The time stamp is added to the nonce, so it is optimized for not repeating.
613 * The current time is ideal for this purpose, provided the computer's clock
616 static uint64_t get_time_stamp(void)
618 # if defined(OSSL_POSIX_TIMER_OKAY)
622 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
623 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
626 # if defined(__unix__) \
627 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
631 if (gettimeofday(&tv, NULL) == 0)
632 return TWO32TO64(tv.tv_sec, tv.tv_usec);
639 * Get an arbitrary timer value of the highest possible resolution
641 * The timer value is added as random noise to the additional data,
642 * which is not considered a trusted entropy sourec, so any result
645 static uint64_t get_timer_bits(void)
647 uint64_t res = OPENSSL_rdtsc();
652 # if defined(__sun) || defined(__hpux)
658 read_wall_time(&t, TIMEBASE_SZ);
659 return TWO32TO64(t.tb_high, t.tb_low);
661 # elif defined(OSSL_POSIX_TIMER_OKAY)
665 # ifdef CLOCK_BOOTTIME
666 # define CLOCK_TYPE CLOCK_BOOTTIME
667 # elif defined(_POSIX_MONOTONIC_CLOCK)
668 # define CLOCK_TYPE CLOCK_MONOTONIC
670 # define CLOCK_TYPE CLOCK_REALTIME
673 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
674 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
677 # if defined(__unix__) \
678 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
682 if (gettimeofday(&tv, NULL) == 0)
683 return TWO32TO64(tv.tv_sec, tv.tv_usec);
688 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */