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
13 #include "internal/cryptlib.h"
14 #include <openssl/rand.h>
16 #include "internal/rand_int.h"
18 #include "internal/dso.h"
20 # include <sys/syscall.h>
22 #if defined(__FreeBSD__)
23 # include <sys/types.h>
24 # include <sys/sysctl.h>
25 # include <sys/param.h>
27 #if defined(__OpenBSD__) || defined(__NetBSD__)
28 # include <sys/param.h>
31 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
32 # include <sys/types.h>
33 # include <sys/stat.h>
36 # include <sys/time.h>
38 static uint64_t get_time_stamp(void);
39 static uint64_t get_timer_bits(void);
41 /* Macro to convert two thirty two bit values into a sixty four bit one */
42 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
45 * Check for the existence and support of POSIX timers. The standard
46 * says that the _POSIX_TIMERS macro will have a positive value if they
49 * However, we want an additional constraint: that the timer support does
50 * not require an extra library dependency. Early versions of glibc
51 * require -lrt to be specified on the link line to access the timers,
52 * so this needs to be checked for.
54 * It is worse because some libraries define __GLIBC__ but don't
55 * support the version testing macro (e.g. uClibc). This means
56 * an extra check is needed.
58 * The final condition is:
59 * "have posix timers and either not glibc or glibc without -lrt"
61 * The nested #if sequences are required to avoid using a parameterised
62 * macro that might be undefined.
64 # undef OSSL_POSIX_TIMER_OKAY
65 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
66 # if defined(__GLIBC__)
67 # if defined(__GLIBC_PREREQ)
68 # if __GLIBC_PREREQ(2, 17)
69 # define OSSL_POSIX_TIMER_OKAY
73 # define OSSL_POSIX_TIMER_OKAY
76 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
78 int syscall_random(void *buf, size_t buflen);
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 # if defined(OPENSSL_SYS_VOS)
91 # ifndef OPENSSL_RAND_SEED_OS
92 # error "Unsupported seeding method configured; must be os"
95 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
96 # error "Unsupported HP-PA and IA32 at the same time."
98 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
99 # error "Must have one of HP-PA or IA32"
103 * The following algorithm repeatedly samples the real-time clock (RTC) to
104 * generate a sequence of unpredictable data. The algorithm relies upon the
105 * uneven execution speed of the code (due to factors such as cache misses,
106 * interrupts, bus activity, and scheduling) and upon the rather large
107 * relative difference between the speed of the clock and the rate at which
108 * it can be read. If it is ported to an environment where execution speed
109 * is more constant or where the RTC ticks at a much slower rate, or the
110 * clock can be read with fewer instructions, it is likely that the results
111 * would be far more predictable. This should only be used for legacy
114 * As a precaution, we assume only 2 bits of entropy per byte.
116 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
123 # ifdef OPENSSL_SYS_VOS_HPPA
125 extern void s$sleep(long *_duration, short int *_code);
128 extern void s$sleep2(long long *_duration, short int *_code);
131 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
133 for (i = 0; i < bytes_needed; i++) {
135 * burn some cpu; hope for interrupts, cache collisions, bus
138 for (k = 0; k < 99; k++)
139 ts.tv_nsec = random();
141 # ifdef OPENSSL_SYS_VOS_HPPA
142 /* sleep for 1/1024 of a second (976 us). */
144 s$sleep(&duration, &code);
146 /* sleep for 1/65536 of a second (15 us). */
148 s$sleep2(&duration, &code);
151 /* Get wall clock time, take 8 bits. */
152 clock_gettime(CLOCK_REALTIME, &ts);
153 v = (unsigned char)(ts.tv_nsec & 0xFF);
154 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
156 return rand_pool_entropy_available(pool);
159 void rand_pool_cleanup(void)
163 void rand_pool_keep_random_devices_open(int keep)
169 # if defined(OPENSSL_RAND_SEED_EGD) && \
170 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
171 # error "Seeding uses EGD but EGD is turned off or no device given"
174 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
175 # error "Seeding uses urandom but DEVRANDOM is not configured"
178 # if defined(OPENSSL_RAND_SEED_OS)
179 # if !defined(DEVRANDOM)
180 # error "OS seeding requires DEVRANDOM to be configured"
182 # define OPENSSL_RAND_SEED_GETRANDOM
183 # define OPENSSL_RAND_SEED_DEVRANDOM
186 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
187 # error "librandom not (yet) supported"
190 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
192 * sysctl_random(): Use sysctl() to read a random number from the kernel
193 * Returns the size on success, 0 on failure.
195 static size_t sysctl_random(char *buf, size_t buflen)
202 * On FreeBSD old implementations returned longs, newer versions support
203 * variable sizes up to 256 byte. The code below would not work properly
204 * when the sysctl returns long and we want to request something not a
205 * multiple of longs, which should never be the case.
207 if (!ossl_assert(buflen % sizeof(long) == 0))
211 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
212 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
213 * it returns a variable number of bytes with the current version supporting
215 * Just return an error on older NetBSD versions.
217 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
226 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
231 } while (buflen > 0);
238 * syscall_random(): Try to get random data using a system call
239 * returns the number of bytes returned in buf, or <= 0 on error.
241 int syscall_random(void *buf, size_t buflen)
244 * Do runtime detection to find getentropy().
246 * Known OSs that should support this:
247 * - Darwin since 16 (OSX 10.12, IOS 10.0).
248 * - Solaris since 11.3
249 * - OpenBSD since 5.6
250 * - Linux since 3.17 with glibc 2.25
251 * - FreeBSD since 12.0 (1200061)
253 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
254 extern int getentropy(void *bufer, size_t length) __attribute__((weak));
256 if (getentropy != NULL)
257 return getentropy(buf, buflen) == 0 ? buflen : 0;
261 int (*f)(void *buffer, size_t length);
265 * We could cache the result of the lookup, but we normally don't
266 * call this function often.
269 p_getentropy.p = DSO_global_lookup("getentropy");
271 if (p_getentropy.p != NULL)
272 return p_getentropy.f(buf, buflen) == 0 ? buflen : 0;
275 /* Linux supports this since version 3.17 */
276 # if defined(__linux) && defined(SYS_getrandom)
277 return (int)syscall(SYS_getrandom, buf, buflen, 0);
280 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
281 return (int)sysctl_random(buf, buflen);
287 #if !defined(OPENSSL_RAND_SEED_NONE) && defined(OPENSSL_RAND_SEED_DEVRANDOM)
288 static const char *random_device_paths[] = { DEVRANDOM };
289 static struct random_device {
295 } random_devices[OSSL_NELEM(random_device_paths)];
296 static int keep_random_devices_open = 1;
299 * Verify that the file descriptor associated with the random source is
300 * still valid. The rationale for doing this is the fact that it is not
301 * uncommon for daemons to close all open file handles when daemonizing.
302 * So the handle might have been closed or even reused for opening
305 static int check_random_device(struct random_device * rd)
310 && fstat(rd->fd, &st) != -1
311 && rd->dev == st.st_dev
312 && rd->ino == st.st_ino
313 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
314 && rd->rdev == st.st_rdev;
318 * Open a random device if required and return its file descriptor or -1 on error
320 static int get_random_device(size_t n)
323 struct random_device * rd = &random_devices[n];
325 /* reuse existing file descriptor if it is (still) valid */
326 if (check_random_device(rd))
329 /* open the random device ... */
330 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
333 /* ... and cache its relevant stat(2) data */
334 if (fstat(rd->fd, &st) != -1) {
337 rd->mode = st.st_mode;
338 rd->rdev = st.st_rdev;
348 * Close a random device making sure it is a random device
350 static void close_random_device(size_t n)
352 struct random_device * rd = &random_devices[n];
354 if (check_random_device(rd))
359 static void open_random_devices(void)
363 for (i = 0; i < OSSL_NELEM(random_devices); i++)
364 (void)get_random_device(i);
367 int rand_pool_init(void)
371 for (i = 0; i < OSSL_NELEM(random_devices); i++)
372 random_devices[i].fd = -1;
373 open_random_devices();
377 void rand_pool_cleanup(void)
381 for (i = 0; i < OSSL_NELEM(random_devices); i++)
382 close_random_device(i);
385 void rand_pool_keep_random_devices_open(int keep)
388 open_random_devices();
391 keep_random_devices_open = keep;
394 # else /* defined(OPENSSL_RAND_SEED_NONE)
395 * || !defined(OPENSSL_RAND_SEED_DEVRANDOM)
398 int rand_pool_init(void)
403 void rand_pool_cleanup(void)
407 void rand_pool_keep_random_devices_open(int keep)
411 # endif /* !defined(OPENSSL_RAND_SEED_NONE)
412 * && defined(OPENSSL_RAND_SEED_DEVRANDOM)
416 * Try the various seeding methods in turn, exit when successful.
418 * TODO(DRBG): If more than one entropy source is available, is it
419 * preferable to stop as soon as enough entropy has been collected
420 * (as favored by @rsalz) or should one rather be defensive and add
421 * more entropy than requested and/or from different sources?
423 * Currently, the user can select multiple entropy sources in the
424 * configure step, yet in practice only the first available source
425 * will be used. A more flexible solution has been requested, but
426 * currently it is not clear how this can be achieved without
427 * overengineering the problem. There are many parameters which
428 * could be taken into account when selecting the order and amount
429 * of input from the different entropy sources (trust, quality,
430 * possibility of blocking).
432 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
434 # ifdef OPENSSL_RAND_SEED_NONE
435 return rand_pool_entropy_available(pool);
438 size_t entropy_available = 0;
439 unsigned char *buffer;
441 # ifdef OPENSSL_RAND_SEED_GETRANDOM
442 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
443 buffer = rand_pool_add_begin(pool, bytes_needed);
444 if (buffer != NULL) {
447 if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
448 bytes = bytes_needed;
450 rand_pool_add_end(pool, bytes, 8 * bytes);
451 entropy_available = rand_pool_entropy_available(pool);
453 if (entropy_available > 0)
454 return entropy_available;
457 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
459 /* Not yet implemented. */
463 # ifdef OPENSSL_RAND_SEED_DEVRANDOM
464 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
468 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths); i++) {
469 const int fd = get_random_device(i);
473 buffer = rand_pool_add_begin(pool, bytes_needed);
474 if (buffer != NULL) {
475 const ssize_t n = read(fd, buffer, bytes_needed);
478 close_random_device(i);
482 rand_pool_add_end(pool, n, 8 * n);
484 if (!keep_random_devices_open)
485 close_random_device(i);
487 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
489 entropy_available = rand_pool_entropy_available(pool);
490 if (entropy_available > 0)
491 return entropy_available;
495 # ifdef OPENSSL_RAND_SEED_RDTSC
496 entropy_available = rand_acquire_entropy_from_tsc(pool);
497 if (entropy_available > 0)
498 return entropy_available;
501 # ifdef OPENSSL_RAND_SEED_RDCPU
502 entropy_available = rand_acquire_entropy_from_cpu(pool);
503 if (entropy_available > 0)
504 return entropy_available;
507 # ifdef OPENSSL_RAND_SEED_EGD
508 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
509 if (bytes_needed > 0) {
510 static const char *paths[] = { DEVRANDOM_EGD, NULL };
513 for (i = 0; paths[i] != NULL; i++) {
514 buffer = rand_pool_add_begin(pool, bytes_needed);
515 if (buffer != NULL) {
517 int num = RAND_query_egd_bytes(paths[i],
518 buffer, (int)bytes_needed);
519 if (num == (int)bytes_needed)
520 bytes = bytes_needed;
522 rand_pool_add_end(pool, bytes, 8 * bytes);
523 entropy_available = rand_pool_entropy_available(pool);
525 if (entropy_available > 0)
526 return entropy_available;
531 return rand_pool_entropy_available(pool);
537 #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
538 int rand_pool_add_nonce_data(RAND_POOL *pool)
542 CRYPTO_THREAD_ID tid;
547 * Add process id, thread id, and a high resolution timestamp to
548 * ensure that the nonce is unique whith high probability for
549 * different process instances.
552 data.tid = CRYPTO_THREAD_get_current_id();
553 data.time = get_time_stamp();
555 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
558 int rand_pool_add_additional_data(RAND_POOL *pool)
561 CRYPTO_THREAD_ID tid;
566 * Add some noise from the thread id and a high resolution timer.
567 * The thread id adds a little randomness if the drbg is accessed
568 * concurrently (which is the case for the <master> drbg).
570 data.tid = CRYPTO_THREAD_get_current_id();
571 data.time = get_timer_bits();
573 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
578 * Get the current time with the highest possible resolution
580 * The time stamp is added to the nonce, so it is optimized for not repeating.
581 * The current time is ideal for this purpose, provided the computer's clock
584 static uint64_t get_time_stamp(void)
586 # if defined(OSSL_POSIX_TIMER_OKAY)
590 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
591 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
594 # if defined(__unix__) \
595 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
599 if (gettimeofday(&tv, NULL) == 0)
600 return TWO32TO64(tv.tv_sec, tv.tv_usec);
607 * Get an arbitrary timer value of the highest possible resolution
609 * The timer value is added as random noise to the additional data,
610 * which is not considered a trusted entropy sourec, so any result
613 static uint64_t get_timer_bits(void)
615 uint64_t res = OPENSSL_rdtsc();
620 # if defined(__sun) || defined(__hpux)
626 read_wall_time(&t, TIMEBASE_SZ);
627 return TWO32TO64(t.tb_high, t.tb_low);
629 # elif defined(OSSL_POSIX_TIMER_OKAY)
633 # ifdef CLOCK_BOOTTIME
634 # define CLOCK_TYPE CLOCK_BOOTTIME
635 # elif defined(_POSIX_MONOTONIC_CLOCK)
636 # define CLOCK_TYPE CLOCK_MONOTONIC
638 # define CLOCK_TYPE CLOCK_REALTIME
641 if (clock_gettime(CLOCK_TYPE, &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);
656 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */