]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bootspec.c
systemd-boot: fix off-by-one buffer overrun
[thirdparty/systemd.git] / src / shared / bootspec.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2017 Zbigniew Jędrzejewski-Szmek
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <stdio.h>
21 #include <linux/magic.h>
22
23 #include "sd-id128.h"
24
25 #include "alloc-util.h"
26 #include "blkid-util.h"
27 #include "bootspec.h"
28 #include "conf-files.h"
29 #include "def.h"
30 #include "device-nodes.h"
31 #include "efivars.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "parse-util.h"
35 #include "stat-util.h"
36 #include "string-util.h"
37 #include "strv.h"
38 #include "virt.h"
39
40 void boot_entry_free(BootEntry *entry) {
41 assert(entry);
42
43 free(entry->filename);
44 free(entry->title);
45 free(entry->show_title);
46 free(entry->version);
47 free(entry->machine_id);
48 free(entry->architecture);
49 strv_free(entry->options);
50 free(entry->kernel);
51 free(entry->efi);
52 strv_free(entry->initrd);
53 free(entry->device_tree);
54 }
55
56 int boot_entry_load(const char *path, BootEntry *entry) {
57 _cleanup_(boot_entry_free) BootEntry tmp = {};
58 _cleanup_fclose_ FILE *f = NULL;
59 unsigned line = 1;
60 char *b, *c;
61 int r;
62
63 assert(path);
64 assert(entry);
65
66 c = endswith_no_case(path, ".conf");
67 if (!c) {
68 log_error("Invalid loader entry filename: %s", path);
69 return -EINVAL;
70 }
71
72 b = basename(path);
73 tmp.filename = strndup(b, c - b);
74 if (!tmp.filename)
75 return log_oom();
76
77 f = fopen(path, "re");
78 if (!f)
79 return log_error_errno(errno, "Failed to open \"%s\": %m", path);
80
81 for (;;) {
82 _cleanup_free_ char *buf = NULL;
83 char *p;
84
85 r = read_line(f, LONG_LINE_MAX, &buf);
86 if (r == 0)
87 break;
88 if (r == -ENOBUFS)
89 return log_error_errno(r, "%s:%u: Line too long", path, line);
90 if (r < 0)
91 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
92
93 line++;
94
95 if (IN_SET(*strstrip(buf), '#', '\0'))
96 continue;
97
98 p = strchr(buf, ' ');
99 if (!p) {
100 log_warning("%s:%u: Bad syntax", path, line);
101 continue;
102 }
103 *p = '\0';
104 p = strstrip(p + 1);
105
106 if (streq(buf, "title"))
107 r = free_and_strdup(&tmp.title, p);
108 else if (streq(buf, "version"))
109 r = free_and_strdup(&tmp.version, p);
110 else if (streq(buf, "machine-id"))
111 r = free_and_strdup(&tmp.machine_id, p);
112 else if (streq(buf, "architecture"))
113 r = free_and_strdup(&tmp.architecture, p);
114 else if (streq(buf, "options"))
115 r = strv_extend(&tmp.options, p);
116 else if (streq(buf, "linux"))
117 r = free_and_strdup(&tmp.kernel, p);
118 else if (streq(buf, "efi"))
119 r = free_and_strdup(&tmp.efi, p);
120 else if (streq(buf, "initrd"))
121 r = strv_extend(&tmp.initrd, p);
122 else if (streq(buf, "devicetree"))
123 r = free_and_strdup(&tmp.device_tree, p);
124 else {
125 log_notice("%s:%u: Unknown line \"%s\"", path, line, buf);
126 continue;
127 }
128 if (r < 0)
129 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
130 }
131
132 *entry = tmp;
133 tmp = (BootEntry) {};
134 return 0;
135 }
136
137 void boot_config_free(BootConfig *config) {
138 unsigned i;
139
140 assert(config);
141
142 free(config->default_pattern);
143 free(config->timeout);
144 free(config->editor);
145 free(config->auto_entries);
146 free(config->auto_firmware);
147
148 free(config->entry_oneshot);
149 free(config->entry_default);
150
151 for (i = 0; i < config->n_entries; i++)
152 boot_entry_free(config->entries + i);
153 free(config->entries);
154 }
155
156 int boot_loader_read_conf(const char *path, BootConfig *config) {
157 _cleanup_fclose_ FILE *f = NULL;
158 unsigned line = 1;
159 int r;
160
161 assert(path);
162 assert(config);
163
164 f = fopen(path, "re");
165 if (!f)
166 return log_error_errno(errno, "Failed to open \"%s\": %m", path);
167
168 for (;;) {
169 _cleanup_free_ char *buf = NULL;
170 char *p;
171
172 r = read_line(f, LONG_LINE_MAX, &buf);
173 if (r == 0)
174 break;
175 if (r == -ENOBUFS)
176 return log_error_errno(r, "%s:%u: Line too long", path, line);
177 if (r < 0)
178 return log_error_errno(r, "%s:%u: Error while reading: %m", path, line);
179
180 line++;
181
182 if (IN_SET(*strstrip(buf), '#', '\0'))
183 continue;
184
185 p = strchr(buf, ' ');
186 if (!p) {
187 log_warning("%s:%u: Bad syntax", path, line);
188 continue;
189 }
190 *p = '\0';
191 p = strstrip(p + 1);
192
193 if (streq(buf, "default"))
194 r = free_and_strdup(&config->default_pattern, p);
195 else if (streq(buf, "timeout"))
196 r = free_and_strdup(&config->timeout, p);
197 else if (streq(buf, "editor"))
198 r = free_and_strdup(&config->editor, p);
199 else if (streq(buf, "auto-entries"))
200 r = free_and_strdup(&config->auto_entries, p);
201 else if (streq(buf, "auto-firmware"))
202 r = free_and_strdup(&config->auto_firmware, p);
203 else {
204 log_notice("%s:%u: Unknown line \"%s\"", path, line, buf);
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 0;
212 }
213
214 static int boot_entry_compare(const void *a, const void *b) {
215 const BootEntry *aa = a, *bb = b;
216
217 return str_verscmp(aa->filename, bb->filename);
218 }
219
220 int boot_entries_find(const char *dir, BootEntry **ret_entries, size_t *ret_n_entries) {
221 _cleanup_strv_free_ char **files = NULL;
222 char **f;
223 int r;
224 BootEntry *array = NULL;
225 size_t n_allocated = 0, n = 0;
226
227 assert(dir);
228 assert(ret_entries);
229 assert(ret_n_entries);
230
231 r = conf_files_list(&files, ".conf", NULL, 0, dir, NULL);
232 if (r < 0)
233 return log_error_errno(r, "Failed to list files in \"%s\": %m", dir);
234
235 STRV_FOREACH(f, files) {
236 if (!GREEDY_REALLOC0(array, n_allocated, n + 1))
237 return log_oom();
238
239 r = boot_entry_load(*f, array + n);
240 if (r < 0)
241 continue;
242
243 n++;
244 }
245
246 qsort_safe(array, n, sizeof(BootEntry), boot_entry_compare);
247
248 *ret_entries = array;
249 *ret_n_entries = n;
250
251 return 0;
252 }
253
254 static bool find_nonunique(BootEntry *entries, size_t n_entries, bool *arr) {
255 unsigned i, j;
256 bool non_unique = false;
257
258 assert(entries || n_entries == 0);
259 assert(arr || n_entries == 0);
260
261 for (i = 0; i < n_entries; i++)
262 arr[i] = false;
263
264 for (i = 0; i < n_entries; i++)
265 for (j = 0; j < n_entries; j++)
266 if (i != j && streq(boot_entry_title(entries + i),
267 boot_entry_title(entries + j)))
268 non_unique = arr[i] = arr[j] = true;
269
270 return non_unique;
271 }
272
273 static int boot_entries_uniquify(BootEntry *entries, size_t n_entries) {
274 char *s;
275 unsigned i;
276 int r;
277 bool arr[n_entries];
278
279 assert(entries || n_entries == 0);
280
281 /* Find _all_ non-unique titles */
282 if (!find_nonunique(entries, n_entries, arr))
283 return 0;
284
285 /* Add version to non-unique titles */
286 for (i = 0; i < n_entries; i++)
287 if (arr[i] && entries[i].version) {
288 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].version);
289 if (r < 0)
290 return -ENOMEM;
291
292 free_and_replace(entries[i].show_title, s);
293 }
294
295 if (!find_nonunique(entries, n_entries, arr))
296 return 0;
297
298 /* Add machine-id to non-unique titles */
299 for (i = 0; i < n_entries; i++)
300 if (arr[i] && entries[i].machine_id) {
301 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].machine_id);
302 if (r < 0)
303 return -ENOMEM;
304
305 free_and_replace(entries[i].show_title, s);
306 }
307
308 if (!find_nonunique(entries, n_entries, arr))
309 return 0;
310
311 /* Add file name to non-unique titles */
312 for (i = 0; i < n_entries; i++)
313 if (arr[i]) {
314 r = asprintf(&s, "%s (%s)", boot_entry_title(entries + i), entries[i].filename);
315 if (r < 0)
316 return -ENOMEM;
317
318 free_and_replace(entries[i].show_title, s);
319 }
320
321 return 0;
322 }
323
324 static int boot_entries_select_default(const BootConfig *config) {
325 int i;
326
327 assert(config);
328
329 if (config->entry_oneshot)
330 for (i = config->n_entries - 1; i >= 0; i--)
331 if (streq(config->entry_oneshot, config->entries[i].filename)) {
332 log_debug("Found default: filename \"%s\" is matched by LoaderEntryOneShot",
333 config->entries[i].filename);
334 return i;
335 }
336
337 if (config->entry_default)
338 for (i = config->n_entries - 1; i >= 0; i--)
339 if (streq(config->entry_default, config->entries[i].filename)) {
340 log_debug("Found default: filename \"%s\" is matched by LoaderEntryDefault",
341 config->entries[i].filename);
342 return i;
343 }
344
345 if (config->default_pattern)
346 for (i = config->n_entries - 1; i >= 0; i--)
347 if (fnmatch(config->default_pattern, config->entries[i].filename, FNM_CASEFOLD) == 0) {
348 log_debug("Found default: filename \"%s\" is matched by pattern \"%s\"",
349 config->entries[i].filename, config->default_pattern);
350 return i;
351 }
352
353 if (config->n_entries > 0)
354 log_debug("Found default: last entry \"%s\"", config->entries[config->n_entries - 1].filename);
355 else
356 log_debug("Found no default boot entry :(");
357
358 return config->n_entries - 1; /* -1 means "no default" */
359 }
360
361 int boot_entries_load_config(const char *esp_path, BootConfig *config) {
362 const char *p;
363 int r;
364
365 assert(esp_path);
366 assert(config);
367
368 p = strjoina(esp_path, "/loader/loader.conf");
369 r = boot_loader_read_conf(p, config);
370 if (r < 0)
371 return log_error_errno(r, "Failed to read boot config from \"%s\": %m", p);
372
373 p = strjoina(esp_path, "/loader/entries");
374 r = boot_entries_find(p, &config->entries, &config->n_entries);
375 if (r < 0)
376 return log_error_errno(r, "Failed to read boot entries from \"%s\": %m", p);
377
378 r = boot_entries_uniquify(config->entries, config->n_entries);
379 if (r < 0)
380 return log_error_errno(r, "Failed to uniquify boot entries: %m");
381
382 r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntryOneShot", &config->entry_oneshot);
383 if (r < 0 && r != -ENOENT)
384 return log_error_errno(r, "Failed to read EFI var \"LoaderEntryOneShot\": %m");
385
386 r = efi_get_variable_string(EFI_VENDOR_LOADER, "LoaderEntryDefault", &config->entry_default);
387 if (r < 0 && r != -ENOENT)
388 return log_error_errno(r, "Failed to read EFI var \"LoaderEntryDefault\": %m");
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_probe_ 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 }