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