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