Coverage Report

Created: 2025-12-31 06:58

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