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