2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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 <asm/unistd.h>
26 # include <sys/utsname.h>
28 #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
29 # include <sys/types.h>
30 # include <sys/sysctl.h>
31 # include <sys/param.h>
33 #if defined(__OpenBSD__) || defined(__NetBSD__)
34 # include <sys/param.h>
37 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
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_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
97 # error "UEFI only supports seeding NONE"
100 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
101 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
102 || defined(OPENSSL_SYS_UEFI))
104 # if defined(OPENSSL_SYS_VOS)
106 # ifndef OPENSSL_RAND_SEED_OS
107 # error "Unsupported seeding method configured; must be os"
110 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
111 # error "Unsupported HP-PA and IA32 at the same time."
113 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
114 # error "Must have one of HP-PA or IA32"
118 * The following algorithm repeatedly samples the real-time clock (RTC) to
119 * generate a sequence of unpredictable data. The algorithm relies upon the
120 * uneven execution speed of the code (due to factors such as cache misses,
121 * interrupts, bus activity, and scheduling) and upon the rather large
122 * relative difference between the speed of the clock and the rate at which
123 * it can be read. If it is ported to an environment where execution speed
124 * is more constant or where the RTC ticks at a much slower rate, or the
125 * clock can be read with fewer instructions, it is likely that the results
126 * would be far more predictable. This should only be used for legacy
129 * As a precaution, we assume only 2 bits of entropy per byte.
131 size_t rand_pool_acquire_entropy(RAND_POOL
*pool
)
138 # ifdef OPENSSL_SYS_VOS_HPPA
140 extern void s$
sleep(long *_duration
, short int *_code
);
143 extern void s$
sleep2(long long *_duration
, short int *_code
);
146 bytes_needed
= rand_pool_bytes_needed(pool
, 4 /*entropy_factor*/);
148 for (i
= 0; i
< bytes_needed
; i
++) {
150 * burn some cpu; hope for interrupts, cache collisions, bus
153 for (k
= 0; k
< 99; k
++)
154 ts
.tv_nsec
= random();
156 # ifdef OPENSSL_SYS_VOS_HPPA
157 /* sleep for 1/1024 of a second (976 us). */
159 s$
sleep(&duration
, &code
);
161 /* sleep for 1/65536 of a second (15 us). */
163 s$
sleep2(&duration
, &code
);
166 /* Get wall clock time, take 8 bits. */
167 clock_gettime(CLOCK_REALTIME
, &ts
);
168 v
= (unsigned char)(ts
.tv_nsec
& 0xFF);
169 rand_pool_add(pool
, arg
, &v
, sizeof(v
) , 2);
171 return rand_pool_entropy_available(pool
);
174 void rand_pool_cleanup(void)
178 void rand_pool_keep_random_devices_open(int keep
)
184 # if defined(OPENSSL_RAND_SEED_EGD) && \
185 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
186 # error "Seeding uses EGD but EGD is turned off or no device given"
189 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
190 # error "Seeding uses urandom but DEVRANDOM is not configured"
193 # if defined(OPENSSL_RAND_SEED_OS)
194 # if !defined(DEVRANDOM)
195 # error "OS seeding requires DEVRANDOM to be configured"
197 # define OPENSSL_RAND_SEED_GETRANDOM
198 # define OPENSSL_RAND_SEED_DEVRANDOM
201 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
202 # error "librandom not (yet) supported"
205 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
207 * sysctl_random(): Use sysctl() to read a random number from the kernel
208 * Returns the number of bytes returned in buf on success, -1 on failure.
210 static ssize_t
sysctl_random(char *buf
, size_t buflen
)
217 * Note: sign conversion between size_t and ssize_t is safe even
218 * without a range check, see comment in syscall_random()
222 * On FreeBSD old implementations returned longs, newer versions support
223 * variable sizes up to 256 byte. The code below would not work properly
224 * when the sysctl returns long and we want to request something not a
225 * multiple of longs, which should never be the case.
227 if (!ossl_assert(buflen
% sizeof(long) == 0)) {
233 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
234 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
235 * it returns a variable number of bytes with the current version supporting
237 * Just return an error on older NetBSD versions.
239 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
249 if (sysctl(mib
, 2, buf
, &len
, NULL
, 0) == -1)
250 return done
> 0 ? done
: -1;
254 } while (buflen
> 0);
260 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
262 # if defined(__linux) && !defined(__NR_getrandom)
263 # if defined(__arm__) && defined(__NR_SYSCALL_BASE)
264 # define __NR_getrandom (__NR_SYSCALL_BASE+384)
265 # elif defined(__i386__)
266 # define __NR_getrandom 355
267 # elif defined(__x86_64__) && !defined(__ILP32__)
268 # define __NR_getrandom 318
273 * syscall_random(): Try to get random data using a system call
274 * returns the number of bytes returned in buf, or < 0 on error.
276 static ssize_t
syscall_random(void *buf
, size_t buflen
)
279 * Note: 'buflen' equals the size of the buffer which is used by the
280 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
282 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
284 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
285 * between size_t and ssize_t is safe even without a range check.
289 * Do runtime detection to find getentropy().
291 * Known OSs that should support this:
292 * - Darwin since 16 (OSX 10.12, IOS 10.0).
293 * - Solaris since 11.3
294 * - OpenBSD since 5.6
295 * - Linux since 3.17 with glibc 2.25
296 * - FreeBSD since 12.0 (1200061)
298 # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
299 extern int getentropy(void *buffer
, size_t length
) __attribute__((weak
));
301 if (getentropy
!= NULL
)
302 return getentropy(buf
, buflen
) == 0 ? (ssize_t
)buflen
: -1;
303 # elif !defined(FIPS_MODE)
306 int (*f
)(void *buffer
, size_t length
);
310 * We could cache the result of the lookup, but we normally don't
311 * call this function often.
314 p_getentropy
.p
= DSO_global_lookup("getentropy");
316 if (p_getentropy
.p
!= NULL
)
317 return p_getentropy
.f(buf
, buflen
) == 0 ? (ssize_t
)buflen
: -1;
320 /* Linux supports this since version 3.17 */
321 # if defined(__linux) && defined(__NR_getrandom)
322 return syscall(__NR_getrandom
, buf
, buflen
, 0);
323 # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
324 return sysctl_random(buf
, buflen
);
330 # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
332 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
333 static const char *random_device_paths
[] = { DEVRANDOM
};
334 static struct random_device
{
340 } random_devices
[OSSL_NELEM(random_device_paths
)];
341 static int keep_random_devices_open
= 1;
343 # if defined(__linux) && defined(DEVRANDOM_WAIT)
344 static void *shm_addr
;
346 # if !defined(FIPS_MODE)
347 static void cleanup_shm(void)
354 * Ensure that the system randomness source has been adequately seeded.
355 * This is done by having the first start of libcrypto, wait until the device
356 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
357 * of the library and later reseedings do not need to do this.
359 static int wait_random_seeded(void)
361 static int seeded
= OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID
< 0;
362 static const int kernel_version
[] = { DEVRANDOM_SAFE_KERNEL
};
370 /* See if anthing has created the global seeded indication */
371 if ((shm_id
= shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID
, 1, 0)) == -1) {
373 * Check the kernel's version and fail if it is too recent.
375 * Linux kernels from 4.8 onwards do not guarantee that
376 * /dev/urandom is properly seeded when /dev/random becomes
377 * readable. However, such kernels support the getentropy(2)
378 * system call and this should always succeed which renders
379 * this alternative but essentially identical source moot.
381 if (uname(&un
) == 0) {
382 kernel
[0] = atoi(un
.release
);
383 p
= strchr(un
.release
, '.');
384 kernel
[1] = p
== NULL
? 0 : atoi(p
+ 1);
385 if (kernel
[0] > kernel_version
[0]
386 || (kernel
[0] == kernel_version
[0]
387 && kernel
[1] >= kernel_version
[1])) {
391 /* Open /dev/random and wait for it to be readable */
392 if ((fd
= open(DEVRANDOM_WAIT
, O_RDONLY
)) != -1) {
393 if (DEVRANDM_WAIT_USE_SELECT
) {
396 while ((r
= select(fd
+ 1, &fds
, NULL
, NULL
, NULL
)) < 0
399 while ((r
= read(fd
, &c
, 1)) < 0 && errno
== EINTR
);
404 /* Craete the shared memory indicator */
405 shm_id
= shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID
, 1,
406 IPC_CREAT
| S_IRUSR
| S_IRGRP
| S_IROTH
);
413 * Map the shared memory to prevent its premature destruction.
414 * If this call fails, it isn't a big problem.
416 shm_addr
= shmat(shm_id
, NULL
, SHM_RDONLY
);
418 /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
419 if (shm_addr
!= (void *)-1)
420 OPENSSL_atexit(&cleanup_shm
);
426 # else /* defined __linux */
427 static int wait_random_seeded(void)
434 * Verify that the file descriptor associated with the random source is
435 * still valid. The rationale for doing this is the fact that it is not
436 * uncommon for daemons to close all open file handles when daemonizing.
437 * So the handle might have been closed or even reused for opening
440 static int check_random_device(struct random_device
* rd
)
445 && fstat(rd
->fd
, &st
) != -1
446 && rd
->dev
== st
.st_dev
447 && rd
->ino
== st
.st_ino
448 && ((rd
->mode
^ st
.st_mode
) & ~(S_IRWXU
| S_IRWXG
| S_IRWXO
)) == 0
449 && rd
->rdev
== st
.st_rdev
;
453 * Open a random device if required and return its file descriptor or -1 on error
455 static int get_random_device(size_t n
)
458 struct random_device
* rd
= &random_devices
[n
];
460 /* reuse existing file descriptor if it is (still) valid */
461 if (check_random_device(rd
))
464 /* open the random device ... */
465 if ((rd
->fd
= open(random_device_paths
[n
], O_RDONLY
)) == -1)
468 /* ... and cache its relevant stat(2) data */
469 if (fstat(rd
->fd
, &st
) != -1) {
472 rd
->mode
= st
.st_mode
;
473 rd
->rdev
= st
.st_rdev
;
483 * Close a random device making sure it is a random device
485 static void close_random_device(size_t n
)
487 struct random_device
* rd
= &random_devices
[n
];
489 if (check_random_device(rd
))
494 int rand_pool_init(void)
498 for (i
= 0; i
< OSSL_NELEM(random_devices
); i
++)
499 random_devices
[i
].fd
= -1;
504 void rand_pool_cleanup(void)
508 for (i
= 0; i
< OSSL_NELEM(random_devices
); i
++)
509 close_random_device(i
);
512 void rand_pool_keep_random_devices_open(int keep
)
517 keep_random_devices_open
= keep
;
520 # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
522 int rand_pool_init(void)
527 void rand_pool_cleanup(void)
531 void rand_pool_keep_random_devices_open(int keep
)
535 # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
538 * Try the various seeding methods in turn, exit when successful.
540 * TODO(DRBG): If more than one entropy source is available, is it
541 * preferable to stop as soon as enough entropy has been collected
542 * (as favored by @rsalz) or should one rather be defensive and add
543 * more entropy than requested and/or from different sources?
545 * Currently, the user can select multiple entropy sources in the
546 * configure step, yet in practice only the first available source
547 * will be used. A more flexible solution has been requested, but
548 * currently it is not clear how this can be achieved without
549 * overengineering the problem. There are many parameters which
550 * could be taken into account when selecting the order and amount
551 * of input from the different entropy sources (trust, quality,
552 * possibility of blocking).
554 size_t rand_pool_acquire_entropy(RAND_POOL
*pool
)
556 # if defined(OPENSSL_RAND_SEED_NONE)
557 return rand_pool_entropy_available(pool
);
560 size_t entropy_available
= 0;
561 unsigned char *buffer
;
563 # if defined(OPENSSL_RAND_SEED_GETRANDOM)
566 /* Maximum allowed number of consecutive unsuccessful attempts */
569 bytes_needed
= rand_pool_bytes_needed(pool
, 1 /*entropy_factor*/);
570 while (bytes_needed
!= 0 && attempts
-- > 0) {
571 buffer
= rand_pool_add_begin(pool
, bytes_needed
);
572 bytes
= syscall_random(buffer
, bytes_needed
);
574 rand_pool_add_end(pool
, bytes
, 8 * bytes
);
575 bytes_needed
-= bytes
;
576 attempts
= 3; /* reset counter after successful attempt */
577 } else if (bytes
< 0 && errno
!= EINTR
) {
582 entropy_available
= rand_pool_entropy_available(pool
);
583 if (entropy_available
> 0)
584 return entropy_available
;
587 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
589 /* Not yet implemented. */
593 # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
594 if (wait_random_seeded()) {
597 bytes_needed
= rand_pool_bytes_needed(pool
, 1 /*entropy_factor*/);
598 for (i
= 0; bytes_needed
> 0 && i
< OSSL_NELEM(random_device_paths
);
601 /* Maximum number of consecutive unsuccessful attempts */
603 const int fd
= get_random_device(i
);
608 while (bytes_needed
!= 0 && attempts
-- > 0) {
609 buffer
= rand_pool_add_begin(pool
, bytes_needed
);
610 bytes
= read(fd
, buffer
, bytes_needed
);
613 rand_pool_add_end(pool
, bytes
, 8 * bytes
);
614 bytes_needed
-= bytes
;
615 attempts
= 3; /* reset counter on successful attempt */
616 } else if (bytes
< 0 && errno
!= EINTR
) {
620 if (bytes
< 0 || !keep_random_devices_open
)
621 close_random_device(i
);
623 bytes_needed
= rand_pool_bytes_needed(pool
, 1);
625 entropy_available
= rand_pool_entropy_available(pool
);
626 if (entropy_available
> 0)
627 return entropy_available
;
631 # if defined(OPENSSL_RAND_SEED_RDTSC)
632 entropy_available
= rand_acquire_entropy_from_tsc(pool
);
633 if (entropy_available
> 0)
634 return entropy_available
;
637 # if defined(OPENSSL_RAND_SEED_RDCPU)
638 entropy_available
= rand_acquire_entropy_from_cpu(pool
);
639 if (entropy_available
> 0)
640 return entropy_available
;
643 # if defined(OPENSSL_RAND_SEED_EGD)
644 bytes_needed
= rand_pool_bytes_needed(pool
, 1 /*entropy_factor*/);
645 if (bytes_needed
> 0) {
646 static const char *paths
[] = { DEVRANDOM_EGD
, NULL
};
649 for (i
= 0; paths
[i
] != NULL
; i
++) {
650 buffer
= rand_pool_add_begin(pool
, bytes_needed
);
651 if (buffer
!= NULL
) {
653 int num
= RAND_query_egd_bytes(paths
[i
],
654 buffer
, (int)bytes_needed
);
655 if (num
== (int)bytes_needed
)
656 bytes
= bytes_needed
;
658 rand_pool_add_end(pool
, bytes
, 8 * bytes
);
659 entropy_available
= rand_pool_entropy_available(pool
);
661 if (entropy_available
> 0)
662 return entropy_available
;
667 return rand_pool_entropy_available(pool
);
673 #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
674 || defined(__DJGPP__)
675 int rand_pool_add_nonce_data(RAND_POOL
*pool
)
679 CRYPTO_THREAD_ID tid
;
683 /* Erase the entire structure including any padding */
684 memset(&data
, 0, sizeof(data
));
687 * Add process id, thread id, and a high resolution timestamp to
688 * ensure that the nonce is unique with high probability for
689 * different process instances.
692 data
.tid
= CRYPTO_THREAD_get_current_id();
693 data
.time
= get_time_stamp();
695 return rand_pool_add(pool
, (unsigned char *)&data
, sizeof(data
), 0);
698 int rand_pool_add_additional_data(RAND_POOL
*pool
)
701 CRYPTO_THREAD_ID tid
;
705 /* Erase the entire structure including any padding */
706 memset(&data
, 0, sizeof(data
));
709 * Add some noise from the thread id and a high resolution timer.
710 * The thread id adds a little randomness if the drbg is accessed
711 * concurrently (which is the case for the <master> drbg).
713 data
.tid
= CRYPTO_THREAD_get_current_id();
714 data
.time
= get_timer_bits();
716 return rand_pool_add(pool
, (unsigned char *)&data
, sizeof(data
), 0);
721 * Get the current time with the highest possible resolution
723 * The time stamp is added to the nonce, so it is optimized for not repeating.
724 * The current time is ideal for this purpose, provided the computer's clock
727 static uint64_t get_time_stamp(void)
729 # if defined(OSSL_POSIX_TIMER_OKAY)
733 if (clock_gettime(CLOCK_REALTIME
, &ts
) == 0)
734 return TWO32TO64(ts
.tv_sec
, ts
.tv_nsec
);
737 # if defined(__unix__) \
738 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
742 if (gettimeofday(&tv
, NULL
) == 0)
743 return TWO32TO64(tv
.tv_sec
, tv
.tv_usec
);
750 * Get an arbitrary timer value of the highest possible resolution
752 * The timer value is added as random noise to the additional data,
753 * which is not considered a trusted entropy sourec, so any result
756 static uint64_t get_timer_bits(void)
758 uint64_t res
= OPENSSL_rdtsc();
763 # if defined(__sun) || defined(__hpux)
769 read_wall_time(&t
, TIMEBASE_SZ
);
770 return TWO32TO64(t
.tb_high
, t
.tb_low
);
772 # elif defined(OSSL_POSIX_TIMER_OKAY)
776 # ifdef CLOCK_BOOTTIME
777 # define CLOCK_TYPE CLOCK_BOOTTIME
778 # elif defined(_POSIX_MONOTONIC_CLOCK)
779 # define CLOCK_TYPE CLOCK_MONOTONIC
781 # define CLOCK_TYPE CLOCK_REALTIME
784 if (clock_gettime(CLOCK_TYPE
, &ts
) == 0)
785 return TWO32TO64(ts
.tv_sec
, ts
.tv_nsec
);
788 # if defined(__unix__) \
789 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
793 if (gettimeofday(&tv
, NULL
) == 0)
794 return TWO32TO64(tv
.tv_sec
, tv
.tv_usec
);
799 #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */