]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/efivars.c
tree-wide: fix links to systemd.io pages
[thirdparty/systemd.git] / src / basic / efivars.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
0bb2f0f1
ZJS
2
3#include <errno.h>
4#include <fcntl.h>
5#include <limits.h>
6#include <linux/fs.h>
0bb2f0f1 7#include <stdlib.h>
0bb2f0f1
ZJS
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"
209b2592 17#include "fileio.h"
0bb2f0f1
ZJS
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"
c7d26acc 24#include "virt.h"
0bb2f0f1
ZJS
25
26#if ENABLE_EFI
27
7229ec02 28/* Reads from efivarfs sometimes fail with EINTR. Retry that many times. */
eee9b30a
ZJS
29#define EFI_N_RETRIES_NO_DELAY 20
30#define EFI_N_RETRIES_TOTAL 25
7229ec02
ZJS
31#define EFI_RETRY_DELAY (50 * USEC_PER_MSEC)
32
0bb2f0f1
ZJS
33char* 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
209b2592
FB
44static 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
0bb2f0f1
ZJS
55int 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;
698564d1 66 usec_t begin;
0bb2f0f1
ZJS
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) {
7229ec02
ZJS
77 /* If caller is not interested in anything, just check if the variable exists and is
78 * readable. */
0bb2f0f1
ZJS
79 if (access(p, R_OK) < 0)
80 return -errno;
81
82 return 0;
83 }
84
84190644
LP
85 if (DEBUG_LOGGING) {
86 log_debug("Reading EFI variable %s.", p);
698564d1 87 begin = now(CLOCK_MONOTONIC);
84190644 88 }
698564d1 89
0bb2f0f1
ZJS
90 fd = open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC);
91 if (fd < 0)
7229ec02 92 return log_debug_errno(errno, "open(\"%s\") failed: %m", p);
0bb2f0f1
ZJS
93
94 if (fstat(fd, &st) < 0)
84190644 95 return log_debug_errno(errno, "fstat(\"%s\") failed: %m", p);
0bb2f0f1 96 if (st.st_size < 4)
84190644 97 return log_debug_errno(SYNTHETIC_ERRNO(ENODATA), "EFI variable %s is shorter than 4 bytes, refusing.", p);
0bb2f0f1 98 if (st.st_size > 4*1024*1024 + 4)
84190644 99 return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "EFI variable %s is ridiculously large, refusing.", p);
0bb2f0f1
ZJS
100
101 if (ret_value || ret_attribute) {
7229ec02
ZJS
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;
84190644 114 log_debug_errno(errno, "Reading from \"%s\" failed: %m", p);
7229ec02
ZJS
115 if (errno != EINTR)
116 return -errno;
eee9b30a 117 if (try >= EFI_N_RETRIES_TOTAL)
7229ec02 118 return -EBUSY;
c75e7da0 119
eee9b30a
ZJS
120 if (try >= EFI_N_RETRIES_NO_DELAY)
121 (void) usleep(EFI_RETRY_DELAY);
7229ec02
ZJS
122 }
123
0bb2f0f1 124 if (n != sizeof(a))
84190644
LP
125 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
126 "Read %zi bytes from EFI variable %s, expected %zu.", n, p, sizeof(a));
0bb2f0f1
ZJS
127 }
128
129 if (ret_value) {
c75e7da0 130 buf = malloc(st.st_size - 4 + 3);
0bb2f0f1
ZJS
131 if (!buf)
132 return -ENOMEM;
133
134 n = read(fd, buf, (size_t) st.st_size - 4);
135 if (n < 0)
84190644 136 return log_debug_errno(errno, "Failed to read value of EFI variable %s: %m", p);
35b9eb0a 137 assert(n <= st.st_size - 4);
0bb2f0f1 138
c75e7da0 139 /* Always NUL terminate (3 bytes, to properly protect UTF-16, even if truncated in the middle of a character) */
861f1789
LP
140 ((char*) buf)[n] = 0;
141 ((char*) buf)[n + 1] = 0;
c75e7da0 142 ((char*) buf)[n + 2] = 0;
35b9eb0a
ZJS
143 } else
144 /* Assume that the reported size is accurate */
145 n = st.st_size - 4;
0bb2f0f1 146
698564d1
LP
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
0bb2f0f1
ZJS
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)
35b9eb0a 167 *ret_size = n;
0bb2f0f1
ZJS
168
169 return 0;
170}
171
172int 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
190int 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
6b000af4
LP
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. */
0bb2f0f1
ZJS
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
d197c403
LP
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
0bb2f0f1
ZJS
259 r = 0;
260
261finish:
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
277int 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
c7d26acc 287bool is_efi_boot(void) {
f46ba939 288 static int cache = -1;
c7d26acc 289
f46ba939
LP
290 if (cache < 0) {
291 if (detect_container() > 0)
292 cache = false;
5b4c1630 293 else {
f46ba939 294 cache = access("/sys/firmware/efi/", F_OK) >= 0;
5b4c1630
LP
295 if (!cache && errno != ENOENT)
296 log_debug_errno(errno, "Unable to test whether /sys/firmware/efi/ exists, assuming EFI not available: %m");
297 }
f46ba939
LP
298 }
299
300 return cache;
c7d26acc
AP
301}
302
303static int read_flag(const char *varname) {
304 _cleanup_free_ void *v = NULL;
305 uint8_t b;
306 size_t s;
307 int r;
308
309 if (!is_efi_boot()) /* If this is not an EFI boot, assume the queried flags are zero */
310 return 0;
311
312 r = efi_get_variable(EFI_VENDOR_GLOBAL, varname, NULL, &v, &s);
313 if (r < 0)
314 return r;
315
316 if (s != 1)
317 return -EINVAL;
318
319 b = *(uint8_t *)v;
320 return !!b;
321}
322
323bool is_efi_secure_boot(void) {
f46ba939
LP
324 static int cache = -1;
325
326 if (cache < 0)
327 cache = read_flag("SecureBoot");
328
329 return cache > 0;
c7d26acc
AP
330}
331
332bool is_efi_secure_boot_setup_mode(void) {
f46ba939
LP
333 static int cache = -1;
334
335 if (cache < 0)
336 cache = read_flag("SetupMode");
337
338 return cache > 0;
c7d26acc
AP
339}
340
209b2592
FB
341int cache_efi_options_variable(void) {
342 _cleanup_free_ char *line = NULL, *cachepath = NULL;
53aa0d02
ZJS
343 int r;
344
484f4e5b 345 /* In SecureBoot mode this is probably not what you want. As your cmdline is cryptographically signed
1d10005b 346 * like when using Type #2 EFI Unified Kernel Images (https://systemd.io/BOOT_LOADER_SPECIFICATION)
484f4e5b
LP
347 * The user's intention is then that the cmdline should not be modified. You want to make sure that
348 * the system starts up as exactly specified in the signed artifact.
349 *
209b2592
FB
350 * (NB: For testing purposes, we still check the $SYSTEMD_EFI_OPTIONS env var before accessing this
351 * cache, even when in SecureBoot mode.) */
484f4e5b
LP
352 if (is_efi_secure_boot()) {
353 _cleanup_free_ char *k;
354
355 k = efi_variable_path(EFI_VENDOR_SYSTEMD, "SystemdOptions");
356 if (!k)
357 return -ENOMEM;
358
359 /* Let's be helpful with the returned error and check if the variable exists at all. If it
360 * does, let's return a recognizable error (EPERM), and if not ENODATA. */
361
362 if (access(k, F_OK) < 0)
a0fa2683 363 return errno == ENOENT ? -ENODATA : -errno;
484f4e5b
LP
364
365 return -EPERM;
366 }
367
209b2592 368 r = efi_get_variable_string(EFI_VENDOR_SYSTEMD, "SystemdOptions", &line);
53aa0d02
ZJS
369 if (r == -ENOENT)
370 return -ENODATA;
209b2592
FB
371 if (r < 0)
372 return r;
53aa0d02 373
209b2592
FB
374 cachepath = efi_variable_cache_path(EFI_VENDOR_SYSTEMD, "SystemdOptions");
375 if (!cachepath)
376 return -ENOMEM;
377
378 return write_string_file(cachepath, line, WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755);
379}
380
381int systemd_efi_options_variable(char **line) {
382 const char *e;
383 _cleanup_free_ char *cachepath = NULL;
384 int r;
385
386 assert(line);
387
388 /* For testing purposes it is sometimes useful to be able to override this */
389 e = secure_getenv("SYSTEMD_EFI_OPTIONS");
390 if (e) {
391 char *m;
392
393 m = strdup(e);
394 if (!m)
395 return -ENOMEM;
396
397 *line = m;
398 return 0;
399 }
400
401 cachepath = efi_variable_cache_path(EFI_VENDOR_SYSTEMD, "SystemdOptions");
402 if (!cachepath)
403 return -ENOMEM;
404
405 r = read_one_line_file(cachepath, line);
406 if (r == -ENOENT)
407 return -ENODATA;
53aa0d02
ZJS
408 return r;
409}
0bb2f0f1 410#endif