1 /*-
2 * Copyright (c) 2017-2018 Netflix, Inc.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer
9 * in this position and unchanged.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26 #include <sys/cdefs.h>
27 #include <sys/stat.h>
28 #include <sys/param.h>
29 #include <assert.h>
30 #include <ctype.h>
31 #include <err.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <libgeom.h>
35 #include <paths.h>
36 #include <signal.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <getopt.h>
41 #include <limits.h>
42 #include <inttypes.h>
43 #include <stdbool.h>
44 #include <string.h>
45 #include <strings.h>
46 #include <unistd.h>
47 #include <libgeom.h>
48 #include <geom/geom.h>
49 #include <geom/geom_ctl.h>
50 #include <geom/geom_int.h>
51
52 #include <efivar.h>
53 #include <efichar.h>
54 #include <efivar-dp.h>
55
56 #ifndef LOAD_OPTION_ACTIVE
57 #define LOAD_OPTION_ACTIVE 0x00000001
58 #endif
59
60 #ifndef LOAD_OPTION_FORCE_RECONNECT
61 #define LOAD_OPTION_FORCE_RECONNECT 0x00000002
62 #endif
63
64 #ifndef LOAD_OPTION_HIDDEN
65 #define LOAD_OPTION_HIDDEN 0x00000008
66 #endif
67
68 #ifndef LOAD_OPTION_CATEGORY
69 #define LOAD_OPTION_CATEGORY 0x00001F00
70 #endif
71
72 #ifndef LOAD_OPTION_CATEGORY_BOOT
73 #define LOAD_OPTION_CATEGORY_BOOT 0x00000000
74 #endif
75
76 #ifndef LOAD_OPTION_CATEGORY_APP
77 #define LOAD_OPTION_CATEGORY_APP 0x00000100
78 #endif
79
80 #define BAD_LENGTH ((size_t)-1)
81
82 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001
83
84 typedef struct _bmgr_opts {
85 char *dev;
86 char *env;
87 char *loader;
88 char *label;
89 char *kernel;
90 char *name;
91 char *order;
92 int bootnum;
93 bool copy;
94 bool create;
95 bool delete;
96 bool delete_bootnext;
97 bool del_timeout;
98 bool dry_run;
99 bool device_path;
100 bool esp_device;
101 bool find_dev;
102 bool fw_ui;
103 bool no_fw_ui;
104 bool has_bootnum;
105 bool once;
106 int cp_src;
107 bool set_active;
108 bool set_bootnext;
109 bool set_inactive;
110 bool set_timeout;
111 int timeout;
112 bool unix_path;
113 bool verbose;
114 } bmgr_opts_t;
115
116 static struct option lopts[] = {
117 {"activate", no_argument, NULL, 'a'},
118 {"bootnext", no_argument, NULL, 'n'}, /* set bootnext */
119 {"bootnum", required_argument, NULL, 'b'},
120 {"bootorder", required_argument, NULL, 'o'}, /* set order */
121 {"copy", required_argument, NULL, 'C'}, /* Copy boot method */
122 {"create", no_argument, NULL, 'c'},
123 {"deactivate", no_argument, NULL, 'A'},
124 {"del-timeout", no_argument, NULL, 'T'},
125 {"delete", no_argument, NULL, 'B'},
126 {"delete-bootnext", no_argument, NULL, 'N'},
127 {"device-path", no_argument, NULL, 'd'},
128 {"dry-run", no_argument, NULL, 'D'},
129 {"env", required_argument, NULL, 'e'},
130 {"esp", no_argument, NULL, 'E'},
131 {"efidev", required_argument, NULL, 'u'},
132 {"fw-ui", no_argument, NULL, 'f'},
133 {"no-fw-ui", no_argument, NULL, 'F'},
134 {"help", no_argument, NULL, 'h'},
135 {"kernel", required_argument, NULL, 'k'},
136 {"label", required_argument, NULL, 'L'},
137 {"loader", required_argument, NULL, 'l'},
138 {"once", no_argument, NULL, 'O'},
139 {"set-timeout", required_argument, NULL, 't'},
140 {"unix-path", no_argument, NULL, 'p'},
141 {"verbose", no_argument, NULL, 'v'},
142 { NULL, 0, NULL, 0}
143 };
144
145 /* global efibootmgr opts */
146 static bmgr_opts_t opts;
147
148 static LIST_HEAD(efivars_head, entry) efivars =
149 LIST_HEAD_INITIALIZER(efivars);
150
151 struct entry {
152 efi_guid_t guid;
153 uint32_t attrs;
154 uint8_t *data;
155 size_t size;
156 char *name;
157 char *label;
158 int idx;
159 int flags;
160 #define SEEN 1
161
162 LIST_ENTRY(entry) entries;
163 };
164
165 #define MAX_DP_LEN 4096
166 #define MAX_LOADOPT_LEN 8192
167
168
169 static char *
mangle_loader(char * loader)170 mangle_loader(char *loader)
171 {
172 char *c;
173
174 for (c = loader; *c; c++)
175 if (*c == '/')
176 *c = '\\';
177
178 return loader;
179 }
180
181
182 #define COMMON_ATTRS EFI_VARIABLE_NON_VOLATILE | \
183 EFI_VARIABLE_BOOTSERVICE_ACCESS | \
184 EFI_VARIABLE_RUNTIME_ACCESS
185
186 /*
187 * We use global guid, and common var attrs and
188 * find it better to just delete and re-create a var.
189 */
190 static int
set_bootvar(const char * name,uint8_t * data,size_t size)191 set_bootvar(const char *name, uint8_t *data, size_t size)
192 {
193
194 return efi_set_variable(EFI_GLOBAL_GUID, name, data, size,
195 COMMON_ATTRS);
196 }
197
198
199 #define USAGE \
200 " [-aAnB -b bootnum] [-N] [-t timeout] [-T] [-o bootorder] [-O] [--verbose] [--help]\n\
201 [-c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum]]"
202
203 #define CREATE_USAGE \
204 " efibootmgr -c -l loader [-k kernel] [-L label] [--dry-run] [-b bootnum] [-a]"
205 #define ORDER_USAGE \
206 " efibootmgr -o bootvarnum1,bootvarnum2,..."
207 #define TIMEOUT_USAGE \
208 " efibootmgr -t seconds"
209 #define DELETE_USAGE \
210 " efibootmgr -B -b bootnum"
211 #define ACTIVE_USAGE \
212 " efibootmgr [-a | -A] -b bootnum"
213 #define BOOTNEXT_USAGE \
214 " efibootmgr [-n | -N] -b bootnum"
215
216 static void
parse_args(int argc,char * argv[])217 parse_args(int argc, char *argv[])
218 {
219 int ch;
220 const char *arg;
221
222 while ((ch = getopt_long(argc, argv,
223 "AaBb:C:cdDe:EFfhk:L:l:NnOo:pTt:u:v", lopts, NULL)) != -1) {
224 switch (ch) {
225 case 'A':
226 opts.set_inactive = true;
227 break;
228 case 'a':
229 opts.set_active = true;
230 break;
231 case 'b':
232 opts.has_bootnum = true;
233 arg = optarg;
234 if (strncasecmp(arg, "boot", 4) == 0)
235 arg += 4;
236 opts.bootnum = strtoul(arg, NULL, 16);
237 break;
238 case 'B':
239 opts.delete = true;
240 break;
241 case 'C':
242 opts.copy = true;
243 opts.cp_src = strtoul(optarg, NULL, 16);
244 errx(1, "Copy not implemented");
245 break;
246 case 'c':
247 opts.create = true;
248 break;
249 case 'D': /* should be remove dups XXX */
250 opts.dry_run = true;
251 break;
252 case 'd':
253 opts.device_path = true;
254 break;
255 case 'e':
256 free(opts.env);
257 opts.env = strdup(optarg);
258 break;
259 case 'E':
260 opts.esp_device = true;
261 break;
262 case 'F':
263 opts.no_fw_ui = true;
264 break;
265 case 'f':
266 opts.fw_ui = true;
267 break;
268 case 'h':
269 default:
270 errx(1, "%s", USAGE);
271 break;
272 case 'k':
273 free(opts.kernel);
274 opts.kernel = strdup(optarg);
275 break;
276 case 'L':
277 free(opts.label);
278 opts.label = strdup(optarg);
279 break;
280 case 'l':
281 free(opts.loader);
282 opts.loader = strdup(optarg);
283 opts.loader = mangle_loader(opts.loader);
284 break;
285 case 'N':
286 opts.delete_bootnext = true;
287 break;
288 case 'n':
289 opts.set_bootnext = true;
290 break;
291 case 'O':
292 opts.once = true;
293 break;
294 case 'o':
295 free(opts.order);
296 opts.order = strdup(optarg);
297 break;
298 case 'p':
299 opts.unix_path = true;
300 break;
301 case 'T':
302 opts.del_timeout = true;
303 break;
304 case 't':
305 opts.set_timeout = true;
306 opts.timeout = strtoul(optarg, NULL, 10);
307 break;
308 case 'u':
309 opts.find_dev = true;
310 opts.dev = strdup(optarg);
311 break;
312 case 'v':
313 opts.verbose = true;
314 break;
315 }
316 }
317 if (opts.create) {
318 if (!opts.loader)
319 errx(1, "%s",CREATE_USAGE);
320 return;
321 }
322
323 if (opts.order != NULL && *opts.order == '\0')
324 errx(1, "%s", ORDER_USAGE);
325
326 if ((opts.set_inactive || opts.set_active) && !opts.has_bootnum)
327 errx(1, "%s", ACTIVE_USAGE);
328
329 if (opts.delete && !opts.has_bootnum)
330 errx(1, "%s", DELETE_USAGE);
331
332 if (opts.set_bootnext && !opts.has_bootnum)
333 errx(1, "%s", BOOTNEXT_USAGE);
334 }
335
336
337 static void
read_vars(void)338 read_vars(void)
339 {
340
341 efi_guid_t *guid;
342 char *next_name = NULL;
343 int ret = 0;
344
345 struct entry *nent;
346
347 LIST_INIT(&efivars);
348 while ((ret = efi_get_next_variable_name(&guid, &next_name)) > 0) {
349 /*
350 * Only pay attention to EFI:BootXXXX variables to get the list.
351 */
352 if (efi_guid_cmp(guid, &EFI_GLOBAL_GUID) != 0 ||
353 strlen(next_name) != 8 ||
354 strncmp(next_name, "Boot", 4) != 0 ||
355 !isxdigit(next_name[4]) ||
356 !isxdigit(next_name[5]) ||
357 !isxdigit(next_name[6]) ||
358 !isxdigit(next_name[7]))
359 continue;
360 nent = malloc(sizeof(struct entry));
361 nent->name = strdup(next_name);
362
363 ret = efi_get_variable(*guid, next_name, &nent->data,
364 &nent->size, &nent->attrs);
365 if (ret < 0)
366 err(1, "efi_get_variable");
367 nent->guid = *guid;
368 nent->idx = strtoul(&next_name[4], NULL, 16);
369 LIST_INSERT_HEAD(&efivars, nent, entries);
370 }
371 }
372
373
374 static void
set_boot_order(char * order)375 set_boot_order(char *order)
376 {
377 uint16_t *new_data;
378 size_t size;
379 char *next, *cp;
380 int cnt;
381 int i;
382
383 cp = order;
384 cnt = 1;
385 while (*cp) {
386 if (*cp++ == ',')
387 cnt++;
388 }
389 size = sizeof(uint16_t) * cnt;
390 new_data = malloc(size);
391
392 i = 0;
393 cp = strdup(order);
394 while ((next = strsep(&cp, ",")) != NULL) {
395 new_data[i] = strtoul(next, NULL, 16);
396 if (new_data[i] == 0 && errno == EINVAL) {
397 warnx("can't parse %s as a numb", next);
398 errx(1, "%s", ORDER_USAGE);
399 }
400 i++;
401 }
402 free(cp);
403 if (set_bootvar("BootOrder", (uint8_t*)new_data, size) < 0)
404 err(1, "Unabke to set BootOrder to %s", order);
405 free(new_data);
406 }
407
408 static void
handle_activity(int bootnum,bool active)409 handle_activity(int bootnum, bool active)
410 {
411 uint32_t attrs, load_attrs;
412 uint8_t *data;
413 size_t size;
414 char *name;
415
416 asprintf(&name, "%s%04X", "Boot", bootnum);
417 if (name == NULL)
418 err(1, "asprintf");
419 if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, &attrs) < 0)
420 err(1, "No such bootvar %s\n", name);
421
422 load_attrs = le32dec(data);
423
424 if (active)
425 load_attrs |= LOAD_OPTION_ACTIVE;
426 else
427 load_attrs &= ~LOAD_OPTION_ACTIVE;
428
429 le32enc(data, load_attrs);
430
431 if (set_bootvar(name, data, size) < 0)
432 err(1, "handle activity efi_set_variable");
433 }
434
435
436 /*
437 * add boot var to boot order.
438 * called by create boot var. There is no option
439 * to add one independent of create.
440 *
441 * Note: we currently don't support where it goes
442 * so it goes on the front, inactive.
443 * use -o 2,3,7 etc to affect order, -a to activate.
444 */
445 static void
add_to_boot_order(char * bootvar)446 add_to_boot_order(char *bootvar)
447 {
448 size_t size;
449 uint32_t attrs;
450 uint16_t val;
451 uint8_t *data, *new;
452
453 val = strtoul(&bootvar[4], NULL, 16);
454
455 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0) {
456 if (errno == ENOENT) { /* create it and set this bootvar to active */
457 size = 0;
458 data = NULL;
459 } else
460 err(1, "efi_get_variable BootOrder");
461 }
462
463 /*
464 * We have BootOrder with the current order
465 * so grow the array by one, add the value
466 * and write the new variable value.
467 */
468 size += sizeof(uint16_t);
469 new = malloc(size);
470 if (!new)
471 err(1, "malloc");
472
473 le16enc(new, val);
474 if (size > sizeof(uint16_t))
475 memcpy(new + sizeof(uint16_t), data, size - sizeof(uint16_t));
476
477 if (set_bootvar("BootOrder", new, size) < 0)
478 err(1, "set_bootvar");
479 free(new);
480 }
481
482
483 static void
remove_from_order(uint16_t bootnum)484 remove_from_order(uint16_t bootnum)
485 {
486 uint32_t attrs;
487 size_t size, i, j;
488 uint8_t *new, *data;
489
490 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) < 0)
491 return;
492
493 new = malloc(size);
494 if (new == NULL)
495 err(1, "malloc");
496
497 for (j = i = 0; i < size; i += sizeof(uint16_t)) {
498 if (le16dec(data + i) == bootnum)
499 continue;
500 memcpy(new + j, data + i, sizeof(uint16_t));
501 j += sizeof(uint16_t);
502 }
503 if (i == j)
504 warnx("Boot variable %04x not in BootOrder", bootnum);
505 else if (set_bootvar("BootOrder", new, j) < 0)
506 err(1, "Unable to update BootOrder with new value");
507 free(new);
508 }
509
510
511 static void
delete_bootvar(int bootnum)512 delete_bootvar(int bootnum)
513 {
514 char *name;
515 int defer = 0;
516
517 /*
518 * Try to delete the boot variable and remocve it
519 * from the boot order. We always do both actions
520 * to make it easy to clean up from oopses.
521 */
522 if (bootnum < 0 || bootnum > 0xffff)
523 errx(1, "Bad boot variable %#x", bootnum);
524 asprintf(&name, "%s%04X", "Boot", bootnum);
525 if (name == NULL)
526 err(1, "asprintf");
527 printf("Removing boot variable '%s'\n", name);
528 if (efi_del_variable(EFI_GLOBAL_GUID, name) < 0) {
529 defer = 1;
530 warn("cannot delete variable %s", name);
531 }
532 printf("Removing 0x%x from BootOrder\n", bootnum);
533 remove_from_order(bootnum);
534 free(name);
535 if (defer)
536 exit(defer);
537 }
538
539
540 static void
del_bootnext(void)541 del_bootnext(void)
542 {
543
544 if (efi_del_variable(EFI_GLOBAL_GUID, "BootNext") < 0)
545 err(1, "efi_del_variable");
546 }
547
548 static void
handle_bootnext(uint16_t bootnum)549 handle_bootnext(uint16_t bootnum)
550 {
551 uint16_t num;
552
553 le16enc(&num, bootnum);
554 if (set_bootvar("BootNext", (uint8_t*)&bootnum, sizeof(uint16_t)) < 0)
555 err(1, "set_bootvar");
556 }
557
558
559 static int
compare(const void * a,const void * b)560 compare(const void *a, const void *b)
561 {
562 uint16_t c;
563 uint16_t d;
564
565 memcpy(&c, a, sizeof(uint16_t));
566 memcpy(&d, b, sizeof(uint16_t));
567
568 if (c < d)
569 return -1;
570 if (c == d)
571 return 0;
572 return 1;
573 }
574
575 static char *
make_next_boot_var_name(void)576 make_next_boot_var_name(void)
577 {
578 struct entry *v;
579 uint16_t *vals;
580 char *name;
581 int cnt = 0;
582 int i;
583
584 LIST_FOREACH(v, &efivars, entries) {
585 cnt++;
586 }
587
588 vals = malloc(sizeof(uint16_t) * cnt);
589 if (!vals)
590 return NULL;
591
592 i = 0;
593 LIST_FOREACH(v, &efivars, entries) {
594 vals[i++] = v->idx;
595 }
596 qsort(vals, cnt, sizeof(uint16_t), compare);
597 /* Find the first hole (could be at start or end) */
598 for (i = 0; i < cnt; ++i)
599 if (vals[i] != i)
600 break;
601 free(vals);
602 /* In theory we could have used all 65k slots -- what to do? */
603
604 asprintf(&name, "%s%04X", "Boot", i);
605 if (name == NULL)
606 err(1, "asprintf");
607 return name;
608 }
609
610 static char *
make_boot_var_name(uint16_t bootnum)611 make_boot_var_name(uint16_t bootnum)
612 {
613 struct entry *v;
614 char *name;
615
616 LIST_FOREACH(v, &efivars, entries) {
617 if (v->idx == bootnum)
618 return NULL;
619 }
620
621 asprintf(&name, "%s%04X", "Boot", bootnum);
622 if (name == NULL)
623 err(1, "asprintf");
624 return name;
625 }
626
627 static size_t
create_loadopt(uint8_t * buf,size_t bufmax,uint32_t attributes,efidp dp,size_t dp_size,const char * description,const uint8_t * optional_data,size_t optional_data_size)628 create_loadopt(uint8_t *buf, size_t bufmax, uint32_t attributes, efidp dp, size_t dp_size,
629 const char *description, const uint8_t *optional_data, size_t optional_data_size)
630 {
631 efi_char *bbuf = NULL;
632 uint8_t *pos = buf;
633 size_t desc_len = 0;
634 size_t len;
635
636 if (optional_data == NULL && optional_data_size != 0)
637 return BAD_LENGTH;
638 if (dp == NULL && dp_size != 0)
639 return BAD_LENGTH;
640
641 /*
642 * Compute the length to make sure the passed in buffer is long enough.
643 */
644 utf8_to_ucs2(description, &bbuf, &desc_len);
645 len = sizeof(uint32_t) + sizeof(uint16_t) + desc_len + dp_size + optional_data_size;
646 if (len > bufmax) {
647 free(bbuf);
648 return BAD_LENGTH;
649 }
650
651 le32enc(pos, attributes);
652 pos += sizeof (attributes);
653
654 le16enc(pos, dp_size);
655 pos += sizeof (uint16_t);
656
657 memcpy(pos, bbuf, desc_len); /* NB:desc_len includes strailing NUL */
658 pos += desc_len;
659 free(bbuf);
660
661 memcpy(pos, dp, dp_size);
662 pos += dp_size;
663
664 if (optional_data && optional_data_size > 0) {
665 memcpy(pos, optional_data, optional_data_size);
666 pos += optional_data_size;
667 }
668
669 return pos - buf;
670 }
671
672
673 static int
make_boot_var(const char * label,const char * loader,const char * kernel,const char * env,bool dry_run,int bootnum,bool activate)674 make_boot_var(const char *label, const char *loader, const char *kernel, const char *env, bool dry_run,
675 int bootnum, bool activate)
676 {
677 struct entry *new_ent;
678 uint32_t load_attrs = 0;
679 uint8_t *load_opt_buf;
680 size_t lopt_size, llen, klen;
681 efidp dp, loaderdp, kerneldp;
682 char *bootvar = NULL;
683 int ret;
684
685 assert(label != NULL);
686
687 if (bootnum == -1)
688 bootvar = make_next_boot_var_name();
689 else
690 bootvar = make_boot_var_name((uint16_t)bootnum);
691 if (bootvar == NULL)
692 err(1, "bootvar creation");
693 if (loader == NULL)
694 errx(1, "Must specify boot loader");
695 ret = efivar_unix_path_to_device_path(loader, &loaderdp);
696 if (ret != 0)
697 errc(1, ret, "Cannot translate unix loader path '%s' to UEFI",
698 loader);
699 if (kernel != NULL) {
700 ret = efivar_unix_path_to_device_path(kernel, &kerneldp);
701 if (ret != 0)
702 errc(1, ret,
703 "Cannot translate unix kernel path '%s' to UEFI",
704 kernel);
705 } else {
706 kerneldp = NULL;
707 }
708 llen = efidp_size(loaderdp);
709 if (llen > MAX_DP_LEN)
710 errx(1, "Loader path too long.");
711 klen = efidp_size(kerneldp);
712 if (klen > MAX_DP_LEN)
713 errx(1, "Kernel path too long.");
714 dp = malloc(llen + klen);
715 if (dp == NULL)
716 errx(1, "Can't allocate memory for new device paths");
717 memcpy(dp, loaderdp, llen);
718 if (kerneldp != NULL)
719 memcpy((char *)dp + llen, kerneldp, klen);
720
721 /* don't make the new bootvar active by default, use the -a option later */
722 load_attrs = LOAD_OPTION_CATEGORY_BOOT;
723 if (activate)
724 load_attrs |= LOAD_OPTION_ACTIVE;
725 load_opt_buf = malloc(MAX_LOADOPT_LEN);
726 if (load_opt_buf == NULL)
727 err(1, "malloc");
728
729 lopt_size = create_loadopt(load_opt_buf, MAX_LOADOPT_LEN, load_attrs,
730 dp, llen + klen, label, env, env ? strlen(env) + 1 : 0);
731 if (lopt_size == BAD_LENGTH)
732 errx(1, "Can't create loadopt");
733
734 ret = 0;
735 if (!dry_run) {
736 ret = efi_set_variable(EFI_GLOBAL_GUID, bootvar,
737 (uint8_t*)load_opt_buf, lopt_size, COMMON_ATTRS);
738 }
739
740 if (ret)
741 err(1, "efi_set_variable");
742
743 if (!dry_run)
744 add_to_boot_order(bootvar); /* first, still not active */
745 new_ent = malloc(sizeof(struct entry));
746 if (new_ent == NULL)
747 err(1, "malloc");
748 memset(new_ent, 0, sizeof(struct entry));
749 new_ent->name = bootvar;
750 new_ent->guid = EFI_GLOBAL_GUID;
751 LIST_INSERT_HEAD(&efivars, new_ent, entries);
752 free(load_opt_buf);
753 free(dp);
754
755 return 0;
756 }
757
758
759 static void
print_loadopt_str(uint8_t * data,size_t datalen)760 print_loadopt_str(uint8_t *data, size_t datalen)
761 {
762 char *dev, *relpath, *abspath;
763 uint32_t attr, categ;
764 uint16_t fplen;
765 efi_char *descr;
766 uint8_t *ep = data + datalen;
767 uint8_t *walker = data, *opt;
768 efidp dp, edp;
769 char buf[1024];
770 int len, optlen;
771 int rv;
772 int indent;
773
774 if (datalen < sizeof(attr) + sizeof(fplen) + sizeof(efi_char))
775 return;
776 // First 4 bytes are attribute flags
777 attr = le32dec(walker);
778 walker += sizeof(attr);
779 // Next two bytes are length of the file paths
780 fplen = le16dec(walker);
781 walker += sizeof(fplen);
782 // Next we have a 0 terminated UCS2 string that we know to be aligned
783 descr = (efi_char *)(intptr_t)(void *)walker;
784 len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
785 walker += (len + 1) * sizeof(efi_char);
786 if (walker > ep)
787 return;
788 // Now we have fplen bytes worth of file path stuff
789 dp = (efidp)walker;
790 walker += fplen;
791 if (walker > ep)
792 return;
793 edp = (efidp)walker;
794
795 /* Everything left is the binary option args */
796 opt = walker;
797 optlen = ep - walker;
798
799 printf("\n");
800 printf(" dp:");
801 indent = 1;
802 while (dp < edp) {
803 if (efidp_size(dp) == 0)
804 break;
805 efidp_format_device_path(buf, sizeof(buf), dp,
806 (intptr_t)(void *)edp - (intptr_t)(void *)dp);
807 printf("%*s%s\n", indent, "", buf);
808 indent = 11;
809 rv = efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath);
810 if (rv == 0) {
811 printf("%*s%s:%s %s\n", indent + 4, "", dev, relpath, abspath);
812 free(dev);
813 free(relpath);
814 free(abspath);
815 }
816 dp = (efidp)((char *)dp + efidp_size(dp));
817 }
818
819 /* Optional Data */
820 if (optlen > 0) {
821 printf(" opt/x: ");
822 efi_hexdump(opt, optlen, 11);
823 printf(" opt/a: ");
824 efi_asciidump(opt, optlen, 11);
825 }
826
827 /* Attributes */
828 printf(" attr: %#x<", attr);
829 if (attr & LOAD_OPTION_ACTIVE)
830 printf("ACTIVE,");
831 if (attr & LOAD_OPTION_FORCE_RECONNECT)
832 printf("FORCE_RECONNECT,");
833 if (attr & LOAD_OPTION_HIDDEN)
834 printf("HIDDEN,");
835 printf(">\n");
836
837 /* Category */
838 categ = (attr & LOAD_OPTION_CATEGORY);
839 printf(" categ: %#x<", categ);
840 switch (categ) {
841 case LOAD_OPTION_CATEGORY_APP:
842 printf("APP");
843 break;
844 case LOAD_OPTION_CATEGORY_BOOT:
845 printf("BOOT");
846 break;
847 }
848 printf(">\n");
849 }
850
851 static char *
get_descr(uint8_t * data)852 get_descr(uint8_t *data)
853 {
854 uint8_t *pos = data;
855 efi_char *desc;
856 int len;
857 char *buf;
858 int i = 0;
859
860 pos += sizeof(uint32_t) + sizeof(uint16_t);
861 desc = (efi_char*)(intptr_t)(void *)pos;
862 len = ucs2len(desc);
863 buf = malloc(len + 1);
864 memset(buf, 0, len + 1);
865 while (desc[i]) {
866 buf[i] = desc[i];
867 i++;
868 }
869 return (char*)buf;
870 }
871
872
873 static bool
print_boot_var(const char * name,bool verbose,bool curboot)874 print_boot_var(const char *name, bool verbose, bool curboot)
875 {
876 size_t size;
877 uint32_t load_attrs;
878 uint8_t *data;
879 int ret;
880 char *d;
881
882 ret = efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL);
883 if (ret < 0)
884 return false;
885 load_attrs = le32dec(data);
886 d = get_descr(data);
887 printf("%c%s%c %s", curboot ? '+' : ' ', name,
888 ((load_attrs & LOAD_OPTION_ACTIVE) ? '*': ' '), d);
889 free(d);
890 if (verbose)
891 print_loadopt_str(data, size);
892 else
893 printf("\n");
894 return true;
895 }
896
897
898 static bool
os_indication_supported(uint64_t indication)899 os_indication_supported(uint64_t indication)
900 {
901 uint8_t *data;
902 size_t size;
903 uint32_t attrs;
904 int ret;
905
906 ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndicationsSupported", &data,
907 &size, &attrs);
908 if (ret < 0)
909 return false;
910 return (le64dec(data) & indication) == indication;
911 }
912
913 static uint64_t
os_indications(void)914 os_indications(void)
915 {
916 uint8_t *data;
917 size_t size;
918 uint32_t attrs;
919 int ret;
920
921 ret = efi_get_variable(EFI_GLOBAL_GUID, "OsIndications", &data, &size,
922 &attrs);
923 if (ret < 0)
924 return 0;
925 return le64dec(data);
926 }
927
928 static int
os_indications_set(uint64_t mask,uint64_t val)929 os_indications_set(uint64_t mask, uint64_t val)
930 {
931 uint8_t new[sizeof(uint64_t)];
932
933 le64enc(&new, (os_indications() & ~mask) | (val & mask));
934 return set_bootvar("OsIndications", new, sizeof(new));
935 }
936
937 /* Cmd epilogue, or just the default with no args.
938 * The order is [bootnext] bootcurrent, timeout, order, and the bootvars [-v]
939 */
940 static int
print_boot_vars(bool verbose)941 print_boot_vars(bool verbose)
942 {
943 /*
944 * just read and print the current values
945 * as a command epilogue
946 */
947 struct entry *v;
948 uint8_t *data;
949 size_t size;
950 uint32_t attrs;
951 int ret, bolen;
952 uint16_t *boot_order = NULL, current;
953 bool boot_to_fw_ui;
954
955 if (os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
956 boot_to_fw_ui =
957 (os_indications() & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0;
958 printf("Boot to FW : %s\n", boot_to_fw_ui != 0 ?
959 "true" : "false");
960 }
961
962 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootNext", &data, &size, &attrs);
963 if (ret > 0) {
964 printf("BootNext : %04x\n", le16dec(data));
965 }
966
967 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
968 current = le16dec(data);
969 printf("BootCurrent: %04x\n", current);
970
971 ret = efi_get_variable(EFI_GLOBAL_GUID, "Timeout", &data, &size, &attrs);
972 if (ret > 0) {
973 printf("Timeout : %d seconds\n", le16dec(data));
974 }
975
976 if (efi_get_variable(EFI_GLOBAL_GUID, "BootOrder", &data, &size, &attrs) > 0) {
977 if (size % 2 == 1)
978 warn("Bad BootOrder variable: odd length %d", (int)size);
979 boot_order = malloc(size);
980 bolen = size / 2;
981 printf("BootOrder : ");
982 for (size_t i = 0; i < size; i += 2) {
983 boot_order[i / 2] = le16dec(data + i);
984 printf("%04X%s", boot_order[i / 2], i == size - 2 ? "\n" : ", ");
985 }
986 }
987
988 if (boot_order == NULL) {
989 /*
990 * now we want to fetch 'em all fresh again
991 * which possibly includes a newly created bootvar
992 */
993 LIST_FOREACH(v, &efivars, entries) {
994 print_boot_var(v->name, verbose, v->idx == current);
995 }
996 } else {
997 LIST_FOREACH(v, &efivars, entries) {
998 v->flags = 0;
999 }
1000 for (int i = 0; i < bolen; i++) {
1001 char buffer[10];
1002
1003 snprintf(buffer, sizeof(buffer), "Boot%04X", boot_order[i]);
1004 if (!print_boot_var(buffer, verbose, boot_order[i] == current))
1005 printf("%s: MISSING!\n", buffer);
1006 LIST_FOREACH(v, &efivars, entries) {
1007 if (v->idx == boot_order[i]) {
1008 v->flags |= SEEN;
1009 break;
1010 }
1011 }
1012 }
1013 if (verbose) {
1014 printf("\n\nUnreferenced Variables:\n");
1015 LIST_FOREACH(v, &efivars, entries) {
1016 if (v->flags == 0)
1017 print_boot_var(v->name, verbose, v->idx == current);
1018 }
1019 }
1020 }
1021 return 0;
1022 }
1023
1024 static void
delete_timeout(void)1025 delete_timeout(void)
1026 {
1027
1028 efi_del_variable(EFI_GLOBAL_GUID,"Timeout");
1029 }
1030
1031 static void
handle_timeout(int to)1032 handle_timeout(int to)
1033 {
1034 uint16_t timeout;
1035
1036 le16enc(&timeout, to);
1037 if (set_bootvar("Timeout", (uint8_t *)&timeout, sizeof(timeout)) < 0)
1038 errx(1, "Can't set Timeout for booting.");
1039 }
1040
1041 static void
report_esp_device(bool do_dp,bool do_unix)1042 report_esp_device(bool do_dp, bool do_unix)
1043 {
1044 uint8_t *data;
1045 size_t size, len;
1046 uint32_t attrs;
1047 int ret;
1048 uint16_t current, fplen;
1049 char *name, *dev, *relpath, *abspath;
1050 uint8_t *walker, *ep;
1051 efi_char *descr;
1052 efidp dp;
1053 char buf[PATH_MAX];
1054
1055 if (do_dp && do_unix)
1056 errx(1, "Can't report both UEFI device-path and Unix path together");
1057
1058 ret = efi_get_variable(EFI_GLOBAL_GUID, "BootCurrent", &data, &size,&attrs);
1059 if (ret < 0)
1060 err(1, "Can't get BootCurrent");
1061 current = le16dec(data);
1062 if (asprintf(&name, "Boot%04X", current) < 0)
1063 err(1, "Can't format boot var\n");
1064 if (efi_get_variable(EFI_GLOBAL_GUID, name, &data, &size, NULL) < 0)
1065 err(1, "Can't retrieve EFI var %s", name);
1066 // First 4 bytes are attribute flags
1067 walker = data;
1068 ep = walker + size;
1069 walker += sizeof(uint32_t);
1070 // Next two bytes are length of the file paths
1071 fplen = le16dec(walker);
1072 walker += sizeof(fplen);
1073 // Next we have a 0 terminated UCS2 string that we know to be aligned
1074 descr = (efi_char *)(intptr_t)(void *)walker;
1075 len = ucs2len(descr); // XXX need to sanity check that len < (datalen - (ep - walker) / 2)
1076 walker += (len + 1) * sizeof(efi_char);
1077 if (walker > ep)
1078 errx(1, "malformed boot variable %s", name);
1079 // Now we have fplen bytes worth of file path stuff
1080 dp = (efidp)walker;
1081 walker += fplen;
1082 if (walker > ep)
1083 errx(1, "malformed boot variable %s", name);
1084 if (do_dp) {
1085 efidp_format_device_path_node(buf, sizeof(buf), dp);
1086 printf("%s\n", buf);
1087 exit(0);
1088 }
1089 if (efivar_device_path_to_unix_path(dp, &dev, &relpath, &abspath) != 0)
1090 errx(1, "Can't convert to unix path");
1091 if (do_unix) {
1092 if (abspath == NULL)
1093 errx(1, "Can't find where %s:%s is mounted",
1094 dev, relpath);
1095 abspath[strlen(abspath) - strlen(relpath) - 1] = '\0';
1096 printf("%s\n", abspath);
1097 } else {
1098 printf("/dev/%s\n", dev);
1099 }
1100 free(dev);
1101 free(relpath);
1102 free(abspath);
1103 exit(0);
1104 }
1105
1106 static void
set_boot_to_fw_ui(bool to_fw)1107 set_boot_to_fw_ui(bool to_fw)
1108 {
1109 int ret;
1110
1111 if (!os_indication_supported(EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
1112 if (to_fw)
1113 errx(1, "boot to fw ui not supported");
1114 else
1115 return;
1116 }
1117 ret = os_indications_set(EFI_OS_INDICATIONS_BOOT_TO_FW_UI,
1118 to_fw ? ~0 : 0);
1119 if (ret < 0)
1120 errx(1, "failed to set boot to fw ui");
1121 }
1122
1123 static void
find_efi_device(const char * path)1124 find_efi_device(const char *path)
1125 {
1126 efidp dp = NULL;
1127 size_t len;
1128 int ret;
1129 char buf[1024];
1130
1131 ret = efivar_unix_path_to_device_path(path, &dp);
1132 if (ret != 0)
1133 errc(1, ret,
1134 "Cannot translate path '%s' to UEFI", path);
1135 len = efidp_size(dp);
1136 if (len > MAX_DP_LEN)
1137 errx(1, "Resulting device path too long.");
1138 efidp_format_device_path(buf, sizeof(buf), dp, len);
1139 printf("%s -> %s\n", path, buf);
1140 exit (0);
1141 }
1142
1143 int
main(int argc,char * argv[])1144 main(int argc, char *argv[])
1145 {
1146
1147 memset(&opts, 0, sizeof (bmgr_opts_t));
1148 parse_args(argc, argv);
1149
1150 /*
1151 * find_dev can operate without any efi variables
1152 */
1153 if (!efi_variables_supported() && !opts.find_dev) {
1154 if (errno == EACCES && geteuid() != 0)
1155 errx(1, "must be run as root");
1156 errx(1, "efi variables not supported on this system. kldload efirt?");
1157 }
1158
1159 read_vars();
1160
1161 if (opts.create)
1162 /*
1163 * side effect, adds to boot order, but not yet active.
1164 */
1165 make_boot_var(opts.label ? opts.label : "",
1166 opts.loader, opts.kernel, opts.env, opts.dry_run,
1167 opts.has_bootnum ? opts.bootnum : -1, opts.set_active);
1168 else if (opts.set_active || opts.set_inactive )
1169 handle_activity(opts.bootnum, opts.set_active);
1170 else if (opts.order != NULL)
1171 set_boot_order(opts.order); /* create a new bootorder with opts.order */
1172 else if (opts.set_bootnext)
1173 handle_bootnext(opts.bootnum);
1174 else if (opts.delete_bootnext)
1175 del_bootnext();
1176 else if (opts.delete)
1177 delete_bootvar(opts.bootnum);
1178 else if (opts.del_timeout)
1179 delete_timeout();
1180 else if (opts.set_timeout)
1181 handle_timeout(opts.timeout);
1182 else if (opts.esp_device)
1183 report_esp_device(opts.device_path, opts.unix_path);
1184 else if (opts.fw_ui)
1185 set_boot_to_fw_ui(true);
1186 else if (opts.no_fw_ui)
1187 set_boot_to_fw_ui(false);
1188 else if (opts.find_dev)
1189 find_efi_device(opts.dev);
1190
1191 print_boot_vars(opts.verbose);
1192 }
1193