]> git.proxmox.com Git - efi-boot-shim.git/blob - shim.c
Tweak the version dependency of the -helpers-ARCH-signed packages
[efi-boot-shim.git] / shim.c
1 /*
2 * shim - trivial UEFI first-stage bootloader
3 *
4 * Copyright 2012 Red Hat, Inc <mjg@redhat.com>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the
16 * distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
29 * OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 * Significant portions of this code are derived from Tianocore
32 * (http://tianocore.sf.net) and are Copyright 2009-2012 Intel
33 * Corporation.
34 */
35
36 #include "shim.h"
37
38 #include <stdarg.h>
39
40 #include <openssl/err.h>
41 #include <openssl/bn.h>
42 #include <openssl/dh.h>
43 #include <openssl/ocsp.h>
44 #include <openssl/pkcs12.h>
45 #include <openssl/rand.h>
46 #include <openssl/crypto.h>
47 #include <openssl/ssl.h>
48 #include <openssl/x509.h>
49 #include <openssl/x509v3.h>
50 #include <openssl/rsa.h>
51 #include <internal/dso.h>
52
53 #include <Library/BaseCryptLib.h>
54
55 #include <stdint.h>
56
57 #define OID_EKU_MODSIGN "1.3.6.1.4.1.2312.16.1.2"
58
59 static EFI_SYSTEM_TABLE *systab;
60 static EFI_HANDLE global_image_handle;
61
62 static CHAR16 *second_stage;
63 static void *load_options;
64 static UINT32 load_options_size;
65
66 /*
67 * The vendor certificate used for validating the second stage loader
68 */
69 extern struct {
70 UINT32 vendor_cert_size;
71 UINT32 vendor_dbx_size;
72 UINT32 vendor_cert_offset;
73 UINT32 vendor_dbx_offset;
74 } cert_table;
75
76 UINT32 vendor_cert_size;
77 UINT32 vendor_dbx_size;
78 UINT8 *vendor_cert;
79 UINT8 *vendor_dbx;
80
81 /*
82 * indicator of how an image has been verified
83 */
84 verification_method_t verification_method;
85 int loader_is_participating;
86
87 #define EFI_IMAGE_SECURITY_DATABASE_GUID { 0xd719b2cb, 0x3d3a, 0x4596, { 0xa3, 0xbc, 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f }}
88
89 UINT8 user_insecure_mode;
90 UINT8 ignore_db;
91
92 typedef enum {
93 DATA_FOUND,
94 DATA_NOT_FOUND,
95 VAR_NOT_FOUND
96 } CHECK_STATUS;
97
98 typedef struct {
99 UINT32 MokSize;
100 UINT8 *Mok;
101 } MokListNode;
102
103 /*
104 * Perform basic bounds checking of the intra-image pointers
105 */
106 static void *ImageAddress (void *image, uint64_t size, uint64_t address)
107 {
108 /* ensure our local pointer isn't bigger than our size */
109 if (address > size)
110 return NULL;
111
112 /* Insure our math won't overflow */
113 if (UINT64_MAX - address < (uint64_t)(intptr_t)image)
114 return NULL;
115
116 /* return the absolute pointer */
117 return image + address;
118 }
119
120 /* here's a chart:
121 * i686 x86_64 aarch64
122 * 64-on-64: nyet yes yes
123 * 64-on-32: nyet yes nyet
124 * 32-on-32: yes yes no
125 */
126 static int
127 allow_64_bit(void)
128 {
129 #if defined(__x86_64__) || defined(__aarch64__)
130 return 1;
131 #elif defined(__i386__) || defined(__i686__)
132 /* Right now blindly assuming the kernel will correctly detect this
133 * and /halt the system/ if you're not really on a 64-bit cpu */
134 if (in_protocol)
135 return 1;
136 return 0;
137 #else /* assuming everything else is 32-bit... */
138 return 0;
139 #endif
140 }
141
142 static int
143 allow_32_bit(void)
144 {
145 #if defined(__x86_64__)
146 #if defined(ALLOW_32BIT_KERNEL_ON_X64)
147 if (in_protocol)
148 return 1;
149 return 0;
150 #else
151 return 0;
152 #endif
153 #elif defined(__i386__) || defined(__i686__)
154 return 1;
155 #elif defined(__arch64__)
156 return 0;
157 #else /* assuming everything else is 32-bit... */
158 return 1;
159 #endif
160 }
161
162 static int
163 image_is_64_bit(EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr)
164 {
165 /* .Magic is the same offset in all cases */
166 if (PEHdr->Pe32Plus.OptionalHeader.Magic
167 == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC)
168 return 1;
169 return 0;
170 }
171
172 static const UINT16 machine_type =
173 #if defined(__x86_64__)
174 IMAGE_FILE_MACHINE_X64;
175 #elif defined(__aarch64__)
176 IMAGE_FILE_MACHINE_ARM64;
177 #elif defined(__arm__)
178 IMAGE_FILE_MACHINE_ARMTHUMB_MIXED;
179 #elif defined(__i386__) || defined(__i486__) || defined(__i686__)
180 IMAGE_FILE_MACHINE_I386;
181 #elif defined(__ia64__)
182 IMAGE_FILE_MACHINE_IA64;
183 #else
184 #error this architecture is not supported by shim
185 #endif
186
187 static int
188 image_is_loadable(EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr)
189 {
190 /* If the machine type doesn't match the binary, bail, unless
191 * we're in an allowed 64-on-32 scenario */
192 if (PEHdr->Pe32.FileHeader.Machine != machine_type) {
193 if (!(machine_type == IMAGE_FILE_MACHINE_I386 &&
194 PEHdr->Pe32.FileHeader.Machine == IMAGE_FILE_MACHINE_X64 &&
195 allow_64_bit())) {
196 return 0;
197 }
198 }
199
200 /* If it's not a header type we recognize at all, bail */
201 switch (PEHdr->Pe32Plus.OptionalHeader.Magic) {
202 case EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC:
203 case EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC:
204 break;
205 default:
206 return 0;
207 }
208
209 /* and now just check for general 64-vs-32 compatibility */
210 if (image_is_64_bit(PEHdr)) {
211 if (allow_64_bit())
212 return 1;
213 } else {
214 if (allow_32_bit())
215 return 1;
216 }
217 return 0;
218 }
219
220 /*
221 * Perform the actual relocation
222 */
223 static EFI_STATUS relocate_coff (PE_COFF_LOADER_IMAGE_CONTEXT *context,
224 EFI_IMAGE_SECTION_HEADER *Section,
225 void *orig, void *data)
226 {
227 EFI_IMAGE_BASE_RELOCATION *RelocBase, *RelocBaseEnd;
228 UINT64 Adjust;
229 UINT16 *Reloc, *RelocEnd;
230 char *Fixup, *FixupBase;
231 UINT16 *Fixup16;
232 UINT32 *Fixup32;
233 UINT64 *Fixup64;
234 int size = context->ImageSize;
235 void *ImageEnd = (char *)orig + size;
236 int n = 0;
237
238 /* Alright, so here's how this works:
239 *
240 * context->RelocDir gives us two things:
241 * - the VA the table of base relocation blocks are (maybe) to be
242 * mapped at (RelocDir->VirtualAddress)
243 * - the virtual size (RelocDir->Size)
244 *
245 * The .reloc section (Section here) gives us some other things:
246 * - the name! kind of. (Section->Name)
247 * - the virtual size (Section->VirtualSize), which should be the same
248 * as RelocDir->Size
249 * - the virtual address (Section->VirtualAddress)
250 * - the file section size (Section->SizeOfRawData), which is
251 * a multiple of OptHdr->FileAlignment. Only useful for image
252 * validation, not really useful for iteration bounds.
253 * - the file address (Section->PointerToRawData)
254 * - a bunch of stuff we don't use that's 0 in our binaries usually
255 * - Flags (Section->Characteristics)
256 *
257 * and then the thing that's actually at the file address is an array
258 * of EFI_IMAGE_BASE_RELOCATION structs with some values packed behind
259 * them. The SizeOfBlock field of this structure includes the
260 * structure itself, and adding it to that structure's address will
261 * yield the next entry in the array.
262 */
263 RelocBase = ImageAddress(orig, size, Section->PointerToRawData);
264 /* RelocBaseEnd here is the address of the first entry /past/ the
265 * table. */
266 RelocBaseEnd = ImageAddress(orig, size, Section->PointerToRawData +
267 Section->Misc.VirtualSize);
268
269 if (!RelocBase && !RelocBaseEnd)
270 return EFI_SUCCESS;
271
272 if (!RelocBase || !RelocBaseEnd) {
273 perror(L"Reloc table overflows binary\n");
274 return EFI_UNSUPPORTED;
275 }
276
277 Adjust = (UINTN)data - context->ImageAddress;
278
279 if (Adjust == 0)
280 return EFI_SUCCESS;
281
282 while (RelocBase < RelocBaseEnd) {
283 Reloc = (UINT16 *) ((char *) RelocBase + sizeof (EFI_IMAGE_BASE_RELOCATION));
284
285 if (RelocBase->SizeOfBlock == 0) {
286 perror(L"Reloc %d block size 0 is invalid\n", n);
287 return EFI_UNSUPPORTED;
288 } else if (RelocBase->SizeOfBlock > context->RelocDir->Size) {
289 perror(L"Reloc %d block size %d greater than reloc dir"
290 "size %d, which is invalid\n", n,
291 RelocBase->SizeOfBlock,
292 context->RelocDir->Size);
293 return EFI_UNSUPPORTED;
294 }
295
296 RelocEnd = (UINT16 *) ((char *) RelocBase + RelocBase->SizeOfBlock);
297 if ((void *)RelocEnd < orig || (void *)RelocEnd > ImageEnd) {
298 perror(L"Reloc %d entry overflows binary\n", n);
299 return EFI_UNSUPPORTED;
300 }
301
302 FixupBase = ImageAddress(data, size, RelocBase->VirtualAddress);
303 if (!FixupBase) {
304 perror(L"Reloc %d Invalid fixupbase\n", n);
305 return EFI_UNSUPPORTED;
306 }
307
308 while (Reloc < RelocEnd) {
309 Fixup = FixupBase + (*Reloc & 0xFFF);
310 switch ((*Reloc) >> 12) {
311 case EFI_IMAGE_REL_BASED_ABSOLUTE:
312 break;
313
314 case EFI_IMAGE_REL_BASED_HIGH:
315 Fixup16 = (UINT16 *) Fixup;
316 *Fixup16 = (UINT16) (*Fixup16 + ((UINT16) ((UINT32) Adjust >> 16)));
317 break;
318
319 case EFI_IMAGE_REL_BASED_LOW:
320 Fixup16 = (UINT16 *) Fixup;
321 *Fixup16 = (UINT16) (*Fixup16 + (UINT16) Adjust);
322 break;
323
324 case EFI_IMAGE_REL_BASED_HIGHLOW:
325 Fixup32 = (UINT32 *) Fixup;
326 *Fixup32 = *Fixup32 + (UINT32) Adjust;
327 break;
328
329 case EFI_IMAGE_REL_BASED_DIR64:
330 Fixup64 = (UINT64 *) Fixup;
331 *Fixup64 = *Fixup64 + (UINT64) Adjust;
332 break;
333
334 default:
335 perror(L"Reloc %d Unknown relocation\n", n);
336 return EFI_UNSUPPORTED;
337 }
338 Reloc += 1;
339 }
340 RelocBase = (EFI_IMAGE_BASE_RELOCATION *) RelocEnd;
341 n++;
342 }
343
344 return EFI_SUCCESS;
345 }
346
347 static void
348 drain_openssl_errors(void)
349 {
350 unsigned long err = -1;
351 while (err != 0)
352 err = ERR_get_error();
353 }
354
355 static BOOLEAN verify_x509(UINT8 *Cert, UINTN CertSize)
356 {
357 UINTN length;
358
359 if (!Cert || CertSize < 4)
360 return FALSE;
361
362 /*
363 * A DER encoding x509 certificate starts with SEQUENCE(0x30),
364 * the number of length bytes, and the number of value bytes.
365 * The size of a x509 certificate is usually between 127 bytes
366 * and 64KB. For convenience, assume the number of value bytes
367 * is 2, i.e. the second byte is 0x82.
368 */
369 if (Cert[0] != 0x30 || Cert[1] != 0x82)
370 return FALSE;
371
372 length = Cert[2]<<8 | Cert[3];
373 if (length != (CertSize - 4))
374 return FALSE;
375
376 return TRUE;
377 }
378
379 static BOOLEAN verify_eku(UINT8 *Cert, UINTN CertSize)
380 {
381 X509 *x509;
382 CONST UINT8 *Temp = Cert;
383 EXTENDED_KEY_USAGE *eku;
384 ASN1_OBJECT *module_signing;
385
386 module_signing = OBJ_nid2obj(OBJ_create(OID_EKU_MODSIGN, NULL, NULL));
387
388 x509 = d2i_X509 (NULL, &Temp, (long) CertSize);
389 if (x509 != NULL) {
390 eku = X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL);
391
392 if (eku) {
393 int i = 0;
394 for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
395 ASN1_OBJECT *key_usage = sk_ASN1_OBJECT_value(eku, i);
396
397 if (OBJ_cmp(module_signing, key_usage) == 0)
398 return FALSE;
399 }
400 EXTENDED_KEY_USAGE_free(eku);
401 }
402
403 X509_free(x509);
404 }
405
406 return TRUE;
407 }
408
409 static void show_ca_warning()
410 {
411 CHAR16 *text[9];
412
413 text[0] = L"WARNING!";
414 text[1] = L"";
415 text[2] = L"The CA certificate used to verify this image doesn't ";
416 text[3] = L"contain the CA flag in Basic Constraints or KeyCertSign";
417 text[4] = L"in KeyUsage. Such CA certificates will not be supported";
418 text[5] = L"in the future. ";
419 text[6] = L"";
420 text[7] = L"Please contact the issuer to update the certificate. ";
421 text[8] = NULL;
422
423 console_reset();
424 console_print_box(text, -1);
425 }
426
427 static CHECK_STATUS check_db_cert_in_ram(EFI_SIGNATURE_LIST *CertList,
428 UINTN dbsize,
429 WIN_CERTIFICATE_EFI_PKCS *data,
430 UINT8 *hash, CHAR16 *dbname,
431 EFI_GUID guid)
432 {
433 EFI_SIGNATURE_DATA *Cert;
434 UINTN CertSize;
435 BOOLEAN IsFound = FALSE;
436
437 while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
438 if (CompareGuid (&CertList->SignatureType, &EFI_CERT_TYPE_X509_GUID) == 0) {
439 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
440 CertSize = CertList->SignatureSize - sizeof(EFI_GUID);
441 if (verify_x509(Cert->SignatureData, CertSize)) {
442 if (verify_eku(Cert->SignatureData, CertSize)) {
443 clear_ca_warning();
444 IsFound = AuthenticodeVerify (data->CertData,
445 data->Hdr.dwLength - sizeof(data->Hdr),
446 Cert->SignatureData,
447 CertSize,
448 hash, SHA256_DIGEST_SIZE);
449 if (IsFound) {
450 if (get_ca_warning()) {
451 show_ca_warning();
452 }
453 tpm_measure_variable(dbname, guid, CertSize, Cert->SignatureData);
454 drain_openssl_errors();
455 return DATA_FOUND;
456 } else {
457 LogError(L"AuthenticodeVerify(): %d\n", IsFound);
458 }
459 }
460 } else if (verbose) {
461 console_notify(L"Not a DER encoding x.509 Certificate");
462 }
463 }
464
465 dbsize -= CertList->SignatureListSize;
466 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
467 }
468
469 return DATA_NOT_FOUND;
470 }
471
472 static CHECK_STATUS check_db_cert(CHAR16 *dbname, EFI_GUID guid,
473 WIN_CERTIFICATE_EFI_PKCS *data, UINT8 *hash)
474 {
475 CHECK_STATUS rc;
476 EFI_STATUS efi_status;
477 EFI_SIGNATURE_LIST *CertList;
478 UINTN dbsize = 0;
479 UINT8 *db;
480
481 efi_status = get_variable(dbname, &db, &dbsize, guid);
482 if (EFI_ERROR(efi_status))
483 return VAR_NOT_FOUND;
484
485 CertList = (EFI_SIGNATURE_LIST *)db;
486
487 rc = check_db_cert_in_ram(CertList, dbsize, data, hash, dbname, guid);
488
489 FreePool(db);
490
491 return rc;
492 }
493
494 /*
495 * Check a hash against an EFI_SIGNATURE_LIST in a buffer
496 */
497 static CHECK_STATUS check_db_hash_in_ram(EFI_SIGNATURE_LIST *CertList,
498 UINTN dbsize, UINT8 *data,
499 int SignatureSize, EFI_GUID CertType,
500 CHAR16 *dbname, EFI_GUID guid)
501 {
502 EFI_SIGNATURE_DATA *Cert;
503 UINTN CertCount, Index;
504 BOOLEAN IsFound = FALSE;
505
506 while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
507 CertCount = (CertList->SignatureListSize -sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
508 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
509 if (CompareGuid(&CertList->SignatureType, &CertType) == 0) {
510 for (Index = 0; Index < CertCount; Index++) {
511 if (CompareMem (Cert->SignatureData, data, SignatureSize) == 0) {
512 //
513 // Find the signature in database.
514 //
515 IsFound = TRUE;
516 tpm_measure_variable(dbname, guid, SignatureSize, data);
517 break;
518 }
519
520 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
521 }
522 if (IsFound) {
523 break;
524 }
525 }
526
527 dbsize -= CertList->SignatureListSize;
528 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
529 }
530
531 if (IsFound)
532 return DATA_FOUND;
533
534 return DATA_NOT_FOUND;
535 }
536
537 /*
538 * Check a hash against an EFI_SIGNATURE_LIST in a UEFI variable
539 */
540 static CHECK_STATUS check_db_hash(CHAR16 *dbname, EFI_GUID guid, UINT8 *data,
541 int SignatureSize, EFI_GUID CertType)
542 {
543 EFI_STATUS efi_status;
544 EFI_SIGNATURE_LIST *CertList;
545 UINTN dbsize = 0;
546 UINT8 *db;
547
548 efi_status = get_variable(dbname, &db, &dbsize, guid);
549 if (EFI_ERROR(efi_status)) {
550 return VAR_NOT_FOUND;
551 }
552
553 CertList = (EFI_SIGNATURE_LIST *)db;
554
555 CHECK_STATUS rc = check_db_hash_in_ram(CertList, dbsize, data,
556 SignatureSize, CertType,
557 dbname, guid);
558 FreePool(db);
559 return rc;
560
561 }
562
563 /*
564 * Check whether the binary signature or hash are present in dbx or the
565 * built-in blacklist
566 */
567 static EFI_STATUS check_blacklist (WIN_CERTIFICATE_EFI_PKCS *cert,
568 UINT8 *sha256hash, UINT8 *sha1hash)
569 {
570 EFI_SIGNATURE_LIST *dbx = (EFI_SIGNATURE_LIST *)vendor_dbx;
571
572 if (check_db_hash_in_ram(dbx, vendor_dbx_size, sha256hash,
573 SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID, L"dbx",
574 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
575 LogError(L"binary sha256hash found in vendor dbx\n");
576 return EFI_SECURITY_VIOLATION;
577 }
578 if (check_db_hash_in_ram(dbx, vendor_dbx_size, sha1hash,
579 SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID, L"dbx",
580 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
581 LogError(L"binary sha1hash found in vendor dbx\n");
582 return EFI_SECURITY_VIOLATION;
583 }
584 if (cert &&
585 check_db_cert_in_ram(dbx, vendor_dbx_size, cert, sha256hash, L"dbx",
586 EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
587 LogError(L"cert sha256hash found in vendor dbx\n");
588 return EFI_SECURITY_VIOLATION;
589 }
590 if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha256hash,
591 SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
592 LogError(L"binary sha256hash found in system dbx\n");
593 return EFI_SECURITY_VIOLATION;
594 }
595 if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha1hash,
596 SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID) == DATA_FOUND) {
597 LogError(L"binary sha1hash found in system dbx\n");
598 return EFI_SECURITY_VIOLATION;
599 }
600 if (cert &&
601 check_db_cert(L"dbx", EFI_SECURE_BOOT_DB_GUID,
602 cert, sha256hash) == DATA_FOUND) {
603 LogError(L"cert sha256hash found in system dbx\n");
604 return EFI_SECURITY_VIOLATION;
605 }
606 if (check_db_hash(L"MokListX", SHIM_LOCK_GUID, sha256hash,
607 SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
608 LogError(L"binary sha256hash found in Mok dbx\n");
609 return EFI_SECURITY_VIOLATION;
610 }
611 if (cert &&
612 check_db_cert(L"MokListX", SHIM_LOCK_GUID,
613 cert, sha256hash) == DATA_FOUND) {
614 LogError(L"cert sha256hash found in Mok dbx\n");
615 return EFI_SECURITY_VIOLATION;
616 }
617
618 drain_openssl_errors();
619 return EFI_SUCCESS;
620 }
621
622 static void update_verification_method(verification_method_t method)
623 {
624 if (verification_method == VERIFIED_BY_NOTHING)
625 verification_method = method;
626 }
627
628 /*
629 * Check whether the binary signature or hash are present in db or MokList
630 */
631 static EFI_STATUS check_whitelist (WIN_CERTIFICATE_EFI_PKCS *cert,
632 UINT8 *sha256hash, UINT8 *sha1hash)
633 {
634 if (!ignore_db) {
635 if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha256hash, SHA256_DIGEST_SIZE,
636 EFI_CERT_SHA256_GUID) == DATA_FOUND) {
637 update_verification_method(VERIFIED_BY_HASH);
638 return EFI_SUCCESS;
639 } else {
640 LogError(L"check_db_hash(db, sha256hash) != DATA_FOUND\n");
641 }
642 if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha1hash, SHA1_DIGEST_SIZE,
643 EFI_CERT_SHA1_GUID) == DATA_FOUND) {
644 verification_method = VERIFIED_BY_HASH;
645 update_verification_method(VERIFIED_BY_HASH);
646 return EFI_SUCCESS;
647 } else {
648 LogError(L"check_db_hash(db, sha1hash) != DATA_FOUND\n");
649 }
650 if (cert && check_db_cert(L"db", EFI_SECURE_BOOT_DB_GUID, cert, sha256hash)
651 == DATA_FOUND) {
652 verification_method = VERIFIED_BY_CERT;
653 update_verification_method(VERIFIED_BY_CERT);
654 return EFI_SUCCESS;
655 } else {
656 LogError(L"check_db_cert(db, sha256hash) != DATA_FOUND\n");
657 }
658 }
659
660 if (check_db_hash(L"MokList", SHIM_LOCK_GUID, sha256hash,
661 SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID)
662 == DATA_FOUND) {
663 verification_method = VERIFIED_BY_HASH;
664 update_verification_method(VERIFIED_BY_HASH);
665 return EFI_SUCCESS;
666 } else {
667 LogError(L"check_db_hash(MokList, sha256hash) != DATA_FOUND\n");
668 }
669 if (cert && check_db_cert(L"MokList", SHIM_LOCK_GUID, cert, sha256hash)
670 == DATA_FOUND) {
671 verification_method = VERIFIED_BY_CERT;
672 update_verification_method(VERIFIED_BY_CERT);
673 return EFI_SUCCESS;
674 } else {
675 LogError(L"check_db_cert(MokList, sha256hash) != DATA_FOUND\n");
676 }
677
678 update_verification_method(VERIFIED_BY_NOTHING);
679 return EFI_SECURITY_VIOLATION;
680 }
681
682 /*
683 * Check whether we're in Secure Boot and user mode
684 */
685
686 static BOOLEAN secure_mode (void)
687 {
688 static int first = 1;
689 if (user_insecure_mode)
690 return FALSE;
691
692 if (variable_is_secureboot() != 1) {
693 if (verbose && !in_protocol && first)
694 console_notify(L"Secure boot not enabled");
695 first = 0;
696 return FALSE;
697 }
698
699 /* If we /do/ have "SecureBoot", but /don't/ have "SetupMode",
700 * then the implementation is bad, but we assume that secure boot is
701 * enabled according to the status of "SecureBoot". If we have both
702 * of them, then "SetupMode" may tell us additional data, and we need
703 * to consider it.
704 */
705 if (variable_is_setupmode(0) == 1) {
706 if (verbose && !in_protocol && first)
707 console_notify(L"Platform is in setup mode");
708 first = 0;
709 return FALSE;
710 }
711
712 first = 0;
713 return TRUE;
714 }
715
716 #define check_size_line(data, datasize_in, hashbase, hashsize, l) ({ \
717 if ((unsigned long)hashbase > \
718 (unsigned long)data + datasize_in) { \
719 efi_status = EFI_INVALID_PARAMETER; \
720 perror(L"shim.c:%d Invalid hash base 0x%016x\n", l, \
721 hashbase); \
722 goto done; \
723 } \
724 if ((unsigned long)hashbase + hashsize > \
725 (unsigned long)data + datasize_in) { \
726 efi_status = EFI_INVALID_PARAMETER; \
727 perror(L"shim.c:%d Invalid hash size 0x%016x\n", l, \
728 hashsize); \
729 goto done; \
730 } \
731 })
732 #define check_size(d,ds,h,hs) check_size_line(d,ds,h,hs,__LINE__)
733
734 /*
735 * Calculate the SHA1 and SHA256 hashes of a binary
736 */
737
738 static EFI_STATUS generate_hash (char *data, unsigned int datasize_in,
739 PE_COFF_LOADER_IMAGE_CONTEXT *context,
740 UINT8 *sha256hash, UINT8 *sha1hash)
741
742 {
743 unsigned int sha256ctxsize, sha1ctxsize;
744 unsigned int size = datasize_in;
745 void *sha256ctx = NULL, *sha1ctx = NULL;
746 char *hashbase;
747 unsigned int hashsize;
748 unsigned int SumOfBytesHashed, SumOfSectionBytes;
749 unsigned int index, pos;
750 unsigned int datasize;
751 EFI_IMAGE_SECTION_HEADER *Section;
752 EFI_IMAGE_SECTION_HEADER *SectionHeader = NULL;
753 EFI_STATUS efi_status = EFI_SUCCESS;
754 EFI_IMAGE_DOS_HEADER *DosHdr = (void *)data;
755 unsigned int PEHdr_offset = 0;
756
757 size = datasize = datasize_in;
758
759 if (datasize <= sizeof (*DosHdr) ||
760 DosHdr->e_magic != EFI_IMAGE_DOS_SIGNATURE) {
761 perror(L"Invalid signature\n");
762 return EFI_INVALID_PARAMETER;
763 }
764 PEHdr_offset = DosHdr->e_lfanew;
765
766 sha256ctxsize = Sha256GetContextSize();
767 sha256ctx = AllocatePool(sha256ctxsize);
768
769 sha1ctxsize = Sha1GetContextSize();
770 sha1ctx = AllocatePool(sha1ctxsize);
771
772 if (!sha256ctx || !sha1ctx) {
773 perror(L"Unable to allocate memory for hash context\n");
774 return EFI_OUT_OF_RESOURCES;
775 }
776
777 if (!Sha256Init(sha256ctx) || !Sha1Init(sha1ctx)) {
778 perror(L"Unable to initialise hash\n");
779 efi_status = EFI_OUT_OF_RESOURCES;
780 goto done;
781 }
782
783 /* Hash start to checksum */
784 hashbase = data;
785 hashsize = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum -
786 hashbase;
787 check_size(data, datasize_in, hashbase, hashsize);
788
789 if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
790 !(Sha1Update(sha1ctx, hashbase, hashsize))) {
791 perror(L"Unable to generate hash\n");
792 efi_status = EFI_OUT_OF_RESOURCES;
793 goto done;
794 }
795
796 /* Hash post-checksum to start of certificate table */
797 hashbase = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum +
798 sizeof (int);
799 hashsize = (char *)context->SecDir - hashbase;
800 check_size(data, datasize_in, hashbase, hashsize);
801
802 if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
803 !(Sha1Update(sha1ctx, hashbase, hashsize))) {
804 perror(L"Unable to generate hash\n");
805 efi_status = EFI_OUT_OF_RESOURCES;
806 goto done;
807 }
808
809 /* Hash end of certificate table to end of image header */
810 EFI_IMAGE_DATA_DIRECTORY *dd = context->SecDir + 1;
811 hashbase = (char *)dd;
812 hashsize = context->SizeOfHeaders - (unsigned long)((char *)dd - data);
813 if (hashsize > datasize_in) {
814 perror(L"Data Directory size %d is invalid\n", hashsize);
815 efi_status = EFI_INVALID_PARAMETER;
816 goto done;
817 }
818 check_size(data, datasize_in, hashbase, hashsize);
819
820 if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
821 !(Sha1Update(sha1ctx, hashbase, hashsize))) {
822 perror(L"Unable to generate hash\n");
823 efi_status = EFI_OUT_OF_RESOURCES;
824 goto done;
825 }
826
827 /* Sort sections */
828 SumOfBytesHashed = context->SizeOfHeaders;
829
830 /* Validate section locations and sizes */
831 for (index = 0, SumOfSectionBytes = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
832 EFI_IMAGE_SECTION_HEADER *SectionPtr;
833
834 /* Validate SectionPtr is within image */
835 SectionPtr = ImageAddress(data, datasize,
836 PEHdr_offset +
837 sizeof (UINT32) +
838 sizeof (EFI_IMAGE_FILE_HEADER) +
839 context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader +
840 (index * sizeof(*SectionPtr)));
841 if (!SectionPtr) {
842 perror(L"Malformed section %d\n", index);
843 efi_status = EFI_INVALID_PARAMETER;
844 goto done;
845 }
846 /* Validate section size is within image. */
847 if (SectionPtr->SizeOfRawData >
848 datasize - SumOfBytesHashed - SumOfSectionBytes) {
849 perror(L"Malformed section %d size\n", index);
850 efi_status = EFI_INVALID_PARAMETER;
851 goto done;
852 }
853 SumOfSectionBytes += SectionPtr->SizeOfRawData;
854 }
855
856 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * context->PEHdr->Pe32.FileHeader.NumberOfSections);
857 if (SectionHeader == NULL) {
858 perror(L"Unable to allocate section header\n");
859 efi_status = EFI_OUT_OF_RESOURCES;
860 goto done;
861 }
862
863 /* Already validated above */
864 Section = ImageAddress(data, datasize,
865 PEHdr_offset +
866 sizeof (UINT32) +
867 sizeof (EFI_IMAGE_FILE_HEADER) +
868 context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader);
869 /* But check it again just for better error messaging, and so
870 * clang-analyzer doesn't get confused. */
871 if (Section == NULL) {
872 uint64_t addr;
873
874 addr = PEHdr_offset + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER)
875 + context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader;
876 perror(L"Malformed file header.\n");
877 perror(L"Image address for Section 0 is 0x%016llx\n", addr);
878 perror(L"File size is 0x%016llx\n", datasize);
879 efi_status = EFI_INVALID_PARAMETER;
880 goto done;
881 }
882
883 /* Sort the section headers */
884 for (index = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
885 pos = index;
886 while ((pos > 0) && (Section->PointerToRawData < SectionHeader[pos - 1].PointerToRawData)) {
887 CopyMem (&SectionHeader[pos], &SectionHeader[pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
888 pos--;
889 }
890 CopyMem (&SectionHeader[pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
891 Section += 1;
892 }
893
894 /* Hash the sections */
895 for (index = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
896 Section = &SectionHeader[index];
897 if (Section->SizeOfRawData == 0) {
898 continue;
899 }
900 hashbase = ImageAddress(data, size, Section->PointerToRawData);
901
902 if (!hashbase) {
903 perror(L"Malformed section header\n");
904 efi_status = EFI_INVALID_PARAMETER;
905 goto done;
906 }
907
908 /* Verify hashsize within image. */
909 if (Section->SizeOfRawData >
910 datasize - Section->PointerToRawData) {
911 perror(L"Malformed section raw size %d\n", index);
912 efi_status = EFI_INVALID_PARAMETER;
913 goto done;
914 }
915 hashsize = (unsigned int) Section->SizeOfRawData;
916 check_size(data, datasize_in, hashbase, hashsize);
917
918 if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
919 !(Sha1Update(sha1ctx, hashbase, hashsize))) {
920 perror(L"Unable to generate hash\n");
921 efi_status = EFI_OUT_OF_RESOURCES;
922 goto done;
923 }
924 SumOfBytesHashed += Section->SizeOfRawData;
925 }
926
927 /* Hash all remaining data up to SecDir if SecDir->Size is not 0 */
928 if (datasize > SumOfBytesHashed && context->SecDir->Size) {
929 hashbase = data + SumOfBytesHashed;
930 hashsize = datasize - context->SecDir->Size - SumOfBytesHashed;
931
932 if ((datasize - SumOfBytesHashed < context->SecDir->Size) ||
933 (SumOfBytesHashed + hashsize != context->SecDir->VirtualAddress)) {
934 perror(L"Malformed binary after Attribute Certificate Table\n");
935 console_print(L"datasize: %u SumOfBytesHashed: %u SecDir->Size: %lu\n",
936 datasize, SumOfBytesHashed, context->SecDir->Size);
937 console_print(L"hashsize: %u SecDir->VirtualAddress: 0x%08lx\n",
938 hashsize, context->SecDir->VirtualAddress);
939 efi_status = EFI_INVALID_PARAMETER;
940 goto done;
941 }
942 check_size(data, datasize_in, hashbase, hashsize);
943
944 if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
945 !(Sha1Update(sha1ctx, hashbase, hashsize))) {
946 perror(L"Unable to generate hash\n");
947 efi_status = EFI_OUT_OF_RESOURCES;
948 goto done;
949 }
950
951 #if 1
952 }
953 #else // we have to migrate to doing this later :/
954 SumOfBytesHashed += hashsize;
955 }
956
957 /* Hash all remaining data */
958 if (datasize > SumOfBytesHashed) {
959 hashbase = data + SumOfBytesHashed;
960 hashsize = datasize - SumOfBytesHashed;
961
962 check_size(data, datasize_in, hashbase, hashsize);
963
964 if (!(Sha256Update(sha256ctx, hashbase, hashsize)) ||
965 !(Sha1Update(sha1ctx, hashbase, hashsize))) {
966 perror(L"Unable to generate hash\n");
967 efi_status = EFI_OUT_OF_RESOURCES;
968 goto done;
969 }
970
971 SumOfBytesHashed += hashsize;
972 }
973 #endif
974
975 if (!(Sha256Final(sha256ctx, sha256hash)) ||
976 !(Sha1Final(sha1ctx, sha1hash))) {
977 perror(L"Unable to finalise hash\n");
978 efi_status = EFI_OUT_OF_RESOURCES;
979 goto done;
980 }
981
982 done:
983 if (SectionHeader)
984 FreePool(SectionHeader);
985 if (sha1ctx)
986 FreePool(sha1ctx);
987 if (sha256ctx)
988 FreePool(sha256ctx);
989
990 return efi_status;
991 }
992
993 /*
994 * Check that the signature is valid and matches the binary
995 */
996 static EFI_STATUS verify_buffer (char *data, int datasize,
997 PE_COFF_LOADER_IMAGE_CONTEXT *context,
998 UINT8 *sha256hash, UINT8 *sha1hash)
999 {
1000 EFI_STATUS efi_status = EFI_SECURITY_VIOLATION;
1001 WIN_CERTIFICATE_EFI_PKCS *cert = NULL;
1002 unsigned int size = datasize;
1003
1004 if (datasize < 0)
1005 return EFI_INVALID_PARAMETER;
1006
1007 if (context->SecDir->Size != 0) {
1008 if (context->SecDir->Size >= size) {
1009 perror(L"Certificate Database size is too large\n");
1010 return EFI_INVALID_PARAMETER;
1011 }
1012
1013 cert = ImageAddress (data, size,
1014 context->SecDir->VirtualAddress);
1015
1016 if (!cert) {
1017 perror(L"Certificate located outside the image\n");
1018 return EFI_INVALID_PARAMETER;
1019 }
1020
1021 if (cert->Hdr.dwLength > context->SecDir->Size) {
1022 perror(L"Certificate list size is inconsistent with PE headers");
1023 return EFI_INVALID_PARAMETER;
1024 }
1025
1026 if (cert->Hdr.wCertificateType !=
1027 WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1028 perror(L"Unsupported certificate type %x\n",
1029 cert->Hdr.wCertificateType);
1030 return EFI_UNSUPPORTED;
1031 }
1032 }
1033
1034 /*
1035 * Clear OpenSSL's error log, because we get some DSO unimplemented
1036 * errors during its intialization, and we don't want those to look
1037 * like they're the reason for validation failures.
1038 */
1039 drain_openssl_errors();
1040
1041 efi_status = generate_hash(data, datasize, context, sha256hash, sha1hash);
1042 if (EFI_ERROR(efi_status)) {
1043 LogError(L"generate_hash: %r\n", efi_status);
1044 return efi_status;
1045 }
1046
1047 /*
1048 * Ensure that the binary isn't blacklisted
1049 */
1050 efi_status = check_blacklist(cert, sha256hash, sha1hash);
1051 if (EFI_ERROR(efi_status)) {
1052 perror(L"Binary is blacklisted\n");
1053 LogError(L"Binary is blacklisted: %r\n", efi_status);
1054 return efi_status;
1055 }
1056
1057 /*
1058 * Check whether the binary is whitelisted in any of the firmware
1059 * databases
1060 */
1061 efi_status = check_whitelist(cert, sha256hash, sha1hash);
1062 if (EFI_ERROR(efi_status)) {
1063 LogError(L"check_whitelist(): %r\n", efi_status);
1064 } else {
1065 drain_openssl_errors();
1066 return efi_status;
1067 }
1068
1069 if (cert) {
1070 #if defined(ENABLE_SHIM_CERT)
1071 /*
1072 * Check against the shim build key
1073 */
1074 clear_ca_warning();
1075 if (sizeof(shim_cert) &&
1076 AuthenticodeVerify(cert->CertData,
1077 cert->Hdr.dwLength - sizeof(cert->Hdr),
1078 shim_cert, sizeof(shim_cert), sha256hash,
1079 SHA256_DIGEST_SIZE)) {
1080 if (get_ca_warning()) {
1081 show_ca_warning();
1082 }
1083 update_verification_method(VERIFIED_BY_CERT);
1084 tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
1085 sizeof(shim_cert), shim_cert);
1086 efi_status = EFI_SUCCESS;
1087 drain_openssl_errors();
1088 return efi_status;
1089 } else {
1090 LogError(L"AuthenticodeVerify(shim_cert) failed\n");
1091 }
1092 #endif /* defined(ENABLE_SHIM_CERT) */
1093
1094 /*
1095 * And finally, check against shim's built-in key
1096 */
1097 clear_ca_warning();
1098 if (vendor_cert_size &&
1099 AuthenticodeVerify(cert->CertData,
1100 cert->Hdr.dwLength - sizeof(cert->Hdr),
1101 vendor_cert, vendor_cert_size,
1102 sha256hash, SHA256_DIGEST_SIZE)) {
1103 if (get_ca_warning()) {
1104 show_ca_warning();
1105 }
1106 update_verification_method(VERIFIED_BY_CERT);
1107 tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
1108 vendor_cert_size, vendor_cert);
1109 efi_status = EFI_SUCCESS;
1110 drain_openssl_errors();
1111 return efi_status;
1112 } else {
1113 LogError(L"AuthenticodeVerify(vendor_cert) failed\n");
1114 }
1115 }
1116
1117 LogError(L"Binary is not whitelisted\n");
1118 crypterr(EFI_SECURITY_VIOLATION);
1119 PrintErrors();
1120 efi_status = EFI_SECURITY_VIOLATION;
1121 return efi_status;
1122 }
1123
1124 /*
1125 * Read the binary header and grab appropriate information from it
1126 */
1127 static EFI_STATUS read_header(void *data, unsigned int datasize,
1128 PE_COFF_LOADER_IMAGE_CONTEXT *context)
1129 {
1130 EFI_IMAGE_DOS_HEADER *DosHdr = data;
1131 EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr = data;
1132 unsigned long HeaderWithoutDataDir, SectionHeaderOffset, OptHeaderSize;
1133 unsigned long FileAlignment = 0;
1134
1135 if (datasize < sizeof (PEHdr->Pe32)) {
1136 perror(L"Invalid image\n");
1137 return EFI_UNSUPPORTED;
1138 }
1139
1140 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE)
1141 PEHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((char *)data + DosHdr->e_lfanew);
1142
1143 if (!image_is_loadable(PEHdr)) {
1144 perror(L"Platform does not support this image\n");
1145 return EFI_UNSUPPORTED;
1146 }
1147
1148 if (image_is_64_bit(PEHdr)) {
1149 context->NumberOfRvaAndSizes = PEHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes;
1150 context->SizeOfHeaders = PEHdr->Pe32Plus.OptionalHeader.SizeOfHeaders;
1151 context->ImageSize = PEHdr->Pe32Plus.OptionalHeader.SizeOfImage;
1152 context->SectionAlignment = PEHdr->Pe32Plus.OptionalHeader.SectionAlignment;
1153 FileAlignment = PEHdr->Pe32Plus.OptionalHeader.FileAlignment;
1154 OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER64);
1155 } else {
1156 context->NumberOfRvaAndSizes = PEHdr->Pe32.OptionalHeader.NumberOfRvaAndSizes;
1157 context->SizeOfHeaders = PEHdr->Pe32.OptionalHeader.SizeOfHeaders;
1158 context->ImageSize = (UINT64)PEHdr->Pe32.OptionalHeader.SizeOfImage;
1159 context->SectionAlignment = PEHdr->Pe32.OptionalHeader.SectionAlignment;
1160 FileAlignment = PEHdr->Pe32.OptionalHeader.FileAlignment;
1161 OptHeaderSize = sizeof(EFI_IMAGE_OPTIONAL_HEADER32);
1162 }
1163
1164 if (FileAlignment % 2 != 0) {
1165 perror(L"File Alignment is invalid (%d)\n", FileAlignment);
1166 return EFI_UNSUPPORTED;
1167 }
1168 if (FileAlignment == 0)
1169 FileAlignment = 0x200;
1170 if (context->SectionAlignment == 0)
1171 context->SectionAlignment = PAGE_SIZE;
1172 if (context->SectionAlignment < FileAlignment)
1173 context->SectionAlignment = FileAlignment;
1174
1175 context->NumberOfSections = PEHdr->Pe32.FileHeader.NumberOfSections;
1176
1177 if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES < context->NumberOfRvaAndSizes) {
1178 perror(L"Image header too small\n");
1179 return EFI_UNSUPPORTED;
1180 }
1181
1182 HeaderWithoutDataDir = OptHeaderSize
1183 - sizeof (EFI_IMAGE_DATA_DIRECTORY) * EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES;
1184 if (((UINT32)PEHdr->Pe32.FileHeader.SizeOfOptionalHeader - HeaderWithoutDataDir) !=
1185 context->NumberOfRvaAndSizes * sizeof (EFI_IMAGE_DATA_DIRECTORY)) {
1186 perror(L"Image header overflows data directory\n");
1187 return EFI_UNSUPPORTED;
1188 }
1189
1190 SectionHeaderOffset = DosHdr->e_lfanew
1191 + sizeof (UINT32)
1192 + sizeof (EFI_IMAGE_FILE_HEADER)
1193 + PEHdr->Pe32.FileHeader.SizeOfOptionalHeader;
1194 if (((UINT32)context->ImageSize - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER
1195 <= context->NumberOfSections) {
1196 perror(L"Image sections overflow image size\n");
1197 return EFI_UNSUPPORTED;
1198 }
1199
1200 if ((context->SizeOfHeaders - SectionHeaderOffset) / EFI_IMAGE_SIZEOF_SECTION_HEADER
1201 < (UINT32)context->NumberOfSections) {
1202 perror(L"Image sections overflow section headers\n");
1203 return EFI_UNSUPPORTED;
1204 }
1205
1206 if ((((UINT8 *)PEHdr - (UINT8 *)data) + sizeof(EFI_IMAGE_OPTIONAL_HEADER_UNION)) > datasize) {
1207 perror(L"Invalid image\n");
1208 return EFI_UNSUPPORTED;
1209 }
1210
1211 if (PEHdr->Te.Signature != EFI_IMAGE_NT_SIGNATURE) {
1212 perror(L"Unsupported image type\n");
1213 return EFI_UNSUPPORTED;
1214 }
1215
1216 if (PEHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) {
1217 perror(L"Unsupported image - Relocations have been stripped\n");
1218 return EFI_UNSUPPORTED;
1219 }
1220
1221 context->PEHdr = PEHdr;
1222
1223 if (image_is_64_bit(PEHdr)) {
1224 context->ImageAddress = PEHdr->Pe32Plus.OptionalHeader.ImageBase;
1225 context->EntryPoint = PEHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint;
1226 context->RelocDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
1227 context->SecDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1228 } else {
1229 context->ImageAddress = PEHdr->Pe32.OptionalHeader.ImageBase;
1230 context->EntryPoint = PEHdr->Pe32.OptionalHeader.AddressOfEntryPoint;
1231 context->RelocDir = &PEHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
1232 context->SecDir = &PEHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1233 }
1234
1235 context->FirstSection = (EFI_IMAGE_SECTION_HEADER *)((char *)PEHdr + PEHdr->Pe32.FileHeader.SizeOfOptionalHeader + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER));
1236
1237 if (context->ImageSize < context->SizeOfHeaders) {
1238 perror(L"Invalid image\n");
1239 return EFI_UNSUPPORTED;
1240 }
1241
1242 if ((unsigned long)((UINT8 *)context->SecDir - (UINT8 *)data) >
1243 (datasize - sizeof(EFI_IMAGE_DATA_DIRECTORY))) {
1244 perror(L"Invalid image\n");
1245 return EFI_UNSUPPORTED;
1246 }
1247
1248 if (context->SecDir->VirtualAddress > datasize ||
1249 (context->SecDir->VirtualAddress == datasize &&
1250 context->SecDir->Size > 0)) {
1251 perror(L"Malformed security header\n");
1252 return EFI_INVALID_PARAMETER;
1253 }
1254 return EFI_SUCCESS;
1255 }
1256
1257 /*
1258 * Once the image has been loaded it needs to be validated and relocated
1259 */
1260 static EFI_STATUS handle_image (void *data, unsigned int datasize,
1261 EFI_LOADED_IMAGE *li,
1262 EFI_IMAGE_ENTRY_POINT *entry_point,
1263 EFI_PHYSICAL_ADDRESS *alloc_address,
1264 UINTN *alloc_pages)
1265 {
1266 EFI_STATUS efi_status;
1267 char *buffer;
1268 int i;
1269 EFI_IMAGE_SECTION_HEADER *Section;
1270 char *base, *end;
1271 PE_COFF_LOADER_IMAGE_CONTEXT context;
1272 unsigned int alignment, alloc_size;
1273 int found_entry_point = 0;
1274 UINT8 sha1hash[SHA1_DIGEST_SIZE];
1275 UINT8 sha256hash[SHA256_DIGEST_SIZE];
1276
1277 /*
1278 * The binary header contains relevant context and section pointers
1279 */
1280 efi_status = read_header(data, datasize, &context);
1281 if (EFI_ERROR(efi_status)) {
1282 perror(L"Failed to read header: %r\n", efi_status);
1283 return efi_status;
1284 }
1285
1286 /*
1287 * We only need to verify the binary if we're in secure mode
1288 */
1289 efi_status = generate_hash(data, datasize, &context, sha256hash,
1290 sha1hash);
1291 if (EFI_ERROR(efi_status))
1292 return efi_status;
1293
1294 /* Measure the binary into the TPM */
1295 #ifdef REQUIRE_TPM
1296 efi_status =
1297 #endif
1298 tpm_log_pe((EFI_PHYSICAL_ADDRESS)(UINTN)data, datasize, sha1hash, 4);
1299 #ifdef REQUIRE_TPM
1300 if (efi_status != EFI_SUCCESS) {
1301 return efi_status;
1302 }
1303 #endif
1304
1305 if (secure_mode ()) {
1306 efi_status = verify_buffer(data, datasize, &context,
1307 sha256hash, sha1hash);
1308
1309 if (EFI_ERROR(efi_status)) {
1310 console_error(L"Verification failed", efi_status);
1311 return efi_status;
1312 } else {
1313 if (verbose)
1314 console_print(L"Verification succeeded\n");
1315 }
1316 }
1317
1318 /* The spec says, uselessly, of SectionAlignment:
1319 * =====
1320 * The alignment (in bytes) of sections when they are loaded into
1321 * memory. It must be greater than or equal to FileAlignment. The
1322 * default is the page size for the architecture.
1323 * =====
1324 * Which doesn't tell you whose responsibility it is to enforce the
1325 * "default", or when. It implies that the value in the field must
1326 * be > FileAlignment (also poorly defined), but it appears visual
1327 * studio will happily write 512 for FileAlignment (its default) and
1328 * 0 for SectionAlignment, intending to imply PAGE_SIZE.
1329 *
1330 * We only support one page size, so if it's zero, nerf it to 4096.
1331 */
1332 alignment = context.SectionAlignment;
1333 if (!alignment)
1334 alignment = 4096;
1335
1336 alloc_size = ALIGN_VALUE(context.ImageSize + context.SectionAlignment,
1337 PAGE_SIZE);
1338 *alloc_pages = alloc_size / PAGE_SIZE;
1339
1340 efi_status = gBS->AllocatePages(AllocateAnyPages, EfiLoaderCode,
1341 *alloc_pages, alloc_address);
1342 if (EFI_ERROR(efi_status)) {
1343 perror(L"Failed to allocate image buffer\n");
1344 return EFI_OUT_OF_RESOURCES;
1345 }
1346
1347 buffer = (void *)ALIGN_VALUE((unsigned long)*alloc_address, alignment);
1348
1349 CopyMem(buffer, data, context.SizeOfHeaders);
1350
1351 *entry_point = ImageAddress(buffer, context.ImageSize, context.EntryPoint);
1352 if (!*entry_point) {
1353 perror(L"Entry point is invalid\n");
1354 gBS->FreePages(*alloc_address, *alloc_pages);
1355 return EFI_UNSUPPORTED;
1356 }
1357
1358
1359 char *RelocBase, *RelocBaseEnd;
1360 /*
1361 * These are relative virtual addresses, so we have to check them
1362 * against the image size, not the data size.
1363 */
1364 RelocBase = ImageAddress(buffer, context.ImageSize,
1365 context.RelocDir->VirtualAddress);
1366 /*
1367 * RelocBaseEnd here is the address of the last byte of the table
1368 */
1369 RelocBaseEnd = ImageAddress(buffer, context.ImageSize,
1370 context.RelocDir->VirtualAddress +
1371 context.RelocDir->Size - 1);
1372
1373 EFI_IMAGE_SECTION_HEADER *RelocSection = NULL;
1374
1375 /*
1376 * Copy the executable's sections to their desired offsets
1377 */
1378 Section = context.FirstSection;
1379 for (i = 0; i < context.NumberOfSections; i++, Section++) {
1380 base = ImageAddress (buffer, context.ImageSize,
1381 Section->VirtualAddress);
1382 end = ImageAddress (buffer, context.ImageSize,
1383 Section->VirtualAddress
1384 + Section->Misc.VirtualSize - 1);
1385
1386 if (end < base) {
1387 perror(L"Section %d has negative size\n", i);
1388 gBS->FreePages(*alloc_address, *alloc_pages);
1389 return EFI_UNSUPPORTED;
1390 }
1391
1392 if (Section->VirtualAddress <= context.EntryPoint &&
1393 (Section->VirtualAddress + Section->SizeOfRawData - 1)
1394 > context.EntryPoint)
1395 found_entry_point++;
1396
1397 /* We do want to process .reloc, but it's often marked
1398 * discardable, so we don't want to memcpy it. */
1399 if (CompareMem(Section->Name, ".reloc\0\0", 8) == 0) {
1400 if (RelocSection) {
1401 perror(L"Image has multiple relocation sections\n");
1402 return EFI_UNSUPPORTED;
1403 }
1404 /* If it has nonzero sizes, and our bounds check
1405 * made sense, and the VA and size match RelocDir's
1406 * versions, then we believe in this section table. */
1407 if (Section->SizeOfRawData &&
1408 Section->Misc.VirtualSize &&
1409 base && end &&
1410 RelocBase == base &&
1411 RelocBaseEnd == end) {
1412 RelocSection = Section;
1413 }
1414 }
1415
1416 if (Section->Characteristics & EFI_IMAGE_SCN_MEM_DISCARDABLE) {
1417 continue;
1418 }
1419
1420 if (!base) {
1421 perror(L"Section %d has invalid base address\n", i);
1422 return EFI_UNSUPPORTED;
1423 }
1424 if (!end) {
1425 perror(L"Section %d has zero size\n", i);
1426 return EFI_UNSUPPORTED;
1427 }
1428
1429 if (!(Section->Characteristics & EFI_IMAGE_SCN_CNT_UNINITIALIZED_DATA) &&
1430 (Section->VirtualAddress < context.SizeOfHeaders ||
1431 Section->PointerToRawData < context.SizeOfHeaders)) {
1432 perror(L"Section %d is inside image headers\n", i);
1433 return EFI_UNSUPPORTED;
1434 }
1435
1436 if (Section->Characteristics & EFI_IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
1437 ZeroMem(base, Section->Misc.VirtualSize);
1438 } else {
1439 if (Section->PointerToRawData < context.SizeOfHeaders) {
1440 perror(L"Section %d is inside image headers\n", i);
1441 return EFI_UNSUPPORTED;
1442 }
1443
1444 if (Section->SizeOfRawData > 0)
1445 CopyMem(base, data + Section->PointerToRawData,
1446 Section->SizeOfRawData);
1447
1448 if (Section->SizeOfRawData < Section->Misc.VirtualSize)
1449 ZeroMem(base + Section->SizeOfRawData,
1450 Section->Misc.VirtualSize - Section->SizeOfRawData);
1451 }
1452 }
1453
1454 if (context.NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
1455 perror(L"Image has no relocation entry\n");
1456 FreePool(buffer);
1457 return EFI_UNSUPPORTED;
1458 }
1459
1460 if (context.RelocDir->Size && RelocSection) {
1461 /*
1462 * Run the relocation fixups
1463 */
1464 efi_status = relocate_coff(&context, RelocSection, data,
1465 buffer);
1466
1467 if (EFI_ERROR(efi_status)) {
1468 perror(L"Relocation failed: %r\n", efi_status);
1469 FreePool(buffer);
1470 return efi_status;
1471 }
1472 }
1473
1474 /*
1475 * grub needs to know its location and size in memory, so fix up
1476 * the loaded image protocol values
1477 */
1478 li->ImageBase = buffer;
1479 li->ImageSize = context.ImageSize;
1480
1481 /* Pass the load options to the second stage loader */
1482 if ( load_options ) {
1483 li->LoadOptions = load_options;
1484 li->LoadOptionsSize = load_options_size;
1485 }
1486
1487 if (!found_entry_point) {
1488 perror(L"Entry point is not within sections\n");
1489 return EFI_UNSUPPORTED;
1490 }
1491 if (found_entry_point > 1) {
1492 perror(L"%d sections contain entry point\n");
1493 return EFI_UNSUPPORTED;
1494 }
1495
1496 return EFI_SUCCESS;
1497 }
1498
1499 static int
1500 should_use_fallback(EFI_HANDLE image_handle)
1501 {
1502 EFI_LOADED_IMAGE *li;
1503 unsigned int pathlen = 0;
1504 CHAR16 *bootpath = NULL;
1505 EFI_FILE_IO_INTERFACE *fio = NULL;
1506 EFI_FILE *vh = NULL;
1507 EFI_FILE *fh = NULL;
1508 EFI_STATUS efi_status;
1509 int ret = 0;
1510
1511 efi_status = gBS->HandleProtocol(image_handle, &EFI_LOADED_IMAGE_GUID,
1512 (void **)&li);
1513 if (EFI_ERROR(efi_status)) {
1514 perror(L"Could not get image for bootx64.efi: %r\n",
1515 efi_status);
1516 return 0;
1517 }
1518
1519 bootpath = DevicePathToStr(li->FilePath);
1520
1521 /* Check the beginning of the string and the end, to avoid
1522 * caring about which arch this is. */
1523 /* I really don't know why, but sometimes bootpath gives us
1524 * L"\\EFI\\BOOT\\/BOOTX64.EFI". So just handle that here...
1525 */
1526 if (StrnCaseCmp(bootpath, L"\\EFI\\BOOT\\BOOT", 14) &&
1527 StrnCaseCmp(bootpath, L"\\EFI\\BOOT\\/BOOT", 15) &&
1528 StrnCaseCmp(bootpath, L"EFI\\BOOT\\BOOT", 13) &&
1529 StrnCaseCmp(bootpath, L"EFI\\BOOT\\/BOOT", 14))
1530 goto error;
1531
1532 pathlen = StrLen(bootpath);
1533 if (pathlen < 5 || StrCaseCmp(bootpath + pathlen - 4, L".EFI"))
1534 goto error;
1535
1536 efi_status = gBS->HandleProtocol(li->DeviceHandle, &FileSystemProtocol,
1537 (void **) &fio);
1538 if (EFI_ERROR(efi_status)) {
1539 perror(L"Could not get fio for li->DeviceHandle: %r\n",
1540 efi_status);
1541 goto error;
1542 }
1543
1544 efi_status = fio->OpenVolume(fio, &vh);
1545 if (EFI_ERROR(efi_status)) {
1546 perror(L"Could not open fio volume: %r\n", efi_status);
1547 goto error;
1548 }
1549
1550 efi_status = vh->Open(vh, &fh, L"\\EFI\\BOOT" FALLBACK,
1551 EFI_FILE_MODE_READ, 0);
1552 if (EFI_ERROR(efi_status)) {
1553 /* Do not print the error here - this is an acceptable case
1554 * for removable media, where we genuinely don't want
1555 * fallback.efi to exist.
1556 * Print(L"Could not open \"\\EFI\\BOOT%s\": %r\n", FALLBACK,
1557 * efi_status);
1558 */
1559 goto error;
1560 }
1561
1562 ret = 1;
1563 error:
1564 if (fh)
1565 fh->Close(fh);
1566 if (vh)
1567 vh->Close(vh);
1568 if (bootpath)
1569 FreePool(bootpath);
1570
1571 return ret;
1572 }
1573
1574 /*
1575 * Generate the path of an executable given shim's path and the name
1576 * of the executable
1577 */
1578 static EFI_STATUS generate_path_from_image_path(EFI_LOADED_IMAGE *li,
1579 CHAR16 *ImagePath,
1580 CHAR16 **PathName)
1581 {
1582 EFI_DEVICE_PATH *devpath;
1583 unsigned int i;
1584 int j, last = -1;
1585 unsigned int pathlen = 0;
1586 EFI_STATUS efi_status = EFI_SUCCESS;
1587 CHAR16 *bootpath;
1588
1589 /*
1590 * Suuuuper lazy technique here, but check and see if this is a full
1591 * path to something on the ESP. Backwards compatibility demands
1592 * that we don't just use \\, becuase we (not particularly brightly)
1593 * used to require that the relative file path started with that.
1594 *
1595 * If it is a full path, don't try to merge it with the directory
1596 * from our Loaded Image handle.
1597 */
1598 if (StrSize(ImagePath) > 5 && StrnCmp(ImagePath, L"\\EFI\\", 5) == 0) {
1599 *PathName = StrDuplicate(ImagePath);
1600 if (!*PathName) {
1601 perror(L"Failed to allocate path buffer\n");
1602 return EFI_OUT_OF_RESOURCES;
1603 }
1604 return EFI_SUCCESS;
1605 }
1606
1607 devpath = li->FilePath;
1608
1609 bootpath = DevicePathToStr(devpath);
1610
1611 pathlen = StrLen(bootpath);
1612
1613 /*
1614 * DevicePathToStr() concatenates two nodes with '/'.
1615 * Convert '/' to '\\'.
1616 */
1617 for (i = 0; i < pathlen; i++) {
1618 if (bootpath[i] == '/')
1619 bootpath[i] = '\\';
1620 }
1621
1622 for (i=pathlen; i>0; i--) {
1623 if (bootpath[i] == '\\' && bootpath[i-1] == '\\')
1624 bootpath[i] = '/';
1625 else if (last == -1 && bootpath[i] == '\\')
1626 last = i;
1627 }
1628
1629 if (last == -1 && bootpath[0] == '\\')
1630 last = 0;
1631 bootpath[last+1] = '\0';
1632
1633 if (last > 0) {
1634 for (i = 0, j = 0; bootpath[i] != '\0'; i++) {
1635 if (bootpath[i] != '/') {
1636 bootpath[j] = bootpath[i];
1637 j++;
1638 }
1639 }
1640 bootpath[j] = '\0';
1641 }
1642
1643 while (*ImagePath == '\\')
1644 ImagePath++;
1645
1646 *PathName = AllocatePool(StrSize(bootpath) + StrSize(ImagePath));
1647
1648 if (!*PathName) {
1649 perror(L"Failed to allocate path buffer\n");
1650 efi_status = EFI_OUT_OF_RESOURCES;
1651 goto error;
1652 }
1653
1654 *PathName[0] = '\0';
1655 if (StrnCaseCmp(bootpath, ImagePath, StrLen(bootpath)))
1656 StrCat(*PathName, bootpath);
1657 StrCat(*PathName, ImagePath);
1658
1659 error:
1660 FreePool(bootpath);
1661
1662 return efi_status;
1663 }
1664
1665 /*
1666 * Open the second stage bootloader and read it into a buffer
1667 */
1668 static EFI_STATUS load_image (EFI_LOADED_IMAGE *li, void **data,
1669 int *datasize, CHAR16 *PathName)
1670 {
1671 EFI_STATUS efi_status;
1672 EFI_HANDLE device;
1673 EFI_FILE_INFO *fileinfo = NULL;
1674 EFI_FILE_IO_INTERFACE *drive;
1675 EFI_FILE *root, *grub;
1676 UINTN buffersize = sizeof(EFI_FILE_INFO);
1677
1678 device = li->DeviceHandle;
1679
1680 /*
1681 * Open the device
1682 */
1683 efi_status = gBS->HandleProtocol(device, &EFI_SIMPLE_FILE_SYSTEM_GUID,
1684 (void **) &drive);
1685 if (EFI_ERROR(efi_status)) {
1686 perror(L"Failed to find fs: %r\n", efi_status);
1687 goto error;
1688 }
1689
1690 efi_status = drive->OpenVolume(drive, &root);
1691 if (EFI_ERROR(efi_status)) {
1692 perror(L"Failed to open fs: %r\n", efi_status);
1693 goto error;
1694 }
1695
1696 /*
1697 * And then open the file
1698 */
1699 efi_status = root->Open(root, &grub, PathName, EFI_FILE_MODE_READ, 0);
1700 if (EFI_ERROR(efi_status)) {
1701 perror(L"Failed to open %s - %r\n", PathName, efi_status);
1702 goto error;
1703 }
1704
1705 fileinfo = AllocatePool(buffersize);
1706
1707 if (!fileinfo) {
1708 perror(L"Unable to allocate file info buffer\n");
1709 efi_status = EFI_OUT_OF_RESOURCES;
1710 goto error;
1711 }
1712
1713 /*
1714 * Find out how big the file is in order to allocate the storage
1715 * buffer
1716 */
1717 efi_status = grub->GetInfo(grub, &EFI_FILE_INFO_GUID, &buffersize,
1718 fileinfo);
1719 if (efi_status == EFI_BUFFER_TOO_SMALL) {
1720 FreePool(fileinfo);
1721 fileinfo = AllocatePool(buffersize);
1722 if (!fileinfo) {
1723 perror(L"Unable to allocate file info buffer\n");
1724 efi_status = EFI_OUT_OF_RESOURCES;
1725 goto error;
1726 }
1727 efi_status = grub->GetInfo(grub, &EFI_FILE_INFO_GUID,
1728 &buffersize, fileinfo);
1729 }
1730
1731 if (EFI_ERROR(efi_status)) {
1732 perror(L"Unable to get file info: %r\n", efi_status);
1733 goto error;
1734 }
1735
1736 buffersize = fileinfo->FileSize;
1737 *data = AllocatePool(buffersize);
1738 if (!*data) {
1739 perror(L"Unable to allocate file buffer\n");
1740 efi_status = EFI_OUT_OF_RESOURCES;
1741 goto error;
1742 }
1743
1744 /*
1745 * Perform the actual read
1746 */
1747 efi_status = grub->Read(grub, &buffersize, *data);
1748 if (efi_status == EFI_BUFFER_TOO_SMALL) {
1749 FreePool(*data);
1750 *data = AllocatePool(buffersize);
1751 efi_status = grub->Read(grub, &buffersize, *data);
1752 }
1753 if (EFI_ERROR(efi_status)) {
1754 perror(L"Unexpected return from initial read: %r, buffersize %x\n",
1755 efi_status, buffersize);
1756 goto error;
1757 }
1758
1759 *datasize = buffersize;
1760
1761 FreePool(fileinfo);
1762
1763 return EFI_SUCCESS;
1764 error:
1765 if (*data) {
1766 FreePool(*data);
1767 *data = NULL;
1768 }
1769
1770 if (fileinfo)
1771 FreePool(fileinfo);
1772 return efi_status;
1773 }
1774
1775 /*
1776 * Protocol entry point. If secure boot is enabled, verify that the provided
1777 * buffer is signed with a trusted key.
1778 */
1779 EFI_STATUS shim_verify (void *buffer, UINT32 size)
1780 {
1781 EFI_STATUS efi_status = EFI_SUCCESS;
1782 PE_COFF_LOADER_IMAGE_CONTEXT context;
1783 UINT8 sha1hash[SHA1_DIGEST_SIZE];
1784 UINT8 sha256hash[SHA256_DIGEST_SIZE];
1785
1786 if ((INT32)size < 0)
1787 return EFI_INVALID_PARAMETER;
1788
1789 loader_is_participating = 1;
1790 in_protocol = 1;
1791
1792 efi_status = read_header(buffer, size, &context);
1793 if (EFI_ERROR(efi_status))
1794 goto done;
1795
1796 efi_status = generate_hash(buffer, size, &context,
1797 sha256hash, sha1hash);
1798 if (EFI_ERROR(efi_status))
1799 goto done;
1800
1801 /* Measure the binary into the TPM */
1802 #ifdef REQUIRE_TPM
1803 efi_status =
1804 #endif
1805 tpm_log_pe((EFI_PHYSICAL_ADDRESS)(UINTN)buffer, size, sha1hash, 4);
1806 #ifdef REQUIRE_TPM
1807 if (EFI_ERROR(efi_status))
1808 goto done;
1809 #endif
1810
1811 if (!secure_mode()) {
1812 efi_status = EFI_SUCCESS;
1813 goto done;
1814 }
1815
1816 efi_status = verify_buffer(buffer, size, &context,
1817 sha256hash, sha1hash);
1818 done:
1819 in_protocol = 0;
1820 return efi_status;
1821 }
1822
1823 static EFI_STATUS shim_hash (char *data, int datasize,
1824 PE_COFF_LOADER_IMAGE_CONTEXT *context,
1825 UINT8 *sha256hash, UINT8 *sha1hash)
1826 {
1827 EFI_STATUS efi_status;
1828
1829 if (datasize < 0)
1830 return EFI_INVALID_PARAMETER;
1831
1832 in_protocol = 1;
1833 efi_status = generate_hash(data, datasize, context,
1834 sha256hash, sha1hash);
1835 in_protocol = 0;
1836
1837 return efi_status;
1838 }
1839
1840 static EFI_STATUS shim_read_header(void *data, unsigned int datasize,
1841 PE_COFF_LOADER_IMAGE_CONTEXT *context)
1842 {
1843 EFI_STATUS efi_status;
1844
1845 in_protocol = 1;
1846 efi_status = read_header(data, datasize, context);
1847 in_protocol = 0;
1848
1849 return efi_status;
1850 }
1851
1852 /*
1853 * Load and run an EFI executable
1854 */
1855 EFI_STATUS start_image(EFI_HANDLE image_handle, CHAR16 *ImagePath)
1856 {
1857 EFI_STATUS efi_status;
1858 EFI_LOADED_IMAGE *li, li_bak;
1859 EFI_IMAGE_ENTRY_POINT entry_point;
1860 EFI_PHYSICAL_ADDRESS alloc_address;
1861 UINTN alloc_pages;
1862 CHAR16 *PathName = NULL;
1863 void *sourcebuffer = NULL;
1864 UINT64 sourcesize = 0;
1865 void *data = NULL;
1866 int datasize;
1867
1868 /*
1869 * We need to refer to the loaded image protocol on the running
1870 * binary in order to find our path
1871 */
1872 efi_status = gBS->HandleProtocol(image_handle, &EFI_LOADED_IMAGE_GUID,
1873 (void **)&li);
1874 if (EFI_ERROR(efi_status)) {
1875 perror(L"Unable to init protocol\n");
1876 return efi_status;
1877 }
1878
1879 /*
1880 * Build a new path from the existing one plus the executable name
1881 */
1882 efi_status = generate_path_from_image_path(li, ImagePath, &PathName);
1883 if (EFI_ERROR(efi_status)) {
1884 perror(L"Unable to generate path %s: %r\n", ImagePath,
1885 efi_status);
1886 goto done;
1887 }
1888
1889 if (findNetboot(li->DeviceHandle)) {
1890 efi_status = parseNetbootinfo(image_handle);
1891 if (EFI_ERROR(efi_status)) {
1892 perror(L"Netboot parsing failed: %r\n", efi_status);
1893 return EFI_PROTOCOL_ERROR;
1894 }
1895 efi_status = FetchNetbootimage(image_handle, &sourcebuffer,
1896 &sourcesize);
1897 if (EFI_ERROR(efi_status)) {
1898 perror(L"Unable to fetch TFTP image: %r\n",
1899 efi_status);
1900 return efi_status;
1901 }
1902 data = sourcebuffer;
1903 datasize = sourcesize;
1904 #if defined(ENABLE_HTTPBOOT)
1905 } else if (find_httpboot(li->DeviceHandle)) {
1906 efi_status = httpboot_fetch_buffer (image_handle,
1907 &sourcebuffer,
1908 &sourcesize);
1909 if (EFI_ERROR(efi_status)) {
1910 perror(L"Unable to fetch HTTP image: %r\n",
1911 efi_status);
1912 return efi_status;
1913 }
1914 data = sourcebuffer;
1915 datasize = sourcesize;
1916 #endif
1917 } else {
1918 /*
1919 * Read the new executable off disk
1920 */
1921 efi_status = load_image(li, &data, &datasize, PathName);
1922 if (EFI_ERROR(efi_status)) {
1923 perror(L"Failed to load image %s: %r\n",
1924 PathName, efi_status);
1925 PrintErrors();
1926 ClearErrors();
1927 goto done;
1928 }
1929 }
1930
1931 if (datasize < 0) {
1932 efi_status = EFI_INVALID_PARAMETER;
1933 goto done;
1934 }
1935
1936 /*
1937 * We need to modify the loaded image protocol entry before running
1938 * the new binary, so back it up
1939 */
1940 CopyMem(&li_bak, li, sizeof(li_bak));
1941
1942 /*
1943 * Verify and, if appropriate, relocate and execute the executable
1944 */
1945 efi_status = handle_image(data, datasize, li, &entry_point,
1946 &alloc_address, &alloc_pages);
1947 if (EFI_ERROR(efi_status)) {
1948 perror(L"Failed to load image: %r\n", efi_status);
1949 PrintErrors();
1950 ClearErrors();
1951 CopyMem(li, &li_bak, sizeof(li_bak));
1952 goto done;
1953 }
1954
1955 loader_is_participating = 0;
1956
1957 /*
1958 * The binary is trusted and relocated. Run it
1959 */
1960 efi_status = entry_point(image_handle, systab);
1961
1962 /*
1963 * Restore our original loaded image values
1964 */
1965 CopyMem(li, &li_bak, sizeof(li_bak));
1966 done:
1967 if (PathName)
1968 FreePool(PathName);
1969
1970 if (data)
1971 FreePool(data);
1972
1973 return efi_status;
1974 }
1975
1976 /*
1977 * Load and run grub. If that fails because grub isn't trusted, load and
1978 * run MokManager.
1979 */
1980 EFI_STATUS init_grub(EFI_HANDLE image_handle)
1981 {
1982 EFI_STATUS efi_status;
1983 int use_fb = should_use_fallback(image_handle);
1984
1985 efi_status = start_image(image_handle, use_fb ? FALLBACK :second_stage);
1986 if (efi_status == EFI_SECURITY_VIOLATION ||
1987 efi_status == EFI_ACCESS_DENIED) {
1988 efi_status = start_image(image_handle, MOK_MANAGER);
1989 if (EFI_ERROR(efi_status)) {
1990 console_print(L"start_image() returned %r\n", efi_status);
1991 msleep(2000000);
1992 return efi_status;
1993 }
1994
1995 efi_status = start_image(image_handle,
1996 use_fb ? FALLBACK : second_stage);
1997 }
1998
1999 if (EFI_ERROR(efi_status)) {
2000 console_print(L"start_image() returned %r\n", efi_status);
2001 msleep(2000000);
2002 }
2003
2004 return efi_status;
2005 }
2006
2007 static inline EFI_STATUS
2008 get_load_option_optional_data(UINT8 *data, UINTN data_size,
2009 UINT8 **od, UINTN *ods)
2010 {
2011 /*
2012 * If it's not at least Attributes + FilePathListLength +
2013 * Description=L"" + 0x7fff0400 (EndEntrireDevicePath), it can't
2014 * be valid.
2015 */
2016 if (data_size < (sizeof(UINT32) + sizeof(UINT16) + 2 + 4))
2017 return EFI_INVALID_PARAMETER;
2018
2019 UINT8 *cur = data + sizeof(UINT32);
2020 UINT16 fplistlen = *(UINT16 *)cur;
2021 /*
2022 * If there's not enough space for the file path list and the
2023 * smallest possible description (L""), it's not valid.
2024 */
2025 if (fplistlen > data_size - (sizeof(UINT32) + 2 + 4))
2026 return EFI_INVALID_PARAMETER;
2027
2028 cur += sizeof(UINT16);
2029 UINTN limit = data_size - (cur - data) - fplistlen;
2030 UINTN i;
2031 for (i = 0; i < limit ; i++) {
2032 /* If the description isn't valid UCS2-LE, it's not valid. */
2033 if (i % 2 != 0) {
2034 if (cur[i] != 0)
2035 return EFI_INVALID_PARAMETER;
2036 } else if (cur[i] == 0) {
2037 /* we've found the end */
2038 i++;
2039 if (i >= limit || cur[i] != 0)
2040 return EFI_INVALID_PARAMETER;
2041 break;
2042 }
2043 }
2044 i++;
2045 if (i > limit)
2046 return EFI_INVALID_PARAMETER;
2047
2048 /*
2049 * If i is limit, we know the rest of this is the FilePathList and
2050 * there's no optional data. So just bail now.
2051 */
2052 if (i == limit) {
2053 *od = NULL;
2054 *ods = 0;
2055 return EFI_SUCCESS;
2056 }
2057
2058 cur += i;
2059 limit -= i;
2060 limit += fplistlen;
2061 i = 0;
2062 while (limit - i >= 4) {
2063 struct {
2064 UINT8 type;
2065 UINT8 subtype;
2066 UINT16 len;
2067 } dp = {
2068 .type = cur[i],
2069 .subtype = cur[i+1],
2070 /*
2071 * it's a little endian UINT16, but we're not
2072 * guaranteed alignment is sane, so we can't just
2073 * typecast it directly.
2074 */
2075 .len = (cur[i+3] << 8) | cur[i+2],
2076 };
2077
2078 /*
2079 * We haven't found an EndEntire, so this has to be a valid
2080 * EFI_DEVICE_PATH in order for the data to be valid. That
2081 * means it has to fit, and it can't be smaller than 4 bytes.
2082 */
2083 if (dp.len < 4 || dp.len > limit)
2084 return EFI_INVALID_PARAMETER;
2085
2086 /*
2087 * see if this is an EndEntire node...
2088 */
2089 if (dp.type == 0x7f && dp.subtype == 0xff) {
2090 /*
2091 * if we've found the EndEntire node, it must be 4
2092 * bytes
2093 */
2094 if (dp.len != 4)
2095 return EFI_INVALID_PARAMETER;
2096
2097 i += dp.len;
2098 break;
2099 }
2100
2101 /*
2102 * It's just some random DP node; skip it.
2103 */
2104 i += dp.len;
2105 }
2106 if (i != fplistlen)
2107 return EFI_INVALID_PARAMETER;
2108
2109 /*
2110 * if there's any space left, it's "optional data"
2111 */
2112 *od = cur + i;
2113 *ods = limit - i;
2114 return EFI_SUCCESS;
2115 }
2116
2117 static int is_our_path(EFI_LOADED_IMAGE *li, CHAR16 *path, UINTN len)
2118 {
2119 CHAR16 *dppath = NULL;
2120 int ret = 1;
2121
2122 dppath = DevicePathToStr(li->FilePath);
2123 if (!dppath)
2124 return 0;
2125
2126 dprint(L"dppath: %s\n", dppath);
2127 dprint(L"path: %s\n", path);
2128 if (StrnCaseCmp(dppath, path, len))
2129 ret = 0;
2130
2131 FreePool(dppath);
2132 return ret;
2133 }
2134
2135 /*
2136 * Check the load options to specify the second stage loader
2137 */
2138 EFI_STATUS set_second_stage (EFI_HANDLE image_handle)
2139 {
2140 EFI_STATUS efi_status;
2141 EFI_LOADED_IMAGE *li = NULL;
2142 CHAR16 *start = NULL;
2143 int remaining_size = 0;
2144 CHAR16 *loader_str = NULL;
2145 UINTN loader_len = 0;
2146 unsigned int i;
2147
2148 second_stage = DEFAULT_LOADER;
2149 load_options = NULL;
2150 load_options_size = 0;
2151
2152 efi_status = gBS->HandleProtocol(image_handle, &LoadedImageProtocol,
2153 (void **) &li);
2154 if (EFI_ERROR(efi_status)) {
2155 perror (L"Failed to get load options: %r\n", efi_status);
2156 return efi_status;
2157 }
2158
2159 /* So, load options are a giant pain in the ass. If we're invoked
2160 * from the EFI shell, we get something like this:
2161
2162 00000000 5c 00 45 00 36 00 49 00 5c 00 66 00 65 00 64 00 |\.E.F.I.\.f.e.d.|
2163 00000010 6f 00 72 00 61 00 5c 00 73 00 68 00 69 00 6d 00 |o.r.a.\.s.h.i.m.|
2164 00000020 78 00 36 00 34 00 2e 00 64 00 66 00 69 00 20 00 |x.6.4...e.f.i. .|
2165 00000030 5c 00 45 00 46 00 49 00 5c 00 66 00 65 00 64 00 |\.E.F.I.\.f.e.d.|
2166 00000040 6f 00 72 00 61 00 5c 00 66 00 77 00 75 00 70 00 |o.r.a.\.f.w.u.p.|
2167 00000050 64 00 61 00 74 00 65 00 2e 00 65 00 66 00 20 00 |d.a.t.e.e.f.i. .|
2168 00000060 00 00 66 00 73 00 30 00 3a 00 5c 00 00 00 |..f.s.0.:.\...|
2169
2170 *
2171 * which is just some paths rammed together separated by a UCS-2 NUL.
2172 * But if we're invoked from BDS, we get something more like:
2173 *
2174
2175 00000000 01 00 00 00 62 00 4c 00 69 00 6e 00 75 00 78 00 |....b.L.i.n.u.x.|
2176 00000010 20 00 46 00 69 00 72 00 6d 00 77 00 61 00 72 00 | .F.i.r.m.w.a.r.|
2177 00000020 65 00 20 00 55 00 70 00 64 00 61 00 74 00 65 00 |e. .U.p.d.a.t.e.|
2178 00000030 72 00 00 00 40 01 2a 00 01 00 00 00 00 08 00 00 |r.....*.........|
2179 00000040 00 00 00 00 00 40 06 00 00 00 00 00 1a 9e 55 bf |.....@........U.|
2180 00000050 04 57 f2 4f b4 4a ed 26 4a 40 6a 94 02 02 04 04 |.W.O.:.&J@j.....|
2181 00000060 34 00 5c 00 45 00 46 00 49 00 5c 00 66 00 65 00 |4.\.E.F.I.f.e.d.|
2182 00000070 64 00 6f 00 72 00 61 00 5c 00 73 00 68 00 69 00 |o.r.a.\.s.h.i.m.|
2183 00000080 6d 00 78 00 36 00 34 00 2e 00 65 00 66 00 69 00 |x.6.4...e.f.i...|
2184 00000090 00 00 7f ff 40 00 20 00 5c 00 66 00 77 00 75 00 |...... .\.f.w.u.|
2185 000000a0 70 00 78 00 36 00 34 00 2e 00 65 00 66 00 69 00 |p.x.6.4...e.f.i.|
2186 000000b0 00 00 |..|
2187
2188 *
2189 * which is clearly an EFI_LOAD_OPTION filled in halfway reasonably.
2190 * In short, the UEFI shell is still a useless piece of junk.
2191 *
2192 * But then on some versions of BDS, we get:
2193
2194 00000000 5c 00 66 00 77 00 75 00 70 00 78 00 36 00 34 00 |\.f.w.u.p.x.6.4.|
2195 00000010 2e 00 65 00 66 00 69 00 00 00 |..e.f.i...|
2196 0000001a
2197
2198 * which as you can see is one perfectly normal UCS2-EL string
2199 * containing the load option from the Boot#### variable.
2200 *
2201 * We also sometimes find a guid or partial guid at the end, because
2202 * BDS will add that, but we ignore that here.
2203 */
2204
2205 /*
2206 * In either case, we've got to have at least a UCS2 NUL...
2207 */
2208 if (li->LoadOptionsSize < 2)
2209 return EFI_BAD_BUFFER_SIZE;
2210
2211 /*
2212 * Some awesome versions of BDS will add entries for Linux. On top
2213 * of that, some versions of BDS will "tag" any Boot#### entries they
2214 * create by putting a GUID at the very end of the optional data in
2215 * the EFI_LOAD_OPTIONS, thus screwing things up for everybody who
2216 * tries to actually *use* the optional data for anything. Why they
2217 * did this instead of adding a flag to the spec to /say/ it's
2218 * created by BDS, I do not know. For shame.
2219 *
2220 * Anyway, just nerf that out from the start. It's always just
2221 * garbage at the end.
2222 */
2223 if (li->LoadOptionsSize > 16) {
2224 if (CompareGuid((EFI_GUID *)(li->LoadOptions
2225 + (li->LoadOptionsSize - 16)),
2226 &BDS_GUID) == 0)
2227 li->LoadOptionsSize -= 16;
2228 }
2229
2230 /*
2231 * Apparently sometimes we get L"\0\0"? Which isn't useful at all.
2232 */
2233 if (is_all_nuls(li->LoadOptions, li->LoadOptionsSize))
2234 return EFI_SUCCESS;
2235
2236 /*
2237 * Check and see if this is just a list of strings. If it's an
2238 * EFI_LOAD_OPTION, it'll be 0, since we know EndEntire device path
2239 * won't pass muster as UCS2-LE.
2240 *
2241 * If there are 3 strings, we're launched from the shell most likely,
2242 * But we actually only care about the second one.
2243 */
2244 UINTN strings = count_ucs2_strings(li->LoadOptions,
2245 li->LoadOptionsSize);
2246 /*
2247 * If it's not string data, try it as an EFI_LOAD_OPTION.
2248 */
2249 if (strings == 0) {
2250 /*
2251 * We at least didn't find /enough/ strings. See if it works
2252 * as an EFI_LOAD_OPTION.
2253 */
2254 efi_status = get_load_option_optional_data(li->LoadOptions,
2255 li->LoadOptionsSize,
2256 (UINT8 **)&start,
2257 &loader_len);
2258 if (EFI_ERROR(efi_status))
2259 return EFI_SUCCESS;
2260
2261 remaining_size = 0;
2262 } else if (strings >= 2) {
2263 /*
2264 * UEFI shell copies the whole line of the command into
2265 * LoadOptions. We ignore the string before the first L' ',
2266 * i.e. the name of this program.
2267 * Counting by two bytes is safe, because we know the size is
2268 * compatible with a UCS2-LE string.
2269 */
2270 UINT8 *cur = li->LoadOptions;
2271 for (i = 0; i < li->LoadOptionsSize - 2; i += 2) {
2272 CHAR16 c = (cur[i+1] << 8) | cur[i];
2273 if (c == L' ') {
2274 start = (CHAR16 *)&cur[i+2];
2275 remaining_size = li->LoadOptionsSize - i - 2;
2276 break;
2277 }
2278 }
2279
2280 if (!start || remaining_size <= 0 || start[0] == L'\0')
2281 return EFI_SUCCESS;
2282
2283 for (i = 0; start[i] != '\0'; i++) {
2284 if (start[i] == L' ')
2285 start[i] = L'\0';
2286 if (start[i] == L'\0') {
2287 loader_len = 2 * i + 2;
2288 break;
2289 }
2290 }
2291 if (loader_len)
2292 remaining_size -= loader_len;
2293 } else {
2294 /* only find one string */
2295 start = li->LoadOptions;
2296 loader_len = li->LoadOptionsSize;
2297 }
2298
2299 /*
2300 * Just to be sure all that math is right...
2301 */
2302 if (loader_len % 2 != 0)
2303 return EFI_INVALID_PARAMETER;
2304
2305 strings = count_ucs2_strings((UINT8 *)start, loader_len);
2306 if (strings < 1)
2307 return EFI_SUCCESS;
2308
2309 /*
2310 * And then I found a version of BDS that gives us our own path in
2311 * LoadOptions:
2312
2313 77162C58 5c 00 45 00 46 00 49 00 |\.E.F.I.|
2314 77162C60 5c 00 42 00 4f 00 4f 00 54 00 5c 00 42 00 4f 00 |\.B.O.O.T.\.B.O.|
2315 77162C70 4f 00 54 00 58 00 36 00 34 00 2e 00 45 00 46 00 |O.T.X.6.4...E.F.|
2316 77162C80 49 00 00 00 |I...|
2317
2318 * which is just cruel... So yeah, just don't use it.
2319 */
2320 if (strings == 1 && is_our_path(li, start, loader_len))
2321 return EFI_SUCCESS;
2322
2323 /*
2324 * Set up the name of the alternative loader and the LoadOptions for
2325 * the loader
2326 */
2327 if (loader_len > 0) {
2328 loader_str = AllocatePool(loader_len);
2329 if (!loader_str) {
2330 perror(L"Failed to allocate loader string\n");
2331 return EFI_OUT_OF_RESOURCES;
2332 }
2333
2334 for (i = 0; i < loader_len / 2; i++)
2335 loader_str[i] = start[i];
2336 loader_str[loader_len/2-1] = L'\0';
2337
2338 second_stage = loader_str;
2339 load_options = remaining_size ? start + (loader_len/2) : NULL;
2340 load_options_size = remaining_size;
2341 }
2342
2343 return EFI_SUCCESS;
2344 }
2345
2346 static void *
2347 ossl_malloc(size_t num, const char *file, int line)
2348 {
2349 return AllocatePool(num);
2350 }
2351
2352 static void
2353 ossl_free(void *addr, const char *file, int line)
2354 {
2355 FreePool(addr);
2356 }
2357
2358 static void
2359 init_openssl(void)
2360 {
2361 CRYPTO_set_mem_functions(ossl_malloc, NULL, ossl_free);
2362 OPENSSL_init();
2363 CRYPTO_set_mem_functions(ossl_malloc, NULL, ossl_free);
2364 ERR_load_ERR_strings();
2365 ERR_load_BN_strings();
2366 ERR_load_RSA_strings();
2367 ERR_load_DH_strings();
2368 ERR_load_EVP_strings();
2369 ERR_load_BUF_strings();
2370 ERR_load_OBJ_strings();
2371 ERR_load_PEM_strings();
2372 ERR_load_X509_strings();
2373 ERR_load_ASN1_strings();
2374 ERR_load_CONF_strings();
2375 ERR_load_CRYPTO_strings();
2376 ERR_load_COMP_strings();
2377 ERR_load_BIO_strings();
2378 ERR_load_PKCS7_strings();
2379 ERR_load_X509V3_strings();
2380 ERR_load_PKCS12_strings();
2381 ERR_load_RAND_strings();
2382 ERR_load_DSO_strings();
2383 ERR_load_OCSP_strings();
2384 }
2385
2386 static SHIM_LOCK shim_lock_interface;
2387 static EFI_HANDLE shim_lock_handle;
2388
2389 EFI_STATUS
2390 install_shim_protocols(void)
2391 {
2392 SHIM_LOCK *shim_lock;
2393 EFI_STATUS efi_status;
2394
2395 /*
2396 * Did another instance of shim earlier already install the
2397 * protocol? If so, get rid of it.
2398 *
2399 * We have to uninstall shim's protocol here, because if we're
2400 * On the fallback.efi path, then our call pathway is:
2401 *
2402 * shim->fallback->shim->grub
2403 * ^ ^ ^
2404 * | | \- gets protocol #0
2405 * | \- installs its protocol (#1)
2406 * \- installs its protocol (#0)
2407 * and if we haven't removed this, then grub will get the *first*
2408 * shim's protocol, but it'll get the second shim's systab
2409 * replacements. So even though it will participate and verify
2410 * the kernel, the systab never finds out.
2411 */
2412 efi_status = LibLocateProtocol(&SHIM_LOCK_GUID, (VOID **)&shim_lock);
2413 if (!EFI_ERROR(efi_status))
2414 uninstall_shim_protocols();
2415
2416 /*
2417 * Install the protocol
2418 */
2419 efi_status = gBS->InstallProtocolInterface(&shim_lock_handle,
2420 &SHIM_LOCK_GUID,
2421 EFI_NATIVE_INTERFACE,
2422 &shim_lock_interface);
2423 if (EFI_ERROR(efi_status)) {
2424 console_error(L"Could not install security protocol",
2425 efi_status);
2426 return efi_status;
2427 }
2428
2429 if (!secure_mode())
2430 return EFI_SUCCESS;
2431
2432 #if defined(OVERRIDE_SECURITY_POLICY)
2433 /*
2434 * Install the security protocol hook
2435 */
2436 security_policy_install(shim_verify);
2437 #endif
2438
2439 return EFI_SUCCESS;
2440 }
2441
2442 void
2443 uninstall_shim_protocols(void)
2444 {
2445 /*
2446 * If we're back here then clean everything up before exiting
2447 */
2448 gBS->UninstallProtocolInterface(shim_lock_handle, &SHIM_LOCK_GUID,
2449 &shim_lock_interface);
2450
2451 if (!secure_mode())
2452 return;
2453
2454 #if defined(OVERRIDE_SECURITY_POLICY)
2455 /*
2456 * Clean up the security protocol hook
2457 */
2458 security_policy_uninstall();
2459 #endif
2460 }
2461
2462 EFI_STATUS
2463 shim_init(void)
2464 {
2465 setup_verbosity();
2466 dprint(L"%a", shim_version);
2467
2468 /* Set the second stage loader */
2469 set_second_stage (global_image_handle);
2470
2471 if (secure_mode()) {
2472 if (vendor_cert_size || vendor_dbx_size) {
2473 /*
2474 * If shim includes its own certificates then ensure
2475 * that anything it boots has performed some
2476 * validation of the next image.
2477 */
2478 hook_system_services(systab);
2479 loader_is_participating = 0;
2480 }
2481
2482 hook_exit(systab);
2483 }
2484
2485 return install_shim_protocols();
2486 }
2487
2488 void
2489 shim_fini(void)
2490 {
2491 /*
2492 * Remove our protocols
2493 */
2494 uninstall_shim_protocols();
2495
2496 if (secure_mode()) {
2497
2498 /*
2499 * Remove our hooks from system services.
2500 */
2501 unhook_system_services();
2502 unhook_exit();
2503 }
2504
2505 /*
2506 * Free the space allocated for the alternative 2nd stage loader
2507 */
2508 if (load_options_size > 0 && second_stage)
2509 FreePool(second_stage);
2510
2511 console_fini();
2512 }
2513
2514 extern EFI_STATUS
2515 efi_main(EFI_HANDLE passed_image_handle, EFI_SYSTEM_TABLE *passed_systab);
2516
2517 static void
2518 __attribute__((__optimize__("0")))
2519 debug_hook(void)
2520 {
2521 UINT8 *data = NULL;
2522 UINTN dataSize = 0;
2523 EFI_STATUS efi_status;
2524 volatile register UINTN x = 0;
2525 extern char _text, _data;
2526
2527 if (x)
2528 return;
2529
2530 efi_status = get_variable(L"SHIM_DEBUG", &data, &dataSize,
2531 SHIM_LOCK_GUID);
2532 if (EFI_ERROR(efi_status)) {
2533 return;
2534 }
2535
2536 FreePool(data);
2537
2538 console_print(L"add-symbol-file "DEBUGDIR
2539 L"shim" EFI_ARCH L".efi.debug 0x%08x -s .data 0x%08x\n",
2540 &_text, &_data);
2541
2542 console_print(L"Pausing for debugger attachment.\n");
2543 console_print(L"To disable this, remove the EFI variable SHIM_DEBUG-%g .\n",
2544 &SHIM_LOCK_GUID);
2545 x = 1;
2546 while (x++) {
2547 /* Make this so it can't /totally/ DoS us. */
2548 #if defined(__x86_64__) || defined(__i386__) || defined(__i686__)
2549 if (x > 4294967294ULL)
2550 break;
2551 __asm__ __volatile__("pause");
2552 #elif defined(__aarch64__)
2553 if (x > 1000)
2554 break;
2555 __asm__ __volatile__("wfi");
2556 #else
2557 if (x > 12000)
2558 break;
2559 msleep(5000);
2560 #endif
2561 }
2562 x = 1;
2563 }
2564
2565 EFI_STATUS
2566 efi_main (EFI_HANDLE passed_image_handle, EFI_SYSTEM_TABLE *passed_systab)
2567 {
2568 EFI_STATUS efi_status;
2569 EFI_HANDLE image_handle;
2570
2571 verification_method = VERIFIED_BY_NOTHING;
2572
2573 vendor_cert_size = cert_table.vendor_cert_size;
2574 vendor_dbx_size = cert_table.vendor_dbx_size;
2575 vendor_cert = (UINT8 *)&cert_table + cert_table.vendor_cert_offset;
2576 vendor_dbx = (UINT8 *)&cert_table + cert_table.vendor_dbx_offset;
2577 CHAR16 *msgs[] = {
2578 L"import_mok_state() failed\n",
2579 L"shim_int() failed\n",
2580 NULL
2581 };
2582 int msg = 0;
2583
2584
2585 /*
2586 * Set up the shim lock protocol so that grub and MokManager can
2587 * call back in and use shim functions
2588 */
2589 shim_lock_interface.Verify = shim_verify;
2590 shim_lock_interface.Hash = shim_hash;
2591 shim_lock_interface.Context = shim_read_header;
2592
2593 systab = passed_systab;
2594 image_handle = global_image_handle = passed_image_handle;
2595
2596 /*
2597 * Ensure that gnu-efi functions are available
2598 */
2599 InitializeLib(image_handle, systab);
2600
2601 init_openssl();
2602
2603 /*
2604 * if SHIM_DEBUG is set, wait for a debugger to attach.
2605 */
2606 debug_hook();
2607
2608 /*
2609 * Before we do anything else, validate our non-volatile,
2610 * boot-services-only state variables are what we think they are.
2611 */
2612 efi_status = import_mok_state(image_handle);
2613 if (EFI_ERROR(efi_status)) {
2614 die:
2615 console_print(L"Something has gone seriously wrong: %s: %r\n",
2616 msgs[msg], efi_status);
2617 msleep(5000000);
2618 gRT->ResetSystem(EfiResetShutdown, EFI_SECURITY_VIOLATION,
2619 0, NULL);
2620 }
2621
2622 efi_status = shim_init();
2623 if (EFI_ERROR(efi_status)) {
2624 msg = 1;
2625 goto die;
2626 }
2627
2628 /*
2629 * Tell the user that we're in insecure mode if necessary
2630 */
2631 if (user_insecure_mode) {
2632 console_print(L"Booting in insecure mode\n");
2633 msleep(2000000);
2634 }
2635
2636 /*
2637 * Hand over control to the second stage bootloader
2638 */
2639 efi_status = init_grub(image_handle);
2640
2641 shim_fini();
2642 return efi_status;
2643 }