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