]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/random-util.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[thirdparty/systemd.git] / src / basic / random-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #if defined(__i386__) || defined(__x86_64__)
4 #include <cpuid.h>
5 #endif
6
7 #include <elf.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <stdbool.h>
11 #include <stdint.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/time.h>
15
16 #if HAVE_SYS_AUXV_H
17 # include <sys/auxv.h>
18 #endif
19
20 #if USE_SYS_RANDOM_H
21 # include <sys/random.h>
22 #else
23 # include <linux/random.h>
24 #endif
25
26 #include "alloc-util.h"
27 #include "fd-util.h"
28 #include "io-util.h"
29 #include "missing.h"
30 #include "random-util.h"
31 #include "time-util.h"
32
33 int rdrand(unsigned long *ret) {
34
35 #if defined(__i386__) || defined(__x86_64__)
36 static int have_rdrand = -1;
37 unsigned char err;
38
39 if (have_rdrand < 0) {
40 uint32_t eax, ebx, ecx, edx;
41
42 /* Check if RDRAND is supported by the CPU */
43 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0) {
44 have_rdrand = false;
45 return -EOPNOTSUPP;
46 }
47
48 have_rdrand = !!(ecx & (1U << 30));
49 }
50
51 if (have_rdrand == 0)
52 return -EOPNOTSUPP;
53
54 asm volatile("rdrand %0;"
55 "setc %1"
56 : "=r" (*ret),
57 "=qm" (err));
58 msan_unpoison(&err, sizeof(err));
59 if (!err)
60 return -EAGAIN;
61
62 return 0;
63 #else
64 return -EOPNOTSUPP;
65 #endif
66 }
67
68 int genuine_random_bytes(void *p, size_t n, RandomFlags flags) {
69 static int have_syscall = -1;
70 _cleanup_close_ int fd = -1;
71 bool got_some = false;
72 int r;
73
74 /* Gathers some randomness from the kernel (or the CPU if the RANDOM_ALLOW_RDRAND flag is set). This call won't
75 * block, unless the RANDOM_BLOCK flag is set. If RANDOM_DONT_DRAIN is set, an error is returned if the random
76 * pool is not initialized. Otherwise it will always return some data from the kernel, regardless of whether
77 * the random pool is fully initialized or not. */
78
79 if (n == 0)
80 return 0;
81
82 if (FLAGS_SET(flags, RANDOM_ALLOW_RDRAND))
83 /* Try x86-64' RDRAND intrinsic if we have it. We only use it if high quality randomness is not
84 * required, as we don't trust it (who does?). Note that we only do a single iteration of RDRAND here,
85 * even though the Intel docs suggest calling this in a tight loop of 10 invocations or so. That's
86 * because we don't really care about the quality here. We generally prefer using RDRAND if the caller
87 * allows us too, since this way we won't drain the kernel randomness pool if we don't need it, as the
88 * pool's entropy is scarce. */
89 for (;;) {
90 unsigned long u;
91 size_t m;
92
93 if (rdrand(&u) < 0) {
94 if (got_some && FLAGS_SET(flags, RANDOM_EXTEND_WITH_PSEUDO)) {
95 /* Fill in the remaining bytes using pseudo-random values */
96 pseudo_random_bytes(p, n);
97 return 0;
98 }
99
100 /* OK, this didn't work, let's go to getrandom() + /dev/urandom instead */
101 break;
102 }
103
104 m = MIN(sizeof(u), n);
105 memcpy(p, &u, m);
106
107 p = (uint8_t*) p + m;
108 n -= m;
109
110 if (n == 0)
111 return 0; /* Yay, success! */
112
113 got_some = true;
114 }
115
116 /* Use the getrandom() syscall unless we know we don't have it. */
117 if (have_syscall != 0 && !HAS_FEATURE_MEMORY_SANITIZER) {
118
119 for (;;) {
120 r = getrandom(p, n, FLAGS_SET(flags, RANDOM_BLOCK) ? 0 : GRND_NONBLOCK);
121 if (r > 0) {
122 have_syscall = true;
123
124 if ((size_t) r == n)
125 return 0; /* Yay, success! */
126
127 assert((size_t) r < n);
128 p = (uint8_t*) p + r;
129 n -= r;
130
131 if (FLAGS_SET(flags, RANDOM_EXTEND_WITH_PSEUDO)) {
132 /* Fill in the remaining bytes using pseudo-random values */
133 pseudo_random_bytes(p, n);
134 return 0;
135 }
136
137 got_some = true;
138
139 /* Hmm, we didn't get enough good data but the caller insists on good data? Then try again */
140 if (FLAGS_SET(flags, RANDOM_BLOCK))
141 continue;
142
143 /* Fill in the rest with /dev/urandom */
144 break;
145
146 } else if (r == 0) {
147 have_syscall = true;
148 return -EIO;
149
150 } else if (errno == ENOSYS) {
151 /* We lack the syscall, continue with reading from /dev/urandom. */
152 have_syscall = false;
153 break;
154
155 } else if (errno == EAGAIN) {
156 /* The kernel has no entropy whatsoever. Let's remember to use the syscall the next
157 * time again though.
158 *
159 * If RANDOM_DONT_DRAIN is set, return an error so that random_bytes() can produce some
160 * pseudo-random bytes instead. Otherwise, fall back to /dev/urandom, which we know is empty,
161 * but the kernel will produce some bytes for us on a best-effort basis. */
162 have_syscall = true;
163
164 if (got_some && FLAGS_SET(flags, RANDOM_EXTEND_WITH_PSEUDO)) {
165 /* Fill in the remaining bytes using pseudorandom values */
166 pseudo_random_bytes(p, n);
167 return 0;
168 }
169
170 if (FLAGS_SET(flags, RANDOM_DONT_DRAIN))
171 return -ENODATA;
172
173 /* Use /dev/urandom instead */
174 break;
175 } else
176 return -errno;
177 }
178 }
179
180 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
181 if (fd < 0)
182 return errno == ENOENT ? -ENOSYS : -errno;
183
184 return loop_read_exact(fd, p, n, true);
185 }
186
187 void initialize_srand(void) {
188 static bool srand_called = false;
189 unsigned x;
190 #if HAVE_SYS_AUXV_H
191 const void *auxv;
192 #endif
193 unsigned long k;
194
195 if (srand_called)
196 return;
197
198 #if HAVE_SYS_AUXV_H
199 /* The kernel provides us with 16 bytes of entropy in auxv, so let's
200 * try to make use of that to seed the pseudo-random generator. It's
201 * better than nothing... */
202
203 auxv = (const void*) getauxval(AT_RANDOM);
204 if (auxv) {
205 assert_cc(sizeof(x) <= 16);
206 memcpy(&x, auxv, sizeof(x));
207 } else
208 #endif
209 x = 0;
210
211 x ^= (unsigned) now(CLOCK_REALTIME);
212 x ^= (unsigned) gettid();
213
214 if (rdrand(&k) >= 0)
215 x ^= (unsigned) k;
216
217 srand(x);
218 srand_called = true;
219 }
220
221 /* INT_MAX gives us only 31 bits, so use 24 out of that. */
222 #if RAND_MAX >= INT_MAX
223 # define RAND_STEP 3
224 #else
225 /* SHORT_INT_MAX or lower gives at most 15 bits, we just just 8 out of that. */
226 # define RAND_STEP 1
227 #endif
228
229 void pseudo_random_bytes(void *p, size_t n) {
230 uint8_t *q;
231
232 initialize_srand();
233
234 for (q = p; q < (uint8_t*) p + n; q += RAND_STEP) {
235 unsigned rr;
236
237 rr = (unsigned) rand();
238
239 #if RAND_STEP >= 3
240 if ((size_t) (q - (uint8_t*) p + 2) < n)
241 q[2] = rr >> 16;
242 #endif
243 #if RAND_STEP >= 2
244 if ((size_t) (q - (uint8_t*) p + 1) < n)
245 q[1] = rr >> 8;
246 #endif
247 q[0] = rr;
248 }
249 }
250
251 void random_bytes(void *p, size_t n) {
252
253 if (genuine_random_bytes(p, n, RANDOM_EXTEND_WITH_PSEUDO|RANDOM_DONT_DRAIN|RANDOM_ALLOW_RDRAND) >= 0)
254 return;
255
256 /* If for some reason some user made /dev/urandom unavailable to us, or the kernel has no entropy, use a PRNG instead. */
257 pseudo_random_bytes(p, n);
258 }