Coverage Report

Created: 2026-01-09 07:00

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