]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/random-seed/random-seed.c
Merge pull request #20893 from poettering/per-user-oom-score
[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>
26ded557 5#include <linux/random.h>
26ded557
LP
6#include <sys/ioctl.h>
7#if USE_SYS_RANDOM_H
8# include <sys/random.h>
9#endif
6e200d55 10#include <sys/stat.h>
26ded557 11#include <sys/xattr.h>
07630cea 12#include <unistd.h>
6e200d55 13
8ba12aef
LP
14#include "sd-id128.h"
15
b5efdb8a 16#include "alloc-util.h"
3ffd4af2 17#include "fd-util.h"
4b3b5bc7 18#include "fs-util.h"
c004493c 19#include "io-util.h"
6e200d55 20#include "log.h"
5e332028 21#include "main-func.h"
123aeae2 22#include "missing_random.h"
f5947a5e 23#include "missing_syscall.h"
49e942b2 24#include "mkdir.h"
26ded557 25#include "parse-util.h"
3e155eba 26#include "random-util.h"
07630cea
LP
27#include "string-util.h"
28#include "util.h"
26ded557
LP
29#include "xattr-util.h"
30
31typedef enum CreditEntropy {
32 CREDIT_ENTROPY_NO_WAY,
33 CREDIT_ENTROPY_YES_PLEASE,
34 CREDIT_ENTROPY_YES_FORCED,
35} CreditEntropy;
36
37static CreditEntropy may_credit(int seed_fd) {
38 _cleanup_free_ char *creditable = NULL;
39 const char *e;
40 int r;
41
42 assert(seed_fd >= 0);
43
44 e = getenv("SYSTEMD_RANDOM_SEED_CREDIT");
45 if (!e) {
46 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is not set, not crediting entropy.");
47 return CREDIT_ENTROPY_NO_WAY;
48 }
49 if (streq(e, "force")) {
50 log_debug("$SYSTEMD_RANDOM_SEED_CREDIT is set to 'force', crediting entropy.");
51 return CREDIT_ENTROPY_YES_FORCED;
52 }
53
54 r = parse_boolean(e);
55 if (r <= 0) {
56 if (r < 0)
57 log_warning_errno(r, "Failed to parse $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy: %m");
58 else
59 log_debug("Crediting entropy is turned off via $SYSTEMD_RANDOM_SEED_CREDIT, not crediting entropy.");
60
61 return CREDIT_ENTROPY_NO_WAY;
62 }
63
64 /* Determine if the file is marked as creditable */
65 r = fgetxattr_malloc(seed_fd, "user.random-seed-creditable", &creditable);
66 if (r < 0) {
67 if (IN_SET(r, -ENODATA, -ENOSYS, -EOPNOTSUPP))
68 log_debug_errno(r, "Seed file is not marked as creditable, not crediting.");
69 else
70 log_warning_errno(r, "Failed to read extended attribute, ignoring: %m");
71
72 return CREDIT_ENTROPY_NO_WAY;
73 }
74
75 r = parse_boolean(creditable);
76 if (r <= 0) {
77 if (r < 0)
78 log_warning_errno(r, "Failed to parse user.random-seed-creditable extended attribute, ignoring: %s", creditable);
79 else
80 log_debug("Seed file is marked as not creditable, not crediting.");
81
82 return CREDIT_ENTROPY_NO_WAY;
83 }
84
85 /* Don't credit the random seed if we are in first-boot mode, because we are supposed to start from
86 * scratch. This is a safety precaution for cases where we people ship "golden" images with empty
87 * /etc but populated /var that contains a random seed. */
88 if (access("/run/systemd/first-boot", F_OK) < 0) {
89
90 if (errno != ENOENT) {
91 log_warning_errno(errno, "Failed to check whether we are in first-boot mode, not crediting entropy: %m");
92 return CREDIT_ENTROPY_NO_WAY;
93 }
94
95 /* If ENOENT all is good, we are not in first-boot mode. */
96 } else {
97 log_debug("Not crediting entropy, since booted in first-boot mode.");
98 return CREDIT_ENTROPY_NO_WAY;
99 }
100
101 return CREDIT_ENTROPY_YES_PLEASE;
102}
6e200d55 103
72d0d7a6 104static int run(int argc, char *argv[]) {
ce179470 105 _cleanup_close_ int seed_fd = -1, random_fd = -1;
26ded557 106 bool read_seed_file, write_seed_file, synchronous;
ce179470 107 _cleanup_free_ void* buf = NULL;
3e155eba 108 size_t buf_size;
ac93390b 109 struct stat st;
ce179470 110 ssize_t k;
ac93390b 111 int r;
6e200d55 112
d2acb93d 113 log_setup();
6e200d55 114
baaa35ad
ZJS
115 if (argc != 2)
116 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
117 "This program requires one argument.");
72d0d7a6 118
4c12626c
LP
119 umask(0022);
120
3e155eba 121 buf_size = random_pool_size();
26192dfc 122
5468d9af 123 r = mkdir_parents(RANDOM_SEED, 0755);
72d0d7a6
ZJS
124 if (r < 0)
125 return log_error_errno(r, "Failed to create directory " RANDOM_SEED_DIR ": %m");
b56e5747 126
ac93390b
LP
127 /* When we load the seed we read it and write it to the device and then immediately update the saved seed with
128 * new data, to make sure the next boot gets seeded differently. */
6e200d55
LP
129
130 if (streq(argv[1], "load")) {
131
ce179470
LP
132 seed_fd = open(RANDOM_SEED, O_RDWR|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
133 if (seed_fd < 0) {
15d961bf
LP
134 int open_rw_error = -errno;
135
ac93390b 136 write_seed_file = false;
8edc2d22 137
ce179470
LP
138 seed_fd = open(RANDOM_SEED, O_RDONLY|O_CLOEXEC|O_NOCTTY);
139 if (seed_fd < 0) {
8edc2d22
ZJS
140 bool missing = errno == ENOENT;
141
142 log_full_errno(missing ? LOG_DEBUG : LOG_ERR,
143 open_rw_error, "Failed to open " RANDOM_SEED " for writing: %m");
144 r = log_full_errno(missing ? LOG_DEBUG : LOG_ERR,
145 errno, "Failed to open " RANDOM_SEED " for reading: %m");
72d0d7a6 146 return missing ? 0 : r;
6e200d55 147 }
ac93390b
LP
148 } else
149 write_seed_file = true;
6e200d55 150
ce179470 151 random_fd = open("/dev/urandom", O_RDWR|O_CLOEXEC|O_NOCTTY, 0600);
c6127c39
LP
152 if (random_fd < 0)
153 return log_error_errno(errno, "Failed to open /dev/urandom: %m");
6e200d55 154
ac93390b 155 read_seed_file = true;
26ded557 156 synchronous = true; /* make this invocation a synchronous barrier for random pool initialization */
6e200d55
LP
157
158 } else if (streq(argv[1], "save")) {
159
ac93390b 160 random_fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
72d0d7a6
ZJS
161 if (random_fd < 0)
162 return log_error_errno(errno, "Failed to open /dev/urandom: %m");
ac93390b 163
ce179470 164 seed_fd = open(RANDOM_SEED, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_CREAT, 0600);
72d0d7a6
ZJS
165 if (seed_fd < 0)
166 return log_error_errno(errno, "Failed to open " RANDOM_SEED ": %m");
6e200d55 167
ac93390b
LP
168 read_seed_file = false;
169 write_seed_file = true;
26ded557 170 synchronous = false;
baaa35ad
ZJS
171 } else
172 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
173 "Unknown verb '%s'.", argv[1]);
6e200d55 174
72d0d7a6
ZJS
175 if (fstat(seed_fd, &st) < 0)
176 return log_error_errno(errno, "Failed to stat() seed file " RANDOM_SEED ": %m");
ac93390b
LP
177
178 /* If the seed file is larger than what we expect, then honour the existing size and save/restore as much as it says */
179 if ((uint64_t) st.st_size > buf_size)
3e155eba 180 buf_size = MIN(st.st_size, RANDOM_POOL_SIZE_MAX);
ac93390b
LP
181
182 buf = malloc(buf_size);
72d0d7a6
ZJS
183 if (!buf)
184 return log_oom();
ac93390b
LP
185
186 if (read_seed_file) {
8ba12aef 187 sd_id128_t mid;
26ded557
LP
188
189 /* First, let's write the machine ID into /dev/urandom, not crediting entropy. Why? As an
190 * extra protection against "golden images" that are put together sloppily, i.e. images which
191 * are duplicated on multiple systems but where the random seed file is not properly
192 * reset. Frequently the machine ID is properly reset on those systems however (simply
193 * because it's easier to notice, if it isn't due to address clashes and so on, while random
194 * seed equivalence is generally not noticed easily), hence let's simply write the machined
195 * ID into the random pool too. */
196 r = sd_id128_get_machine(&mid);
197 if (r < 0)
198 log_debug_errno(r, "Failed to get machine ID, ignoring: %m");
199 else {
200 r = loop_write(random_fd, &mid, sizeof(mid), false);
201 if (r < 0)
202 log_debug_errno(r, "Failed to write machine ID to /dev/urandom, ignoring: %m");
203 }
ac93390b
LP
204
205 k = loop_read(seed_fd, buf, buf_size, false);
206 if (k < 0)
26ded557
LP
207 log_error_errno(k, "Failed to read seed from " RANDOM_SEED ": %m");
208 else if (k == 0)
ac93390b 209 log_debug("Seed file " RANDOM_SEED " not yet initialized, proceeding.");
26ded557
LP
210 else {
211 CreditEntropy lets_credit;
212
ac93390b
LP
213 (void) lseek(seed_fd, 0, SEEK_SET);
214
26ded557 215 lets_credit = may_credit(seed_fd);
8ba12aef 216
26ded557
LP
217 /* Before we credit or use the entropy, let's make sure to securely drop the
218 * creditable xattr from the file, so that we never credit the same random seed
219 * again. Note that further down we'll write a new seed again, and likely mark it as
220 * credible again, hence this is just paranoia to close the short time window between
221 * the time we upload the random seed into the kernel and download the new one from
222 * it. */
223
224 if (fremovexattr(seed_fd, "user.random-seed-creditable") < 0) {
225 if (!IN_SET(errno, ENODATA, ENOSYS, EOPNOTSUPP))
226 log_warning_errno(errno, "Failed to remove extended attribute, ignoring: %m");
227
228 /* Otherwise, there was no creditable flag set, which is OK. */
229 } else {
230 r = fsync_full(seed_fd);
231 if (r < 0) {
232 log_warning_errno(r, "Failed to synchronize seed to disk, not crediting entropy: %m");
233
234 if (lets_credit == CREDIT_ENTROPY_YES_PLEASE)
235 lets_credit = CREDIT_ENTROPY_NO_WAY;
236 }
237 }
238
4dd055f9
LP
239 r = random_write_entropy(random_fd, buf, k,
240 IN_SET(lets_credit, CREDIT_ENTROPY_YES_PLEASE, CREDIT_ENTROPY_YES_FORCED));
241 if (r < 0)
242 log_error_errno(r, "Failed to write seed to /dev/urandom: %m");
8ba12aef 243 }
ac93390b
LP
244 }
245
246 if (write_seed_file) {
26ded557 247 bool getrandom_worked = false;
6e200d55 248
26ded557
LP
249 /* This is just a safety measure. Given that we are root and most likely created the file
250 * ourselves the mode and owner should be correct anyway. */
251 r = fchmod_and_chown(seed_fd, 0600, 0, 0);
252 if (r < 0)
253 return log_error_errno(r, "Failed to adjust seed file ownership and access mode.");
254
255 /* Let's make this whole job asynchronous, i.e. let's make ourselves a barrier for
256 * proper initialization of the random pool. */
257 k = getrandom(buf, buf_size, GRND_NONBLOCK);
258 if (k < 0 && errno == EAGAIN && synchronous) {
259 log_notice("Kernel entropy pool is not initialized yet, waiting until it is.");
260 k = getrandom(buf, buf_size, 0); /* retry synchronously */
261 }
72d0d7a6 262 if (k < 0)
26ded557
LP
263 log_debug_errno(errno, "Failed to read random data with getrandom(), falling back to /dev/urandom: %m");
264 else if ((size_t) k < buf_size)
111a3aae 265 log_debug("Short read from getrandom(), falling back to /dev/urandom.");
26ded557
LP
266 else
267 getrandom_worked = true;
268
269 if (!getrandom_worked) {
270 /* Retry with classic /dev/urandom */
271 k = loop_read(random_fd, buf, buf_size, false);
272 if (k < 0)
273 return log_error_errno(k, "Failed to read new seed from /dev/urandom: %m");
274 if (k == 0)
275 return log_error_errno(SYNTHETIC_ERRNO(EIO),
276 "Got EOF while reading from /dev/urandom.");
277 }
1509fb87
LP
278
279 r = loop_write(seed_fd, buf, (size_t) k, false);
280 if (r < 0)
72d0d7a6 281 return log_error_errno(r, "Failed to write new random seed file: %m");
26ded557
LP
282
283 if (ftruncate(seed_fd, k) < 0)
284 return log_error_errno(r, "Failed to truncate random seed file: %m");
285
286 r = fsync_full(seed_fd);
287 if (r < 0)
288 return log_error_errno(r, "Failed to synchronize seed file: %m");
289
290 /* If we got this random seed data from getrandom() the data is suitable for crediting
291 * entropy later on. Let's keep that in mind by setting an extended attribute. on the file */
292 if (getrandom_worked)
293 if (fsetxattr(seed_fd, "user.random-seed-creditable", "1", 1, 0) < 0)
97f1c6af 294 log_full_errno(ERRNO_IS_NOT_SUPPORTED(errno) ? LOG_DEBUG : LOG_WARNING, errno,
26ded557 295 "Failed to mark seed file as creditable, ignoring: %m");
6e200d55
LP
296 }
297
26ded557 298 return 0;
6e200d55 299}
72d0d7a6
ZJS
300
301DEFINE_MAIN_FUNCTION(run);