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(&k
, sizeof(k
), hash_state
); /* Hash length to distinguish from new seed. */
198 sha256_process_bytes(buf
, k
, hash_state
);
200 *ret_hash_state
= hash_state
;
203 (void) lseek(seed_fd
, 0, SEEK_SET
);
205 lets_credit
= may_credit(seed_fd
);
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
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");
217 /* Otherwise, there was no creditable flag set, which is OK. */
219 r
= fsync_full(seed_fd
);
221 log_warning_errno(r
, "Failed to synchronize seed to disk, not crediting entropy: %m");
223 if (lets_credit
== CREDIT_ENTROPY_YES_PLEASE
)
224 lets_credit
= CREDIT_ENTROPY_NO_WAY
;
228 r
= random_write_entropy(urandom_fd
, buf
, k
,
229 IN_SET(lets_credit
, CREDIT_ENTROPY_YES_PLEASE
, CREDIT_ENTROPY_YES_FORCED
));
231 log_warning_errno(r
, "Failed to write seed to /dev/urandom: %m");
236 static int save_seed_file(
241 struct sha256_ctx
*hash_state
) {
243 _cleanup_free_
void *buf
= NULL
;
244 bool getrandom_worked
= false;
248 assert(seed_fd
>= 0);
249 assert(urandom_fd
>= 0);
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);
255 return log_error_errno(r
, "Failed to adjust seed file ownership and access mode: %m");
257 buf
= malloc(seed_size
);
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);
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.");
274 getrandom_worked
= true;
276 if (!getrandom_worked
) {
277 /* Retry with classic /dev/urandom */
278 k
= loop_read(urandom_fd
, buf
, seed_size
, false);
280 return log_error_errno(k
, "Failed to read new seed from /dev/urandom: %m");
282 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Got EOF while reading from /dev/urandom.");
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
289 uint8_t hash
[SHA256_DIGEST_SIZE
];
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
);
298 r
= loop_write(seed_fd
, buf
, (size_t) k
, false);
300 return log_error_errno(r
, "Failed to write new random seed file: %m");
302 if (ftruncate(seed_fd
, k
) < 0)
303 return log_error_errno(r
, "Failed to truncate random seed file: %m");
305 r
= fsync_full(seed_fd
);
307 return log_error_errno(r
, "Failed to synchronize seed file: %m");
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");
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;
327 assert_cc(RANDOM_EFI_SEED_SIZE
== SHA256_DIGEST_SIZE
);
329 r
= find_esp_and_warn(NULL
, NULL
, /* unprivileged_mode= */ false, &esp_path
,
330 NULL
, NULL
, NULL
, NULL
, NULL
);
333 log_debug_errno(r
, "Couldn't find any ESP, so not updating ESP random seed.");
336 return r
; /* find_esp_and_warn() already logged */
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
) {
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
);
351 seed_fd
= openat(dir_fd
, "random-seed", O_CREAT
|O_EXCL
|O_RDWR
|O_CLOEXEC
|O_NOCTTY
, 0600);
357 log_debug_errno(seed_fd
, "Failed to open EFI seed path: %m");
360 r
= random_seed_size(seed_fd
, &len
);
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
)
366 r
= loop_read(seed_fd
, seed_file_bytes
, len
, false);
368 return log_error_errno(r
, "Failed to read EFI seed file: %m");
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
);
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
);
381 if (errno
== EAGAIN
) {
382 log_debug_errno(errno
, "Random pool not initialized yet, so skipping EFI seed update");
385 if (errno
== ENOSYS
) {
386 log_debug_errno(errno
, "getrandom() not available, so skipping EFI seed update");
389 return log_error_errno(errno
, "Failed to generate random bytes for EFI seed: %m");
391 assert(r
== sizeof(buffer
));
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
);
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);
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
);
407 return log_error_errno(errno
, "Failed to fsync EFI seed file: %m");
409 log_debug("Updated random seed in ESP");
413 static int help(int argc
, char *argv
[], void *userdata
) {
414 _cleanup_free_
char *link
= NULL
;
417 r
= terminal_urlify_man("systemd-random-seed", "8", &link
);
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
,
440 static const char* const seed_action_table
[_ACTION_MAX
] = {
441 [ACTION_LOAD
] = "load",
442 [ACTION_SAVE
] = "save",
445 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(seed_action
, SeedAction
);
447 static int parse_argv(int argc
, char *argv
[]) {
452 static const struct option options
[] = {
453 { "help", no_argument
, NULL
, 'h' },
454 { "version", no_argument
, NULL
, ARG_VERSION
},
462 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
465 return help(0, NULL
, NULL
);
472 assert_not_reached();
475 if (optind
+ 1 != argc
)
476 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "This program requires one argument.");
478 arg_action
= seed_action_from_string(argv
[optind
]);
480 return log_error_errno(arg_action
, "Unknown action '%s'", argv
[optind
]);
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
;
494 r
= parse_argv(argc
, argv
);
500 r
= mkdir_parents(RANDOM_SEED
, 0755);
502 return log_error_errno(r
, "Failed to create directory " RANDOM_SEED_DIR
": %m");
504 random_fd
= open("/dev/urandom", O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
506 return log_error_errno(errno
, "Failed to open /dev/urandom: %m");
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. */
511 switch (arg_action
) {
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
);
517 seed_fd
= open(RANDOM_SEED
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_CREAT
, 0600);
519 int open_rw_error
= -errno
;
521 write_seed_file
= false;
523 seed_fd
= open(RANDOM_SEED
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
525 bool missing
= errno
== ENOENT
;
526 int level
= missing
? LOG_DEBUG
: LOG_ERR
;
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");
532 (void) refresh_boot_seed();
533 return missing
? 0 : r
;
536 write_seed_file
= true;
538 read_seed_file
= true;
539 synchronous
= true; /* make this invocation a synchronous barrier for random pool initialization */
543 (void) refresh_boot_seed();
544 seed_fd
= open(RANDOM_SEED
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|O_CREAT
, 0600);
546 return log_error_errno(errno
, "Failed to open " RANDOM_SEED
": %m");
548 read_seed_file
= false;
549 write_seed_file
= true;
554 assert_not_reached();
557 r
= random_seed_size(seed_fd
, &seed_size
);
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();
567 if (r
>= 0 && write_seed_file
)
568 r
= save_seed_file(seed_fd
, random_fd
, seed_size
, synchronous
, hash_state
);
573 DEFINE_MAIN_FUNCTION(run
);