]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/random-seed/random-seed.c
sha256: add helper than hashes a buffer *and* its size
[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_and_size(buf, k, hash_state); /* Hash with length to distinguish from new seed. */
198
199 *ret_hash_state = hash_state;
200 }
201
202 (void) lseek(seed_fd, 0, SEEK_SET);
203
204 lets_credit = may_credit(seed_fd);
205
206 /* Before we credit or use the entropy, let's make sure to securely drop the creditable xattr from
207 * the file, so that we never credit the same random seed again. Note that further down we'll write a
208 * new seed again, and likely mark it as credible again, hence this is just paranoia to close the
209 * short time window between the time we upload the random seed into the kernel and download the new
210 * one from it. */
211
212 if (fremovexattr(seed_fd, "user.random-seed-creditable") < 0) {
213 if (!ERRNO_IS_XATTR_ABSENT(errno))
214 log_warning_errno(errno, "Failed to remove extended attribute, ignoring: %m");
215
216 /* Otherwise, there was no creditable flag set, which is OK. */
217 } else {
218 r = fsync_full(seed_fd);
219 if (r < 0) {
220 log_warning_errno(r, "Failed to synchronize seed to disk, not crediting entropy: %m");
221
222 if (lets_credit == CREDIT_ENTROPY_YES_PLEASE)
223 lets_credit = CREDIT_ENTROPY_NO_WAY;
224 }
225 }
226
227 r = random_write_entropy(urandom_fd, buf, k,
228 IN_SET(lets_credit, CREDIT_ENTROPY_YES_PLEASE, CREDIT_ENTROPY_YES_FORCED));
229 if (r < 0)
230 log_warning_errno(r, "Failed to write seed to /dev/urandom: %m");
231
232 return 0;
233 }
234
235 static int save_seed_file(
236 int seed_fd,
237 int urandom_fd,
238 size_t seed_size,
239 bool synchronous,
240 struct sha256_ctx *hash_state) {
241
242 _cleanup_free_ void *buf = NULL;
243 bool getrandom_worked = false;
244 ssize_t k, l;
245 int r;
246
247 assert(seed_fd >= 0);
248 assert(urandom_fd >= 0);
249
250 /* This is just a safety measure. Given that we are root and most likely created the file ourselves
251 * the mode and owner should be correct anyway. */
252 r = fchmod_and_chown(seed_fd, 0600, 0, 0);
253 if (r < 0)
254 return log_error_errno(r, "Failed to adjust seed file ownership and access mode: %m");
255
256 buf = malloc(seed_size);
257 if (!buf)
258 return log_oom();
259
260 k = getrandom(buf, seed_size, GRND_NONBLOCK);
261 if (k < 0 && errno == EAGAIN && synchronous) {
262 /* If we're asked to make ourselves a barrier for proper initialization of the random pool
263 * make this whole job synchronous by asking getrandom() to wait until the requested number
264 * of random bytes is available. */
265 log_notice("Kernel entropy pool is not initialized yet, waiting until it is.");
266 k = getrandom(buf, seed_size, 0);
267 }
268 if (k < 0)
269 log_debug_errno(errno, "Failed to read random data with getrandom(), falling back to /dev/urandom: %m");
270 else if ((size_t) k < seed_size)
271 log_debug("Short read from getrandom(), falling back to /dev/urandom.");
272 else
273 getrandom_worked = true;
274
275 if (!getrandom_worked) {
276 /* Retry with classic /dev/urandom */
277 k = loop_read(urandom_fd, buf, seed_size, false);
278 if (k < 0)
279 return log_error_errno(k, "Failed to read new seed from /dev/urandom: %m");
280 if (k == 0)
281 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Got EOF while reading from /dev/urandom.");
282 }
283
284 /* If we previously read in a seed file, then hash the new seed into the old one, and replace the
285 * last 32 bytes of the seed with the hash output, so that the new seed file can't regress in
286 * entropy. */
287 if (hash_state) {
288 uint8_t hash[SHA256_DIGEST_SIZE];
289
290 sha256_process_bytes_and_size(buf, k, hash_state); /* Hash with length to distinguish from old seed. */
291 sha256_finish_ctx(hash_state, hash);
292 l = MIN((size_t)k, sizeof(hash));
293 memcpy((uint8_t *)buf + k - l, hash, l);
294 }
295
296 r = loop_write(seed_fd, buf, (size_t) k, false);
297 if (r < 0)
298 return log_error_errno(r, "Failed to write new random seed file: %m");
299
300 if (ftruncate(seed_fd, k) < 0)
301 return log_error_errno(r, "Failed to truncate random seed file: %m");
302
303 r = fsync_full(seed_fd);
304 if (r < 0)
305 return log_error_errno(r, "Failed to synchronize seed file: %m");
306
307 /* If we got this random seed data from getrandom() the data is suitable for crediting entropy later
308 * on. Let's keep that in mind by setting an extended attribute. on the file */
309 if (getrandom_worked)
310 if (fsetxattr(seed_fd, "user.random-seed-creditable", "1", 1, 0) < 0)
311 log_full_errno(ERRNO_IS_NOT_SUPPORTED(errno) ? LOG_DEBUG : LOG_WARNING, errno,
312 "Failed to mark seed file as creditable, ignoring: %m");
313 return 0;
314 }
315
316 static int refresh_boot_seed(void) {
317 uint8_t buffer[RANDOM_EFI_SEED_SIZE];
318 struct sha256_ctx hash_state;
319 _cleanup_free_ void *seed_file_bytes = NULL;
320 _cleanup_free_ char *esp_path = NULL;
321 _cleanup_close_ int seed_fd = -EBADF, dir_fd = -EBADF;
322 size_t len;
323 ssize_t n;
324 int r;
325
326 assert_cc(RANDOM_EFI_SEED_SIZE == SHA256_DIGEST_SIZE);
327
328 r = find_esp_and_warn(NULL, NULL, /* unprivileged_mode= */ false, &esp_path,
329 NULL, NULL, NULL, NULL, NULL);
330 if (r < 0) {
331 if (r == -ENOKEY) {
332 log_debug_errno(r, "Couldn't find any ESP, so not updating ESP random seed.");
333 return 0;
334 }
335 return r; /* find_esp_and_warn() already logged */
336 }
337
338 r = chase_symlinks("/loader", esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, NULL, &dir_fd);
339 if (r < 0) {
340 if (r == -ENOENT) {
341 log_debug_errno(r, "Couldn't find ESP loader directory, so not updating ESP random seed.");
342 return 0;
343 }
344 return log_error_errno(r, "Failed to open ESP loader directory: %m");
345 }
346 seed_fd = openat(dir_fd, "random-seed", O_NOFOLLOW|O_RDWR|O_CLOEXEC|O_NOCTTY);
347 if (seed_fd < 0 && errno == ENOENT) {
348 uint64_t features;
349 r = efi_loader_get_features(&features);
350 if (r == 0 && FLAGS_SET(features, EFI_LOADER_FEATURE_RANDOM_SEED))
351 seed_fd = openat(dir_fd, "random-seed", O_CREAT|O_EXCL|O_RDWR|O_CLOEXEC|O_NOCTTY, 0600);
352 else {
353 log_debug_errno(seed_fd, "Couldn't find ESP random seed, and not booted with systemd-boot, so not updating ESP random seed.");
354 return 0;
355 }
356 }
357 if (seed_fd < 0)
358 return log_error_errno(errno, "Failed to open EFI seed path: %m");
359 r = random_seed_size(seed_fd, &len);
360 if (r < 0)
361 return log_error_errno(r, "Failed to determine EFI seed path length: %m");
362 seed_file_bytes = malloc(len);
363 if (!seed_file_bytes)
364 return log_oom();
365 n = loop_read(seed_fd, seed_file_bytes, len, false);
366 if (n < 0)
367 return log_error_errno(n, "Failed to read EFI seed file: %m");
368
369 /* Hash the old seed in so that we never regress in entropy. */
370 sha256_init_ctx(&hash_state);
371 sha256_process_bytes_and_size(seed_file_bytes, n, &hash_state);
372
373 /* We're doing this opportunistically, so if the seeding dance before didn't manage to initialize the
374 * RNG, there's no point in doing it here. Secondly, getrandom(GRND_NONBLOCK) has been around longer
375 * than EFI seeding anyway, so there's no point in having non-getrandom() fallbacks here. So if this
376 * fails, just return early to cut our losses. */
377 n = getrandom(buffer, sizeof(buffer), GRND_NONBLOCK);
378 if (n < 0) {
379 if (errno == EAGAIN) {
380 log_debug_errno(errno, "Random pool not initialized yet, so skipping EFI seed update");
381 return 0;
382 }
383 if (errno == ENOSYS) {
384 log_debug_errno(errno, "getrandom() not available, so skipping EFI seed update");
385 return 0;
386 }
387 return log_error_errno(errno, "Failed to generate random bytes for EFI seed: %m");
388 }
389 assert(n == sizeof(buffer));
390
391 /* Hash the new seed into the state containing the old one to generate our final seed. */
392 sha256_process_bytes_and_size(buffer, n, &hash_state);
393 sha256_finish_ctx(&hash_state, buffer);
394
395 if (lseek(seed_fd, 0, SEEK_SET) < 0)
396 return log_error_errno(errno, "Failed to seek to beginning of EFI seed file: %m");
397 r = loop_write(seed_fd, buffer, sizeof(buffer), false);
398 if (r < 0)
399 return log_error_errno(r, "Failed to write new EFI seed file: %m");
400 if (ftruncate(seed_fd, sizeof(buffer)) < 0)
401 return log_error_errno(errno, "Failed to truncate EFI seed file: %m");
402 r = fsync_full(seed_fd);
403 if (r < 0)
404 return log_error_errno(r, "Failed to fsync EFI seed file: %m");
405
406 log_debug("Updated random seed in ESP");
407 return 0;
408 }
409
410 static int help(int argc, char *argv[], void *userdata) {
411 _cleanup_free_ char *link = NULL;
412 int r;
413
414 r = terminal_urlify_man("systemd-random-seed", "8", &link);
415 if (r < 0)
416 return log_oom();
417
418 printf("%1$s [OPTIONS...] COMMAND\n"
419 "\n%5$sLoad and save the system random seed at boot and shutdown.%6$s\n"
420 "\n%3$sCommands:%4$s\n"
421 " load Load a random seed saved on disk into the kernel entropy pool\n"
422 " save Save a new random seed on disk\n"
423 "\n%3$sOptions:%4$s\n"
424 " -h --help Show this help\n"
425 " --version Show package version\n"
426 "\nSee the %2$s for details.\n",
427 program_invocation_short_name,
428 link,
429 ansi_underline(),
430 ansi_normal(),
431 ansi_highlight(),
432 ansi_normal());
433
434 return 0;
435 }
436
437 static const char* const seed_action_table[_ACTION_MAX] = {
438 [ACTION_LOAD] = "load",
439 [ACTION_SAVE] = "save",
440 };
441
442 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(seed_action, SeedAction);
443
444 static int parse_argv(int argc, char *argv[]) {
445 enum {
446 ARG_VERSION = 0x100,
447 };
448
449 static const struct option options[] = {
450 { "help", no_argument, NULL, 'h' },
451 { "version", no_argument, NULL, ARG_VERSION },
452 };
453
454 int c;
455
456 assert(argc >= 0);
457 assert(argv);
458
459 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
460 switch (c) {
461 case 'h':
462 return help(0, NULL, NULL);
463 case ARG_VERSION:
464 return version();
465 case '?':
466 return -EINVAL;
467
468 default:
469 assert_not_reached();
470 }
471
472 if (optind + 1 != argc)
473 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires one argument.");
474
475 arg_action = seed_action_from_string(argv[optind]);
476 if (arg_action < 0)
477 return log_error_errno(arg_action, "Unknown action '%s'", argv[optind]);
478
479 return 1;
480 }
481
482 static int run(int argc, char *argv[]) {
483 _cleanup_free_ struct sha256_ctx *hash_state = NULL;
484 _cleanup_close_ int seed_fd = -EBADF, random_fd = -EBADF;
485 bool read_seed_file, write_seed_file, synchronous;
486 size_t seed_size;
487 int r;
488
489 log_setup();
490
491 r = parse_argv(argc, argv);
492 if (r <= 0)
493 return r;
494
495 umask(0022);
496
497 r = mkdir_parents(RANDOM_SEED, 0755);
498 if (r < 0)
499 return log_error_errno(r, "Failed to create directory " RANDOM_SEED_DIR ": %m");
500
501 random_fd = open("/dev/urandom", O_RDWR|O_CLOEXEC|O_NOCTTY);
502 if (random_fd < 0)
503 return log_error_errno(errno, "Failed to open /dev/urandom: %m");
504
505 /* When we load the seed we read it and write it to the device and then immediately update the saved
506 * seed with new data, to make sure the next boot gets seeded differently. */
507
508 switch (arg_action) {
509 case ACTION_LOAD:
510 /* First, let's write the machine ID into /dev/urandom, not crediting entropy. See
511 * load_machine_id() for an explanation why. */
512 load_machine_id(random_fd);
513
514 seed_fd = open(RANDOM_SEED, O_RDWR|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
515 if (seed_fd < 0) {
516 int open_rw_error = -errno;
517
518 write_seed_file = false;
519
520 seed_fd = open(RANDOM_SEED, O_RDONLY|O_CLOEXEC|O_NOCTTY);
521 if (seed_fd < 0) {
522 bool missing = errno == ENOENT;
523 int level = missing ? LOG_DEBUG : LOG_ERR;
524
525 log_full_errno(level, open_rw_error, "Failed to open " RANDOM_SEED " for writing: %m");
526 log_full_errno(level, errno, "Failed to open " RANDOM_SEED " for reading: %m");
527 r = -errno;
528
529 (void) refresh_boot_seed();
530 return missing ? 0 : r;
531 }
532 } else
533 write_seed_file = true;
534
535 read_seed_file = true;
536 synchronous = true; /* make this invocation a synchronous barrier for random pool initialization */
537 break;
538
539 case ACTION_SAVE:
540 (void) refresh_boot_seed();
541 seed_fd = open(RANDOM_SEED, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
542 if (seed_fd < 0)
543 return log_error_errno(errno, "Failed to open " RANDOM_SEED ": %m");
544
545 read_seed_file = false;
546 write_seed_file = true;
547 synchronous = false;
548 break;
549
550 default:
551 assert_not_reached();
552 }
553
554 r = random_seed_size(seed_fd, &seed_size);
555 if (r < 0)
556 return r;
557
558 if (read_seed_file) {
559 r = load_seed_file(seed_fd, random_fd, seed_size,
560 write_seed_file ? &hash_state : NULL);
561 (void) refresh_boot_seed();
562 }
563
564 if (r >= 0 && write_seed_file)
565 r = save_seed_file(seed_fd, random_fd, seed_size, synchronous, hash_state);
566
567 return r;
568 }
569
570 DEFINE_MAIN_FUNCTION(run);