Coverage Report

Created: 2026-02-14 07:20

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