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"
19 # include <sys/syscall.h>
21 #if defined(__FreeBSD__)
22 # include <sys/types.h>
23 # include <sys/sysctl.h>
24 # include <sys/param.h>
26 #if defined(__OpenBSD__)
27 # include <sys/param.h>
29 #ifdef OPENSSL_SYS_UNIX
30 # include <sys/types.h>
32 # include <sys/time.h>
34 static uint64_t get_time_stamp(void);
35 static uint64_t get_timer_bits(void);
37 /* Macro to convert two thirty two bit values into a sixty four bit one */
38 # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
41 * Check for the existence and support of POSIX timers. The standard
42 * says that the _POSIX_TIMERS macro will have a positive value if they
45 * However, we want an additional constraint: that the timer support does
46 * not require an extra library dependency. Early versions of glibc
47 * require -lrt to be specified on the link line to access the timers,
48 * so this needs to be checked for.
50 * It is worse because some libraries define __GLIBC__ but don't
51 * support the version testing macro (e.g. uClibc). This means
52 * an extra check is needed.
54 * The final condition is:
55 * "have posix timers and either not glibc or glibc without -lrt"
57 * The nested #if sequences are required to avoid using a parameterised
58 * macro that might be undefined.
60 # undef OSSL_POSIX_TIMER_OKAY
61 # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
62 # if defined(__GLIBC__)
63 # if defined(__GLIBC_PREREQ)
64 # if __GLIBC_PREREQ(2, 17)
65 # define OSSL_POSIX_TIMER_OKAY
69 # define OSSL_POSIX_TIMER_OKAY
74 int syscall_random(void *buf, size_t buflen);
76 #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
77 !defined(OPENSSL_RAND_SEED_NONE)
78 # error "UEFI and VXWorks only support seeding NONE"
81 #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
82 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
83 || defined(OPENSSL_SYS_UEFI))
85 # if defined(OPENSSL_SYS_VOS)
87 # ifndef OPENSSL_RAND_SEED_OS
88 # error "Unsupported seeding method configured; must be os"
91 # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
92 # error "Unsupported HP-PA and IA32 at the same time."
94 # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
95 # error "Must have one of HP-PA or IA32"
99 * The following algorithm repeatedly samples the real-time clock (RTC) to
100 * generate a sequence of unpredictable data. The algorithm relies upon the
101 * uneven execution speed of the code (due to factors such as cache misses,
102 * interrupts, bus activity, and scheduling) and upon the rather large
103 * relative difference between the speed of the clock and the rate at which
104 * it can be read. If it is ported to an environment where execution speed
105 * is more constant or where the RTC ticks at a much slower rate, or the
106 * clock can be read with fewer instructions, it is likely that the results
107 * would be far more predictable. This should only be used for legacy
110 * As a precaution, we assume only 2 bits of entropy per byte.
112 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
119 # ifdef OPENSSL_SYS_VOS_HPPA
121 extern void s$sleep(long *_duration, short int *_code);
124 extern void s$sleep2(long long *_duration, short int *_code);
127 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
129 for (i = 0; i < bytes_needed; i++) {
131 * burn some cpu; hope for interrupts, cache collisions, bus
134 for (k = 0; k < 99; k++)
135 ts.tv_nsec = random();
137 # ifdef OPENSSL_SYS_VOS_HPPA
138 /* sleep for 1/1024 of a second (976 us). */
140 s$sleep(&duration, &code);
142 /* sleep for 1/65536 of a second (15 us). */
144 s$sleep2(&duration, &code);
147 /* Get wall clock time, take 8 bits. */
148 clock_gettime(CLOCK_REALTIME, &ts);
149 v = (unsigned char)(ts.tv_nsec & 0xFF);
150 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
152 return rand_pool_entropy_available(pool);
157 # if defined(OPENSSL_RAND_SEED_EGD) && \
158 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
159 # error "Seeding uses EGD but EGD is turned off or no device given"
162 # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
163 # error "Seeding uses urandom but DEVRANDOM is not configured"
166 # if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
167 # if __GLIBC_PREREQ(2, 25)
168 # define OPENSSL_HAVE_GETRANDOM
172 # if (defined(__FreeBSD__) && __FreeBSD_version >= 1200061)
173 # define OPENSSL_HAVE_GETRANDOM
176 # if defined(OPENSSL_HAVE_GETRANDOM)
177 # include <sys/random.h>
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(KERN_ARND)
194 * sysctl_random(): Use sysctl() to read a random number from the kernel
195 * Returns the size on success, 0 on failure.
197 static size_t sysctl_random(char *buf, size_t buflen)
204 * Old implementations returned longs, newer versions support variable
205 * sizes up to 256 byte. The code below would not work properly when
206 * the sysctl returns long and we want to request something not a multiple
207 * of longs, which should never be the case.
209 if (!ossl_assert(buflen % sizeof(long) == 0))
217 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
222 } while (buflen > 0);
229 * syscall_random(): Try to get random data using a system call
230 * returns the number of bytes returned in buf, or <= 0 on error.
232 int syscall_random(void *buf, size_t buflen)
234 # if defined(OPENSSL_HAVE_GETRANDOM)
235 return (int)getrandom(buf, buflen, 0);
238 # if defined(__linux) && defined(SYS_getrandom)
239 return (int)syscall(SYS_getrandom, buf, buflen, 0);
242 # if defined(__FreeBSD__) && defined(KERN_ARND)
243 return (int)sysctl_random(buf, buflen);
246 /* Supported since OpenBSD 5.6 */
247 # if defined(__OpenBSD__) && OpenBSD >= 201411
248 return getentropy(buf, buflen);
255 * Try the various seeding methods in turn, exit when successful.
257 * TODO(DRBG): If more than one entropy source is available, is it
258 * preferable to stop as soon as enough entropy has been collected
259 * (as favored by @rsalz) or should one rather be defensive and add
260 * more entropy than requested and/or from different sources?
262 * Currently, the user can select multiple entropy sources in the
263 * configure step, yet in practice only the first available source
264 * will be used. A more flexible solution has been requested, but
265 * currently it is not clear how this can be achieved without
266 * overengineering the problem. There are many parameters which
267 * could be taken into account when selecting the order and amount
268 * of input from the different entropy sources (trust, quality,
269 * possibility of blocking).
271 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
273 # ifdef OPENSSL_RAND_SEED_NONE
274 return rand_pool_entropy_available(pool);
277 size_t entropy_available = 0;
278 unsigned char *buffer;
280 # ifdef OPENSSL_RAND_SEED_GETRANDOM
281 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
282 buffer = rand_pool_add_begin(pool, bytes_needed);
283 if (buffer != NULL) {
286 if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
287 bytes = bytes_needed;
289 rand_pool_add_end(pool, bytes, 8 * bytes);
290 entropy_available = rand_pool_entropy_available(pool);
292 if (entropy_available > 0)
293 return entropy_available;
296 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
298 /* Not yet implemented. */
302 # ifdef OPENSSL_RAND_SEED_DEVRANDOM
303 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
304 if (bytes_needed > 0) {
305 static const char *paths[] = { DEVRANDOM, NULL };
309 for (i = 0; paths[i] != NULL; i++) {
310 if ((fp = fopen(paths[i], "rb")) == NULL)
313 buffer = rand_pool_add_begin(pool, bytes_needed);
314 if (buffer != NULL) {
316 if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
317 bytes = bytes_needed;
319 rand_pool_add_end(pool, bytes, 8 * bytes);
320 entropy_available = rand_pool_entropy_available(pool);
323 if (entropy_available > 0)
324 return entropy_available;
326 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
331 # ifdef OPENSSL_RAND_SEED_RDTSC
332 entropy_available = rand_acquire_entropy_from_tsc(pool);
333 if (entropy_available > 0)
334 return entropy_available;
337 # ifdef OPENSSL_RAND_SEED_RDCPU
338 entropy_available = rand_acquire_entropy_from_cpu(pool);
339 if (entropy_available > 0)
340 return entropy_available;
343 # ifdef OPENSSL_RAND_SEED_EGD
344 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
345 if (bytes_needed > 0) {
346 static const char *paths[] = { DEVRANDOM_EGD, NULL };
349 for (i = 0; paths[i] != NULL; i++) {
350 buffer = rand_pool_add_begin(pool, bytes_needed);
351 if (buffer != NULL) {
353 int num = RAND_query_egd_bytes(paths[i],
354 buffer, (int)bytes_needed);
355 if (num == (int)bytes_needed)
356 bytes = bytes_needed;
358 rand_pool_add_end(pool, bytes, 8 * bytes);
359 entropy_available = rand_pool_entropy_available(pool);
361 if (entropy_available > 0)
362 return entropy_available;
367 return rand_pool_entropy_available(pool);
373 #ifdef OPENSSL_SYS_UNIX
374 int rand_pool_add_nonce_data(RAND_POOL *pool)
378 CRYPTO_THREAD_ID tid;
383 * Add process id, thread id, and a high resolution timestamp to
384 * ensure that the nonce is unique whith high probability for
385 * different process instances.
388 data.tid = CRYPTO_THREAD_get_current_id();
389 data.time = get_time_stamp();
391 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
394 int rand_pool_add_additional_data(RAND_POOL *pool)
397 CRYPTO_THREAD_ID tid;
402 * Add some noise from the thread id and a high resolution timer.
403 * The thread id adds a little randomness if the drbg is accessed
404 * concurrently (which is the case for the <master> drbg).
406 data.tid = CRYPTO_THREAD_get_current_id();
407 data.time = get_timer_bits();
409 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
415 * Get the current time with the highest possible resolution
417 * The time stamp is added to the nonce, so it is optimized for not repeating.
418 * The current time is ideal for this purpose, provided the computer's clock
421 static uint64_t get_time_stamp(void)
423 # if defined(OSSL_POSIX_TIMER_OKAY)
427 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
428 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
431 # if defined(__unix__) \
432 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
436 if (gettimeofday(&tv, NULL) == 0)
437 return TWO32TO64(tv.tv_sec, tv.tv_usec);
444 * Get an arbitrary timer value of the highest possible resolution
446 * The timer value is added as random noise to the additional data,
447 * which is not considered a trusted entropy sourec, so any result
450 static uint64_t get_timer_bits(void)
452 uint64_t res = OPENSSL_rdtsc();
457 # if defined(__sun) || defined(__hpux)
463 read_wall_time(&t, TIMEBASE_SZ);
464 return TWO32TO64(t.tb_high, t.tb_low);
466 # elif defined(OSSL_POSIX_TIMER_OKAY)
470 # ifdef CLOCK_BOOTTIME
471 # define CLOCK_TYPE CLOCK_BOOTTIME
472 # elif defined(_POSIX_MONOTONIC_CLOCK)
473 # define CLOCK_TYPE CLOCK_MONOTONIC
475 # define CLOCK_TYPE CLOCK_REALTIME
478 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
479 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
482 # if defined(__unix__) \
483 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
487 if (gettimeofday(&tv, NULL) == 0)
488 return TWO32TO64(tv.tv_sec, tv.tv_usec);