]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/efivars.c
tree-wide: avoid some loaded terms
[thirdparty/systemd.git] / src / basic / efivars.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <linux/fs.h>
7 #include <stdlib.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10
11 #include "sd-id128.h"
12
13 #include "alloc-util.h"
14 #include "chattr-util.h"
15 #include "efivars.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "io-util.h"
19 #include "macro.h"
20 #include "stdio-util.h"
21 #include "strv.h"
22 #include "time-util.h"
23 #include "utf8.h"
24 #include "virt.h"
25
26 #if ENABLE_EFI
27
28 /* Reads from efivarfs sometimes fail with EINTR. Retry that many times. */
29 #define EFI_N_RETRIES_NO_DELAY 20
30 #define EFI_N_RETRIES_TOTAL 25
31 #define EFI_RETRY_DELAY (50 * USEC_PER_MSEC)
32
33 char* efi_variable_path(sd_id128_t vendor, const char *name) {
34 char *p;
35
36 if (asprintf(&p,
37 "/sys/firmware/efi/efivars/%s-" SD_ID128_UUID_FORMAT_STR,
38 name, SD_ID128_FORMAT_VAL(vendor)) < 0)
39 return NULL;
40
41 return p;
42 }
43
44 static char* efi_variable_cache_path(sd_id128_t vendor, const char *name) {
45 char *p;
46
47 if (asprintf(&p,
48 "/run/systemd/efivars/%s-" SD_ID128_UUID_FORMAT_STR,
49 name, SD_ID128_FORMAT_VAL(vendor)) < 0)
50 return NULL;
51
52 return p;
53 }
54
55 int efi_get_variable(
56 sd_id128_t vendor,
57 const char *name,
58 uint32_t *ret_attribute,
59 void **ret_value,
60 size_t *ret_size) {
61
62 _cleanup_close_ int fd = -1;
63 _cleanup_free_ char *p = NULL;
64 _cleanup_free_ void *buf = NULL;
65 struct stat st;
66 usec_t begin;
67 uint32_t a;
68 ssize_t n;
69
70 assert(name);
71
72 p = efi_variable_path(vendor, name);
73 if (!p)
74 return -ENOMEM;
75
76 if (!ret_value && !ret_size && !ret_attribute) {
77 /* If caller is not interested in anything, just check if the variable exists and is
78 * readable. */
79 if (access(p, R_OK) < 0)
80 return -errno;
81
82 return 0;
83 }
84
85 if (DEBUG_LOGGING) {
86 log_debug("Reading EFI variable %s.", p);
87 begin = now(CLOCK_MONOTONIC);
88 }
89
90 fd = open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC);
91 if (fd < 0)
92 return log_debug_errno(errno, "open(\"%s\") failed: %m", p);
93
94 if (fstat(fd, &st) < 0)
95 return log_debug_errno(errno, "fstat(\"%s\") failed: %m", p);
96 if (st.st_size < 4)
97 return log_debug_errno(SYNTHETIC_ERRNO(ENODATA), "EFI variable %s is shorter than 4 bytes, refusing.", p);
98 if (st.st_size > 4*1024*1024 + 4)
99 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "EFI variable %s is ridiculously large, refusing.", p);
100
101 if (ret_value || ret_attribute) {
102 /* The kernel ratelimits reads from the efivarfs because EFI is inefficient, and we'll
103 * occasionally fail with EINTR here. A slowdown is better than a failure for us, so
104 * retry a few times and eventually fail with -EBUSY.
105 *
106 * See https://github.com/torvalds/linux/blob/master/fs/efivarfs/file.c#L75
107 * and
108 * https://github.com/torvalds/linux/commit/bef3efbeb897b56867e271cdbc5f8adaacaeb9cd.
109 */
110 for (unsigned try = 0;; try++) {
111 n = read(fd, &a, sizeof(a));
112 if (n >= 0)
113 break;
114 log_debug_errno(errno, "Reading from \"%s\" failed: %m", p);
115 if (errno != EINTR)
116 return -errno;
117 if (try >= EFI_N_RETRIES_TOTAL)
118 return -EBUSY;
119
120 if (try >= EFI_N_RETRIES_NO_DELAY)
121 (void) usleep(EFI_RETRY_DELAY);
122 }
123
124 if (n != sizeof(a))
125 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
126 "Read %zi bytes from EFI variable %s, expected %zu.", n, p, sizeof(a));
127 }
128
129 if (ret_value) {
130 buf = malloc(st.st_size - 4 + 3);
131 if (!buf)
132 return -ENOMEM;
133
134 n = read(fd, buf, (size_t) st.st_size - 4);
135 if (n < 0)
136 return log_debug_errno(errno, "Failed to read value of EFI variable %s: %m", p);
137 assert(n <= st.st_size - 4);
138
139 /* Always NUL terminate (3 bytes, to properly protect UTF-16, even if truncated in the middle of a character) */
140 ((char*) buf)[n] = 0;
141 ((char*) buf)[n + 1] = 0;
142 ((char*) buf)[n + 2] = 0;
143 } else
144 /* Assume that the reported size is accurate */
145 n = st.st_size - 4;
146
147 if (DEBUG_LOGGING) {
148 char ts[FORMAT_TIMESPAN_MAX];
149 usec_t end;
150
151 end = now(CLOCK_MONOTONIC);
152 if (end > begin + EFI_RETRY_DELAY)
153 log_debug("Detected slow EFI variable read access on " SD_ID128_FORMAT_STR "-%s: %s",
154 SD_ID128_FORMAT_VAL(vendor), name, format_timespan(ts, sizeof(ts), end - begin, 1));
155 }
156
157 /* Note that efivarfs interestingly doesn't require ftruncate() to update an existing EFI variable
158 * with a smaller value. */
159
160 if (ret_attribute)
161 *ret_attribute = a;
162
163 if (ret_value)
164 *ret_value = TAKE_PTR(buf);
165
166 if (ret_size)
167 *ret_size = n;
168
169 return 0;
170 }
171
172 int efi_get_variable_string(sd_id128_t vendor, const char *name, char **p) {
173 _cleanup_free_ void *s = NULL;
174 size_t ss = 0;
175 int r;
176 char *x;
177
178 r = efi_get_variable(vendor, name, NULL, &s, &ss);
179 if (r < 0)
180 return r;
181
182 x = utf16_to_utf8(s, ss);
183 if (!x)
184 return -ENOMEM;
185
186 *p = x;
187 return 0;
188 }
189
190 int efi_set_variable(
191 sd_id128_t vendor,
192 const char *name,
193 const void *value,
194 size_t size) {
195
196 struct var {
197 uint32_t attr;
198 char buf[];
199 } _packed_ * _cleanup_free_ buf = NULL;
200 _cleanup_free_ char *p = NULL;
201 _cleanup_close_ int fd = -1;
202 bool saved_flags_valid = false;
203 unsigned saved_flags;
204 int r;
205
206 assert(name);
207 assert(value || size == 0);
208
209 p = efi_variable_path(vendor, name);
210 if (!p)
211 return -ENOMEM;
212
213 /* Newer efivarfs protects variables that are not in an allow list with FS_IMMUTABLE_FL by default,
214 * to protect them for accidental removal and modification. We are not changing these variables
215 * accidentally however, hence let's unset the bit first. */
216
217 r = chattr_path(p, 0, FS_IMMUTABLE_FL, &saved_flags);
218 if (r < 0 && r != -ENOENT)
219 log_debug_errno(r, "Failed to drop FS_IMMUTABLE_FL flag from '%s', ignoring: %m", p);
220
221 saved_flags_valid = r >= 0;
222
223 if (size == 0) {
224 if (unlink(p) < 0) {
225 r = -errno;
226 goto finish;
227 }
228
229 return 0;
230 }
231
232 fd = open(p, O_WRONLY|O_CREAT|O_NOCTTY|O_CLOEXEC, 0644);
233 if (fd < 0) {
234 r = -errno;
235 goto finish;
236 }
237
238 buf = malloc(sizeof(uint32_t) + size);
239 if (!buf) {
240 r = -ENOMEM;
241 goto finish;
242 }
243
244 buf->attr = EFI_VARIABLE_NON_VOLATILE|EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
245 memcpy(buf->buf, value, size);
246
247 r = loop_write(fd, buf, sizeof(uint32_t) + size, false);
248 if (r < 0)
249 goto finish;
250
251 /* For some reason efivarfs doesn't update mtime automatically. Let's do it manually then. This is
252 * useful for processes that cache EFI variables to detect when changes occurred. */
253 if (futimens(fd, (struct timespec[2]) {
254 { .tv_nsec = UTIME_NOW },
255 { .tv_nsec = UTIME_NOW }
256 }) < 0)
257 log_debug_errno(errno, "Failed to update mtime/atime on %s, ignoring: %m", p);
258
259 r = 0;
260
261 finish:
262 if (saved_flags_valid) {
263 int q;
264
265 /* Restore the original flags field, just in case */
266 if (fd < 0)
267 q = chattr_path(p, saved_flags, FS_IMMUTABLE_FL, NULL);
268 else
269 q = chattr_fd(fd, saved_flags, FS_IMMUTABLE_FL, NULL);
270 if (q < 0)
271 log_debug_errno(q, "Failed to restore FS_IMMUTABLE_FL on '%s', ignoring: %m", p);
272 }
273
274 return r;
275 }
276
277 int efi_set_variable_string(sd_id128_t vendor, const char *name, const char *v) {
278 _cleanup_free_ char16_t *u16 = NULL;
279
280 u16 = utf8_to_utf16(v, strlen(v));
281 if (!u16)
282 return -ENOMEM;
283
284 return efi_set_variable(vendor, name, u16, (char16_strlen(u16) + 1) * sizeof(char16_t));
285 }
286
287 bool is_efi_boot(void) {
288 static int cache = -1;
289
290 if (cache < 0) {
291 if (detect_container() > 0)
292 cache = false;
293 else
294 cache = access("/sys/firmware/efi/", F_OK) >= 0;
295 }
296
297 return cache;
298 }
299
300 static int read_flag(const char *varname) {
301 _cleanup_free_ void *v = NULL;
302 uint8_t b;
303 size_t s;
304 int r;
305
306 if (!is_efi_boot()) /* If this is not an EFI boot, assume the queried flags are zero */
307 return 0;
308
309 r = efi_get_variable(EFI_VENDOR_GLOBAL, varname, NULL, &v, &s);
310 if (r < 0)
311 return r;
312
313 if (s != 1)
314 return -EINVAL;
315
316 b = *(uint8_t *)v;
317 return !!b;
318 }
319
320 bool is_efi_secure_boot(void) {
321 static int cache = -1;
322
323 if (cache < 0)
324 cache = read_flag("SecureBoot");
325
326 return cache > 0;
327 }
328
329 bool is_efi_secure_boot_setup_mode(void) {
330 static int cache = -1;
331
332 if (cache < 0)
333 cache = read_flag("SetupMode");
334
335 return cache > 0;
336 }
337
338 int cache_efi_options_variable(void) {
339 _cleanup_free_ char *line = NULL, *cachepath = NULL;
340 int r;
341
342 /* In SecureBoot mode this is probably not what you want. As your cmdline is cryptographically signed
343 * like when using Type #2 EFI Unified Kernel Images (https://systemd.io/BOOT_LOADER_SPECIFICATION/)
344 * The user's intention is then that the cmdline should not be modified. You want to make sure that
345 * the system starts up as exactly specified in the signed artifact.
346 *
347 * (NB: For testing purposes, we still check the $SYSTEMD_EFI_OPTIONS env var before accessing this
348 * cache, even when in SecureBoot mode.) */
349 if (is_efi_secure_boot()) {
350 _cleanup_free_ char *k;
351
352 k = efi_variable_path(EFI_VENDOR_SYSTEMD, "SystemdOptions");
353 if (!k)
354 return -ENOMEM;
355
356 /* Let's be helpful with the returned error and check if the variable exists at all. If it
357 * does, let's return a recognizable error (EPERM), and if not ENODATA. */
358
359 if (access(k, F_OK) < 0)
360 return errno == ENOENT ? -ENODATA : -errno;
361
362 return -EPERM;
363 }
364
365 r = efi_get_variable_string(EFI_VENDOR_SYSTEMD, "SystemdOptions", &line);
366 if (r == -ENOENT)
367 return -ENODATA;
368 if (r < 0)
369 return r;
370
371 cachepath = efi_variable_cache_path(EFI_VENDOR_SYSTEMD, "SystemdOptions");
372 if (!cachepath)
373 return -ENOMEM;
374
375 return write_string_file(cachepath, line, WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755);
376 }
377
378 int systemd_efi_options_variable(char **line) {
379 const char *e;
380 _cleanup_free_ char *cachepath = NULL;
381 int r;
382
383 assert(line);
384
385 /* For testing purposes it is sometimes useful to be able to override this */
386 e = secure_getenv("SYSTEMD_EFI_OPTIONS");
387 if (e) {
388 char *m;
389
390 m = strdup(e);
391 if (!m)
392 return -ENOMEM;
393
394 *line = m;
395 return 0;
396 }
397
398 cachepath = efi_variable_cache_path(EFI_VENDOR_SYSTEMD, "SystemdOptions");
399 if (!cachepath)
400 return -ENOMEM;
401
402 r = read_one_line_file(cachepath, line);
403 if (r == -ENOENT)
404 return -ENODATA;
405 return r;
406 }
407 #endif