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