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"
22 #include "main-func.h"
23 #include "missing_random.h"
24 #include "missing_syscall.h"
26 #include "parse-argument.h"
27 #include "parse-util.h"
28 #include "pretty-print.h"
29 #include "random-util.h"
30 #include "string-table.h"
31 #include "string-util.h"
33 #include "sync-util.h"
35 #include "terminal-util.h"
37 #include "xattr-util.h"
39 typedef enum SeedAction
{
43 _ACTION_INVALID
= -EINVAL
,
46 typedef enum CreditEntropy
{
47 CREDIT_ENTROPY_NO_WAY
,
48 CREDIT_ENTROPY_YES_PLEASE
,
49 CREDIT_ENTROPY_YES_FORCED
,
52 static SeedAction arg_action
= _ACTION_INVALID
;
54 static CreditEntropy
may_credit(int seed_fd
) {
55 _cleanup_free_
char *creditable
= NULL
;
61 e
= getenv("SYSTEMD_RANDOM_SEED_CREDIT");
63 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is not set, not crediting entropy.");
64 return CREDIT_ENTROPY_NO_WAY
;
66 if (streq(e
, "force")) {
67 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is set to 'force', crediting entropy.");
68 return CREDIT_ENTROPY_YES_FORCED
;
74 log_warning_errno(r
, "Failed to parse $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy: %m");
76 log_debug("Crediting entropy is turned off via $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy.");
78 return CREDIT_ENTROPY_NO_WAY
;
81 /* Determine if the file is marked as creditable */
82 r
= fgetxattr_malloc(seed_fd
, "user.random-seed-creditable", &creditable
);
84 if (ERRNO_IS_XATTR_ABSENT(r
))
85 log_debug_errno(r
, "Seed file is not marked as creditable, not crediting.");
87 log_warning_errno(r
, "Failed to read extended attribute, ignoring: %m");
89 return CREDIT_ENTROPY_NO_WAY
;
92 r
= parse_boolean(creditable
);
95 log_warning_errno(r
, "Failed to parse user.random-seed-creditable extended attribute, ignoring: %s", creditable
);
97 log_debug("Seed file is marked as not creditable, not crediting.");
99 return CREDIT_ENTROPY_NO_WAY
;
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
));
107 /* All is good, we are not in first-boot mode. */
108 return CREDIT_ENTROPY_YES_PLEASE
;
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
;
114 log_debug("Not crediting entropy, since booted in first-boot mode.");
115 return CREDIT_ENTROPY_NO_WAY
;
118 static int random_seed_size(int seed_fd
, size_t *ret_size
) {
122 assert(seed_fd
>= 0);
124 if (fstat(seed_fd
, &st
) < 0)
125 return log_error_errno(errno
, "Failed to stat() seed file " RANDOM_SEED
": %m");
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 */
130 *ret_size
= CLAMP((uint64_t)st
.st_size
, random_pool_size(), RANDOM_POOL_SIZE_MAX
);
134 static int load_seed_file(
138 struct sha256_ctx
**ret_hash_state
) {
140 _cleanup_free_
void *buf
= NULL
;
141 CreditEntropy lets_credit
;
146 assert(seed_fd
>= 0);
147 assert(urandom_fd
>= 0);
149 /* First, let's write the machine ID into /dev/urandom, not crediting entropy. Why? As an extra
150 * protection against "golden images" that are put together sloppily, i.e. images which are
151 * duplicated on multiple systems but where the random seed file is not properly reset. Frequently
152 * the machine ID is properly reset on those systems however (simply because it's easier to notice,
153 * if it isn't due to address clashes and so on, while random seed equivalence is generally not
154 * noticed easily), hence let's simply write the machined ID into the random pool too. */
155 r
= sd_id128_get_machine(&mid
);
157 log_debug_errno(r
, "Failed to get machine ID, ignoring: %m");
159 r
= random_write_entropy(urandom_fd
, &mid
, sizeof(mid
), /* credit= */ false);
161 log_debug_errno(r
, "Failed to write machine ID to /dev/urandom, ignoring: %m");
164 buf
= malloc(seed_size
);
168 k
= loop_read(seed_fd
, buf
, seed_size
, false);
170 log_warning_errno(k
, "Failed to read seed from " RANDOM_SEED
": %m");
174 log_debug("Seed file " RANDOM_SEED
" not yet initialized, proceeding.");
178 /* If we're going to later write out a seed file, initialize a hash state with the contents of the
179 * seed file we just read, so that the new one can't regress in entropy. */
180 if (ret_hash_state
) {
181 struct sha256_ctx
*hash_state
;
183 hash_state
= malloc(sizeof(struct sha256_ctx
));
187 sha256_init_ctx(hash_state
);
188 sha256_process_bytes(&k
, sizeof(k
), hash_state
); /* Hash length to distinguish from new seed. */
189 sha256_process_bytes(buf
, k
, hash_state
);
191 *ret_hash_state
= hash_state
;
194 (void) lseek(seed_fd
, 0, SEEK_SET
);
196 lets_credit
= may_credit(seed_fd
);
198 /* Before we credit or use the entropy, let's make sure to securely drop the creditable xattr from
199 * the file, so that we never credit the same random seed again. Note that further down we'll write a
200 * new seed again, and likely mark it as credible again, hence this is just paranoia to close the
201 * short time window between the time we upload the random seed into the kernel and download the new
204 if (fremovexattr(seed_fd
, "user.random-seed-creditable") < 0) {
205 if (!ERRNO_IS_XATTR_ABSENT(errno
))
206 log_warning_errno(errno
, "Failed to remove extended attribute, ignoring: %m");
208 /* Otherwise, there was no creditable flag set, which is OK. */
210 r
= fsync_full(seed_fd
);
212 log_warning_errno(r
, "Failed to synchronize seed to disk, not crediting entropy: %m");
214 if (lets_credit
== CREDIT_ENTROPY_YES_PLEASE
)
215 lets_credit
= CREDIT_ENTROPY_NO_WAY
;
219 r
= random_write_entropy(urandom_fd
, buf
, k
,
220 IN_SET(lets_credit
, CREDIT_ENTROPY_YES_PLEASE
, CREDIT_ENTROPY_YES_FORCED
));
222 log_warning_errno(r
, "Failed to write seed to /dev/urandom: %m");
227 static int save_seed_file(
232 struct sha256_ctx
*hash_state
) {
234 _cleanup_free_
void *buf
= NULL
;
235 bool getrandom_worked
= false;
239 assert(seed_fd
>= 0);
240 assert(urandom_fd
>= 0);
242 /* This is just a safety measure. Given that we are root and most likely created the file ourselves
243 * the mode and owner should be correct anyway. */
244 r
= fchmod_and_chown(seed_fd
, 0600, 0, 0);
246 return log_error_errno(r
, "Failed to adjust seed file ownership and access mode: %m");
248 buf
= malloc(seed_size
);
252 k
= getrandom(buf
, seed_size
, GRND_NONBLOCK
);
253 if (k
< 0 && errno
== EAGAIN
&& synchronous
) {
254 /* If we're asked to make ourselves a barrier for proper initialization of the random pool
255 * make this whole job synchronous by asking getrandom() to wait until the requested number
256 * of random bytes is available. */
257 log_notice("Kernel entropy pool is not initialized yet, waiting until it is.");
258 k
= getrandom(buf
, seed_size
, 0);
261 log_debug_errno(errno
, "Failed to read random data with getrandom(), falling back to /dev/urandom: %m");
262 else if ((size_t) k
< seed_size
)
263 log_debug("Short read from getrandom(), falling back to /dev/urandom.");
265 getrandom_worked
= true;
267 if (!getrandom_worked
) {
268 /* Retry with classic /dev/urandom */
269 k
= loop_read(urandom_fd
, buf
, seed_size
, false);
271 return log_error_errno(k
, "Failed to read new seed from /dev/urandom: %m");
273 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Got EOF while reading from /dev/urandom.");
276 /* If we previously read in a seed file, then hash the new seed into the old one, and replace the
277 * last 32 bytes of the seed with the hash output, so that the new seed file can't regress in
280 uint8_t hash
[SHA256_DIGEST_SIZE
];
282 sha256_process_bytes(&k
, sizeof(k
), hash_state
); /* Hash length to distinguish from old seed. */
283 sha256_process_bytes(buf
, k
, hash_state
);
284 sha256_finish_ctx(hash_state
, hash
);
285 l
= MIN((size_t)k
, sizeof(hash
));
286 memcpy((uint8_t *)buf
+ k
- l
, hash
, l
);
289 r
= loop_write(seed_fd
, buf
, (size_t) k
, false);
291 return log_error_errno(r
, "Failed to write new random seed file: %m");
293 if (ftruncate(seed_fd
, k
) < 0)
294 return log_error_errno(r
, "Failed to truncate random seed file: %m");
296 r
= fsync_full(seed_fd
);
298 return log_error_errno(r
, "Failed to synchronize seed file: %m");
300 /* If we got this random seed data from getrandom() the data is suitable for crediting entropy later
301 * on. Let's keep that in mind by setting an extended attribute. on the file */
302 if (getrandom_worked
)
303 if (fsetxattr(seed_fd
, "user.random-seed-creditable", "1", 1, 0) < 0)
304 log_full_errno(ERRNO_IS_NOT_SUPPORTED(errno
) ? LOG_DEBUG
: LOG_WARNING
, errno
,
305 "Failed to mark seed file as creditable, ignoring: %m");
309 static int help(int argc
, char *argv
[], void *userdata
) {
310 _cleanup_free_
char *link
= NULL
;
313 r
= terminal_urlify_man("systemd-random-seed", "8", &link
);
317 printf("%1$s [OPTIONS...] COMMAND\n"
318 "\n%5$sLoad and save the system random seed at boot and shutdown.%6$s\n"
319 "\n%3$sCommands:%4$s\n"
320 " load Load a random seed saved on disk into the kernel entropy pool\n"
321 " save Save a new random seed on disk\n"
322 "\n%3$sOptions:%4$s\n"
323 " -h --help Show this help\n"
324 " --version Show package version\n"
325 "\nSee the %2$s for details.\n",
326 program_invocation_short_name
,
336 static const char* const seed_action_table
[_ACTION_MAX
] = {
337 [ACTION_LOAD
] = "load",
338 [ACTION_SAVE
] = "save",
341 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(seed_action
, SeedAction
);
343 static int parse_argv(int argc
, char *argv
[]) {
348 static const struct option options
[] = {
349 { "help", no_argument
, NULL
, 'h' },
350 { "version", no_argument
, NULL
, ARG_VERSION
},
358 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
361 return help(0, NULL
, NULL
);
368 assert_not_reached();
371 if (optind
+ 1 != argc
)
372 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "This program requires one argument.");
374 arg_action
= seed_action_from_string(argv
[optind
]);
376 return log_error_errno(arg_action
, "Unknown action '%s'", argv
[optind
]);
381 static int run(int argc
, char *argv
[]) {
382 _cleanup_free_
struct sha256_ctx
*hash_state
= NULL
;
383 _cleanup_close_
int seed_fd
= -1, random_fd
= -1;
384 bool read_seed_file
, write_seed_file
, synchronous
;
390 r
= parse_argv(argc
, argv
);
396 r
= mkdir_parents(RANDOM_SEED
, 0755);
398 return log_error_errno(r
, "Failed to create directory " RANDOM_SEED_DIR
": %m");
400 /* When we load the seed we read it and write it to the device and then immediately update the saved
401 * seed with new data, to make sure the next boot gets seeded differently. */
403 switch (arg_action
) {
405 seed_fd
= open(RANDOM_SEED
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_CREAT
, 0600);
407 int open_rw_error
= -errno
;
409 write_seed_file
= false;
411 seed_fd
= open(RANDOM_SEED
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
413 bool missing
= errno
== ENOENT
;
414 int level
= missing
? LOG_DEBUG
: LOG_ERR
;
416 log_full_errno(level
, open_rw_error
, "Failed to open " RANDOM_SEED
" for writing: %m");
417 log_full_errno(level
, errno
, "Failed to open " RANDOM_SEED
" for reading: %m");
419 return missing
? 0 : -errno
;
422 write_seed_file
= true;
424 random_fd
= open("/dev/urandom", O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
426 return log_error_errno(errno
, "Failed to open /dev/urandom: %m");
428 read_seed_file
= true;
429 synchronous
= true; /* make this invocation a synchronous barrier for random pool initialization */
433 random_fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
435 return log_error_errno(errno
, "Failed to open /dev/urandom: %m");
437 seed_fd
= open(RANDOM_SEED
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|O_CREAT
, 0600);
439 return log_error_errno(errno
, "Failed to open " RANDOM_SEED
": %m");
441 read_seed_file
= false;
442 write_seed_file
= true;
447 assert_not_reached();
450 r
= random_seed_size(seed_fd
, &seed_size
);
455 r
= load_seed_file(seed_fd
, random_fd
, seed_size
,
456 write_seed_file
? &hash_state
: NULL
);
458 if (r
>= 0 && write_seed_file
)
459 r
= save_seed_file(seed_fd
, random_fd
, seed_size
, synchronous
, hash_state
);
464 DEFINE_MAIN_FUNCTION(run
);