forked from projectceladon/hardware-intel-kernelflinger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kernelflinger.c
1496 lines (1298 loc) · 38.4 KB
/
kernelflinger.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014, Intel Corporation
* All rights reserved.
*
* Author: Andrew Boie <andrew.p.boie@intel.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <efi.h>
#include <efiapi.h>
#include <efilib.h>
#include <openssl/sha.h>
#include <fastboot.h>
#include "vars.h"
#include "lib.h"
#include "security.h"
#include "android.h"
#include "ux.h"
#include "options.h"
#include "power.h"
#include "targets.h"
#include "unittest.h"
#include "em.h"
#include "storage.h"
#include "version.h"
#include "timer.h"
#ifdef HAL_AUTODETECT
#include "blobstore.h"
#endif
#include "oemvars.h"
#include "slot.h"
#ifdef RPMB_STORAGE
#include "rpmb.h"
#include "rpmb_storage.h"
#endif
#ifdef USE_TRUSTY
#include "trusty_interface.h"
#include "trusty_common.h"
#endif
#include "gpt.h"
#include "protocol.h"
#include "uefi_utils.h"
#include "security_interface.h"
#ifdef USE_TPM
#include "tpm2_security.h"
#endif
/* Ensure this is embedded in the EFI binary somewhere */
static const CHAR16 __attribute__((used)) magic[] = L"### kernelflinger ###";
/* Default max wait time for console reset in units of milliseconds if no EFI
* variable is set for this platform.
* You want this value as small as possible as this is added to
* the boot time for EVERY boot
*/
#define EFI_RESET_WAIT_MS 200
/* Interval in ms to check on startup for initial press of magic key */
#define DETECT_KEY_STALL_TIME_MS 1
/* How long (in milliseconds) magic key should be held to force
* Fastboot mode
*/
#define FASTBOOT_HOLD_DELAY (2 * 1000)
/* Magic key to enter fastboot mode or revovery console */
#define MAGIC_KEY EV_DOWN
/* If we find this in the root of the EFI system partition, unconditionally
* enter Fastboot mode
*/
#define FASTBOOT_SENTINEL L"\\force_fastboot"
/* BIOS Capsule update file */
#define FWUPDATE_FILE L"\\BIOSUPDATE.fv"
#define KFSELF_FILE L"\\EFI\\BOOT\\kernelflinger.efi"
#define KFUPDATE_FILE L"\\EFI\\BOOT\\kernelflinger_new.efi"
#define KFBACKUP_FILE L"\\EFI\\BOOT\\kernelflinger_bak.efi"
#ifndef ARCH_X86_64
#define BOOTLOADER_FILE L"\\EFI\\BOOT\\bootia32.efi"
#define BOOTLOADER_FILE_BAK L"\\EFI\\BOOT\\bootia32_bak.efi"
#else
#define BOOTLOADER_FILE L"\\EFI\\BOOT\\bootx64.efi"
#define BOOTLOADER_FILE_BAK L"\\EFI\\BOOT\\bootx64_bak.efi"
#endif // ARCH_X86_64
/* Crash event menu settings:
* Maximum time between the first and the last watchdog reset. If the
* current difference exceeds this constant, the watchdog counter is
* reset to zero.
*/
#define WATCHDOG_DELAY (10 * 60)
#ifdef USE_TRUSTY
struct rot_data_t g_rot_data = {0};
#endif
static EFI_HANDLE g_disk_device;
static EFI_LOADED_IMAGE *g_loaded_image;
static VOID die(VOID) __attribute__ ((noreturn));
#if DEBUG_MESSAGES
static VOID print_rsci_values(VOID)
{
enum wake_sources raw_wake_source = rsci_get_wake_source();
enum reset_sources raw_reset_source = rsci_get_reset_source();
enum reset_types raw_reset_type = rsci_get_reset_type();
debug(L"wake_source = %s (0x%02hhx)",
wake_source_string(raw_wake_source),
raw_wake_source);
debug(L"reset_source = %s (0x%02hhx)",
reset_source_string(raw_reset_source),
raw_reset_source);
debug(L"reset_type = %s (0x%02hhx)",
reset_type_string(raw_reset_type),
raw_reset_type);
if (raw_reset_source == RESET_PLATFORM_SPECIFIC)
debug(L"reset_extra_info = 0x%08hhx", rsci_get_reset_extra_info());
}
#endif
static enum boot_target check_fastboot_sentinel(VOID)
{
debug(L"checking ESP for %s", FASTBOOT_SENTINEL);
if (file_exists(g_disk_device, FASTBOOT_SENTINEL))
return FASTBOOT;
return NORMAL_BOOT;
}
static enum boot_target check_magic_key(VOID)
{
unsigned long i;
EFI_STATUS ret = EFI_NOT_READY;
EFI_INPUT_KEY key;
unsigned long wait_ms = EFI_RESET_WAIT_MS;
/* Some systems require a short stall before we can be sure there
* wasn't a keypress at boot. Read the EFI variable which determines
* that time for this platform
*/
ret = get_efi_variable_long_from_str8(&loader_guid,
MAGIC_KEY_TIMEOUT_VAR,
&wait_ms);
if (EFI_ERROR(ret)) {
debug(L"Couldn't read timeout variable; assuming default");
} else {
if (wait_ms > 1000) {
debug(L"pathological magic key timeout, use default");
wait_ms = EFI_RESET_WAIT_MS;
}
}
debug(L"Reset wait time: %d", wait_ms);
/* Check for 'magic' key. Some BIOSes are flaky about this
* so wait for the ConIn to be ready after reset
*/
for (i = 0; i <= wait_ms; i += DETECT_KEY_STALL_TIME_MS) {
ret = uefi_call_wrapper(ST->ConIn->ReadKeyStroke, 2,
ST->ConIn, &key);
if (ret == EFI_SUCCESS || i == wait_ms)
break;
uefi_call_wrapper(BS->Stall, 1, DETECT_KEY_STALL_TIME_MS * 1000);
}
if (EFI_ERROR(ret))
return NORMAL_BOOT;
debug(L"ReadKeyStroke: (%d tries) %d %d", i, key.ScanCode, key.UnicodeChar);
if (ui_keycode_to_event(key.ScanCode) != MAGIC_KEY)
return NORMAL_BOOT;
if (ui_enforce_key_held(FASTBOOT_HOLD_DELAY, MAGIC_KEY))
return FASTBOOT;
return NORMAL_BOOT;
}
static enum boot_target check_bcb(CHAR16 **target_path, BOOLEAN *oneshot)
{
EFI_STATUS ret;
struct bootloader_message bcb;
CHAR16 *target = NULL;
enum boot_target t;
CHAR8 *bcb_cmd;
BOOLEAN dirty;
*oneshot = FALSE;
*target_path = NULL;
ret = read_bcb(MISC_LABEL, &bcb);
if (EFI_ERROR(ret)) {
error(L"Unable to read BCB");
t = NORMAL_BOOT;
goto out;
}
dirty = bcb.status[0] != '\0';
/* We own the status field; clear it in case there is any stale data */
bcb.status[0] = '\0';
bcb_cmd = (CHAR8 *)bcb.command;
if (!strncmpa(bcb_cmd, (CHAR8 *)"boot-", 5)) {
target = stra_to_str(bcb_cmd + 5);
debug(L"BCB boot target: '%s'", target);
} else if (!strncmpa(bcb_cmd, (CHAR8 *)"bootonce-", 9)) {
target = stra_to_str(bcb_cmd + 9);
bcb_cmd[0] = '\0';
dirty = TRUE;
debug(L"BCB oneshot boot target: '%s'", target);
*oneshot = TRUE;
}
if (dirty) {
ret = write_bcb(MISC_LABEL, &bcb);
if (EFI_ERROR(ret))
error(L"Unable to update BCB contents!");
}
if (!target) {
t = NORMAL_BOOT;
goto out;
}
if (target[0] == L'\\') {
UINTN len;
if (!file_exists(g_disk_device, target)) {
error(L"Specified BCB file '%s' doesn't exist",
target);
t = NORMAL_BOOT;
goto out;
}
len = StrLen(target);
if (len > 4) {
*target_path = StrDuplicate(target);
if (!StrCmp(target + (len - 4), L".efi") ||
!StrCmp(target + (len - 4), L".EFI")) {
t = ESP_EFI_BINARY;
} else {
t = ESP_BOOTIMAGE;
}
goto out;
}
error(L"BCB file '%s' appears to be malformed", target);
t = NORMAL_BOOT;
goto out;
}
t = name_to_boot_target(target);
if (t != UNKNOWN_TARGET)
goto out;
error(L"Unknown boot target in BCB: '%s'", target);
t = NORMAL_BOOT;
out:
FreePool(target);
return t;
}
static enum boot_target check_loader_entry_one_shot(VOID)
{
EFI_STATUS ret;
CHAR16 *target;
enum boot_target bt;
debug(L"checking %s", LOADER_ENTRY_ONESHOT);
target = get_efi_variable_str(&loader_guid, LOADER_ENTRY_ONESHOT);
del_efi_variable(&loader_guid, LOADER_ENTRY_ONESHOT);
if (!target)
return NORMAL_BOOT;
debug(L"target = %s", target);
bt = name_to_boot_target(target);
if (bt == UNKNOWN_TARGET) {
if (!StrCmp(target, L"dm-verity device corrupted")) {
debug(L"Reboot was triggered by dm-verity module because partition is corrupted");
ret = slot_set_verity_corrupted(TRUE);
if (EFI_ERROR(ret))
efi_perror(ret, L"Failed to set the active slot verity eio flag");
} else
error(L"Unknown oneshot boot target: '%s'", target);
bt = NORMAL_BOOT;
} else if (bt == CHARGER && !get_off_mode_charge()) {
debug(L"Off mode charge is not set, powering off.");
bt = POWER_OFF;
}
FreePool(target);
return bt;
}
static BOOLEAN reset_is_due_to_watchdog_or_panic(void)
{
static enum reset_sources WATCHDOG_RESET_SOURCES[] = {
RESET_KERNEL_WATCHDOG,
RESET_SECURITY_WATCHDOG,
RESET_PMIC_WATCHDOG,
RESET_EC_WATCHDOG
};
enum reset_sources reset_source;
UINTN i;
reset_source = rsci_get_reset_source();
for (i = 0; i < ARRAY_SIZE(WATCHDOG_RESET_SOURCES); i++)
if (reset_source == WATCHDOG_RESET_SOURCES[i]) {
debug(L"Watchdog reset source = %d", reset_source);
return TRUE;
}
return is_reboot_reason(L"kernel_panic") ||
is_reboot_reason(L"watchdog");
}
/* If more than get_watchdog_counter_max() watchdog (or kernel panic)
* resets in a row happened in less than WATCHDOG_DELAY seconds, the
* crash event menu is displayed. This menu informs the user of the
* situation and let him choose which boot target he wants.
*/
static enum boot_target check_watchdog(VOID)
{
EFI_STATUS ret;
UINT8 counter;
EFI_TIME time_ref, now;
if (!get_crash_event_menu())
return NORMAL_BOOT;
ret = get_watchdog_status(&counter, &time_ref);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to get the watchdog status");
return NORMAL_BOOT;
}
if (!reset_is_due_to_watchdog_or_panic()) {
if (counter != 0) {
ret = reset_watchdog_status();
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to reset the watchdog status");
goto error;
}
}
return NORMAL_BOOT;
}
#ifdef USER
if (is_reboot_reason(L"shutdown")) {
del_reboot_reason();
return POWER_OFF;
}
#endif
ret = uefi_call_wrapper(RT->GetTime, 2, &now, NULL);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to get the current time");
goto error;
}
if (counter > 0) {
if (efi_time_to_ctime(&now) < efi_time_to_ctime(&time_ref) ||
efi_time_to_ctime(&now) - efi_time_to_ctime(&time_ref) > WATCHDOG_DELAY)
counter = 0;
}
if (counter == 0) {
time_ref = now;
ret = set_watchdog_time_reference(&now);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to set the watchdog time reference");
goto error;
}
}
counter++;
debug(L"Incrementing watchdog counter (%d)", counter);
if (counter <= get_watchdog_counter_max()) {
ret = set_watchdog_counter(counter);
if (EFI_ERROR(ret))
efi_perror(ret, L"Failed to set the watchdog counter");
goto error;
}
ret = reset_watchdog_status();
if (EFI_ERROR(ret))
efi_perror(ret, L"Failed to reset the watchdog status");
#ifdef USE_UI
return ux_prompt_user_for_boot_target(CRASH_EVENT_CODE);
#else
debug(L"NO_UI,CRASH_EVENT,rebooting");
return NORMAL_BOOT;
#endif
error:
return NORMAL_BOOT;
}
static enum boot_target check_command_line(VOID)
{
UINTN argc, pos;
CHAR16 **argv;
CHAR16 *options;
enum boot_target bt;
bt = NORMAL_BOOT;
if (EFI_ERROR(get_argv(g_loaded_image, &argc, &argv, &options)))
return NORMAL_BOOT;
for (pos = 0; pos < argc; pos++) {
debug(L"Argument %d: %s", pos, argv[pos]);
if (!StrCmp(argv[pos], L"-f")) {
bt = FASTBOOT;
continue;
}
#ifndef USER
if (!StrCmp(argv[pos], L"-U")) {
pos++;
unittest_main(pos >= argc ? NULL : argv[pos]);
FreePool(argv);
return EXIT_SHELL;
}
#endif
if (!StrCmp(argv[pos], L"-a")) {
pos++;
if (pos >= argc) {
error(L"-a requires a memory address");
goto out;
}
/* For compatibility...just ignore the supplied address
* and enter Fastboot mode
*/
bt = FASTBOOT;
continue;
}
/* If we get here the argument isn't recognized */
if (pos == 0) {
/* EFI is inconsistent and only seems to populate the image
* name as argv[0] when called from a shell. Do nothing.
*/
continue;
} else {
error(L"unexpected argument %s", argv[pos]);
goto out;
}
}
out:
FreePool(argv);
FreePool(options);
return bt;
}
static enum boot_target check_battery_inserted(void)
{
enum wake_sources wake_source;
if (!get_off_mode_charge())
return NORMAL_BOOT;
wake_source = rsci_get_wake_source();
if (wake_source == WAKE_BATTERY_INSERTED)
return POWER_OFF;
return NORMAL_BOOT;
}
static enum boot_target check_charge_mode(void)
{
enum wake_sources wake_source;
if (!get_off_mode_charge())
return NORMAL_BOOT;
wake_source = rsci_get_wake_source();
if ((wake_source == WAKE_USB_CHARGER_INSERTED) ||
(wake_source == WAKE_ACDC_CHARGER_INSERTED)) {
debug(L"Wake source = %d", wake_source);
return CHARGER;
}
return NORMAL_BOOT;
}
enum boot_target check_battery(void)
{
if (!get_off_mode_charge())
return NORMAL_BOOT;
if (is_battery_below_boot_OS_threshold()) {
BOOLEAN charger_plugged = is_charger_plugged_in();
debug(L"Battery is below boot OS threshold");
debug(L"Charger is%s plugged", charger_plugged ? L"" : L" not");
return charger_plugged ? CHARGER : POWER_OFF;
}
return NORMAL_BOOT;
}
/* Policy:
* 1. Check if we had multiple watchdog reported in a short period of
* time. If so, let the user choose the boot target.
* 2. Check if the "-a xxxxxxxxx" command line was passed in, if so load an
* android boot image from RAM at that location.
* 3. Check if the fastboot sentinel file \force_fastboot is present, and if
* so, force fastboot mode. Use in bootable media.
* 4. Check for "magic key" being held. Short press loads Recovery. Long press
* loads Fastboot.
* 5. Check if wake source is battery inserted, if so power off
* 6. Check bootloader control block for a boot target, which could be
* the name of a boot image that we know how to read from a partition,
* or a boot image file in the ESP. BCB can specify oneshot or persistent
* targets.
* 7. Check LoaderEntryOneShot for a boot target
* 8. Check if we should go into charge mode or normal boot
*
* target_path - If ESP_EFI_BINARY or ESP_BOOTIMAGE returned, path to the
* image on the EFI System Partition
* oneshot - Whether this is a one-shot boot, indicating that the image at
* target_path should be deleted before chainloading
*
*/
static enum boot_target choose_boot_target(CHAR16 **target_path, BOOLEAN *oneshot)
{
enum boot_target ret;
*target_path = NULL;
*oneshot = TRUE;
#if DEBUG_MESSAGES
print_rsci_values();
#endif
debug(L"Bootlogic: Choosing boot target");
debug(L"Bootlogic: Check osloader command line...");
ret = check_command_line();
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check fastboot sentinel...");
ret = check_fastboot_sentinel();
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check magic key...");
ret = check_magic_key();
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check watchdog...");
ret = check_watchdog();
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check battery insertion...");
ret = check_battery_inserted();
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check BCB...");
ret = check_bcb(target_path, oneshot);
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check reboot target...");
ret = check_loader_entry_one_shot();
if (ret != DNX && ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check battery level...");
ret = check_battery();
#ifdef USE_UI
if (ret == POWER_OFF)
ux_display_low_battery(3);
#else
if (ret == POWER_OFF)
debug(L"NO_UI: low battery");
#endif
if (ret != NORMAL_BOOT)
goto out;
debug(L"Bootlogic: Check charger insertion...");
ret = check_charge_mode();
out:
debug(L"Bootlogic: selected '%s'", boot_target_description(ret));
return ret;
}
#ifdef USE_AVB
/* Use AVB load and verify a boot image into RAM.
*
* boot_target - Boot image to load. Values supported are NORMAL_BOOT, RECOVERY,
* and ESP_BOOTIMAGE (for 'fastboot boot')
* target_path - Path to load boot image from for ESP_BOOTIMAGE case, ignored
* otherwise.
* bootimage - Returned allocated pointer value for the loaded boot image.
* oneshot - For ESP_BOOTIMAGE case, flag indicating that the image should
* be deleted.
* boot_state - The boot state, maybe changed according the load and verify result.
*
* Return values:
* EFI_INVALID_PARAMETER - Unsupported boot target type, key is not well-formed,
* or loaded boot image was missing or corrupt
* EFI_ACCESS_DENIED - Validation failed against OEM or embedded certificate,
* boot image still usable
*/
static EFI_STATUS avb_load_verify_boot_image(
IN enum boot_target boot_target,
IN CHAR16 *target_path,
OUT VOID **bootimage,
IN BOOLEAN oneshot,
UINT8 *boot_state,
AvbSlotVerifyData **slot_data)
{
EFI_STATUS ret;
switch (boot_target) {
case NORMAL_BOOT:
case CHARGER:
ret = android_image_load_partition_avb_ab("boot", bootimage, boot_state, slot_data);
break;
case RECOVERY:
if (recovery_in_boot_partition()) {
ret = avb_load_verify_boot_image(NORMAL_BOOT, target_path, bootimage, oneshot, boot_state, slot_data);
break;
}
#if !defined(USE_AVB)
/* Tries count is handled by avb_ab_flow when AVB is enabled. */
if (use_slot() && !slot_recovery_tries_remaining()) {
ret = EFI_NOT_FOUND;
break;
}
#endif
ret = android_image_load_partition_avb("recovery", bootimage, boot_state, slot_data);
break;
case ESP_BOOTIMAGE:
/* "fastboot boot" case */
ret = android_image_load_file(g_disk_device, target_path, oneshot,
bootimage);
break;
default:
*bootimage = NULL;
return EFI_INVALID_PARAMETER;
}
if (!EFI_ERROR(ret))
debug(L"boot image loaded");
return ret;
}
#else // USE_AVB == false
/* Validate an image.
*
* Parameters:
* boot_target - Boot image to load. Values supported are NORMAL_BOOT,
* RECOVERY, and ESP_BOOTIMAGE (for 'fastboot boot')
* bootimage - Bootimage to validate
* verifier_cert - Return the certificate that validated the boot image
*
* Return values:
* BOOT_STATE_GREEN - Boot image is valid against provided certificate
* BOOT_STATE_YELLOW - Boot image is valid against embedded certificate
* BOOT_STATE_RED - Boot image is not valid
*/
static UINT8 validate_bootimage(
IN enum boot_target boot_target,
IN VOID *bootimage,
X509 **verifier_cert)
{
CHAR16 target[BOOT_TARGET_SIZE];
CHAR16 *expected;
CHAR16 *expected2 = NULL;
UINT8 boot_state;
boot_state = verify_android_boot_image(bootimage, oem_cert,
oem_cert_size, target,
verifier_cert);
if (boot_state == BOOT_STATE_RED) {
debug(L"boot image doesn't verify");
return boot_state;
}
switch (boot_target) {
case NORMAL_BOOT:
expected = L"/boot";
/* in case of multistage ota */
expected2 = L"/recovery";
break;
case CHARGER:
expected = L"/boot";
break;
case RECOVERY:
if (recovery_in_boot_partition())
expected = L"/boot";
else
expected = L"/recovery";
break;
case ESP_BOOTIMAGE:
/* "live" bootable image */
expected = L"/boot";
break;
default:
expected = NULL;
}
if ((!expected || StrCmp(expected, target)) &&
(!expected2 || StrCmp(expected2, target))) {
debug(L"boot image has unexpected target name");
return BOOT_STATE_RED;
}
return boot_state;
}
/* Load a boot image into RAM.
*
* boot_target - Boot image to load. Values supported are NORMAL_BOOT, RECOVERY,
* and ESP_BOOTIMAGE (for 'fastboot boot')
* target_path - Path to load boot image from for ESP_BOOTIMAGE case, ignored
* otherwise.
* bootimage - Returned allocated pointer value for the loaded boot image.
* oneshot - For ESP_BOOTIMAGE case, flag indicating that the image should
* be deleted.
*
* Return values:
* EFI_INVALID_PARAMETER - Unsupported boot target type, key is not well-formed,
* or loaded boot image was missing or corrupt
* EFI_ACCESS_DENIED - Validation failed against OEM or embedded certificate,
* boot image still usable
*/
static EFI_STATUS load_boot_image(
IN enum boot_target boot_target,
IN CHAR16 *target_path,
OUT VOID **bootimage,
IN BOOLEAN oneshot)
{
EFI_STATUS ret;
switch (boot_target) {
case NORMAL_BOOT:
case CHARGER:
ret = EFI_NOT_FOUND;
if (use_slot() && !slot_get_active())
break;
do {
const CHAR16 *label = slot_label(BOOT_LABEL);
ret = android_image_load_partition(label, bootimage);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to load boot image from %s partition",
label);
if (use_slot())
slot_boot_failed(boot_target);
}
} while (EFI_ERROR(ret) && slot_get_active());
break;
case RECOVERY:
if (recovery_in_boot_partition()) {
ret = load_boot_image(NORMAL_BOOT, target_path, bootimage, oneshot);
break;
}
if (use_slot() && !slot_recovery_tries_remaining()) {
ret = EFI_NOT_FOUND;
break;
}
ret = android_image_load_partition(RECOVERY_LABEL, bootimage);
break;
case ESP_BOOTIMAGE:
/* "fastboot boot" case */
ret = android_image_load_file(g_disk_device, target_path, oneshot,
bootimage);
break;
default:
*bootimage = NULL;
return EFI_INVALID_PARAMETER;
}
if (!EFI_ERROR(ret))
debug(L"boot image loaded");
return ret;
}
#endif
#define OEMVARS_MAGIC "#OEMVARS\n"
#define OEMVARS_MAGIC_SZ 9
static EFI_STATUS set_image_oemvars_nocheck(VOID *bootimage,
const EFI_GUID *restricted_guid)
{
VOID *oemvars;
UINT32 osz;
EFI_STATUS ret;
ret = get_bootimage_2nd(bootimage, &oemvars, &osz);
if (ret == EFI_SUCCESS && osz > OEMVARS_MAGIC_SZ &&
!memcmp(oemvars, OEMVARS_MAGIC, OEMVARS_MAGIC_SZ)) {
debug(L"secondstage contains raw oemvars");
return flash_oemvars_silent_write_error((CHAR8 *)oemvars + OEMVARS_MAGIC_SZ,
osz - OEMVARS_MAGIC_SZ,
restricted_guid);
}
#ifdef HAL_AUTODETECT
ret = get_bootimage_blob(bootimage, BLOB_TYPE_OEMVARS, &oemvars, &osz);
if (EFI_ERROR(ret)) {
if (ret == EFI_UNSUPPORTED || ret == EFI_NOT_FOUND) {
debug(L"No blobstore in this boot image");
return EFI_SUCCESS;
}
return ret;
}
return flash_oemvars_silent_write_error(oemvars, osz, restricted_guid);
#else
return EFI_NOT_FOUND;
#endif
}
static EFI_STATUS set_image_oemvars(VOID *bootimage)
{
if (!get_oemvars_update()) {
debug(L"OEM vars should be up-to-date");
return EFI_SUCCESS;
}
debug(L"OEM vars may need to be updated");
set_oemvars_update(FALSE);
return set_image_oemvars_nocheck(bootimage, NULL);
}
static EFI_STATUS load_image(VOID *bootimage, UINT8 boot_state,
enum boot_target boot_target,
#ifdef USE_AVB
AvbSlotVerifyData *slot_data
#else
X509 *verifier_cert
#endif
)
{
EFI_STATUS ret;
#ifdef USE_TRUSTY
VOID *tosimage = NULL;
#endif
#ifdef USER
/* per bootloaderequirements.pdf */
if (boot_state == BOOT_STATE_ORANGE) {
ret = android_clear_memory();
if (EFI_ERROR(ret)) {
error(L"Failed to clear memory. Load image aborted.");
return ret;
}
}
#endif
set_efi_variable(&fastboot_guid, BOOT_STATE_VAR, sizeof(boot_state),
&boot_state, FALSE, TRUE);
#ifdef OS_SECURE_BOOT
ret = set_os_secure_boot(boot_state == BOOT_STATE_GREEN);
if (EFI_ERROR(ret))
efi_perror(ret, L"Failed to set os secure boot");
#endif
/* install acpi tables before starting trusty */
ret = setup_acpi_table(bootimage, boot_target);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"setup_acpi_table");
return ret;
}
#ifdef USE_TRUSTY
if (is_bootimg_target(boot_target)) {
if (boot_state == BOOT_STATE_RED) {
#ifndef USERDEBUG
debug(L"Red state: start trusty anyway as ENG build");
#else
debug(L"Red state: invalid boot image.Unable to start trusty. Stop");
die();
#endif
}
debug(L"loading trusty");
ret = load_tos_image(&tosimage);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Load tos image failed");
die();
}
#ifdef USE_AVB
const UINT8 *vbmeta_pub_key;
UINTN vbmeta_pub_key_len;
if (slot_data != NULL) {
ret = avb_vbmeta_image_verify(slot_data->vbmeta_images[0].vbmeta_data,
slot_data->vbmeta_images[0].vbmeta_size,
&vbmeta_pub_key,
&vbmeta_pub_key_len);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to get the vbmeta_pub_key");
die();
}
ret = get_rot_data(bootimage, boot_state,
vbmeta_pub_key, vbmeta_pub_key_len, &g_rot_data);
}
#else
ret = get_rot_data(bootimage, boot_state, verifier_cert, &g_rot_data);
#endif
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Unable to get the root of trust data for trusty");
die();
}
set_boottime_stamp(TM_LOAD_TOS_DONE);
ret = start_trusty(tosimage);
if (EFI_ERROR(ret)) {
#ifndef BUILD_ANDROID_THINGS
efi_perror(ret, L"Unable to start trusty; stop.");
die();
#else
efi_perror(ret, L"Unable to start trusty");
efi_perror(ret, L"Continue to boot");
#endif
}
set_boottime_stamp(TM_PROCRSS_TRUSTY_DONE);
}
#endif
#if !defined(USE_AVB)
ret = slot_boot(boot_target);
if (EFI_ERROR(ret)) {
efi_perror(ret, L"Failed to write slot boot");
return ret;
}
#endif
#ifdef USE_TPM
// Make sure the TPM2 is ended
tpm2_end();
#endif
debug(L"chainloading boot image, boot state is %s",
boot_state_to_string(boot_state));
ret = android_image_start_buffer(g_parent_image, bootimage,
boot_target, boot_state, NULL,
#ifdef USE_AVB
slot_data,
#else
verifier_cert,
#endif