1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include <linux/random.h>
9 # include <sys/random.h>
12 #include <sys/xattr.h>
17 #include "alloc-util.h"
19 #include "chase-symlinks.h"
20 #include "efi-loader.h"
26 #include "main-func.h"
27 #include "missing_random.h"
28 #include "missing_syscall.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"
38 #include "sync-util.h"
40 #include "terminal-util.h"
41 #include "xattr-util.h"
43 typedef enum SeedAction
{
47 _ACTION_INVALID
= -EINVAL
,
50 typedef enum CreditEntropy
{
51 CREDIT_ENTROPY_NO_WAY
,
52 CREDIT_ENTROPY_YES_PLEASE
,
53 CREDIT_ENTROPY_YES_FORCED
,
56 static SeedAction arg_action
= _ACTION_INVALID
;
58 static CreditEntropy
may_credit(int seed_fd
) {
59 _cleanup_free_
char *creditable
= NULL
;
65 e
= getenv("SYSTEMD_RANDOM_SEED_CREDIT");
67 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is not set, not crediting entropy.");
68 return CREDIT_ENTROPY_NO_WAY
;
70 if (streq(e
, "force")) {
71 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is set to 'force', crediting entropy.");
72 return CREDIT_ENTROPY_YES_FORCED
;
78 log_warning_errno(r
, "Failed to parse $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy: %m");
80 log_debug("Crediting entropy is turned off via $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy.");
82 return CREDIT_ENTROPY_NO_WAY
;
85 /* Determine if the file is marked as creditable */
86 r
= fgetxattr_malloc(seed_fd
, "user.random-seed-creditable", &creditable
);
88 if (ERRNO_IS_XATTR_ABSENT(r
))
89 log_debug_errno(r
, "Seed file is not marked as creditable, not crediting.");
91 log_warning_errno(r
, "Failed to read extended attribute, ignoring: %m");
93 return CREDIT_ENTROPY_NO_WAY
;
96 r
= parse_boolean(creditable
);
99 log_warning_errno(r
, "Failed to parse user.random-seed-creditable extended attribute, ignoring: %s", creditable
);
101 log_debug("Seed file is marked as not creditable, not crediting.");
103 return CREDIT_ENTROPY_NO_WAY
;
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
));
111 /* All is good, we are not in first-boot mode. */
112 return CREDIT_ENTROPY_YES_PLEASE
;
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
;
118 log_debug("Not crediting entropy, since booted in first-boot mode.");
119 return CREDIT_ENTROPY_NO_WAY
;
122 static int random_seed_size(int seed_fd
, size_t *ret_size
) {
126 assert(seed_fd
>= 0);
128 if (fstat(seed_fd
, &st
) < 0)
129 return log_error_errno(errno
, "Failed to stat() seed file " RANDOM_SEED
": %m");
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 */
134 *ret_size
= CLAMP((uint64_t)st
.st_size
, random_pool_size(), RANDOM_POOL_SIZE_MAX
);
138 static void load_machine_id(int urandom_fd
) {
142 assert(urandom_fd
>= 0);
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
150 r
= sd_id128_get_machine(&mid
);
152 return (void) log_debug_errno(r
, "Failed to get machine ID, ignoring: %m");
154 r
= random_write_entropy(urandom_fd
, &mid
, sizeof(mid
), /* credit= */ false);
156 log_debug_errno(r
, "Failed to write machine ID to /dev/urandom, ignoring: %m");
159 static int load_seed_file(
163 struct sha256_ctx
**ret_hash_state
) {
165 _cleanup_free_
void *buf
= NULL
;
166 CreditEntropy lets_credit
;
170 assert(seed_fd
>= 0);
171 assert(urandom_fd
>= 0);
173 buf
= malloc(seed_size
);
177 k
= loop_read(seed_fd
, buf
, seed_size
, false);
179 log_warning_errno(k
, "Failed to read seed from " RANDOM_SEED
": %m");
183 log_debug("Seed file " RANDOM_SEED
" not yet initialized, proceeding.");
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
;
192 hash_state
= new(struct sha256_ctx
, 1);
196 sha256_init_ctx(hash_state
);
197 sha256_process_bytes_and_size(buf
, k
, hash_state
); /* Hash with length to distinguish from new seed. */
199 *ret_hash_state
= hash_state
;
202 (void) lseek(seed_fd
, 0, SEEK_SET
);
204 lets_credit
= may_credit(seed_fd
);
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
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");
216 /* Otherwise, there was no creditable flag set, which is OK. */
218 r
= fsync_full(seed_fd
);
220 log_warning_errno(r
, "Failed to synchronize seed to disk, not crediting entropy: %m");
222 if (lets_credit
== CREDIT_ENTROPY_YES_PLEASE
)
223 lets_credit
= CREDIT_ENTROPY_NO_WAY
;
227 r
= random_write_entropy(urandom_fd
, buf
, k
,
228 IN_SET(lets_credit
, CREDIT_ENTROPY_YES_PLEASE
, CREDIT_ENTROPY_YES_FORCED
));
230 log_warning_errno(r
, "Failed to write seed to /dev/urandom: %m");
235 static int save_seed_file(
240 struct sha256_ctx
*hash_state
) {
242 _cleanup_free_
void *buf
= NULL
;
243 bool getrandom_worked
= false;
247 assert(seed_fd
>= 0);
248 assert(urandom_fd
>= 0);
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);
254 return log_error_errno(r
, "Failed to adjust seed file ownership and access mode: %m");
256 buf
= malloc(seed_size
);
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);
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.");
273 getrandom_worked
= true;
275 if (!getrandom_worked
) {
276 /* Retry with classic /dev/urandom */
277 k
= loop_read(urandom_fd
, buf
, seed_size
, false);
279 return log_error_errno(k
, "Failed to read new seed from /dev/urandom: %m");
281 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Got EOF while reading from /dev/urandom.");
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
288 uint8_t hash
[SHA256_DIGEST_SIZE
];
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
);
296 r
= loop_write(seed_fd
, buf
, (size_t) k
, false);
298 return log_error_errno(r
, "Failed to write new random seed file: %m");
300 if (ftruncate(seed_fd
, k
) < 0)
301 return log_error_errno(r
, "Failed to truncate random seed file: %m");
303 r
= fsync_full(seed_fd
);
305 return log_error_errno(r
, "Failed to synchronize seed file: %m");
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");
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
;
326 assert_cc(RANDOM_EFI_SEED_SIZE
== SHA256_DIGEST_SIZE
);
328 r
= find_esp_and_warn(NULL
, NULL
, /* unprivileged_mode= */ false, &esp_path
,
329 NULL
, NULL
, NULL
, NULL
, NULL
);
332 log_debug_errno(r
, "Couldn't find any ESP, so not updating ESP random seed.");
335 return r
; /* find_esp_and_warn() already logged */
338 r
= chase_symlinks("/loader", esp_path
, CHASE_PREFIX_ROOT
|CHASE_PROHIBIT_SYMLINKS
, NULL
, &dir_fd
);
341 log_debug_errno(r
, "Couldn't find ESP loader directory, so not updating ESP random seed.");
344 return log_error_errno(r
, "Failed to open ESP loader directory: %m");
346 seed_fd
= openat(dir_fd
, "random-seed", O_NOFOLLOW
|O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
347 if (seed_fd
< 0 && errno
== ENOENT
) {
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);
353 log_debug_errno(seed_fd
, "Couldn't find ESP random seed, and not booted with systemd-boot, so not updating ESP random seed.");
358 return log_error_errno(errno
, "Failed to open EFI seed path: %m");
359 r
= random_seed_size(seed_fd
, &len
);
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
)
365 n
= loop_read(seed_fd
, seed_file_bytes
, len
, false);
367 return log_error_errno(n
, "Failed to read EFI seed file: %m");
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
);
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
);
379 if (errno
== EAGAIN
) {
380 log_debug_errno(errno
, "Random pool not initialized yet, so skipping EFI seed update");
383 if (errno
== ENOSYS
) {
384 log_debug_errno(errno
, "getrandom() not available, so skipping EFI seed update");
387 return log_error_errno(errno
, "Failed to generate random bytes for EFI seed: %m");
389 assert(n
== sizeof(buffer
));
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
);
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);
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
);
404 return log_error_errno(r
, "Failed to fsync EFI seed file: %m");
406 log_debug("Updated random seed in ESP");
410 static int help(int argc
, char *argv
[], void *userdata
) {
411 _cleanup_free_
char *link
= NULL
;
414 r
= terminal_urlify_man("systemd-random-seed", "8", &link
);
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
,
437 static const char* const seed_action_table
[_ACTION_MAX
] = {
438 [ACTION_LOAD
] = "load",
439 [ACTION_SAVE
] = "save",
442 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(seed_action
, SeedAction
);
444 static int parse_argv(int argc
, char *argv
[]) {
449 static const struct option options
[] = {
450 { "help", no_argument
, NULL
, 'h' },
451 { "version", no_argument
, NULL
, ARG_VERSION
},
459 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
462 return help(0, NULL
, NULL
);
469 assert_not_reached();
472 if (optind
+ 1 != argc
)
473 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "This program requires one argument.");
475 arg_action
= seed_action_from_string(argv
[optind
]);
477 return log_error_errno(arg_action
, "Unknown action '%s'", argv
[optind
]);
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
;
491 r
= parse_argv(argc
, argv
);
497 r
= mkdir_parents(RANDOM_SEED
, 0755);
499 return log_error_errno(r
, "Failed to create directory " RANDOM_SEED_DIR
": %m");
501 random_fd
= open("/dev/urandom", O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
503 return log_error_errno(errno
, "Failed to open /dev/urandom: %m");
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. */
508 switch (arg_action
) {
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
);
514 seed_fd
= open(RANDOM_SEED
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_CREAT
, 0600);
516 int open_rw_error
= -errno
;
518 write_seed_file
= false;
520 seed_fd
= open(RANDOM_SEED
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
522 bool missing
= errno
== ENOENT
;
523 int level
= missing
? LOG_DEBUG
: LOG_ERR
;
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");
529 (void) refresh_boot_seed();
530 return missing
? 0 : r
;
533 write_seed_file
= true;
535 read_seed_file
= true;
536 synchronous
= true; /* make this invocation a synchronous barrier for random pool initialization */
540 (void) refresh_boot_seed();
541 seed_fd
= open(RANDOM_SEED
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|O_CREAT
, 0600);
543 return log_error_errno(errno
, "Failed to open " RANDOM_SEED
": %m");
545 read_seed_file
= false;
546 write_seed_file
= true;
551 assert_not_reached();
554 r
= random_seed_size(seed_fd
, &seed_size
);
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();
564 if (r
>= 0 && write_seed_file
)
565 r
= save_seed_file(seed_fd
, random_fd
, seed_size
, synchronous
, hash_state
);
570 DEFINE_MAIN_FUNCTION(run
);