]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/random-util.c
Merge pull request #12378 from rbalint/vt-kbd-reset-check
[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 "siphash24.h"
32 #include "time-util.h"
33
34 int rdrand(unsigned long *ret) {
35
36 #if defined(__i386__) || defined(__x86_64__)
37 static int have_rdrand = -1;
38 unsigned long v;
39 uint8_t success;
40
41 if (have_rdrand < 0) {
42 uint32_t eax, ebx, ecx, edx;
43
44 /* Check if RDRAND is supported by the CPU */
45 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0) {
46 have_rdrand = false;
47 return -EOPNOTSUPP;
48 }
49
50 /* Compat with old gcc where bit_RDRND didn't exist yet */
51 #ifndef bit_RDRND
52 #define bit_RDRND (1U << 30)
53 #endif
54
55 have_rdrand = !!(ecx & bit_RDRND);
56 }
57
58 if (have_rdrand == 0)
59 return -EOPNOTSUPP;
60
61 asm volatile("rdrand %0;"
62 "setc %1"
63 : "=r" (v),
64 "=qm" (success));
65 msan_unpoison(&success, sizeof(success));
66 if (!success)
67 return -EAGAIN;
68
69 /* Apparently on some AMD CPUs RDRAND will sometimes (after a suspend/resume cycle?) report success
70 * via the carry flag but nonetheless return the same fixed value -1 in all cases. This appears to be
71 * a bad bug in the CPU or firmware. Let's deal with that and work-around this by explicitly checking
72 * for this special value (and also 0, just to be sure) and filtering it out. This is a work-around
73 * only however and something AMD really should fix properly. The Linux kernel should probably work
74 * around this issue by turning off RDRAND altogether on those CPUs. See:
75 * https://github.com/systemd/systemd/issues/11810 */
76 if (v == 0 || v == ULONG_MAX)
77 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
78 "RDRAND returned suspicious value %lx, assuming bad hardware RNG, not using value.", v);
79
80 *ret = v;
81 return 0;
82 #else
83 return -EOPNOTSUPP;
84 #endif
85 }
86
87 int genuine_random_bytes(void *p, size_t n, RandomFlags flags) {
88 static int have_syscall = -1;
89 _cleanup_close_ int fd = -1;
90 bool got_some = false;
91 int r;
92
93 /* Gathers some randomness from the kernel (or the CPU if the RANDOM_ALLOW_RDRAND flag is set). This
94 * call won't block, unless the RANDOM_BLOCK flag is set. If RANDOM_MAY_FAIL is set, an error is
95 * returned if the random pool is not initialized. Otherwise it will always return some data from the
96 * kernel, regardless of whether the random pool is fully initialized or not. */
97
98 if (n == 0)
99 return 0;
100
101 if (FLAGS_SET(flags, RANDOM_ALLOW_RDRAND))
102 /* Try x86-64' RDRAND intrinsic if we have it. We only use it if high quality randomness is
103 * not required, as we don't trust it (who does?). Note that we only do a single iteration of
104 * RDRAND here, even though the Intel docs suggest calling this in a tight loop of 10
105 * invocations or so. That's because we don't really care about the quality here. We
106 * generally prefer using RDRAND if the caller allows us to, since this way we won't upset
107 * the kernel's random subsystem by accessing it before the pool is initialized (after all it
108 * will kmsg log about every attempt to do so)..*/
109 for (;;) {
110 unsigned long u;
111 size_t m;
112
113 if (rdrand(&u) < 0) {
114 if (got_some && FLAGS_SET(flags, RANDOM_EXTEND_WITH_PSEUDO)) {
115 /* Fill in the remaining bytes using pseudo-random values */
116 pseudo_random_bytes(p, n);
117 return 0;
118 }
119
120 /* OK, this didn't work, let's go to getrandom() + /dev/urandom instead */
121 break;
122 }
123
124 m = MIN(sizeof(u), n);
125 memcpy(p, &u, m);
126
127 p = (uint8_t*) p + m;
128 n -= m;
129
130 if (n == 0)
131 return 0; /* Yay, success! */
132
133 got_some = true;
134 }
135
136 /* Use the getrandom() syscall unless we know we don't have it. */
137 if (have_syscall != 0 && !HAS_FEATURE_MEMORY_SANITIZER) {
138
139 for (;;) {
140 r = getrandom(p, n, FLAGS_SET(flags, RANDOM_BLOCK) ? 0 : GRND_NONBLOCK);
141 if (r > 0) {
142 have_syscall = true;
143
144 if ((size_t) r == n)
145 return 0; /* Yay, success! */
146
147 assert((size_t) r < n);
148 p = (uint8_t*) p + r;
149 n -= r;
150
151 if (FLAGS_SET(flags, RANDOM_EXTEND_WITH_PSEUDO)) {
152 /* Fill in the remaining bytes using pseudo-random values */
153 pseudo_random_bytes(p, n);
154 return 0;
155 }
156
157 got_some = true;
158
159 /* Hmm, we didn't get enough good data but the caller insists on good data? Then try again */
160 if (FLAGS_SET(flags, RANDOM_BLOCK))
161 continue;
162
163 /* Fill in the rest with /dev/urandom */
164 break;
165
166 } else if (r == 0) {
167 have_syscall = true;
168 return -EIO;
169
170 } else if (errno == ENOSYS) {
171 /* We lack the syscall, continue with reading from /dev/urandom. */
172 have_syscall = false;
173 break;
174
175 } else if (errno == EAGAIN) {
176 /* The kernel has no entropy whatsoever. Let's remember to use the syscall
177 * the next time again though.
178 *
179 * If RANDOM_MAY_FAIL is set, return an error so that random_bytes() can
180 * produce some pseudo-random bytes instead. Otherwise, fall back to
181 * /dev/urandom, which we know is empty, but the kernel will produce some
182 * bytes for us on a best-effort basis. */
183 have_syscall = true;
184
185 if (got_some && FLAGS_SET(flags, RANDOM_EXTEND_WITH_PSEUDO)) {
186 /* Fill in the remaining bytes using pseudorandom values */
187 pseudo_random_bytes(p, n);
188 return 0;
189 }
190
191 if (FLAGS_SET(flags, RANDOM_MAY_FAIL))
192 return -ENODATA;
193
194 /* Use /dev/urandom instead */
195 break;
196 } else
197 return -errno;
198 }
199 }
200
201 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
202 if (fd < 0)
203 return errno == ENOENT ? -ENOSYS : -errno;
204
205 return loop_read_exact(fd, p, n, true);
206 }
207
208 void initialize_srand(void) {
209 static bool srand_called = false;
210 unsigned x;
211 #if HAVE_SYS_AUXV_H
212 const void *auxv;
213 #endif
214 unsigned long k;
215
216 if (srand_called)
217 return;
218
219 #if HAVE_SYS_AUXV_H
220 /* The kernel provides us with 16 bytes of entropy in auxv, so let's try to make use of that to seed
221 * the pseudo-random generator. It's better than nothing... But let's first hash it to make it harder
222 * to recover the original value by watching any pseudo-random bits we generate. After all the
223 * AT_RANDOM data might be used by other stuff too (in particular: ASLR), and we probably shouldn't
224 * leak the seed for that. */
225
226 auxv = ULONG_TO_PTR(getauxval(AT_RANDOM));
227 if (auxv) {
228 static const uint8_t auxval_hash_key[16] = {
229 0x92, 0x6e, 0xfe, 0x1b, 0xcf, 0x00, 0x52, 0x9c, 0xcc, 0x42, 0xcf, 0xdc, 0x94, 0x1f, 0x81, 0x0f
230 };
231
232 x = (unsigned) siphash24(auxv, 16, auxval_hash_key);
233 } else
234 #endif
235 x = 0;
236
237 x ^= (unsigned) now(CLOCK_REALTIME);
238 x ^= (unsigned) gettid();
239
240 if (rdrand(&k) >= 0)
241 x ^= (unsigned) k;
242
243 srand(x);
244 srand_called = true;
245 }
246
247 /* INT_MAX gives us only 31 bits, so use 24 out of that. */
248 #if RAND_MAX >= INT_MAX
249 # define RAND_STEP 3
250 #else
251 /* SHORT_INT_MAX or lower gives at most 15 bits, we just just 8 out of that. */
252 # define RAND_STEP 1
253 #endif
254
255 void pseudo_random_bytes(void *p, size_t n) {
256 uint8_t *q;
257
258 initialize_srand();
259
260 for (q = p; q < (uint8_t*) p + n; q += RAND_STEP) {
261 unsigned rr;
262
263 rr = (unsigned) rand();
264
265 #if RAND_STEP >= 3
266 if ((size_t) (q - (uint8_t*) p + 2) < n)
267 q[2] = rr >> 16;
268 #endif
269 #if RAND_STEP >= 2
270 if ((size_t) (q - (uint8_t*) p + 1) < n)
271 q[1] = rr >> 8;
272 #endif
273 q[0] = rr;
274 }
275 }
276
277 void random_bytes(void *p, size_t n) {
278
279 if (genuine_random_bytes(p, n, RANDOM_EXTEND_WITH_PSEUDO|RANDOM_MAY_FAIL|RANDOM_ALLOW_RDRAND) >= 0)
280 return;
281
282 /* If for some reason some user made /dev/urandom unavailable to us, or the kernel has no entropy, use a PRNG instead. */
283 pseudo_random_bytes(p, n);
284 }