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