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__) || defined(__NetBSD__)
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(__NetBSD__)) && 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 * On FreeBSD old implementations returned longs, newer versions support
205 * variable sizes up to 256 byte. The code below would not work properly
206 * when the sysctl returns long and we want to request something not a
207 * multiple of longs, which should never be the case.
209 if (!ossl_assert(buflen % sizeof(long) == 0))
213 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
214 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
215 * it returns a variable number of bytes with the current version supporting
217 * Just return an error on older NetBSD versions.
219 #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
228 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
233 } while (buflen > 0);
240 * syscall_random(): Try to get random data using a system call
241 * returns the number of bytes returned in buf, or <= 0 on error.
243 int syscall_random(void *buf, size_t buflen)
245 # if defined(OPENSSL_HAVE_GETRANDOM)
246 return (int)getrandom(buf, buflen, 0);
249 # if defined(__linux) && defined(SYS_getrandom)
250 return (int)syscall(SYS_getrandom, buf, buflen, 0);
253 # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
254 return (int)sysctl_random(buf, buflen);
257 /* Supported since OpenBSD 5.6 */
258 # if defined(__OpenBSD__) && OpenBSD >= 201411
259 return getentropy(buf, buflen);
266 * Try the various seeding methods in turn, exit when successful.
268 * TODO(DRBG): If more than one entropy source is available, is it
269 * preferable to stop as soon as enough entropy has been collected
270 * (as favored by @rsalz) or should one rather be defensive and add
271 * more entropy than requested and/or from different sources?
273 * Currently, the user can select multiple entropy sources in the
274 * configure step, yet in practice only the first available source
275 * will be used. A more flexible solution has been requested, but
276 * currently it is not clear how this can be achieved without
277 * overengineering the problem. There are many parameters which
278 * could be taken into account when selecting the order and amount
279 * of input from the different entropy sources (trust, quality,
280 * possibility of blocking).
282 size_t rand_pool_acquire_entropy(RAND_POOL *pool)
284 # ifdef OPENSSL_RAND_SEED_NONE
285 return rand_pool_entropy_available(pool);
288 size_t entropy_available = 0;
289 unsigned char *buffer;
291 # ifdef OPENSSL_RAND_SEED_GETRANDOM
292 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
293 buffer = rand_pool_add_begin(pool, bytes_needed);
294 if (buffer != NULL) {
297 if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
298 bytes = bytes_needed;
300 rand_pool_add_end(pool, bytes, 8 * bytes);
301 entropy_available = rand_pool_entropy_available(pool);
303 if (entropy_available > 0)
304 return entropy_available;
307 # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
309 /* Not yet implemented. */
313 # ifdef OPENSSL_RAND_SEED_DEVRANDOM
314 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
315 if (bytes_needed > 0) {
316 static const char *paths[] = { DEVRANDOM, NULL };
320 for (i = 0; paths[i] != NULL; i++) {
321 if ((fp = fopen(paths[i], "rb")) == NULL)
324 buffer = rand_pool_add_begin(pool, bytes_needed);
325 if (buffer != NULL) {
327 if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
328 bytes = bytes_needed;
330 rand_pool_add_end(pool, bytes, 8 * bytes);
331 entropy_available = rand_pool_entropy_available(pool);
334 if (entropy_available > 0)
335 return entropy_available;
337 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
342 # ifdef OPENSSL_RAND_SEED_RDTSC
343 entropy_available = rand_acquire_entropy_from_tsc(pool);
344 if (entropy_available > 0)
345 return entropy_available;
348 # ifdef OPENSSL_RAND_SEED_RDCPU
349 entropy_available = rand_acquire_entropy_from_cpu(pool);
350 if (entropy_available > 0)
351 return entropy_available;
354 # ifdef OPENSSL_RAND_SEED_EGD
355 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
356 if (bytes_needed > 0) {
357 static const char *paths[] = { DEVRANDOM_EGD, NULL };
360 for (i = 0; paths[i] != NULL; i++) {
361 buffer = rand_pool_add_begin(pool, bytes_needed);
362 if (buffer != NULL) {
364 int num = RAND_query_egd_bytes(paths[i],
365 buffer, (int)bytes_needed);
366 if (num == (int)bytes_needed)
367 bytes = bytes_needed;
369 rand_pool_add_end(pool, bytes, 8 * bytes);
370 entropy_available = rand_pool_entropy_available(pool);
372 if (entropy_available > 0)
373 return entropy_available;
378 return rand_pool_entropy_available(pool);
384 #ifdef OPENSSL_SYS_UNIX
385 int rand_pool_add_nonce_data(RAND_POOL *pool)
389 CRYPTO_THREAD_ID tid;
394 * Add process id, thread id, and a high resolution timestamp to
395 * ensure that the nonce is unique whith high probability for
396 * different process instances.
399 data.tid = CRYPTO_THREAD_get_current_id();
400 data.time = get_time_stamp();
402 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
405 int rand_pool_add_additional_data(RAND_POOL *pool)
408 CRYPTO_THREAD_ID tid;
413 * Add some noise from the thread id and a high resolution timer.
414 * The thread id adds a little randomness if the drbg is accessed
415 * concurrently (which is the case for the <master> drbg).
417 data.tid = CRYPTO_THREAD_get_current_id();
418 data.time = get_timer_bits();
420 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
426 * Get the current time with the highest possible resolution
428 * The time stamp is added to the nonce, so it is optimized for not repeating.
429 * The current time is ideal for this purpose, provided the computer's clock
432 static uint64_t get_time_stamp(void)
434 # if defined(OSSL_POSIX_TIMER_OKAY)
438 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
439 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
442 # if defined(__unix__) \
443 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
447 if (gettimeofday(&tv, NULL) == 0)
448 return TWO32TO64(tv.tv_sec, tv.tv_usec);
455 * Get an arbitrary timer value of the highest possible resolution
457 * The timer value is added as random noise to the additional data,
458 * which is not considered a trusted entropy sourec, so any result
461 static uint64_t get_timer_bits(void)
463 uint64_t res = OPENSSL_rdtsc();
468 # if defined(__sun) || defined(__hpux)
474 read_wall_time(&t, TIMEBASE_SZ);
475 return TWO32TO64(t.tb_high, t.tb_low);
477 # elif defined(OSSL_POSIX_TIMER_OKAY)
481 # ifdef CLOCK_BOOTTIME
482 # define CLOCK_TYPE CLOCK_BOOTTIME
483 # elif defined(_POSIX_MONOTONIC_CLOCK)
484 # define CLOCK_TYPE CLOCK_MONOTONIC
486 # define CLOCK_TYPE CLOCK_REALTIME
489 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
490 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
493 # if defined(__unix__) \
494 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
498 if (gettimeofday(&tv, NULL) == 0)
499 return TWO32TO64(tv.tv_sec, tv.tv_usec);