]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/random-seed/random-seed.c
Merge pull request #24555 from medhefgo/bootctl
[thirdparty/systemd.git] / src / random-seed / random-seed.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <linux/random.h>
7 #include <sys/ioctl.h>
8 #if USE_SYS_RANDOM_H
9 # include <sys/random.h>
10 #endif
11 #include <sys/stat.h>
12 #include <sys/xattr.h>
13 #include <unistd.h>
14
15 #include "sd-id128.h"
16
17 #include "alloc-util.h"
18 #include "build.h"
19 #include "fd-util.h"
20 #include "fs-util.h"
21 #include "io-util.h"
22 #include "log.h"
23 #include "main-func.h"
24 #include "missing_random.h"
25 #include "missing_syscall.h"
26 #include "mkdir.h"
27 #include "parse-argument.h"
28 #include "parse-util.h"
29 #include "pretty-print.h"
30 #include "random-util.h"
31 #include "string-table.h"
32 #include "string-util.h"
33 #include "strv.h"
34 #include "sync-util.h"
35 #include "sha256.h"
36 #include "terminal-util.h"
37 #include "xattr-util.h"
38
39 typedef enum SeedAction {
40 ACTION_LOAD,
41 ACTION_SAVE,
42 _ACTION_MAX,
43 _ACTION_INVALID = -EINVAL,
44 } SeedAction;
45
46 typedef enum CreditEntropy {
47 CREDIT_ENTROPY_NO_WAY,
48 CREDIT_ENTROPY_YES_PLEASE,
49 CREDIT_ENTROPY_YES_FORCED,
50 } CreditEntropy;
51
52 static SeedAction arg_action = _ACTION_INVALID;
53
54 static CreditEntropy may_credit(int seed_fd) {
55 _cleanup_free_ char *creditable = NULL;
56 const char *e;
57 int r;
58
59 assert(seed_fd >= 0);
60
61 e = getenv("SYSTEMD_RANDOM_SEED_CREDIT");
62 if (!e) {
63 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is not set, not crediting entropy.");
64 return CREDIT_ENTROPY_NO_WAY;
65 }
66 if (streq(e, "force")) {
67 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is set to 'force', crediting entropy.");
68 return CREDIT_ENTROPY_YES_FORCED;
69 }
70
71 r = parse_boolean(e);
72 if (r <= 0) {
73 if (r < 0)
74 log_warning_errno(r, "Failed to parse $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy: %m");
75 else
76 log_debug("Crediting entropy is turned off via $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy.");
77
78 return CREDIT_ENTROPY_NO_WAY;
79 }
80
81 /* Determine if the file is marked as creditable */
82 r = fgetxattr_malloc(seed_fd, "user.random-seed-creditable", &creditable);
83 if (r < 0) {
84 if (ERRNO_IS_XATTR_ABSENT(r))
85 log_debug_errno(r, "Seed file is not marked as creditable, not crediting.");
86 else
87 log_warning_errno(r, "Failed to read extended attribute, ignoring: %m");
88
89 return CREDIT_ENTROPY_NO_WAY;
90 }
91
92 r = parse_boolean(creditable);
93 if (r <= 0) {
94 if (r < 0)
95 log_warning_errno(r, "Failed to parse user.random-seed-creditable extended attribute, ignoring: %s", creditable);
96 else
97 log_debug("Seed file is marked as not creditable, not crediting.");
98
99 return CREDIT_ENTROPY_NO_WAY;
100 }
101
102 /* Don't credit the random seed if we are in first-boot mode, because we are supposed to start from
103 * scratch. This is a safety precaution for cases where we people ship "golden" images with empty
104 * /etc but populated /var that contains a random seed. */
105 r = RET_NERRNO(access("/run/systemd/first-boot", F_OK));
106 if (r == -ENOENT)
107 /* All is good, we are not in first-boot mode. */
108 return CREDIT_ENTROPY_YES_PLEASE;
109 if (r < 0) {
110 log_warning_errno(r, "Failed to check whether we are in first-boot mode, not crediting entropy: %m");
111 return CREDIT_ENTROPY_NO_WAY;
112 }
113
114 log_debug("Not crediting entropy, since booted in first-boot mode.");
115 return CREDIT_ENTROPY_NO_WAY;
116 }
117
118 static int random_seed_size(int seed_fd, size_t *ret_size) {
119 struct stat st;
120
121 assert(ret_size);
122 assert(seed_fd >= 0);
123
124 if (fstat(seed_fd, &st) < 0)
125 return log_error_errno(errno, "Failed to stat() seed file " RANDOM_SEED ": %m");
126
127 /* If the seed file is larger than what the kernel expects, then honour the existing size and
128 * save/restore as much as it says */
129
130 *ret_size = CLAMP((uint64_t)st.st_size, random_pool_size(), RANDOM_POOL_SIZE_MAX);
131 return 0;
132 }
133
134 static void load_machine_id(int urandom_fd) {
135 sd_id128_t mid;
136 int r;
137
138 assert(urandom_fd >= 0);
139
140 /* As an extra protection against "golden images" that are put together sloppily, i.e. images which
141 * are duplicated on multiple systems but where the random seed file is not properly
142 * reset. Frequently the machine ID is properly reset on those systems however (simply because it's
143 * easier to notice, if it isn't due to address clashes and so on, while random seed equivalence is
144 * generally not noticed easily), hence let's simply write the machined ID into the random pool
145 * too. */
146 r = sd_id128_get_machine(&mid);
147 if (r < 0)
148 return (void) log_debug_errno(r, "Failed to get machine ID, ignoring: %m");
149
150 r = random_write_entropy(urandom_fd, &mid, sizeof(mid), /* credit= */ false);
151 if (r < 0)
152 log_debug_errno(r, "Failed to write machine ID to /dev/urandom, ignoring: %m");
153 }
154
155 static int load_seed_file(
156 int seed_fd,
157 int urandom_fd,
158 size_t seed_size,
159 struct sha256_ctx **ret_hash_state) {
160
161 _cleanup_free_ void *buf = NULL;
162 CreditEntropy lets_credit;
163 ssize_t k;
164 int r;
165
166 assert(seed_fd >= 0);
167 assert(urandom_fd >= 0);
168
169 buf = malloc(seed_size);
170 if (!buf)
171 return log_oom();
172
173 k = loop_read(seed_fd, buf, seed_size, false);
174 if (k < 0) {
175 log_warning_errno(k, "Failed to read seed from " RANDOM_SEED ": %m");
176 return 0;
177 }
178 if (k == 0) {
179 log_debug("Seed file " RANDOM_SEED " not yet initialized, proceeding.");
180 return 0;
181 }
182
183 /* If we're going to later write out a seed file, initialize a hash state with the contents of the
184 * seed file we just read, so that the new one can't regress in entropy. */
185 if (ret_hash_state) {
186 struct sha256_ctx *hash_state;
187
188 hash_state = malloc(sizeof(struct sha256_ctx));
189 if (!hash_state)
190 return log_oom();
191
192 sha256_init_ctx(hash_state);
193 sha256_process_bytes(&k, sizeof(k), hash_state); /* Hash length to distinguish from new seed. */
194 sha256_process_bytes(buf, k, hash_state);
195
196 *ret_hash_state = hash_state;
197 }
198
199 (void) lseek(seed_fd, 0, SEEK_SET);
200
201 lets_credit = may_credit(seed_fd);
202
203 /* Before we credit or use the entropy, let's make sure to securely drop the creditable xattr from
204 * the file, so that we never credit the same random seed again. Note that further down we'll write a
205 * new seed again, and likely mark it as credible again, hence this is just paranoia to close the
206 * short time window between the time we upload the random seed into the kernel and download the new
207 * one from it. */
208
209 if (fremovexattr(seed_fd, "user.random-seed-creditable") < 0) {
210 if (!ERRNO_IS_XATTR_ABSENT(errno))
211 log_warning_errno(errno, "Failed to remove extended attribute, ignoring: %m");
212
213 /* Otherwise, there was no creditable flag set, which is OK. */
214 } else {
215 r = fsync_full(seed_fd);
216 if (r < 0) {
217 log_warning_errno(r, "Failed to synchronize seed to disk, not crediting entropy: %m");
218
219 if (lets_credit == CREDIT_ENTROPY_YES_PLEASE)
220 lets_credit = CREDIT_ENTROPY_NO_WAY;
221 }
222 }
223
224 r = random_write_entropy(urandom_fd, buf, k,
225 IN_SET(lets_credit, CREDIT_ENTROPY_YES_PLEASE, CREDIT_ENTROPY_YES_FORCED));
226 if (r < 0)
227 log_warning_errno(r, "Failed to write seed to /dev/urandom: %m");
228
229 return 0;
230 }
231
232 static int save_seed_file(
233 int seed_fd,
234 int urandom_fd,
235 size_t seed_size,
236 bool synchronous,
237 struct sha256_ctx *hash_state) {
238
239 _cleanup_free_ void *buf = NULL;
240 bool getrandom_worked = false;
241 ssize_t k, l;
242 int r;
243
244 assert(seed_fd >= 0);
245 assert(urandom_fd >= 0);
246
247 /* This is just a safety measure. Given that we are root and most likely created the file ourselves
248 * the mode and owner should be correct anyway. */
249 r = fchmod_and_chown(seed_fd, 0600, 0, 0);
250 if (r < 0)
251 return log_error_errno(r, "Failed to adjust seed file ownership and access mode: %m");
252
253 buf = malloc(seed_size);
254 if (!buf)
255 return log_oom();
256
257 k = getrandom(buf, seed_size, GRND_NONBLOCK);
258 if (k < 0 && errno == EAGAIN && synchronous) {
259 /* If we're asked to make ourselves a barrier for proper initialization of the random pool
260 * make this whole job synchronous by asking getrandom() to wait until the requested number
261 * of random bytes is available. */
262 log_notice("Kernel entropy pool is not initialized yet, waiting until it is.");
263 k = getrandom(buf, seed_size, 0);
264 }
265 if (k < 0)
266 log_debug_errno(errno, "Failed to read random data with getrandom(), falling back to /dev/urandom: %m");
267 else if ((size_t) k < seed_size)
268 log_debug("Short read from getrandom(), falling back to /dev/urandom.");
269 else
270 getrandom_worked = true;
271
272 if (!getrandom_worked) {
273 /* Retry with classic /dev/urandom */
274 k = loop_read(urandom_fd, buf, seed_size, false);
275 if (k < 0)
276 return log_error_errno(k, "Failed to read new seed from /dev/urandom: %m");
277 if (k == 0)
278 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Got EOF while reading from /dev/urandom.");
279 }
280
281 /* If we previously read in a seed file, then hash the new seed into the old one, and replace the
282 * last 32 bytes of the seed with the hash output, so that the new seed file can't regress in
283 * entropy. */
284 if (hash_state) {
285 uint8_t hash[SHA256_DIGEST_SIZE];
286
287 sha256_process_bytes(&k, sizeof(k), hash_state); /* Hash length to distinguish from old seed. */
288 sha256_process_bytes(buf, k, hash_state);
289 sha256_finish_ctx(hash_state, hash);
290 l = MIN((size_t)k, sizeof(hash));
291 memcpy((uint8_t *)buf + k - l, hash, l);
292 }
293
294 r = loop_write(seed_fd, buf, (size_t) k, false);
295 if (r < 0)
296 return log_error_errno(r, "Failed to write new random seed file: %m");
297
298 if (ftruncate(seed_fd, k) < 0)
299 return log_error_errno(r, "Failed to truncate random seed file: %m");
300
301 r = fsync_full(seed_fd);
302 if (r < 0)
303 return log_error_errno(r, "Failed to synchronize seed file: %m");
304
305 /* If we got this random seed data from getrandom() the data is suitable for crediting entropy later
306 * on. Let's keep that in mind by setting an extended attribute. on the file */
307 if (getrandom_worked)
308 if (fsetxattr(seed_fd, "user.random-seed-creditable", "1", 1, 0) < 0)
309 log_full_errno(ERRNO_IS_NOT_SUPPORTED(errno) ? LOG_DEBUG : LOG_WARNING, errno,
310 "Failed to mark seed file as creditable, ignoring: %m");
311 return 0;
312 }
313
314 static int help(int argc, char *argv[], void *userdata) {
315 _cleanup_free_ char *link = NULL;
316 int r;
317
318 r = terminal_urlify_man("systemd-random-seed", "8", &link);
319 if (r < 0)
320 return log_oom();
321
322 printf("%1$s [OPTIONS...] COMMAND\n"
323 "\n%5$sLoad and save the system random seed at boot and shutdown.%6$s\n"
324 "\n%3$sCommands:%4$s\n"
325 " load Load a random seed saved on disk into the kernel entropy pool\n"
326 " save Save a new random seed on disk\n"
327 "\n%3$sOptions:%4$s\n"
328 " -h --help Show this help\n"
329 " --version Show package version\n"
330 "\nSee the %2$s for details.\n",
331 program_invocation_short_name,
332 link,
333 ansi_underline(),
334 ansi_normal(),
335 ansi_highlight(),
336 ansi_normal());
337
338 return 0;
339 }
340
341 static const char* const seed_action_table[_ACTION_MAX] = {
342 [ACTION_LOAD] = "load",
343 [ACTION_SAVE] = "save",
344 };
345
346 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(seed_action, SeedAction);
347
348 static int parse_argv(int argc, char *argv[]) {
349 enum {
350 ARG_VERSION = 0x100,
351 };
352
353 static const struct option options[] = {
354 { "help", no_argument, NULL, 'h' },
355 { "version", no_argument, NULL, ARG_VERSION },
356 };
357
358 int c;
359
360 assert(argc >= 0);
361 assert(argv);
362
363 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
364 switch (c) {
365 case 'h':
366 return help(0, NULL, NULL);
367 case ARG_VERSION:
368 return version();
369 case '?':
370 return -EINVAL;
371
372 default:
373 assert_not_reached();
374 }
375
376 if (optind + 1 != argc)
377 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires one argument.");
378
379 arg_action = seed_action_from_string(argv[optind]);
380 if (arg_action < 0)
381 return log_error_errno(arg_action, "Unknown action '%s'", argv[optind]);
382
383 return 1;
384 }
385
386 static int run(int argc, char *argv[]) {
387 _cleanup_free_ struct sha256_ctx *hash_state = NULL;
388 _cleanup_close_ int seed_fd = -1, random_fd = -1;
389 bool read_seed_file, write_seed_file, synchronous;
390 size_t seed_size;
391 int r;
392
393 log_setup();
394
395 r = parse_argv(argc, argv);
396 if (r <= 0)
397 return r;
398
399 umask(0022);
400
401 r = mkdir_parents(RANDOM_SEED, 0755);
402 if (r < 0)
403 return log_error_errno(r, "Failed to create directory " RANDOM_SEED_DIR ": %m");
404
405 /* When we load the seed we read it and write it to the device and then immediately update the saved
406 * seed with new data, to make sure the next boot gets seeded differently. */
407
408 switch (arg_action) {
409 case ACTION_LOAD:
410 random_fd = open("/dev/urandom", O_RDWR|O_CLOEXEC|O_NOCTTY);
411 if (random_fd < 0)
412 return log_error_errno(errno, "Failed to open /dev/urandom: %m");
413
414 /* First, let's write the machine ID into /dev/urandom, not crediting entropy. See
415 * load_machine_id() for an explanation why. */
416 load_machine_id(random_fd);
417
418 seed_fd = open(RANDOM_SEED, O_RDWR|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
419 if (seed_fd < 0) {
420 int open_rw_error = -errno;
421
422 write_seed_file = false;
423
424 seed_fd = open(RANDOM_SEED, O_RDONLY|O_CLOEXEC|O_NOCTTY);
425 if (seed_fd < 0) {
426 bool missing = errno == ENOENT;
427 int level = missing ? LOG_DEBUG : LOG_ERR;
428
429 log_full_errno(level, open_rw_error, "Failed to open " RANDOM_SEED " for writing: %m");
430 log_full_errno(level, errno, "Failed to open " RANDOM_SEED " for reading: %m");
431
432 return missing ? 0 : -errno;
433 }
434 } else
435 write_seed_file = true;
436
437 read_seed_file = true;
438 synchronous = true; /* make this invocation a synchronous barrier for random pool initialization */
439 break;
440
441 case ACTION_SAVE:
442 random_fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
443 if (random_fd < 0)
444 return log_error_errno(errno, "Failed to open /dev/urandom: %m");
445
446 seed_fd = open(RANDOM_SEED, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
447 if (seed_fd < 0)
448 return log_error_errno(errno, "Failed to open " RANDOM_SEED ": %m");
449
450 read_seed_file = false;
451 write_seed_file = true;
452 synchronous = false;
453 break;
454
455 default:
456 assert_not_reached();
457 }
458
459 r = random_seed_size(seed_fd, &seed_size);
460 if (r < 0)
461 return r;
462
463 if (read_seed_file)
464 r = load_seed_file(seed_fd, random_fd, seed_size,
465 write_seed_file ? &hash_state : NULL);
466
467 if (r >= 0 && write_seed_file)
468 r = save_seed_file(seed_fd, random_fd, seed_size, synchronous, hash_state);
469
470 return r;
471 }
472
473 DEFINE_MAIN_FUNCTION(run);