]> git.ipfire.org Git - thirdparty/openssl.git/blame - providers/implementations/rands/seeding/rand_unix.c
fix some code with obvious wrong coding style
[thirdparty/openssl.git] / providers / implementations / rands / seeding / rand_unix.c
CommitLineData
b1322259 1/*
8020d79b 2 * Copyright 1995-2021 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
e1c5b1f6 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>
08edd447 18#include "crypto/rand_pool.h"
25f2138b 19#include "crypto/rand.h"
8389ec4b 20#include <stdio.h>
cf0891b8 21#include "internal/dso.h"
bcdea3ba 22#include "prov/seeding.h"
01036e2a 23
41ffd2ab
BE
24#ifdef __linux
25# include <sys/syscall.h>
26# ifdef DEVRANDOM_WAIT
27# include <sys/shm.h>
28# include <sys/utsname.h>
29# endif
14879629 30#endif
e2e4b784 31#if (defined(__FreeBSD__) || defined(__NetBSD__)) && !defined(OPENSSL_SYS_UEFI)
14879629
KR
32# include <sys/types.h>
33# include <sys/sysctl.h>
34# include <sys/param.h>
35#endif
e2e4b784 36#if defined(__OpenBSD__)
14879629
KR
37# include <sys/param.h>
38#endif
0bb450fe
DC
39#if defined(__DragonFly__)
40# include <sys/param.h>
41# include <sys/random.h>
42#endif
45554b5c 43
61783db5
KT
44#if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
45 || defined(__DJGPP__)
5bc6bcf8 46# include <sys/types.h>
c7504aeb
P
47# include <sys/stat.h>
48# include <fcntl.h>
5bc6bcf8
DMSP
49# include <unistd.h>
50# include <sys/time.h>
51
52static uint64_t get_time_stamp(void);
53static uint64_t get_timer_bits(void);
54
55/* Macro to convert two thirty two bit values into a sixty four bit one */
56# define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
57
58/*
59 * Check for the existence and support of POSIX timers. The standard
60 * says that the _POSIX_TIMERS macro will have a positive value if they
61 * are available.
62 *
63 * However, we want an additional constraint: that the timer support does
64 * not require an extra library dependency. Early versions of glibc
65 * require -lrt to be specified on the link line to access the timers,
66 * so this needs to be checked for.
67 *
68 * It is worse because some libraries define __GLIBC__ but don't
69 * support the version testing macro (e.g. uClibc). This means
70 * an extra check is needed.
71 *
72 * The final condition is:
73 * "have posix timers and either not glibc or glibc without -lrt"
74 *
75 * The nested #if sequences are required to avoid using a parameterised
76 * macro that might be undefined.
77 */
78# undef OSSL_POSIX_TIMER_OKAY
907720f0
LN
79/* On some systems, _POSIX_TIMERS is defined but empty.
80 * Subtracting by 0 when comparing avoids an error in this case. */
81# if defined(_POSIX_TIMERS) && _POSIX_TIMERS -0 > 0
5bc6bcf8
DMSP
82# if defined(__GLIBC__)
83# if defined(__GLIBC_PREREQ)
84# if __GLIBC_PREREQ(2, 17)
85# define OSSL_POSIX_TIMER_OKAY
86# endif
87# endif
88# else
89# define OSSL_POSIX_TIMER_OKAY
90# endif
91# endif
2a7e6ed8
DMSP
92#endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
93 || defined(__DJGPP__) */
0c61e299 94
d90e128b
DMSP
95#if defined(OPENSSL_RAND_SEED_NONE)
96/* none means none. this simplifies the following logic */
97# undef OPENSSL_RAND_SEED_OS
98# undef OPENSSL_RAND_SEED_GETRANDOM
99# undef OPENSSL_RAND_SEED_LIBRANDOM
100# undef OPENSSL_RAND_SEED_DEVRANDOM
101# undef OPENSSL_RAND_SEED_RDTSC
102# undef OPENSSL_RAND_SEED_RDCPU
103# undef OPENSSL_RAND_SEED_EGD
104#endif
105
61783db5
KT
106#if defined(OPENSSL_SYS_UEFI) && !defined(OPENSSL_RAND_SEED_NONE)
107# error "UEFI only supports seeding NONE"
5c8b7b4c
KT
108#endif
109
c16de9d8
DMSP
110#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
111 || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
112 || defined(OPENSSL_SYS_UEFI))
0f113f3e
MC
113
114# if defined(OPENSSL_SYS_VOS)
115
8389ec4b
RS
116# ifndef OPENSSL_RAND_SEED_OS
117# error "Unsupported seeding method configured; must be os"
118# endif
119
120# if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
121# error "Unsupported HP-PA and IA32 at the same time."
122# endif
123# if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
124# error "Must have one of HP-PA or IA32"
125# endif
126
0f113f3e
MC
127/*
128 * The following algorithm repeatedly samples the real-time clock (RTC) to
129 * generate a sequence of unpredictable data. The algorithm relies upon the
130 * uneven execution speed of the code (due to factors such as cache misses,
131 * interrupts, bus activity, and scheduling) and upon the rather large
132 * relative difference between the speed of the clock and the rate at which
75e2c877
RS
133 * it can be read. If it is ported to an environment where execution speed
134 * is more constant or where the RTC ticks at a much slower rate, or the
135 * clock can be read with fewer instructions, it is likely that the results
136 * would be far more predictable. This should only be used for legacy
137 * platforms.
0f113f3e 138 *
c16de9d8 139 * As a precaution, we assume only 2 bits of entropy per byte.
0f113f3e 140 */
1dc188ba 141size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
cc7399e7 142{
0f113f3e 143 short int code;
0f113f3e 144 int i, k;
c16de9d8 145 size_t bytes_needed;
0f113f3e
MC
146 struct timespec ts;
147 unsigned char v;
0f113f3e
MC
148# ifdef OPENSSL_SYS_VOS_HPPA
149 long duration;
150 extern void s$sleep(long *_duration, short int *_code);
151# else
0f113f3e
MC
152 long long duration;
153 extern void s$sleep2(long long *_duration, short int *_code);
8389ec4b 154# endif
0f113f3e 155
1335ca4b 156 bytes_needed = ossl_rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
c16de9d8
DMSP
157
158 for (i = 0; i < bytes_needed; i++) {
0f113f3e
MC
159 /*
160 * burn some cpu; hope for interrupts, cache collisions, bus
161 * interference, etc.
162 */
163 for (k = 0; k < 99; k++)
164 ts.tv_nsec = random();
165
166# ifdef OPENSSL_SYS_VOS_HPPA
167 /* sleep for 1/1024 of a second (976 us). */
168 duration = 1;
169 s$sleep(&duration, &code);
170# else
0f113f3e
MC
171 /* sleep for 1/65536 of a second (15 us). */
172 duration = 1;
173 s$sleep2(&duration, &code);
8389ec4b 174# endif
0f113f3e 175
8389ec4b 176 /* Get wall clock time, take 8 bits. */
0f113f3e 177 clock_gettime(CLOCK_REALTIME, &ts);
8389ec4b 178 v = (unsigned char)(ts.tv_nsec & 0xFF);
1287dabd 179 ossl_rand_pool_add(pool, arg, &v, sizeof(v), 2);
0f113f3e 180 }
1335ca4b 181 return ossl_rand_pool_entropy_available(pool);
cc7399e7 182}
8389ec4b 183
1335ca4b 184void ossl_rand_pool_cleanup(void)
c7504aeb
P
185{
186}
187
1335ca4b 188void ossl_rand_pool_keep_random_devices_open(int keep)
c7504aeb
P
189{
190}
191
810ef917 192# else
8389ec4b
RS
193
194# if defined(OPENSSL_RAND_SEED_EGD) && \
195 (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
196# error "Seeding uses EGD but EGD is turned off or no device given"
0f113f3e
MC
197# endif
198
8389ec4b
RS
199# if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
200# error "Seeding uses urandom but DEVRANDOM is not configured"
201# endif
0f113f3e 202
8389ec4b 203# if defined(OPENSSL_RAND_SEED_OS)
72960279 204# if !defined(DEVRANDOM)
8389ec4b 205# error "OS seeding requires DEVRANDOM to be configured"
0f113f3e 206# endif
14879629 207# define OPENSSL_RAND_SEED_GETRANDOM
72960279 208# define OPENSSL_RAND_SEED_DEVRANDOM
8389ec4b 209# endif
0f113f3e 210
8389ec4b
RS
211# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
212# error "librandom not (yet) supported"
213# endif
0f113f3e 214
8f576627 215# if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
14879629
KR
216/*
217 * sysctl_random(): Use sysctl() to read a random number from the kernel
9b5f1c8f 218 * Returns the number of bytes returned in buf on success, -1 on failure.
14879629 219 */
9b5f1c8f 220static ssize_t sysctl_random(char *buf, size_t buflen)
14879629
KR
221{
222 int mib[2];
223 size_t done = 0;
224 size_t len;
225
9b5f1c8f
DMSP
226 /*
227 * Note: sign conversion between size_t and ssize_t is safe even
228 * without a range check, see comment in syscall_random()
229 */
230
14879629 231 /*
8f576627
KR
232 * On FreeBSD old implementations returned longs, newer versions support
233 * variable sizes up to 256 byte. The code below would not work properly
234 * when the sysctl returns long and we want to request something not a
235 * multiple of longs, which should never be the case.
14879629 236 */
0c27ce73 237#if defined(__FreeBSD__)
9b5f1c8f
DMSP
238 if (!ossl_assert(buflen % sizeof(long) == 0)) {
239 errno = EINVAL;
240 return -1;
241 }
0c27ce73 242#endif
14879629 243
8f576627
KR
244 /*
245 * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
246 * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
247 * it returns a variable number of bytes with the current version supporting
248 * up to 256 bytes.
249 * Just return an error on older NetBSD versions.
250 */
251#if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
9b5f1c8f
DMSP
252 errno = ENOSYS;
253 return -1;
8f576627
KR
254#endif
255
14879629
KR
256 mib[0] = CTL_KERN;
257 mib[1] = KERN_ARND;
258
259 do {
7421f085 260 len = buflen > 256 ? 256 : buflen;
14879629 261 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
9b5f1c8f 262 return done > 0 ? done : -1;
14879629
KR
263 done += len;
264 buf += len;
265 buflen -= len;
266 } while (buflen > 0);
267
268 return done;
269}
270# endif
271
d90e128b 272# if defined(OPENSSL_RAND_SEED_GETRANDOM)
24d932ec
BE
273
274# if defined(__linux) && !defined(__NR_getrandom)
4dcb150e 275# if defined(__arm__)
24d932ec 276# define __NR_getrandom (__NR_SYSCALL_BASE+384)
038b381e
BE
277# elif defined(__i386__)
278# define __NR_getrandom 355
4dcb150e
KR
279# elif defined(__x86_64__)
280# if defined(__ILP32__)
281# define __NR_getrandom (__X32_SYSCALL_BIT + 318)
282# else
283# define __NR_getrandom 318
284# endif
285# elif defined(__xtensa__)
286# define __NR_getrandom 338
287# elif defined(__s390__) || defined(__s390x__)
288# define __NR_getrandom 349
289# elif defined(__bfin__)
290# define __NR_getrandom 389
291# elif defined(__powerpc__)
292# define __NR_getrandom 359
293# elif defined(__mips__) || defined(__mips64)
294# if _MIPS_SIM == _MIPS_SIM_ABI32
295# define __NR_getrandom (__NR_Linux + 353)
296# elif _MIPS_SIM == _MIPS_SIM_ABI64
297# define __NR_getrandom (__NR_Linux + 313)
298# elif _MIPS_SIM == _MIPS_SIM_NABI32
299# define __NR_getrandom (__NR_Linux + 317)
300# endif
301# elif defined(__hppa__)
302# define __NR_getrandom (__NR_Linux + 339)
303# elif defined(__sparc__)
304# define __NR_getrandom 347
305# elif defined(__ia64__)
306# define __NR_getrandom 1339
307# elif defined(__alpha__)
308# define __NR_getrandom 511
309# elif defined(__sh__)
310# if defined(__SH5__)
311# define __NR_getrandom 373
312# else
313# define __NR_getrandom 384
314# endif
315# elif defined(__avr32__)
316# define __NR_getrandom 317
317# elif defined(__microblaze__)
318# define __NR_getrandom 385
319# elif defined(__m68k__)
320# define __NR_getrandom 352
321# elif defined(__cris__)
322# define __NR_getrandom 356
323# elif defined(__aarch64__)
324# define __NR_getrandom 278
325# else /* generic */
326# define __NR_getrandom 278
24d932ec
BE
327# endif
328# endif
329
14879629
KR
330/*
331 * syscall_random(): Try to get random data using a system call
9b5f1c8f 332 * returns the number of bytes returned in buf, or < 0 on error.
14879629 333 */
9b5f1c8f 334static ssize_t syscall_random(void *buf, size_t buflen)
14879629 335{
9b5f1c8f
DMSP
336 /*
337 * Note: 'buflen' equals the size of the buffer which is used by the
338 * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
339 *
3064b551 340 * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
9b5f1c8f
DMSP
341 *
342 * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
343 * between size_t and ssize_t is safe even without a range check.
344 */
345
cf0891b8
KR
346 /*
347 * Do runtime detection to find getentropy().
348 *
cf0891b8
KR
349 * Known OSs that should support this:
350 * - Darwin since 16 (OSX 10.12, IOS 10.0).
351 * - Solaris since 11.3
352 * - OpenBSD since 5.6
353 * - Linux since 3.17 with glibc 2.25
354 * - FreeBSD since 12.0 (1200061)
8e596a93
YI
355 *
356 * Note: Sometimes getentropy() can be provided but not implemented
357 * internally. So we need to check errno for ENOSYS
cf0891b8 358 */
ef2a44eb 359# if !defined(__DragonFly__) && !defined(__NetBSD__)
0bb450fe 360# if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
9b5f1c8f 361 extern int getentropy(void *buffer, size_t length) __attribute__((weak));
913cebc8 362
8e596a93
YI
363 if (getentropy != NULL) {
364 if (getentropy(buf, buflen) == 0)
365 return (ssize_t)buflen;
366 if (errno != ENOSYS)
367 return -1;
368 }
c023d98d 369# elif defined(OPENSSL_APPLE_CRYPTO_RANDOM)
f0b9e75e
DC
370
371 if (CCRandomGenerateBytes(buf, buflen) == kCCSuccess)
372 return (ssize_t)buflen;
373
374 return -1;
87994aa8 375# else
913cebc8
AP
376 union {
377 void *p;
378 int (*f)(void *buffer, size_t length);
379 } p_getentropy;
380
381 /*
382 * We could cache the result of the lookup, but we normally don't
383 * call this function often.
384 */
46ceca3c 385 ERR_set_mark();
cf0891b8 386 p_getentropy.p = DSO_global_lookup("getentropy");
46ceca3c 387 ERR_pop_to_mark();
cf0891b8 388 if (p_getentropy.p != NULL)
9b5f1c8f 389 return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
0bb450fe
DC
390# endif
391# endif /* !__DragonFly__ */
cf0891b8 392
cf0891b8 393 /* Linux supports this since version 3.17 */
38023b87
BE
394# if defined(__linux) && defined(__NR_getrandom)
395 return syscall(__NR_getrandom, buf, buflen, 0);
9b5f1c8f
DMSP
396# elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
397 return sysctl_random(buf, buflen);
ef2a44eb
DC
398# elif (defined(__DragonFly__) && __DragonFly_version >= 500700) \
399 || (defined(__NetBSD__) && __NetBSD_Version >= 1000000000)
0bb450fe 400 return getrandom(buf, buflen, 0);
9b5f1c8f
DMSP
401# else
402 errno = ENOSYS;
14879629 403 return -1;
9b5f1c8f 404# endif
14879629 405}
d90e128b 406# endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
14879629 407
d90e128b 408# if defined(OPENSSL_RAND_SEED_DEVRANDOM)
c7504aeb
P
409static const char *random_device_paths[] = { DEVRANDOM };
410static struct random_device {
411 int fd;
412 dev_t dev;
413 ino_t ino;
414 mode_t mode;
415 dev_t rdev;
416} random_devices[OSSL_NELEM(random_device_paths)];
417static int keep_random_devices_open = 1;
418
ddec332f
BE
419# if defined(__linux) && defined(DEVRANDOM_WAIT) \
420 && defined(OPENSSL_RAND_SEED_GETRANDOM)
3a577750
P
421static void *shm_addr;
422
3a577750
P
423static void cleanup_shm(void)
424{
425 shmdt(shm_addr);
426}
3a577750
P
427
428/*
429 * Ensure that the system randomness source has been adequately seeded.
430 * This is done by having the first start of libcrypto, wait until the device
431 * /dev/random becomes able to supply a byte of entropy. Subsequent starts
432 * of the library and later reseedings do not need to do this.
433 */
434static int wait_random_seeded(void)
435{
436 static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
437 static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
438 int kernel[2];
439 int shm_id, fd, r;
440 char c, *p;
441 struct utsname un;
442 fd_set fds;
443
444 if (!seeded) {
46a9cc94 445 /* See if anything has created the global seeded indication */
3a577750
P
446 if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
447 /*
448 * Check the kernel's version and fail if it is too recent.
449 *
450 * Linux kernels from 4.8 onwards do not guarantee that
451 * /dev/urandom is properly seeded when /dev/random becomes
452 * readable. However, such kernels support the getentropy(2)
453 * system call and this should always succeed which renders
454 * this alternative but essentially identical source moot.
455 */
456 if (uname(&un) == 0) {
457 kernel[0] = atoi(un.release);
458 p = strchr(un.release, '.');
459 kernel[1] = p == NULL ? 0 : atoi(p + 1);
460 if (kernel[0] > kernel_version[0]
461 || (kernel[0] == kernel_version[0]
462 && kernel[1] >= kernel_version[1])) {
463 return 0;
464 }
465 }
466 /* Open /dev/random and wait for it to be readable */
467 if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
e1f8584d 468 if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
3a577750
P
469 FD_ZERO(&fds);
470 FD_SET(fd, &fds);
471 while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
472 && errno == EINTR);
473 } else {
474 while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
475 }
476 close(fd);
477 if (r == 1) {
478 seeded = 1;
46a9cc94 479 /* Create the shared memory indicator */
3a577750
P
480 shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
481 IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
482 }
483 }
484 }
485 if (shm_id != -1) {
486 seeded = 1;
487 /*
488 * Map the shared memory to prevent its premature destruction.
489 * If this call fails, it isn't a big problem.
490 */
491 shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
3a577750
P
492 if (shm_addr != (void *)-1)
493 OPENSSL_atexit(&cleanup_shm);
3a577750
P
494 }
495 }
496 return seeded;
497}
ddec332f 498# else /* defined __linux && DEVRANDOM_WAIT && OPENSSL_RAND_SEED_GETRANDOM */
3a577750
P
499static int wait_random_seeded(void)
500{
501 return 1;
502}
503# endif
504
c7504aeb
P
505/*
506 * Verify that the file descriptor associated with the random source is
507 * still valid. The rationale for doing this is the fact that it is not
508 * uncommon for daemons to close all open file handles when daemonizing.
509 * So the handle might have been closed or even reused for opening
510 * another file.
511 */
512static int check_random_device(struct random_device * rd)
513{
514 struct stat st;
515
516 return rd->fd != -1
517 && fstat(rd->fd, &st) != -1
518 && rd->dev == st.st_dev
519 && rd->ino == st.st_ino
520 && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
521 && rd->rdev == st.st_rdev;
522}
523
524/*
525 * Open a random device if required and return its file descriptor or -1 on error
526 */
527static int get_random_device(size_t n)
528{
529 struct stat st;
530 struct random_device * rd = &random_devices[n];
531
532 /* reuse existing file descriptor if it is (still) valid */
533 if (check_random_device(rd))
534 return rd->fd;
535
536 /* open the random device ... */
537 if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
538 return rd->fd;
539
540 /* ... and cache its relevant stat(2) data */
541 if (fstat(rd->fd, &st) != -1) {
542 rd->dev = st.st_dev;
543 rd->ino = st.st_ino;
544 rd->mode = st.st_mode;
545 rd->rdev = st.st_rdev;
546 } else {
547 close(rd->fd);
548 rd->fd = -1;
549 }
550
551 return rd->fd;
552}
553
554/*
555 * Close a random device making sure it is a random device
556 */
557static void close_random_device(size_t n)
558{
559 struct random_device * rd = &random_devices[n];
560
561 if (check_random_device(rd))
562 close(rd->fd);
563 rd->fd = -1;
564}
565
1335ca4b 566int ossl_rand_pool_init(void)
c7504aeb
P
567{
568 size_t i;
569
570 for (i = 0; i < OSSL_NELEM(random_devices); i++)
571 random_devices[i].fd = -1;
8cfc1971 572
c7504aeb
P
573 return 1;
574}
575
1335ca4b 576void ossl_rand_pool_cleanup(void)
c7504aeb
P
577{
578 size_t i;
579
580 for (i = 0; i < OSSL_NELEM(random_devices); i++)
581 close_random_device(i);
582}
583
1335ca4b 584void ossl_rand_pool_keep_random_devices_open(int keep)
c7504aeb 585{
8cfc1971 586 if (!keep)
1335ca4b 587 ossl_rand_pool_cleanup();
8cfc1971 588
c7504aeb
P
589 keep_random_devices_open = keep;
590}
591
d90e128b 592# else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
c7504aeb 593
1335ca4b 594int ossl_rand_pool_init(void)
c7504aeb
P
595{
596 return 1;
597}
598
1335ca4b 599void ossl_rand_pool_cleanup(void)
c7504aeb
P
600{
601}
602
1335ca4b 603void ossl_rand_pool_keep_random_devices_open(int keep)
c7504aeb
P
604{
605}
606
d90e128b 607# endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
c7504aeb 608
75e2c877 609/*
c16de9d8
DMSP
610 * Try the various seeding methods in turn, exit when successful.
611 *
0848b943 612 * If more than one entropy source is available, is it
c16de9d8
DMSP
613 * preferable to stop as soon as enough entropy has been collected
614 * (as favored by @rsalz) or should one rather be defensive and add
615 * more entropy than requested and/or from different sources?
616 *
617 * Currently, the user can select multiple entropy sources in the
618 * configure step, yet in practice only the first available source
619 * will be used. A more flexible solution has been requested, but
620 * currently it is not clear how this can be achieved without
621 * overengineering the problem. There are many parameters which
622 * could be taken into account when selecting the order and amount
623 * of input from the different entropy sources (trust, quality,
624 * possibility of blocking).
75e2c877 625 */
1dc188ba 626size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
8389ec4b 627{
d90e128b 628# if defined(OPENSSL_RAND_SEED_NONE)
1335ca4b 629 return ossl_rand_pool_entropy_available(pool);
8389ec4b 630# else
45554b5c
P
631 size_t entropy_available = 0;
632
633 (void)entropy_available; /* avoid compiler warning */
0f113f3e 634
d90e128b 635# if defined(OPENSSL_RAND_SEED_GETRANDOM)
630ce41e 636 {
e301c147
BE
637 size_t bytes_needed;
638 unsigned char *buffer;
630ce41e
DMSP
639 ssize_t bytes;
640 /* Maximum allowed number of consecutive unsuccessful attempts */
641 int attempts = 3;
642
1335ca4b 643 bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
630ce41e 644 while (bytes_needed != 0 && attempts-- > 0) {
1335ca4b 645 buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
630ce41e
DMSP
646 bytes = syscall_random(buffer, bytes_needed);
647 if (bytes > 0) {
1335ca4b 648 ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
630ce41e
DMSP
649 bytes_needed -= bytes;
650 attempts = 3; /* reset counter after successful attempt */
651 } else if (bytes < 0 && errno != EINTR) {
652 break;
653 }
654 }
75e2c877 655 }
1335ca4b 656 entropy_available = ossl_rand_pool_entropy_available(pool);
c16de9d8
DMSP
657 if (entropy_available > 0)
658 return entropy_available;
0f113f3e
MC
659# endif
660
75e2c877 661# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
8389ec4b 662 {
75e2c877 663 /* Not yet implemented. */
0f113f3e 664 }
8389ec4b 665# endif
0f113f3e 666
d90e128b 667# if defined(OPENSSL_RAND_SEED_DEVRANDOM)
3a577750 668 if (wait_random_seeded()) {
e301c147
BE
669 size_t bytes_needed;
670 unsigned char *buffer;
c7504aeb 671 size_t i;
0f113f3e 672
1335ca4b 673 bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
3a577750
P
674 for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
675 i++) {
cca99621 676 ssize_t bytes = 0;
3a577750 677 /* Maximum number of consecutive unsuccessful attempts */
cca99621 678 int attempts = 3;
c7504aeb
P
679 const int fd = get_random_device(i);
680
681 if (fd == -1)
8389ec4b 682 continue;
c16de9d8 683
cca99621 684 while (bytes_needed != 0 && attempts-- > 0) {
1335ca4b 685 buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
cca99621 686 bytes = read(fd, buffer, bytes_needed);
c7504aeb 687
cca99621 688 if (bytes > 0) {
1335ca4b 689 ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
cca99621 690 bytes_needed -= bytes;
3a577750 691 attempts = 3; /* reset counter on successful attempt */
cca99621
DMSP
692 } else if (bytes < 0 && errno != EINTR) {
693 break;
694 }
8389ec4b 695 }
cca99621 696 if (bytes < 0 || !keep_random_devices_open)
c7504aeb 697 close_random_device(i);
c16de9d8 698
1335ca4b 699 bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
8389ec4b 700 }
1335ca4b 701 entropy_available = ossl_rand_pool_entropy_available(pool);
c7504aeb
P
702 if (entropy_available > 0)
703 return entropy_available;
0f113f3e 704 }
8389ec4b 705# endif
0f113f3e 706
d90e128b 707# if defined(OPENSSL_RAND_SEED_RDTSC)
1335ca4b 708 entropy_available = ossl_prov_acquire_entropy_from_tsc(pool);
c16de9d8
DMSP
709 if (entropy_available > 0)
710 return entropy_available;
75e2c877
RS
711# endif
712
d90e128b 713# if defined(OPENSSL_RAND_SEED_RDCPU)
1335ca4b 714 entropy_available = ossl_prov_acquire_entropy_from_cpu(pool);
c16de9d8
DMSP
715 if (entropy_available > 0)
716 return entropy_available;
75e2c877
RS
717# endif
718
d90e128b 719# if defined(OPENSSL_RAND_SEED_EGD)
e301c147 720 {
75e2c877 721 static const char *paths[] = { DEVRANDOM_EGD, NULL };
e301c147
BE
722 size_t bytes_needed;
723 unsigned char *buffer;
75e2c877 724 int i;
0f113f3e 725
1335ca4b 726 bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
e301c147
BE
727 for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
728 size_t bytes = 0;
729 int num;
730
1335ca4b 731 buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
e301c147
BE
732 num = RAND_query_egd_bytes(paths[i],
733 buffer, (int)bytes_needed);
734 if (num == (int)bytes_needed)
735 bytes = bytes_needed;
c16de9d8 736
1335ca4b
SL
737 ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
738 bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
8389ec4b 739 }
1335ca4b 740 entropy_available = ossl_rand_pool_entropy_available(pool);
e301c147
BE
741 if (entropy_available > 0)
742 return entropy_available;
8389ec4b
RS
743 }
744# endif
0f113f3e 745
1335ca4b 746 return ossl_rand_pool_entropy_available(pool);
0f113f3e 747# endif
0c61e299 748}
8389ec4b 749# endif
5bc6bcf8
DMSP
750#endif
751
61783db5
KT
752#if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
753 || defined(__DJGPP__)
1dc188ba 754int ossl_pool_add_nonce_data(RAND_POOL *pool)
5bc6bcf8
DMSP
755{
756 struct {
757 pid_t pid;
758 CRYPTO_THREAD_ID tid;
759 uint64_t time;
678d2681
P
760 } data;
761
762 /* Erase the entire structure including any padding */
763 memset(&data, 0, sizeof(data));
5bc6bcf8
DMSP
764
765 /*
766 * Add process id, thread id, and a high resolution timestamp to
8bf36651 767 * ensure that the nonce is unique with high probability for
5bc6bcf8
DMSP
768 * different process instances.
769 */
770 data.pid = getpid();
771 data.tid = CRYPTO_THREAD_get_current_id();
772 data.time = get_time_stamp();
773
1335ca4b 774 return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
5bc6bcf8
DMSP
775}
776
1335ca4b 777int ossl_rand_pool_add_additional_data(RAND_POOL *pool)
5bc6bcf8
DMSP
778{
779 struct {
5562dbb3 780 int fork_id;
5bc6bcf8
DMSP
781 CRYPTO_THREAD_ID tid;
782 uint64_t time;
678d2681
P
783 } data;
784
785 /* Erase the entire structure including any padding */
786 memset(&data, 0, sizeof(data));
5bc6bcf8
DMSP
787
788 /*
789 * Add some noise from the thread id and a high resolution timer.
5562dbb3 790 * The fork_id adds some extra fork-safety.
5bc6bcf8
DMSP
791 * The thread id adds a little randomness if the drbg is accessed
792 * concurrently (which is the case for the <master> drbg).
793 */
5562dbb3 794 data.fork_id = openssl_get_fork_id();
5bc6bcf8
DMSP
795 data.tid = CRYPTO_THREAD_get_current_id();
796 data.time = get_timer_bits();
797
1335ca4b 798 return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
5bc6bcf8
DMSP
799}
800
801
5bc6bcf8
DMSP
802/*
803 * Get the current time with the highest possible resolution
804 *
805 * The time stamp is added to the nonce, so it is optimized for not repeating.
806 * The current time is ideal for this purpose, provided the computer's clock
807 * is synchronized.
808 */
809static uint64_t get_time_stamp(void)
810{
811# if defined(OSSL_POSIX_TIMER_OKAY)
812 {
813 struct timespec ts;
814
815 if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
816 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
817 }
818# endif
819# if defined(__unix__) \
820 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
821 {
822 struct timeval tv;
823
824 if (gettimeofday(&tv, NULL) == 0)
825 return TWO32TO64(tv.tv_sec, tv.tv_usec);
826 }
827# endif
828 return time(NULL);
829}
830
831/*
832 * Get an arbitrary timer value of the highest possible resolution
833 *
834 * The timer value is added as random noise to the additional data,
835 * which is not considered a trusted entropy sourec, so any result
836 * is acceptable.
837 */
838static uint64_t get_timer_bits(void)
839{
840 uint64_t res = OPENSSL_rdtsc();
841
842 if (res != 0)
843 return res;
844
845# if defined(__sun) || defined(__hpux)
846 return gethrtime();
847# elif defined(_AIX)
848 {
849 timebasestruct_t t;
850
851 read_wall_time(&t, TIMEBASE_SZ);
852 return TWO32TO64(t.tb_high, t.tb_low);
853 }
854# elif defined(OSSL_POSIX_TIMER_OKAY)
855 {
856 struct timespec ts;
857
858# ifdef CLOCK_BOOTTIME
859# define CLOCK_TYPE CLOCK_BOOTTIME
860# elif defined(_POSIX_MONOTONIC_CLOCK)
861# define CLOCK_TYPE CLOCK_MONOTONIC
862# else
863# define CLOCK_TYPE CLOCK_REALTIME
864# endif
865
866 if (clock_gettime(CLOCK_TYPE, &ts) == 0)
867 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
868 }
869# endif
870# if defined(__unix__) \
871 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
872 {
873 struct timeval tv;
0c61e299 874
5bc6bcf8
DMSP
875 if (gettimeofday(&tv, NULL) == 0)
876 return TWO32TO64(tv.tv_sec, tv.tv_usec);
877 }
878# endif
879 return time(NULL);
880}
2a7e6ed8
DMSP
881#endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
882 || defined(__DJGPP__) */