]> git.ipfire.org Git - thirdparty/openssl.git/blame - crypto/rand/rand_unix.c
Avoid overflowing FDSET when using select(2).
[thirdparty/openssl.git] / crypto / rand / rand_unix.c
CommitLineData
b1322259 1/*
0d664759 2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
0c61e299 3 *
0db63de9 4 * Licensed under the Apache License 2.0 (the "License"). You may not use
b1322259
RS
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
0c61e299 8 */
b1322259 9
a0e53000
AP
10#ifndef _GNU_SOURCE
11# define _GNU_SOURCE
12#endif
da0616cd 13#include "e_os.h"
07016a8a 14#include <stdio.h>
b39fc560 15#include "internal/cryptlib.h"
0c61e299 16#include <openssl/rand.h>
3a577750 17#include <openssl/crypto.h>
0c61e299 18#include "rand_lcl.h"
6decf943 19#include "internal/rand_int.h"
8389ec4b 20#include <stdio.h>
cf0891b8 21#include "internal/dso.h"
14879629 22#if defined(__linux)
38023b87 23# include <asm/unistd.h>
3a577750
P
24# include <sys/ipc.h>
25# include <sys/shm.h>
26# include <sys/utsname.h>
14879629 27#endif
1fa90bb3 28#if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
14879629
KR
29# include <sys/types.h>
30# include <sys/sysctl.h>
31# include <sys/param.h>
32#endif
8f576627 33#if defined(__OpenBSD__) || defined(__NetBSD__)
14879629
KR
34# include <sys/param.h>
35#endif
748eb991 36
61783db5
KT
37#if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
38 || defined(__DJGPP__)
5bc6bcf8 39# include <sys/types.h>
c7504aeb
P
40# include <sys/stat.h>
41# include <fcntl.h>
5bc6bcf8
DMSP
42# include <unistd.h>
43# include <sys/time.h>
44
45static uint64_t get_time_stamp(void);
46static uint64_t get_timer_bits(void);
47
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))
50
51/*
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
54 * are available.
55 *
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.
60 *
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.
64 *
65 * The final condition is:
66 * "have posix timers and either not glibc or glibc without -lrt"
67 *
68 * The nested #if sequences are required to avoid using a parameterised
69 * macro that might be undefined.
70 */
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
77# endif
78# endif
79# else
80# define OSSL_POSIX_TIMER_OKAY
81# endif
82# endif
748eb991 83#endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
0c61e299 84
d90e128b
DMSP
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
94#endif
95
61783db5
KT
96#if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
97# error "UEFI only supports seeding NONE"
5c8b7b4c
KT
98#endif
99
c16de9d8
DMSP
100#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
101 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
102 || defined(OPENSSL_SYS_UEFI))
0f113f3e
MC
103
104# if defined(OPENSSL_SYS_VOS)
105
8389ec4b
RS
106# ifndef OPENSSL_RAND_SEED_OS
107# error "Unsupported seeding method configured; must be os"
108# endif
109
110# if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
111# error "Unsupported HP-PA and IA32 at the same time."
112# endif
113# if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
114# error "Must have one of HP-PA or IA32"
115# endif
116
0f113f3e
MC
117/*
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
75e2c877
RS
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
127 * platforms.
0f113f3e 128 *
c16de9d8 129 * As a precaution, we assume only 2 bits of entropy per byte.
0f113f3e 130 */
6decf943 131size_t rand_pool_acquire_entropy(RAND_POOL *pool)
cc7399e7 132{
0f113f3e 133 short int code;
0f113f3e 134 int i, k;
c16de9d8 135 size_t bytes_needed;
0f113f3e
MC
136 struct timespec ts;
137 unsigned char v;
0f113f3e
MC
138# ifdef OPENSSL_SYS_VOS_HPPA
139 long duration;
140 extern void s$sleep(long *_duration, short int *_code);
141# else
0f113f3e
MC
142 long long duration;
143 extern void s$sleep2(long long *_duration, short int *_code);
8389ec4b 144# endif
0f113f3e 145
6ebb49f3 146 bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
c16de9d8
DMSP
147
148 for (i = 0; i < bytes_needed; i++) {
0f113f3e
MC
149 /*
150 * burn some cpu; hope for interrupts, cache collisions, bus
151 * interference, etc.
152 */
153 for (k = 0; k < 99; k++)
154 ts.tv_nsec = random();
155
156# ifdef OPENSSL_SYS_VOS_HPPA
157 /* sleep for 1/1024 of a second (976 us). */
158 duration = 1;
159 s$sleep(&duration, &code);
160# else
0f113f3e
MC
161 /* sleep for 1/65536 of a second (15 us). */
162 duration = 1;
163 s$sleep2(&duration, &code);
8389ec4b 164# endif
0f113f3e 165
8389ec4b 166 /* Get wall clock time, take 8 bits. */
0f113f3e 167 clock_gettime(CLOCK_REALTIME, &ts);
8389ec4b 168 v = (unsigned char)(ts.tv_nsec & 0xFF);
6decf943 169 rand_pool_add(pool, arg, &v, sizeof(v) , 2);
0f113f3e 170 }
6decf943 171 return rand_pool_entropy_available(pool);
cc7399e7 172}
8389ec4b 173
c7504aeb
P
174void rand_pool_cleanup(void)
175{
176}
177
178void rand_pool_keep_random_devices_open(int keep)
179{
180}
181
810ef917 182# else
8389ec4b
RS
183
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"
0f113f3e
MC
187# endif
188
8389ec4b
RS
189# if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
190# error "Seeding uses urandom but DEVRANDOM is not configured"
191# endif
0f113f3e 192
8389ec4b 193# if defined(OPENSSL_RAND_SEED_OS)
72960279 194# if !defined(DEVRANDOM)
8389ec4b 195# error "OS seeding requires DEVRANDOM to be configured"
0f113f3e 196# endif
14879629 197# define OPENSSL_RAND_SEED_GETRANDOM
72960279 198# define OPENSSL_RAND_SEED_DEVRANDOM
8389ec4b 199# endif
0f113f3e 200
8389ec4b
RS
201# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
202# error "librandom not (yet) supported"
203# endif
0f113f3e 204
8f576627 205# if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
14879629
KR
206/*
207 * sysctl_random(): Use sysctl() to read a random number from the kernel
9b5f1c8f 208 * Returns the number of bytes returned in buf on success, -1 on failure.
14879629 209 */
9b5f1c8f 210static ssize_t sysctl_random(char *buf, size_t buflen)
14879629
KR
211{
212 int mib[2];
213 size_t done = 0;
214 size_t len;
215
9b5f1c8f
DMSP
216 /*
217 * Note: sign conversion between size_t and ssize_t is safe even
218 * without a range check, see comment in syscall_random()
219 */
220
14879629 221 /*
8f576627
KR
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.
14879629 226 */
9b5f1c8f
DMSP
227 if (!ossl_assert(buflen % sizeof(long) == 0)) {
228 errno = EINVAL;
229 return -1;
230 }
14879629 231
8f576627
KR
232 /*
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
236 * up to 256 bytes.
237 * Just return an error on older NetBSD versions.
238 */
239#if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
9b5f1c8f
DMSP
240 errno = ENOSYS;
241 return -1;
8f576627
KR
242#endif
243
14879629
KR
244 mib[0] = CTL_KERN;
245 mib[1] = KERN_ARND;
246
247 do {
248 len = buflen;
249 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
9b5f1c8f 250 return done > 0 ? done : -1;
14879629
KR
251 done += len;
252 buf += len;
253 buflen -= len;
254 } while (buflen > 0);
255
256 return done;
257}
258# endif
259
d90e128b 260# if defined(OPENSSL_RAND_SEED_GETRANDOM)
24d932ec
BE
261
262# if defined(__linux) && !defined(__NR_getrandom)
263# if defined(__arm__) && defined(__NR_SYSCALL_BASE)
264# define __NR_getrandom (__NR_SYSCALL_BASE+384)
038b381e
BE
265# elif defined(__i386__)
266# define __NR_getrandom 355
267# elif defined(__x86_64__) && !defined(__ILP32__)
268# define __NR_getrandom 318
24d932ec
BE
269# endif
270# endif
271
14879629
KR
272/*
273 * syscall_random(): Try to get random data using a system call
9b5f1c8f 274 * returns the number of bytes returned in buf, or < 0 on error.
14879629 275 */
9b5f1c8f 276static ssize_t syscall_random(void *buf, size_t buflen)
14879629 277{
9b5f1c8f
DMSP
278 /*
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
281 *
3064b551 282 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
9b5f1c8f
DMSP
283 *
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.
286 */
287
cf0891b8
KR
288 /*
289 * Do runtime detection to find getentropy().
290 *
cf0891b8
KR
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)
297 */
8d58f017 298# if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
9b5f1c8f 299 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
913cebc8
AP
300
301 if (getentropy != NULL)
9b5f1c8f 302 return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
57ca171a 303# elif !defined(FIPS_MODE)
913cebc8
AP
304 union {
305 void *p;
306 int (*f)(void *buffer, size_t length);
307 } p_getentropy;
308
309 /*
310 * We could cache the result of the lookup, but we normally don't
311 * call this function often.
312 */
46ceca3c 313 ERR_set_mark();
cf0891b8 314 p_getentropy.p = DSO_global_lookup("getentropy");
46ceca3c 315 ERR_pop_to_mark();
cf0891b8 316 if (p_getentropy.p != NULL)
9b5f1c8f 317 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
913cebc8 318# endif
cf0891b8 319
cf0891b8 320 /* Linux supports this since version 3.17 */
38023b87
BE
321# if defined(__linux) && defined(__NR_getrandom)
322 return syscall(__NR_getrandom, buf, buflen, 0);
9b5f1c8f
DMSP
323# elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
324 return sysctl_random(buf, buflen);
325# else
326 errno = ENOSYS;
14879629 327 return -1;
9b5f1c8f 328# endif
14879629 329}
d90e128b 330# endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
14879629 331
d90e128b 332# if defined(OPENSSL_RAND_SEED_DEVRANDOM)
c7504aeb
P
333static const char *random_device_paths[] = { DEVRANDOM };
334static struct random_device {
335 int fd;
336 dev_t dev;
337 ino_t ino;
338 mode_t mode;
339 dev_t rdev;
340} random_devices[OSSL_NELEM(random_device_paths)];
341static int keep_random_devices_open = 1;
342
3a577750
P
343# if defined(__linux) && defined(DEVRANDOM_WAIT)
344static void *shm_addr;
345
346# if !defined(FIPS_MODE)
347static void cleanup_shm(void)
348{
349 shmdt(shm_addr);
350}
351# endif
352
353/*
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.
358 */
359static int wait_random_seeded(void)
360{
361 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
362 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
363 int kernel[2];
364 int shm_id, fd, r;
365 char c, *p;
366 struct utsname un;
367 fd_set fds;
368
369 if (!seeded) {
370 /* See if anthing has created the global seeded indication */
371 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
372 /*
373 * Check the kernel's version and fail if it is too recent.
374 *
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.
380 */
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])) {
388 return 0;
389 }
390 }
391 /* Open /dev/random and wait for it to be readable */
392 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
e1f8584d 393 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
3a577750
P
394 FD_ZERO(&fds);
395 FD_SET(fd, &fds);
396 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
397 && errno == EINTR);
398 } else {
399 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
400 }
401 close(fd);
402 if (r == 1) {
403 seeded = 1;
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);
407 }
408 }
409 }
410 if (shm_id != -1) {
411 seeded = 1;
412 /*
413 * Map the shared memory to prevent its premature destruction.
414 * If this call fails, it isn't a big problem.
415 */
416 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
417# ifndef FIPS_MODE
418 /* TODO 3.0: The FIPS provider doesn't have OPENSSL_atexit */
419 if (shm_addr != (void *)-1)
420 OPENSSL_atexit(&cleanup_shm);
421# endif
422 }
423 }
424 return seeded;
425}
426# else /* defined __linux */
427static int wait_random_seeded(void)
428{
429 return 1;
430}
431# endif
432
c7504aeb
P
433/*
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
438 * another file.
439 */
440static int check_random_device(struct random_device * rd)
441{
442 struct stat st;
443
444 return rd->fd != -1
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;
450}
451
452/*
453 * Open a random device if required and return its file descriptor or -1 on error
454 */
455static int get_random_device(size_t n)
456{
457 struct stat st;
458 struct random_device * rd = &random_devices[n];
459
460 /* reuse existing file descriptor if it is (still) valid */
461 if (check_random_device(rd))
462 return rd->fd;
463
464 /* open the random device ... */
465 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
466 return rd->fd;
467
468 /* ... and cache its relevant stat(2) data */
469 if (fstat(rd->fd, &st) != -1) {
470 rd->dev = st.st_dev;
471 rd->ino = st.st_ino;
472 rd->mode = st.st_mode;
473 rd->rdev = st.st_rdev;
474 } else {
475 close(rd->fd);
476 rd->fd = -1;
477 }
478
479 return rd->fd;
480}
481
482/*
483 * Close a random device making sure it is a random device
484 */
485static void close_random_device(size_t n)
486{
487 struct random_device * rd = &random_devices[n];
488
489 if (check_random_device(rd))
490 close(rd->fd);
491 rd->fd = -1;
492}
493
c7504aeb
P
494int rand_pool_init(void)
495{
496 size_t i;
497
498 for (i = 0; i < OSSL_NELEM(random_devices); i++)
499 random_devices[i].fd = -1;
8cfc1971 500
c7504aeb
P
501 return 1;
502}
503
504void rand_pool_cleanup(void)
505{
506 size_t i;
507
508 for (i = 0; i < OSSL_NELEM(random_devices); i++)
509 close_random_device(i);
510}
511
512void rand_pool_keep_random_devices_open(int keep)
513{
8cfc1971 514 if (!keep)
c7504aeb 515 rand_pool_cleanup();
8cfc1971 516
c7504aeb
P
517 keep_random_devices_open = keep;
518}
519
d90e128b 520# else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
c7504aeb
P
521
522int rand_pool_init(void)
523{
524 return 1;
525}
526
527void rand_pool_cleanup(void)
528{
529}
530
531void rand_pool_keep_random_devices_open(int keep)
532{
533}
534
d90e128b 535# endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
c7504aeb 536
75e2c877 537/*
c16de9d8
DMSP
538 * Try the various seeding methods in turn, exit when successful.
539 *
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?
544 *
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).
75e2c877 553 */
6decf943 554size_t rand_pool_acquire_entropy(RAND_POOL *pool)
8389ec4b 555{
d90e128b 556# if defined(OPENSSL_RAND_SEED_NONE)
6decf943 557 return rand_pool_entropy_available(pool);
8389ec4b 558# else
c16de9d8
DMSP
559 size_t bytes_needed;
560 size_t entropy_available = 0;
561 unsigned char *buffer;
0f113f3e 562
d90e128b 563# if defined(OPENSSL_RAND_SEED_GETRANDOM)
630ce41e
DMSP
564 {
565 ssize_t bytes;
566 /* Maximum allowed number of consecutive unsuccessful attempts */
567 int attempts = 3;
568
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);
573 if (bytes > 0) {
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) {
578 break;
579 }
580 }
75e2c877 581 }
630ce41e 582 entropy_available = rand_pool_entropy_available(pool);
c16de9d8
DMSP
583 if (entropy_available > 0)
584 return entropy_available;
0f113f3e
MC
585# endif
586
75e2c877 587# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
8389ec4b 588 {
75e2c877 589 /* Not yet implemented. */
0f113f3e 590 }
8389ec4b 591# endif
0f113f3e 592
d90e128b 593# if defined(OPENSSL_RAND_SEED_DEVRANDOM)
3a577750 594 if (wait_random_seeded()) {
c7504aeb 595 size_t i;
0f113f3e 596
3a577750
P
597 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
598 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
599 i++) {
cca99621 600 ssize_t bytes = 0;
3a577750 601 /* Maximum number of consecutive unsuccessful attempts */
cca99621 602 int attempts = 3;
c7504aeb
P
603 const int fd = get_random_device(i);
604
605 if (fd == -1)
8389ec4b 606 continue;
c16de9d8 607
cca99621
DMSP
608 while (bytes_needed != 0 && attempts-- > 0) {
609 buffer = rand_pool_add_begin(pool, bytes_needed);
610 bytes = read(fd, buffer, bytes_needed);
c7504aeb 611
cca99621
DMSP
612 if (bytes > 0) {
613 rand_pool_add_end(pool, bytes, 8 * bytes);
614 bytes_needed -= bytes;
3a577750 615 attempts = 3; /* reset counter on successful attempt */
cca99621
DMSP
616 } else if (bytes < 0 && errno != EINTR) {
617 break;
618 }
8389ec4b 619 }
cca99621 620 if (bytes < 0 || !keep_random_devices_open)
c7504aeb 621 close_random_device(i);
c16de9d8 622
3a577750 623 bytes_needed = rand_pool_bytes_needed(pool, 1);
8389ec4b 624 }
c7504aeb
P
625 entropy_available = rand_pool_entropy_available(pool);
626 if (entropy_available > 0)
627 return entropy_available;
0f113f3e 628 }
8389ec4b 629# endif
0f113f3e 630
d90e128b 631# if defined(OPENSSL_RAND_SEED_RDTSC)
c16de9d8
DMSP
632 entropy_available = rand_acquire_entropy_from_tsc(pool);
633 if (entropy_available > 0)
634 return entropy_available;
75e2c877
RS
635# endif
636
d90e128b 637# if defined(OPENSSL_RAND_SEED_RDCPU)
c16de9d8
DMSP
638 entropy_available = rand_acquire_entropy_from_cpu(pool);
639 if (entropy_available > 0)
640 return entropy_available;
75e2c877
RS
641# endif
642
d90e128b 643# if defined(OPENSSL_RAND_SEED_EGD)
6ebb49f3 644 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
c16de9d8 645 if (bytes_needed > 0) {
75e2c877
RS
646 static const char *paths[] = { DEVRANDOM_EGD, NULL };
647 int i;
0f113f3e 648
75e2c877 649 for (i = 0; paths[i] != NULL; i++) {
6decf943 650 buffer = rand_pool_add_begin(pool, bytes_needed);
c16de9d8
DMSP
651 if (buffer != NULL) {
652 size_t bytes = 0;
653 int num = RAND_query_egd_bytes(paths[i],
654 buffer, (int)bytes_needed);
655 if (num == (int)bytes_needed)
656 bytes = bytes_needed;
657
8e2bec9b
RL
658 rand_pool_add_end(pool, bytes, 8 * bytes);
659 entropy_available = rand_pool_entropy_available(pool);
75e2c877 660 }
c16de9d8
DMSP
661 if (entropy_available > 0)
662 return entropy_available;
8389ec4b
RS
663 }
664 }
665# endif
0f113f3e 666
6decf943 667 return rand_pool_entropy_available(pool);
0f113f3e 668# endif
0c61e299 669}
8389ec4b 670# endif
5bc6bcf8
DMSP
671#endif
672
61783db5
KT
673#if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
674 || defined(__DJGPP__)
5bc6bcf8
DMSP
675int rand_pool_add_nonce_data(RAND_POOL *pool)
676{
677 struct {
678 pid_t pid;
679 CRYPTO_THREAD_ID tid;
680 uint64_t time;
678d2681
P
681 } data;
682
683 /* Erase the entire structure including any padding */
684 memset(&data, 0, sizeof(data));
5bc6bcf8
DMSP
685
686 /*
687 * Add process id, thread id, and a high resolution timestamp to
8bf36651 688 * ensure that the nonce is unique with high probability for
5bc6bcf8
DMSP
689 * different process instances.
690 */
691 data.pid = getpid();
692 data.tid = CRYPTO_THREAD_get_current_id();
693 data.time = get_time_stamp();
694
695 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
696}
697
698int rand_pool_add_additional_data(RAND_POOL *pool)
699{
700 struct {
701 CRYPTO_THREAD_ID tid;
702 uint64_t time;
678d2681
P
703 } data;
704
705 /* Erase the entire structure including any padding */
706 memset(&data, 0, sizeof(data));
5bc6bcf8
DMSP
707
708 /*
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).
712 */
713 data.tid = CRYPTO_THREAD_get_current_id();
714 data.time = get_timer_bits();
715
716 return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
717}
718
719
5bc6bcf8
DMSP
720/*
721 * Get the current time with the highest possible resolution
722 *
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
725 * is synchronized.
726 */
727static uint64_t get_time_stamp(void)
728{
729# if defined(OSSL_POSIX_TIMER_OKAY)
730 {
731 struct timespec ts;
732
733 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
734 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
735 }
736# endif
737# if defined(__unix__) \
738 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
739 {
740 struct timeval tv;
741
742 if (gettimeofday(&tv, NULL) == 0)
743 return TWO32TO64(tv.tv_sec, tv.tv_usec);
744 }
745# endif
746 return time(NULL);
747}
748
749/*
750 * Get an arbitrary timer value of the highest possible resolution
751 *
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
754 * is acceptable.
755 */
756static uint64_t get_timer_bits(void)
757{
758 uint64_t res = OPENSSL_rdtsc();
759
760 if (res != 0)
761 return res;
762
763# if defined(__sun) || defined(__hpux)
764 return gethrtime();
765# elif defined(_AIX)
766 {
767 timebasestruct_t t;
768
769 read_wall_time(&t, TIMEBASE_SZ);
770 return TWO32TO64(t.tb_high, t.tb_low);
771 }
772# elif defined(OSSL_POSIX_TIMER_OKAY)
773 {
774 struct timespec ts;
775
776# ifdef CLOCK_BOOTTIME
777# define CLOCK_TYPE CLOCK_BOOTTIME
778# elif defined(_POSIX_MONOTONIC_CLOCK)
779# define CLOCK_TYPE CLOCK_MONOTONIC
780# else
781# define CLOCK_TYPE CLOCK_REALTIME
782# endif
783
784 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
785 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
786 }
787# endif
788# if defined(__unix__) \
789 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
790 {
791 struct timeval tv;
0c61e299 792
5bc6bcf8
DMSP
793 if (gettimeofday(&tv, NULL) == 0)
794 return TWO32TO64(tv.tv_sec, tv.tv_usec);
795 }
796# endif
797 return time(NULL);
798}
748eb991 799#endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */