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