]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/random-seed/random-seed.c
random-seed: don't refresh EFI random seed from random-seed.c anymore
[thirdparty/systemd.git] / src / random-seed / random-seed.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
6e200d55 2
6e200d55 3#include <errno.h>
07630cea 4#include <fcntl.h>
0d0c6639 5#include <getopt.h>
26ded557 6#include <linux/random.h>
26ded557
LP
7#include <sys/ioctl.h>
8#if USE_SYS_RANDOM_H
9# include <sys/random.h>
10#endif
6e200d55 11#include <sys/stat.h>
26ded557 12#include <sys/xattr.h>
07630cea 13#include <unistd.h>
6e200d55 14
8ba12aef
LP
15#include "sd-id128.h"
16
b5efdb8a 17#include "alloc-util.h"
d6b4d1c7 18#include "build.h"
3ffd4af2 19#include "fd-util.h"
4b3b5bc7 20#include "fs-util.h"
c004493c 21#include "io-util.h"
6e200d55 22#include "log.h"
5e332028 23#include "main-func.h"
123aeae2 24#include "missing_random.h"
f5947a5e 25#include "missing_syscall.h"
49e942b2 26#include "mkdir.h"
26ded557 27#include "parse-util.h"
0d0c6639 28#include "pretty-print.h"
3e155eba 29#include "random-util.h"
0d0c6639 30#include "string-table.h"
07630cea 31#include "string-util.h"
bf819d3a 32#include "sync-util.h"
da2862ef 33#include "sha256.h"
26ded557
LP
34#include "xattr-util.h"
35
0d0c6639
FB
36typedef enum SeedAction {
37 ACTION_LOAD,
38 ACTION_SAVE,
39 _ACTION_MAX,
40 _ACTION_INVALID = -EINVAL,
41} SeedAction;
42
26ded557
LP
43typedef enum CreditEntropy {
44 CREDIT_ENTROPY_NO_WAY,
45 CREDIT_ENTROPY_YES_PLEASE,
46 CREDIT_ENTROPY_YES_FORCED,
47} CreditEntropy;
48
0d0c6639
FB
49static SeedAction arg_action = _ACTION_INVALID;
50
26ded557
LP
51static CreditEntropy may_credit(int seed_fd) {
52 _cleanup_free_ char *creditable = NULL;
53 const char *e;
54 int r;
55
56 assert(seed_fd >= 0);
57
58 e = getenv("SYSTEMD_RANDOM_SEED_CREDIT");
59 if (!e) {
60 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is not set, not crediting entropy.");
61 return CREDIT_ENTROPY_NO_WAY;
62 }
63 if (streq(e, "force")) {
64 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is set to 'force', crediting entropy.");
65 return CREDIT_ENTROPY_YES_FORCED;
66 }
67
68 r = parse_boolean(e);
69 if (r <= 0) {
70 if (r < 0)
71 log_warning_errno(r, "Failed to parse $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy: %m");
72 else
73 log_debug("Crediting entropy is turned off via $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy.");
74
75 return CREDIT_ENTROPY_NO_WAY;
76 }
77
78 /* Determine if the file is marked as creditable */
79 r = fgetxattr_malloc(seed_fd, "user.random-seed-creditable", &creditable);
80 if (r < 0) {
00675c36 81 if (ERRNO_IS_XATTR_ABSENT(r))
26ded557
LP
82 log_debug_errno(r, "Seed file is not marked as creditable, not crediting.");
83 else
84 log_warning_errno(r, "Failed to read extended attribute, ignoring: %m");
85
86 return CREDIT_ENTROPY_NO_WAY;
87 }
88
89 r = parse_boolean(creditable);
90 if (r <= 0) {
91 if (r < 0)
92 log_warning_errno(r, "Failed to parse user.random-seed-creditable extended attribute, ignoring: %s", creditable);
93 else
94 log_debug("Seed file is marked as not creditable, not crediting.");
95
96 return CREDIT_ENTROPY_NO_WAY;
97 }
98
99 /* Don't credit the random seed if we are in first-boot mode, because we are supposed to start from
100 * scratch. This is a safety precaution for cases where we people ship "golden" images with empty
101 * /etc but populated /var that contains a random seed. */
249d31b0
FB
102 r = RET_NERRNO(access("/run/systemd/first-boot", F_OK));
103 if (r == -ENOENT)
104 /* All is good, we are not in first-boot mode. */
105 return CREDIT_ENTROPY_YES_PLEASE;
106 if (r < 0) {
107 log_warning_errno(r, "Failed to check whether we are in first-boot mode, not crediting entropy: %m");
26ded557
LP
108 return CREDIT_ENTROPY_NO_WAY;
109 }
110
249d31b0
FB
111 log_debug("Not crediting entropy, since booted in first-boot mode.");
112 return CREDIT_ENTROPY_NO_WAY;
26ded557 113}
6e200d55 114
205138d8
FB
115static int random_seed_size(int seed_fd, size_t *ret_size) {
116 struct stat st;
117
118 assert(ret_size);
119 assert(seed_fd >= 0);
120
121 if (fstat(seed_fd, &st) < 0)
122 return log_error_errno(errno, "Failed to stat() seed file " RANDOM_SEED ": %m");
123
124 /* If the seed file is larger than what the kernel expects, then honour the existing size and
125 * save/restore as much as it says */
126
127 *ret_size = CLAMP((uint64_t)st.st_size, random_pool_size(), RANDOM_POOL_SIZE_MAX);
128 return 0;
129}
130
a2f0dbb8
FB
131static void load_machine_id(int urandom_fd) {
132 sd_id128_t mid;
133 int r;
134
135 assert(urandom_fd >= 0);
136
137 /* As an extra protection against "golden images" that are put together sloppily, i.e. images which
138 * are duplicated on multiple systems but where the random seed file is not properly
139 * reset. Frequently the machine ID is properly reset on those systems however (simply because it's
140 * easier to notice, if it isn't due to address clashes and so on, while random seed equivalence is
141 * generally not noticed easily), hence let's simply write the machined ID into the random pool
142 * too. */
143 r = sd_id128_get_machine(&mid);
144 if (r < 0)
145 return (void) log_debug_errno(r, "Failed to get machine ID, ignoring: %m");
146
147 r = random_write_entropy(urandom_fd, &mid, sizeof(mid), /* credit= */ false);
148 if (r < 0)
149 log_debug_errno(r, "Failed to write machine ID to /dev/urandom, ignoring: %m");
150}
151
d3fa881a
FB
152static int load_seed_file(
153 int seed_fd,
154 int urandom_fd,
155 size_t seed_size,
156 struct sha256_ctx **ret_hash_state) {
157
158 _cleanup_free_ void *buf = NULL;
159 CreditEntropy lets_credit;
d3fa881a
FB
160 ssize_t k;
161 int r;
162
163 assert(seed_fd >= 0);
164 assert(urandom_fd >= 0);
165
d3fa881a
FB
166 buf = malloc(seed_size);
167 if (!buf)
168 return log_oom();
169
170 k = loop_read(seed_fd, buf, seed_size, false);
171 if (k < 0) {
ea37e1ed 172 log_warning_errno(k, "Failed to read seed from " RANDOM_SEED ": %m");
d3fa881a
FB
173 return 0;
174 }
175 if (k == 0) {
176 log_debug("Seed file " RANDOM_SEED " not yet initialized, proceeding.");
177 return 0;
178 }
179
180 /* If we're going to later write out a seed file, initialize a hash state with the contents of the
181 * seed file we just read, so that the new one can't regress in entropy. */
182 if (ret_hash_state) {
183 struct sha256_ctx *hash_state;
184
f913c784 185 hash_state = new(struct sha256_ctx, 1);
d3fa881a
FB
186 if (!hash_state)
187 return log_oom();
188
189 sha256_init_ctx(hash_state);
a16c65f3 190 sha256_process_bytes_and_size(buf, k, hash_state); /* Hash with length to distinguish from new seed. */
d3fa881a
FB
191
192 *ret_hash_state = hash_state;
193 }
194
195 (void) lseek(seed_fd, 0, SEEK_SET);
196
197 lets_credit = may_credit(seed_fd);
198
199 /* Before we credit or use the entropy, let's make sure to securely drop the creditable xattr from
200 * the file, so that we never credit the same random seed again. Note that further down we'll write a
201 * new seed again, and likely mark it as credible again, hence this is just paranoia to close the
202 * short time window between the time we upload the random seed into the kernel and download the new
203 * one from it. */
204
205 if (fremovexattr(seed_fd, "user.random-seed-creditable") < 0) {
206 if (!ERRNO_IS_XATTR_ABSENT(errno))
207 log_warning_errno(errno, "Failed to remove extended attribute, ignoring: %m");
208
209 /* Otherwise, there was no creditable flag set, which is OK. */
210 } else {
211 r = fsync_full(seed_fd);
212 if (r < 0) {
213 log_warning_errno(r, "Failed to synchronize seed to disk, not crediting entropy: %m");
214
215 if (lets_credit == CREDIT_ENTROPY_YES_PLEASE)
216 lets_credit = CREDIT_ENTROPY_NO_WAY;
217 }
218 }
219
220 r = random_write_entropy(urandom_fd, buf, k,
221 IN_SET(lets_credit, CREDIT_ENTROPY_YES_PLEASE, CREDIT_ENTROPY_YES_FORCED));
222 if (r < 0)
ea37e1ed 223 log_warning_errno(r, "Failed to write seed to /dev/urandom: %m");
d3fa881a
FB
224
225 return 0;
226}
227
228static int save_seed_file(
229 int seed_fd,
230 int urandom_fd,
231 size_t seed_size,
232 bool synchronous,
233 struct sha256_ctx *hash_state) {
234
235 _cleanup_free_ void *buf = NULL;
236 bool getrandom_worked = false;
237 ssize_t k, l;
238 int r;
239
240 assert(seed_fd >= 0);
241 assert(urandom_fd >= 0);
242
243 /* This is just a safety measure. Given that we are root and most likely created the file ourselves
244 * the mode and owner should be correct anyway. */
245 r = fchmod_and_chown(seed_fd, 0600, 0, 0);
246 if (r < 0)
247 return log_error_errno(r, "Failed to adjust seed file ownership and access mode: %m");
248
249 buf = malloc(seed_size);
250 if (!buf)
251 return log_oom();
252
d3fa881a
FB
253 k = getrandom(buf, seed_size, GRND_NONBLOCK);
254 if (k < 0 && errno == EAGAIN && synchronous) {
46e0b5dc
FB
255 /* If we're asked to make ourselves a barrier for proper initialization of the random pool
256 * make this whole job synchronous by asking getrandom() to wait until the requested number
257 * of random bytes is available. */
d3fa881a 258 log_notice("Kernel entropy pool is not initialized yet, waiting until it is.");
46e0b5dc 259 k = getrandom(buf, seed_size, 0);
d3fa881a
FB
260 }
261 if (k < 0)
262 log_debug_errno(errno, "Failed to read random data with getrandom(), falling back to /dev/urandom: %m");
263 else if ((size_t) k < seed_size)
264 log_debug("Short read from getrandom(), falling back to /dev/urandom.");
265 else
266 getrandom_worked = true;
267
268 if (!getrandom_worked) {
269 /* Retry with classic /dev/urandom */
270 k = loop_read(urandom_fd, buf, seed_size, false);
271 if (k < 0)
272 return log_error_errno(k, "Failed to read new seed from /dev/urandom: %m");
273 if (k == 0)
274 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Got EOF while reading from /dev/urandom.");
275 }
276
277 /* If we previously read in a seed file, then hash the new seed into the old one, and replace the
278 * last 32 bytes of the seed with the hash output, so that the new seed file can't regress in
279 * entropy. */
280 if (hash_state) {
281 uint8_t hash[SHA256_DIGEST_SIZE];
282
a16c65f3 283 sha256_process_bytes_and_size(buf, k, hash_state); /* Hash with length to distinguish from old seed. */
d3fa881a
FB
284 sha256_finish_ctx(hash_state, hash);
285 l = MIN((size_t)k, sizeof(hash));
286 memcpy((uint8_t *)buf + k - l, hash, l);
287 }
288
289 r = loop_write(seed_fd, buf, (size_t) k, false);
290 if (r < 0)
291 return log_error_errno(r, "Failed to write new random seed file: %m");
292
293 if (ftruncate(seed_fd, k) < 0)
294 return log_error_errno(r, "Failed to truncate random seed file: %m");
295
296 r = fsync_full(seed_fd);
297 if (r < 0)
298 return log_error_errno(r, "Failed to synchronize seed file: %m");
299
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");
306 return 0;
307}
308
0d0c6639
FB
309static int help(int argc, char *argv[], void *userdata) {
310 _cleanup_free_ char *link = NULL;
311 int r;
312
313 r = terminal_urlify_man("systemd-random-seed", "8", &link);
314 if (r < 0)
315 return log_oom();
316
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,
327 link,
328 ansi_underline(),
329 ansi_normal(),
330 ansi_highlight(),
331 ansi_normal());
332
333 return 0;
334}
335
336static const char* const seed_action_table[_ACTION_MAX] = {
337 [ACTION_LOAD] = "load",
338 [ACTION_SAVE] = "save",
339};
340
341DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(seed_action, SeedAction);
342
343static int parse_argv(int argc, char *argv[]) {
344 enum {
345 ARG_VERSION = 0x100,
346 };
347
348 static const struct option options[] = {
349 { "help", no_argument, NULL, 'h' },
350 { "version", no_argument, NULL, ARG_VERSION },
351 };
352
353 int c;
354
355 assert(argc >= 0);
356 assert(argv);
357
358 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
359 switch (c) {
360 case 'h':
361 return help(0, NULL, NULL);
362 case ARG_VERSION:
363 return version();
364 case '?':
365 return -EINVAL;
366
367 default:
368 assert_not_reached();
369 }
370
371 if (optind + 1 != argc)
372 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires one argument.");
373
374 arg_action = seed_action_from_string(argv[optind]);
375 if (arg_action < 0)
376 return log_error_errno(arg_action, "Unknown action '%s'", argv[optind]);
377
378 return 1;
379}
380
72d0d7a6 381static int run(int argc, char *argv[]) {
d3fa881a 382 _cleanup_free_ struct sha256_ctx *hash_state = NULL;
254d1313 383 _cleanup_close_ int seed_fd = -EBADF, random_fd = -EBADF;
d3fa881a
FB
384 bool read_seed_file, write_seed_file, synchronous;
385 size_t seed_size;
ac93390b 386 int r;
6e200d55 387
d2acb93d 388 log_setup();
6e200d55 389
0d0c6639
FB
390 r = parse_argv(argc, argv);
391 if (r <= 0)
392 return r;
72d0d7a6 393
4c12626c
LP
394 umask(0022);
395
5468d9af 396 r = mkdir_parents(RANDOM_SEED, 0755);
72d0d7a6
ZJS
397 if (r < 0)
398 return log_error_errno(r, "Failed to create directory " RANDOM_SEED_DIR ": %m");
b56e5747 399
f913c784
JD
400 random_fd = open("/dev/urandom", O_RDWR|O_CLOEXEC|O_NOCTTY);
401 if (random_fd < 0)
402 return log_error_errno(errno, "Failed to open /dev/urandom: %m");
403
0d0c6639
FB
404 /* When we load the seed we read it and write it to the device and then immediately update the saved
405 * seed with new data, to make sure the next boot gets seeded differently. */
6e200d55 406
0d0c6639
FB
407 switch (arg_action) {
408 case ACTION_LOAD:
a2f0dbb8
FB
409 /* First, let's write the machine ID into /dev/urandom, not crediting entropy. See
410 * load_machine_id() for an explanation why. */
411 load_machine_id(random_fd);
412
ce179470
LP
413 seed_fd = open(RANDOM_SEED, O_RDWR|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
414 if (seed_fd < 0) {
15d961bf
LP
415 int open_rw_error = -errno;
416
ac93390b 417 write_seed_file = false;
8edc2d22 418
ce179470
LP
419 seed_fd = open(RANDOM_SEED, O_RDONLY|O_CLOEXEC|O_NOCTTY);
420 if (seed_fd < 0) {
8edc2d22 421 bool missing = errno == ENOENT;
3f6fbfe6 422 int level = missing ? LOG_DEBUG : LOG_ERR;
8edc2d22 423
3f6fbfe6
FB
424 log_full_errno(level, open_rw_error, "Failed to open " RANDOM_SEED " for writing: %m");
425 log_full_errno(level, errno, "Failed to open " RANDOM_SEED " for reading: %m");
29d487ad 426 return missing ? 0 : -errno;
6e200d55 427 }
ac93390b
LP
428 } else
429 write_seed_file = true;
6e200d55 430
ac93390b 431 read_seed_file = true;
26ded557 432 synchronous = true; /* make this invocation a synchronous barrier for random pool initialization */
0d0c6639 433 break;
6e200d55 434
0d0c6639 435 case ACTION_SAVE:
ce179470 436 seed_fd = open(RANDOM_SEED, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
72d0d7a6
ZJS
437 if (seed_fd < 0)
438 return log_error_errno(errno, "Failed to open " RANDOM_SEED ": %m");
6e200d55 439
ac93390b
LP
440 read_seed_file = false;
441 write_seed_file = true;
26ded557 442 synchronous = false;
0d0c6639
FB
443 break;
444
445 default:
446 assert_not_reached();
447 }
6e200d55 448
d3fa881a 449 r = random_seed_size(seed_fd, &seed_size);
205138d8
FB
450 if (r < 0)
451 return r;
ac93390b 452
29d487ad 453 if (read_seed_file)
d3fa881a
FB
454 r = load_seed_file(seed_fd, random_fd, seed_size,
455 write_seed_file ? &hash_state : NULL);
26ded557 456
d3fa881a
FB
457 if (r >= 0 && write_seed_file)
458 r = save_seed_file(seed_fd, random_fd, seed_size, synchronous, hash_state);
26ded557 459
d3fa881a 460 return r;
6e200d55 461}
72d0d7a6
ZJS
462
463DEFINE_MAIN_FUNCTION(run);