1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
9 //#include <linux/random.h>
17 # include <sys/auxv.h>
21 # include <sys/random.h>
23 # include <linux/random.h>
29 #include "random-util.h"
30 #include "time-util.h"
32 int acquire_random_bytes(void *p, size_t n, bool high_quality_required) {
33 static int have_syscall = -1;
35 _cleanup_close_ int fd = -1;
36 size_t already_done = 0;
39 /* Gathers some randomness from the kernel. This call will never block. If
40 * high_quality_required, it will always return some data from the kernel,
41 * regardless of whether the random pool is fully initialized or not.
42 * Otherwise, it will return success if at least some random bytes were
43 * successfully acquired, and an error if the kernel has no entropy whatsover
46 /* Use the getrandom() syscall unless we know we don't have it. */
47 if (have_syscall != 0 && !HAS_FEATURE_MEMORY_SANITIZER) {
48 r = getrandom(p, n, GRND_NONBLOCK);
53 if (!high_quality_required) {
54 /* Fill in the remaining bytes using pseudorandom values */
55 pseudorandom_bytes((uint8_t*) p + r, n - r);
60 } else if (errno == ENOSYS)
61 /* We lack the syscall, continue with reading from /dev/urandom. */
63 else if (errno == EAGAIN) {
64 /* The kernel has no entropy whatsoever. Let's remember to
65 * use the syscall the next time again though.
67 * If high_quality_required is false, return an error so that
68 * random_bytes() can produce some pseudorandom
69 * bytes. Otherwise, fall back to /dev/urandom, which we know
70 * is empty, but the kernel will produce some bytes for us on
71 * a best-effort basis. */
74 if (!high_quality_required)
80 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
82 return errno == ENOENT ? -ENOSYS : -errno;
84 return loop_read_exact(fd, (uint8_t*) p + already_done, n - already_done, true);
87 void initialize_srand(void) {
88 static bool srand_called = false;
98 /* The kernel provides us with 16 bytes of entropy in auxv, so let's
99 * try to make use of that to seed the pseudo-random generator. It's
100 * better than nothing... */
102 auxv = (void*) getauxval(AT_RANDOM);
104 assert_cc(sizeof(x) <= 16);
105 memcpy(&x, auxv, sizeof(x));
110 x ^= (unsigned) now(CLOCK_REALTIME);
111 x ^= (unsigned) gettid();
117 /* INT_MAX gives us only 31 bits, so use 24 out of that. */
118 #if RAND_MAX >= INT_MAX
121 /* SHORT_INT_MAX or lower gives at most 15 bits, we just just 8 out of that. */
125 void pseudorandom_bytes(void *p, size_t n) {
130 for (q = p; q < (uint8_t*) p + n; q += RAND_STEP) {
133 rr = (unsigned) rand();
136 if ((size_t) (q - (uint8_t*) p + 2) < n)
140 if ((size_t) (q - (uint8_t*) p + 1) < n)
147 void random_bytes(void *p, size_t n) {
150 r = acquire_random_bytes(p, n, false);
154 /* If some idiot made /dev/urandom unavailable to us, or the
155 * kernel has no entropy, use a PRNG instead. */
156 return pseudorandom_bytes(p, n);