Debian Codegraph @

src/random-seed/random-seed-tool.c

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