]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bootspec.c
bootspec: access EFI variables on on EFI boots
[thirdparty/systemd.git] / src / shared / bootspec.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <stdio.h>
4 #include <linux/magic.h>
5
6 #include "sd-id128.h"
7
8 #include "alloc-util.h"
9 #include "blkid-util.h"
10 #include "bootspec.h"
11 #include "conf-files.h"
12 #include "def.h"
13 #include "device-nodes.h"
14 #include "efivars.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "parse-util.h"
18 #include "stat-util.h"
19 #include "string-util.h"
20 #include "strv.h"
21 #include "virt.h"
22
23 static void boot_entry_free(BootEntry *entry) {
24 assert(entry);
25
26 free(entry->id);
27 free(entry->path);
28 free(entry->title);
29 free(entry->show_title);
30 free(entry->version);
31 free(entry->machine_id);
32 free(entry->architecture);
33 strv_free(entry->options);
34 free(entry->kernel);
35 free(entry->efi);
36 strv_free(entry->initrd);
37 free(entry->device_tree);
38 }
39
40 static int boot_entry_load(const char *path, BootEntry *entry) {
41 _cleanup_(boot_entry_free) BootEntry tmp = {};
42 _cleanup_fclose_ FILE *f = NULL;
43 unsigned line = 1;
44 char *b, *c;
45 int r;
46
47 assert(path);
48 assert(entry);
49
50 c = endswith_no_case(path, ".conf");
51 if (!c) {
52 log_error("Invalid loader entry filename: %s", path);
53 return -EINVAL;
54 }
55
56 b = basename(path);
57 tmp.id = strndup(b, c - b);
58 if (!tmp.id)
59 return log_oom();
60
61 tmp.path = strdup(path);
62 if (!tmp.path)
63 return log_oom();
64
65 f = fopen(path, "re");
66 if (!f)
67 return log_error_errno(errno, "Failed to open \"%s\": %m", path);
68
69 for (;;) {
70 _cleanup_free_ char *buf = NULL, *field = NULL;
71 const char *p;
72
73 r = read_line(f, LONG_LINE_MAX, &buf);
74 if (r == 0)
75 break;
76 if (r == -ENOBUFS)
77 return log_error_errno(r, "%s:%u: Line too long", path, line);
78 if (r < 0)
79 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
80
81 line++;
82
83 if (IN_SET(*strstrip(buf), '#', '\0'))
84 continue;
85
86 p = buf;
87 r = extract_first_word(&p, &field, " \t", 0);
88 if (r < 0) {
89 log_error_errno(r, "Failed to parse config file %s line %u: %m", path, line);
90 continue;
91 }
92 if (r == 0) {
93 log_warning("%s:%u: Bad syntax", path, line);
94 continue;
95 }
96
97 if (streq(field, "title"))
98 r = free_and_strdup(&tmp.title, p);
99 else if (streq(field, "version"))
100 r = free_and_strdup(&tmp.version, p);
101 else if (streq(field, "machine-id"))
102 r = free_and_strdup(&tmp.machine_id, p);
103 else if (streq(field, "architecture"))
104 r = free_and_strdup(&tmp.architecture, p);
105 else if (streq(field, "options"))
106 r = strv_extend(&tmp.options, p);
107 else if (streq(field, "linux"))
108 r = free_and_strdup(&tmp.kernel, p);
109 else if (streq(field, "efi"))
110 r = free_and_strdup(&tmp.efi, p);
111 else if (streq(field, "initrd"))
112 r = strv_extend(&tmp.initrd, p);
113 else if (streq(field, "devicetree"))
114 r = free_and_strdup(&tmp.device_tree, p);
115 else {
116 log_notice("%s:%u: Unknown line \"%s\"", path, line, field);
117 continue;
118 }
119 if (r < 0)
120 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
121 }
122
123 *entry = tmp;
124 tmp = (BootEntry) {};
125 return 0;
126 }
127
128 void boot_config_free(BootConfig *config) {
129 size_t i;
130
131 assert(config);
132
133 free(config->default_pattern);
134 free(config->timeout);
135 free(config->editor);
136 free(config->auto_entries);
137 free(config->auto_firmware);
138
139 free(config->entry_oneshot);
140 free(config->entry_default);
141
142 for (i = 0; i < config->n_entries; i++)
143 boot_entry_free(config->entries + i);
144 free(config->entries);
145 }
146
147 static int boot_loader_read_conf(const char *path, BootConfig *config) {
148 _cleanup_fclose_ FILE *f = NULL;
149 unsigned line = 1;
150 int r;
151
152 assert(path);
153 assert(config);
154
155 f = fopen(path, "re");
156 if (!f) {
157 if (errno == ENOENT)
158 return 0;
159
160 return log_error_errno(errno, "Failed to open \"%s\": %m", path);
161 }
162
163 for (;;) {
164 _cleanup_free_ char *buf = NULL, *field = NULL;
165 const char *p;
166
167 r = read_line(f, LONG_LINE_MAX, &buf);
168 if (r == 0)
169 break;
170 if (r == -ENOBUFS)
171 return log_error_errno(r, "%s:%u: Line too long", path, line);
172 if (r < 0)
173 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
174
175 line++;
176
177 if (IN_SET(*strstrip(buf), '#', '\0'))
178 continue;
179
180 p = buf;
181 r = extract_first_word(&p, &field, " \t", 0);
182 if (r < 0) {
183 log_error_errno(r, "Failed to parse config file %s line %u: %m", path, line);
184 continue;
185 }
186 if (r == 0) {
187 log_warning("%s:%u: Bad syntax", path, line);
188 continue;
189 }
190
191 if (streq(field, "default"))
192 r = free_and_strdup(&config->default_pattern, p);
193 else if (streq(field, "timeout"))
194 r = free_and_strdup(&config->timeout, p);
195 else if (streq(field, "editor"))
196 r = free_and_strdup(&config->editor, p);
197 else if (streq(field, "auto-entries"))
198 r = free_and_strdup(&config->auto_entries, p);
199 else if (streq(field, "auto-firmware"))
200 r = free_and_strdup(&config->auto_firmware, p);
201 else if (streq(field, "console-mode"))
202 r = free_and_strdup(&config->console_mode, p);
203 else {
204 log_notice("%s:%u: Unknown line \"%s\"", path, line, field);
205 continue;
206 }
207 if (r < 0)
208 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
209 }
210
211 return 1;
212 }
213
214 static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
215 return str_verscmp(a->id, b->id);
216 }
217
218 static int boot_entries_find(const char *dir, BootEntry **ret_entries, size_t *ret_n_entries) {
219 _cleanup_strv_free_ char **files = NULL;
220 char **f;
221 int r;
222 BootEntry *array = NULL;
223 size_t n_allocated = 0, n = 0;
224
225 assert(dir);
226 assert(ret_entries);
227 assert(ret_n_entries);
228
229 r = conf_files_list(&files, ".conf", NULL, 0, dir, NULL);
230 if (r < 0)
231 return log_error_errno(r, "Failed to list files in \"%s\": %m", dir);
232
233 STRV_FOREACH(f, files) {
234 if (!GREEDY_REALLOC0(array, n_allocated, n + 1))
235 return log_oom();
236
237 r = boot_entry_load(*f, array + n);
238 if (r < 0)
239 continue;
240
241 n++;
242 }
243
244 typesafe_qsort(array, n, boot_entry_compare);
245
246 *ret_entries = array;
247 *ret_n_entries = n;
248
249 return 0;
250 }
251
252 static bool find_nonunique(BootEntry *entries, size_t n_entries, bool *arr) {
253 size_t i, j;
254 bool non_unique = false;
255
256 assert(entries || n_entries == 0);
257 assert(arr || n_entries == 0);
258
259 for (i = 0; i < n_entries; i++)
260 arr[i] = false;
261
262 for (i = 0; i < n_entries; i++)
263 for (j = 0; j < n_entries; j++)
264 if (i != j && streq(boot_entry_title(entries + i),
265 boot_entry_title(entries + j)))
266 non_unique = arr[i] = arr[j] = true;
267
268 return non_unique;
269 }
270
271 static int boot_entries_uniquify(BootEntry *entries, size_t n_entries) {
272 char *s;
273 size_t i;
274 int r;
275 bool arr[n_entries];
276
277 assert(entries || n_entries == 0);
278
279 /* Find _all_ non-unique titles */
280 if (!find_nonunique(entries, n_entries, arr))
281 return 0;
282
283 /* Add version to non-unique titles */
284 for (i = 0; i < n_entries; i++)
285 if (arr[i] && entries[i].version) {
286 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].version);
287 if (r < 0)
288 return -ENOMEM;
289
290 free_and_replace(entries[i].show_title, s);
291 }
292
293 if (!find_nonunique(entries, n_entries, arr))
294 return 0;
295
296 /* Add machine-id to non-unique titles */
297 for (i = 0; i < n_entries; i++)
298 if (arr[i] && entries[i].machine_id) {
299 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].machine_id);
300 if (r < 0)
301 return -ENOMEM;
302
303 free_and_replace(entries[i].show_title, s);
304 }
305
306 if (!find_nonunique(entries, n_entries, arr))
307 return 0;
308
309 /* Add file name to non-unique titles */
310 for (i = 0; i < n_entries; i++)
311 if (arr[i]) {
312 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].id);
313 if (r < 0)
314 return -ENOMEM;
315
316 free_and_replace(entries[i].show_title, s);
317 }
318
319 return 0;
320 }
321
322 static int boot_entries_select_default(const BootConfig *config) {
323 int i;
324
325 assert(config);
326
327 if (config->entry_oneshot)
328 for (i = config->n_entries - 1; i >= 0; i--)
329 if (streq(config->entry_oneshot, config->entries[i].id)) {
330 log_debug("Found default: id \"%s\" is matched by LoaderEntryOneShot",
331 config->entries[i].id);
332 return i;
333 }
334
335 if (config->entry_default)
336 for (i = config->n_entries - 1; i >= 0; i--)
337 if (streq(config->entry_default, config->entries[i].id)) {
338 log_debug("Found default: id \"%s\" is matched by LoaderEntryDefault",
339 config->entries[i].id);
340 return i;
341 }
342
343 if (config->default_pattern)
344 for (i = config->n_entries - 1; i >= 0; i--)
345 if (fnmatch(config->default_pattern, config->entries[i].id, FNM_CASEFOLD) == 0) {
346 log_debug("Found default: id \"%s\" is matched by pattern \"%s\"",
347 config->entries[i].id, config->default_pattern);
348 return i;
349 }
350
351 if (config->n_entries > 0)
352 log_debug("Found default: last entry \"%s\"", config->entries[config->n_entries - 1].id);
353 else
354 log_debug("Found no default boot entry :(");
355
356 return config->n_entries - 1; /* -1 means "no default" */
357 }
358
359 int boot_entries_load_config(const char *esp_path, BootConfig *config) {
360 const char *p;
361 int r;
362
363 assert(esp_path);
364 assert(config);
365
366 p = strjoina(esp_path, "/loader/loader.conf");
367 r = boot_loader_read_conf(p, config);
368 if (r < 0)
369 return r;
370
371 p = strjoina(esp_path, "/loader/entries");
372 r = boot_entries_find(p, &config->entries, &config->n_entries);
373 if (r < 0)
374 return r;
375
376 r = boot_entries_uniquify(config->entries, config->n_entries);
377 if (r < 0)
378 return log_error_errno(r, "Failed to uniquify boot entries: %m");
379
380 if (is_efi_boot()) {
381 r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntryOneShot", &config->entry_oneshot);
382 if (r < 0 && r != -ENOENT)
383 return log_error_errno(r, "Failed to read EFI var \"LoaderEntryOneShot\": %m");
384
385 r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntryDefault", &config->entry_default);
386 if (r < 0 && r != -ENOENT)
387 return log_error_errno(r, "Failed to read EFI var \"LoaderEntryDefault\": %m");
388 }
389
390 config->default_entry = boot_entries_select_default(config);
391 return 0;
392 }
393
394 /********************************************************************************/
395
396 static int verify_esp(
397 const char *p,
398 bool searching,
399 bool unprivileged_mode,
400 uint32_t *ret_part,
401 uint64_t *ret_pstart,
402 uint64_t *ret_psize,
403 sd_id128_t *ret_uuid) {
404 #if HAVE_BLKID
405 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
406 char t[DEV_NUM_PATH_MAX];
407 const char *v;
408 #endif
409 uint64_t pstart = 0, psize = 0;
410 struct stat st, st2;
411 const char *t2;
412 struct statfs sfs;
413 sd_id128_t uuid = SD_ID128_NULL;
414 uint32_t part = 0;
415 int r;
416
417 assert(p);
418
419 /* Non-root user can only check the status, so if an error occured in the following, it does not cause any
420 * issues. Let's also, silence the error messages. */
421
422 if (statfs(p, &sfs) < 0) {
423 /* If we are searching for the mount point, don't generate a log message if we can't find the path */
424 if (errno == ENOENT && searching)
425 return -ENOENT;
426
427 return log_full_errno(unprivileged_mode && errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
428 "Failed to check file system type of \"%s\": %m", p);
429 }
430
431 if (!F_TYPE_EQUAL(sfs.f_type, MSDOS_SUPER_MAGIC)) {
432 if (searching)
433 return -EADDRNOTAVAIL;
434
435 log_error("File system \"%s\" is not a FAT EFI System Partition (ESP) file system.", p);
436 return -ENODEV;
437 }
438
439 if (stat(p, &st) < 0)
440 return log_full_errno(unprivileged_mode && errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
441 "Failed to determine block device node of \"%s\": %m", p);
442
443 if (major(st.st_dev) == 0) {
444 log_error("Block device node of %p is invalid.", p);
445 return -ENODEV;
446 }
447
448 t2 = strjoina(p, "/..");
449 r = stat(t2, &st2);
450 if (r < 0)
451 return log_full_errno(unprivileged_mode && errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
452 "Failed to determine block device node of parent of \"%s\": %m", p);
453
454 if (st.st_dev == st2.st_dev) {
455 log_error("Directory \"%s\" is not the root of the EFI System Partition (ESP) file system.", p);
456 return -ENODEV;
457 }
458
459 /* In a container we don't have access to block devices, skip this part of the verification, we trust the
460 * container manager set everything up correctly on its own. Also skip the following verification for non-root user. */
461 if (detect_container() > 0 || unprivileged_mode)
462 goto finish;
463
464 #if HAVE_BLKID
465 xsprintf_dev_num_path(t, "block", st.st_dev);
466 errno = 0;
467 b = blkid_new_probe_from_filename(t);
468 if (!b)
469 return log_error_errno(errno ?: ENOMEM, "Failed to open file system \"%s\": %m", p);
470
471 blkid_probe_enable_superblocks(b, 1);
472 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
473 blkid_probe_enable_partitions(b, 1);
474 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
475
476 errno = 0;
477 r = blkid_do_safeprobe(b);
478 if (r == -2) {
479 log_error("File system \"%s\" is ambiguous.", p);
480 return -ENODEV;
481 } else if (r == 1) {
482 log_error("File system \"%s\" does not contain a label.", p);
483 return -ENODEV;
484 } else if (r != 0)
485 return log_error_errno(errno ?: EIO, "Failed to probe file system \"%s\": %m", p);
486
487 errno = 0;
488 r = blkid_probe_lookup_value(b, "TYPE", &v, NULL);
489 if (r != 0)
490 return log_error_errno(errno ?: EIO, "Failed to probe file system type \"%s\": %m", p);
491 if (!streq(v, "vfat")) {
492 log_error("File system \"%s\" is not FAT.", p);
493 return -ENODEV;
494 }
495
496 errno = 0;
497 r = blkid_probe_lookup_value(b, "PART_ENTRY_SCHEME", &v, NULL);
498 if (r != 0)
499 return log_error_errno(errno ?: EIO, "Failed to probe partition scheme \"%s\": %m", p);
500 if (!streq(v, "gpt")) {
501 log_error("File system \"%s\" is not on a GPT partition table.", p);
502 return -ENODEV;
503 }
504
505 errno = 0;
506 r = blkid_probe_lookup_value(b, "PART_ENTRY_TYPE", &v, NULL);
507 if (r != 0)
508 return log_error_errno(errno ?: EIO, "Failed to probe partition type UUID \"%s\": %m", p);
509 if (!streq(v, "c12a7328-f81f-11d2-ba4b-00a0c93ec93b")) {
510 log_error("File system \"%s\" has wrong type for an EFI System Partition (ESP).", p);
511 return -ENODEV;
512 }
513
514 errno = 0;
515 r = blkid_probe_lookup_value(b, "PART_ENTRY_UUID", &v, NULL);
516 if (r != 0)
517 return log_error_errno(errno ?: EIO, "Failed to probe partition entry UUID \"%s\": %m", p);
518 r = sd_id128_from_string(v, &uuid);
519 if (r < 0) {
520 log_error("Partition \"%s\" has invalid UUID \"%s\".", p, v);
521 return -EIO;
522 }
523
524 errno = 0;
525 r = blkid_probe_lookup_value(b, "PART_ENTRY_NUMBER", &v, NULL);
526 if (r != 0)
527 return log_error_errno(errno ?: EIO, "Failed to probe partition number \"%s\": m", p);
528 r = safe_atou32(v, &part);
529 if (r < 0)
530 return log_error_errno(r, "Failed to parse PART_ENTRY_NUMBER field.");
531
532 errno = 0;
533 r = blkid_probe_lookup_value(b, "PART_ENTRY_OFFSET", &v, NULL);
534 if (r != 0)
535 return log_error_errno(errno ?: EIO, "Failed to probe partition offset \"%s\": %m", p);
536 r = safe_atou64(v, &pstart);
537 if (r < 0)
538 return log_error_errno(r, "Failed to parse PART_ENTRY_OFFSET field.");
539
540 errno = 0;
541 r = blkid_probe_lookup_value(b, "PART_ENTRY_SIZE", &v, NULL);
542 if (r != 0)
543 return log_error_errno(errno ?: EIO, "Failed to probe partition size \"%s\": %m", p);
544 r = safe_atou64(v, &psize);
545 if (r < 0)
546 return log_error_errno(r, "Failed to parse PART_ENTRY_SIZE field.");
547 #endif
548
549 finish:
550 if (ret_part)
551 *ret_part = part;
552 if (ret_pstart)
553 *ret_pstart = pstart;
554 if (ret_psize)
555 *ret_psize = psize;
556 if (ret_uuid)
557 *ret_uuid = uuid;
558
559 return 0;
560 }
561
562 int find_esp_and_warn(
563 const char *path,
564 bool unprivileged_mode,
565 char **ret_path,
566 uint32_t *ret_part,
567 uint64_t *ret_pstart,
568 uint64_t *ret_psize,
569 sd_id128_t *ret_uuid) {
570
571 int r;
572
573 /* This logs about all errors except:
574 *
575 * -ENOKEY → when we can't find the partition
576 * -EACCESS → when unprivileged_mode is true, and we can't access something
577 */
578
579 if (path) {
580 r = verify_esp(path, false, unprivileged_mode, ret_part, ret_pstart, ret_psize, ret_uuid);
581 if (r < 0)
582 return r;
583
584 goto found;
585 }
586
587 FOREACH_STRING(path, "/efi", "/boot", "/boot/efi") {
588
589 r = verify_esp(path, true, unprivileged_mode, ret_part, ret_pstart, ret_psize, ret_uuid);
590 if (r >= 0)
591 goto found;
592 if (!IN_SET(r, -ENOENT, -EADDRNOTAVAIL)) /* This one is not it */
593 return r;
594 }
595
596 /* No logging here */
597 return -ENOKEY;
598
599 found:
600 if (ret_path) {
601 char *c;
602
603 c = strdup(path);
604 if (!c)
605 return log_oom();
606
607 *ret_path = c;
608 }
609
610 return 0;
611 }
612
613 int find_default_boot_entry(
614 const char *esp_path,
615 char **esp_where,
616 BootConfig *config,
617 const BootEntry **e) {
618
619 _cleanup_free_ char *where = NULL;
620 int r;
621
622 assert(config);
623 assert(e);
624
625 r = find_esp_and_warn(esp_path, false, &where, NULL, NULL, NULL, NULL);
626 if (r < 0)
627 return r;
628
629 r = boot_entries_load_config(where, config);
630 if (r < 0)
631 return log_error_errno(r, "Failed to load bootspec config from \"%s/loader\": %m", where);
632
633 if (config->default_entry < 0) {
634 log_error("No entry suitable as default, refusing to guess.");
635 return -ENOENT;
636 }
637
638 *e = &config->entries[config->default_entry];
639 log_debug("Found default boot entry in file \"%s\"", (*e)->path);
640
641 if (esp_where)
642 *esp_where = TAKE_PTR(where);
643
644 return 0;
645 }