2 * shim - trivial UEFI first-stage bootloader
4 * Copyright 2012 Red Hat, Inc <mjg@redhat.com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
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
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.
31 * Significant portions of this code are derived from Tianocore
32 * (http://tianocore.sf.net) and are Copyright 2009-2012 Intel
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>
53 #include <Library/BaseCryptLib.h>
57 #define OID_EKU_MODSIGN "1.3.6.1.4.1.2312.16.1.2"
59 static EFI_SYSTEM_TABLE
*systab
;
60 static EFI_HANDLE global_image_handle
;
62 static CHAR16
*second_stage
;
63 static void *load_options
;
64 static UINT32 load_options_size
;
67 * The vendor certificate used for validating the second stage loader
70 UINT32 vendor_cert_size
;
71 UINT32 vendor_dbx_size
;
72 UINT32 vendor_cert_offset
;
73 UINT32 vendor_dbx_offset
;
76 UINT32 vendor_cert_size
;
77 UINT32 vendor_dbx_size
;
82 * indicator of how an image has been verified
84 verification_method_t verification_method
;
85 int loader_is_participating
;
87 #define EFI_IMAGE_SECURITY_DATABASE_GUID { 0xd719b2cb, 0x3d3a, 0x4596, { 0xa3, 0xbc, 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f }}
89 UINT8 user_insecure_mode
;
104 * Perform basic bounds checking of the intra-image pointers
106 static void *ImageAddress (void *image
, uint64_t size
, uint64_t address
)
108 /* ensure our local pointer isn't bigger than our size */
112 /* Insure our math won't overflow */
113 if (UINT64_MAX
- address
< (uint64_t)(intptr_t)image
)
116 /* return the absolute pointer */
117 return image
+ address
;
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
129 #if defined(__x86_64__) || defined(__aarch64__)
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 */
137 #else /* assuming everything else is 32-bit... */
145 #if defined(__x86_64__)
146 #if defined(ALLOW_32BIT_KERNEL_ON_X64)
153 #elif defined(__i386__) || defined(__i686__)
155 #elif defined(__arch64__)
157 #else /* assuming everything else is 32-bit... */
163 image_is_64_bit(EFI_IMAGE_OPTIONAL_HEADER_UNION
*PEHdr
)
165 /* .Magic is the same offset in all cases */
166 if (PEHdr
->Pe32Plus
.OptionalHeader
.Magic
167 == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
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
;
184 #error this architecture is not supported by shim
188 image_is_loadable(EFI_IMAGE_OPTIONAL_HEADER_UNION
*PEHdr
)
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
&&
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
:
209 /* and now just check for general 64-vs-32 compatibility */
210 if (image_is_64_bit(PEHdr
)) {
221 * Perform the actual relocation
223 static EFI_STATUS
relocate_coff (PE_COFF_LOADER_IMAGE_CONTEXT
*context
,
224 EFI_IMAGE_SECTION_HEADER
*Section
,
225 void *orig
, void *data
)
227 EFI_IMAGE_BASE_RELOCATION
*RelocBase
, *RelocBaseEnd
;
229 UINT16
*Reloc
, *RelocEnd
;
230 char *Fixup
, *FixupBase
;
234 int size
= context
->ImageSize
;
235 void *ImageEnd
= (char *)orig
+ size
;
238 /* Alright, so here's how this works:
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)
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
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)
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.
263 RelocBase
= ImageAddress(orig
, size
, Section
->PointerToRawData
);
264 /* RelocBaseEnd here is the address of the first entry /past/ the
266 RelocBaseEnd
= ImageAddress(orig
, size
, Section
->PointerToRawData
+
267 Section
->Misc
.VirtualSize
);
269 if (!RelocBase
&& !RelocBaseEnd
)
272 if (!RelocBase
|| !RelocBaseEnd
) {
273 perror(L
"Reloc table overflows binary\n");
274 return EFI_UNSUPPORTED
;
277 Adjust
= (UINTN
)data
- context
->ImageAddress
;
282 while (RelocBase
< RelocBaseEnd
) {
283 Reloc
= (UINT16
*) ((char *) RelocBase
+ sizeof (EFI_IMAGE_BASE_RELOCATION
));
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
;
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
;
302 FixupBase
= ImageAddress(data
, size
, RelocBase
->VirtualAddress
);
304 perror(L
"Reloc %d Invalid fixupbase\n", n
);
305 return EFI_UNSUPPORTED
;
308 while (Reloc
< RelocEnd
) {
309 Fixup
= FixupBase
+ (*Reloc
& 0xFFF);
310 switch ((*Reloc
) >> 12) {
311 case EFI_IMAGE_REL_BASED_ABSOLUTE
:
314 case EFI_IMAGE_REL_BASED_HIGH
:
315 Fixup16
= (UINT16
*) Fixup
;
316 *Fixup16
= (UINT16
) (*Fixup16
+ ((UINT16
) ((UINT32
) Adjust
>> 16)));
319 case EFI_IMAGE_REL_BASED_LOW
:
320 Fixup16
= (UINT16
*) Fixup
;
321 *Fixup16
= (UINT16
) (*Fixup16
+ (UINT16
) Adjust
);
324 case EFI_IMAGE_REL_BASED_HIGHLOW
:
325 Fixup32
= (UINT32
*) Fixup
;
326 *Fixup32
= *Fixup32
+ (UINT32
) Adjust
;
329 case EFI_IMAGE_REL_BASED_DIR64
:
330 Fixup64
= (UINT64
*) Fixup
;
331 *Fixup64
= *Fixup64
+ (UINT64
) Adjust
;
335 perror(L
"Reloc %d Unknown relocation\n", n
);
336 return EFI_UNSUPPORTED
;
340 RelocBase
= (EFI_IMAGE_BASE_RELOCATION
*) RelocEnd
;
348 drain_openssl_errors(void)
350 unsigned long err
= -1;
352 err
= ERR_get_error();
355 static BOOLEAN
verify_x509(UINT8
*Cert
, UINTN CertSize
)
359 if (!Cert
|| CertSize
< 4)
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.
369 if (Cert
[0] != 0x30 || Cert
[1] != 0x82)
372 length
= Cert
[2]<<8 | Cert
[3];
373 if (length
!= (CertSize
- 4))
379 static BOOLEAN
verify_eku(UINT8
*Cert
, UINTN CertSize
)
382 CONST UINT8
*Temp
= Cert
;
383 EXTENDED_KEY_USAGE
*eku
;
384 ASN1_OBJECT
*module_signing
;
386 module_signing
= OBJ_nid2obj(OBJ_create(OID_EKU_MODSIGN
, NULL
, NULL
));
388 x509
= d2i_X509 (NULL
, &Temp
, (long) CertSize
);
390 eku
= X509_get_ext_d2i(x509
, NID_ext_key_usage
, NULL
, NULL
);
394 for (i
= 0; i
< sk_ASN1_OBJECT_num(eku
); i
++) {
395 ASN1_OBJECT
*key_usage
= sk_ASN1_OBJECT_value(eku
, i
);
397 if (OBJ_cmp(module_signing
, key_usage
) == 0)
400 EXTENDED_KEY_USAGE_free(eku
);
409 static void show_ca_warning()
413 text
[0] = L
"WARNING!";
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. ";
420 text
[7] = L
"Please contact the issuer to update the certificate. ";
424 console_print_box(text
, -1);
427 static CHECK_STATUS
check_db_cert_in_ram(EFI_SIGNATURE_LIST
*CertList
,
429 WIN_CERTIFICATE_EFI_PKCS
*data
,
430 UINT8
*hash
, CHAR16
*dbname
,
433 EFI_SIGNATURE_DATA
*Cert
;
435 BOOLEAN IsFound
= FALSE
;
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
)) {
444 IsFound
= AuthenticodeVerify (data
->CertData
,
445 data
->Hdr
.dwLength
- sizeof(data
->Hdr
),
448 hash
, SHA256_DIGEST_SIZE
);
450 if (get_ca_warning()) {
453 tpm_measure_variable(dbname
, guid
, CertSize
, Cert
->SignatureData
);
454 drain_openssl_errors();
457 LogError(L
"AuthenticodeVerify(): %d\n", IsFound
);
460 } else if (verbose
) {
461 console_notify(L
"Not a DER encoding x.509 Certificate");
465 dbsize
-= CertList
->SignatureListSize
;
466 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
469 return DATA_NOT_FOUND
;
472 static CHECK_STATUS
check_db_cert(CHAR16
*dbname
, EFI_GUID guid
,
473 WIN_CERTIFICATE_EFI_PKCS
*data
, UINT8
*hash
)
476 EFI_STATUS efi_status
;
477 EFI_SIGNATURE_LIST
*CertList
;
481 efi_status
= get_variable(dbname
, &db
, &dbsize
, guid
);
482 if (EFI_ERROR(efi_status
))
483 return VAR_NOT_FOUND
;
485 CertList
= (EFI_SIGNATURE_LIST
*)db
;
487 rc
= check_db_cert_in_ram(CertList
, dbsize
, data
, hash
, dbname
, guid
);
495 * Check a hash against an EFI_SIGNATURE_LIST in a buffer
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
)
502 EFI_SIGNATURE_DATA
*Cert
;
503 UINTN CertCount
, Index
;
504 BOOLEAN IsFound
= FALSE
;
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) {
513 // Find the signature in database.
516 tpm_measure_variable(dbname
, guid
, SignatureSize
, data
);
520 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
527 dbsize
-= CertList
->SignatureListSize
;
528 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
534 return DATA_NOT_FOUND
;
538 * Check a hash against an EFI_SIGNATURE_LIST in a UEFI variable
540 static CHECK_STATUS
check_db_hash(CHAR16
*dbname
, EFI_GUID guid
, UINT8
*data
,
541 int SignatureSize
, EFI_GUID CertType
)
543 EFI_STATUS efi_status
;
544 EFI_SIGNATURE_LIST
*CertList
;
548 efi_status
= get_variable(dbname
, &db
, &dbsize
, guid
);
549 if (EFI_ERROR(efi_status
)) {
550 return VAR_NOT_FOUND
;
553 CertList
= (EFI_SIGNATURE_LIST
*)db
;
555 CHECK_STATUS rc
= check_db_hash_in_ram(CertList
, dbsize
, data
,
556 SignatureSize
, CertType
,
564 * Check whether the binary signature or hash are present in dbx or the
567 static EFI_STATUS
check_blacklist (WIN_CERTIFICATE_EFI_PKCS
*cert
,
568 UINT8
*sha256hash
, UINT8
*sha1hash
)
570 EFI_SIGNATURE_LIST
*dbx
= (EFI_SIGNATURE_LIST
*)vendor_dbx
;
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
;
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
;
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
;
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
;
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
;
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
;
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
;
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
;
618 drain_openssl_errors();
622 static void update_verification_method(verification_method_t method
)
624 if (verification_method
== VERIFIED_BY_NOTHING
)
625 verification_method
= method
;
629 * Check whether the binary signature or hash are present in db or MokList
631 static EFI_STATUS
check_whitelist (WIN_CERTIFICATE_EFI_PKCS
*cert
,
632 UINT8
*sha256hash
, UINT8
*sha1hash
)
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
);
640 LogError(L
"check_db_hash(db, sha256hash) != DATA_FOUND\n");
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
);
648 LogError(L
"check_db_hash(db, sha1hash) != DATA_FOUND\n");
650 if (cert
&& check_db_cert(L
"db", EFI_SECURE_BOOT_DB_GUID
, cert
, sha256hash
)
652 verification_method
= VERIFIED_BY_CERT
;
653 update_verification_method(VERIFIED_BY_CERT
);
656 LogError(L
"check_db_cert(db, sha256hash) != DATA_FOUND\n");
660 if (check_db_hash(L
"MokList", SHIM_LOCK_GUID
, sha256hash
,
661 SHA256_DIGEST_SIZE
, EFI_CERT_SHA256_GUID
)
663 verification_method
= VERIFIED_BY_HASH
;
664 update_verification_method(VERIFIED_BY_HASH
);
667 LogError(L
"check_db_hash(MokList, sha256hash) != DATA_FOUND\n");
669 if (cert
&& check_db_cert(L
"MokList", SHIM_LOCK_GUID
, cert
, sha256hash
)
671 verification_method
= VERIFIED_BY_CERT
;
672 update_verification_method(VERIFIED_BY_CERT
);
675 LogError(L
"check_db_cert(MokList, sha256hash) != DATA_FOUND\n");
678 update_verification_method(VERIFIED_BY_NOTHING
);
679 return EFI_SECURITY_VIOLATION
;
683 * Check whether we're in Secure Boot and user mode
686 static BOOLEAN
secure_mode (void)
688 static int first
= 1;
689 if (user_insecure_mode
)
692 if (variable_is_secureboot() != 1) {
693 if (verbose
&& !in_protocol
&& first
)
694 console_notify(L
"Secure boot not enabled");
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
705 if (variable_is_setupmode(0) == 1) {
706 if (verbose
&& !in_protocol
&& first
)
707 console_notify(L
"Platform is in setup mode");
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, \
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, \
732 #define check_size(d,ds,h,hs) check_size_line(d,ds,h,hs,__LINE__)
735 * Calculate the SHA1 and SHA256 hashes of a binary
738 static EFI_STATUS
generate_hash (char *data
, unsigned int datasize_in
,
739 PE_COFF_LOADER_IMAGE_CONTEXT
*context
,
740 UINT8
*sha256hash
, UINT8
*sha1hash
)
743 unsigned int sha256ctxsize
, sha1ctxsize
;
744 unsigned int size
= datasize_in
;
745 void *sha256ctx
= NULL
, *sha1ctx
= NULL
;
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;
757 size
= datasize
= datasize_in
;
759 if (datasize
<= sizeof (*DosHdr
) ||
760 DosHdr
->e_magic
!= EFI_IMAGE_DOS_SIGNATURE
) {
761 perror(L
"Invalid signature\n");
762 return EFI_INVALID_PARAMETER
;
764 PEHdr_offset
= DosHdr
->e_lfanew
;
766 sha256ctxsize
= Sha256GetContextSize();
767 sha256ctx
= AllocatePool(sha256ctxsize
);
769 sha1ctxsize
= Sha1GetContextSize();
770 sha1ctx
= AllocatePool(sha1ctxsize
);
772 if (!sha256ctx
|| !sha1ctx
) {
773 perror(L
"Unable to allocate memory for hash context\n");
774 return EFI_OUT_OF_RESOURCES
;
777 if (!Sha256Init(sha256ctx
) || !Sha1Init(sha1ctx
)) {
778 perror(L
"Unable to initialise hash\n");
779 efi_status
= EFI_OUT_OF_RESOURCES
;
783 /* Hash start to checksum */
785 hashsize
= (char *)&context
->PEHdr
->Pe32
.OptionalHeader
.CheckSum
-
787 check_size(data
, datasize_in
, hashbase
, hashsize
);
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
;
796 /* Hash post-checksum to start of certificate table */
797 hashbase
= (char *)&context
->PEHdr
->Pe32
.OptionalHeader
.CheckSum
+
799 hashsize
= (char *)context
->SecDir
- hashbase
;
800 check_size(data
, datasize_in
, hashbase
, hashsize
);
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
;
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
;
818 check_size(data
, datasize_in
, hashbase
, hashsize
);
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
;
828 SumOfBytesHashed
= context
->SizeOfHeaders
;
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
;
834 /* Validate SectionPtr is within image */
835 SectionPtr
= ImageAddress(data
, datasize
,
838 sizeof (EFI_IMAGE_FILE_HEADER
) +
839 context
->PEHdr
->Pe32
.FileHeader
.SizeOfOptionalHeader
+
840 (index
* sizeof(*SectionPtr
)));
842 perror(L
"Malformed section %d\n", index
);
843 efi_status
= EFI_INVALID_PARAMETER
;
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
;
853 SumOfSectionBytes
+= SectionPtr
->SizeOfRawData
;
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
;
863 /* Already validated above */
864 Section
= ImageAddress(data
, datasize
,
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
) {
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
;
883 /* Sort the section headers */
884 for (index
= 0; index
< context
->PEHdr
->Pe32
.FileHeader
.NumberOfSections
; index
++) {
886 while ((pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[pos
- 1].PointerToRawData
)) {
887 CopyMem (&SectionHeader
[pos
], &SectionHeader
[pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
890 CopyMem (&SectionHeader
[pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
894 /* Hash the sections */
895 for (index
= 0; index
< context
->PEHdr
->Pe32
.FileHeader
.NumberOfSections
; index
++) {
896 Section
= &SectionHeader
[index
];
897 if (Section
->SizeOfRawData
== 0) {
900 hashbase
= ImageAddress(data
, size
, Section
->PointerToRawData
);
903 perror(L
"Malformed section header\n");
904 efi_status
= EFI_INVALID_PARAMETER
;
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
;
915 hashsize
= (unsigned int) Section
->SizeOfRawData
;
916 check_size(data
, datasize_in
, hashbase
, hashsize
);
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
;
924 SumOfBytesHashed
+= Section
->SizeOfRawData
;
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
;
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
;
942 check_size(data
, datasize_in
, hashbase
, hashsize
);
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
;
953 #else // we have to migrate to doing this later :/
954 SumOfBytesHashed
+= hashsize
;
957 /* Hash all remaining data */
958 if (datasize
> SumOfBytesHashed
) {
959 hashbase
= data
+ SumOfBytesHashed
;
960 hashsize
= datasize
- SumOfBytesHashed
;
962 check_size(data
, datasize_in
, hashbase
, hashsize
);
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
;
971 SumOfBytesHashed
+= hashsize
;
975 if (!(Sha256Final(sha256ctx
, sha256hash
)) ||
976 !(Sha1Final(sha1ctx
, sha1hash
))) {
977 perror(L
"Unable to finalise hash\n");
978 efi_status
= EFI_OUT_OF_RESOURCES
;
984 FreePool(SectionHeader
);
994 * Check that the signature is valid and matches the binary
996 static EFI_STATUS
verify_buffer (char *data
, int datasize
,
997 PE_COFF_LOADER_IMAGE_CONTEXT
*context
,
998 UINT8
*sha256hash
, UINT8
*sha1hash
)
1000 EFI_STATUS efi_status
= EFI_SECURITY_VIOLATION
;
1001 WIN_CERTIFICATE_EFI_PKCS
*cert
= NULL
;
1002 unsigned int size
= datasize
;
1005 return EFI_INVALID_PARAMETER
;
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
;
1013 cert
= ImageAddress (data
, size
,
1014 context
->SecDir
->VirtualAddress
);
1017 perror(L
"Certificate located outside the image\n");
1018 return EFI_INVALID_PARAMETER
;
1021 if (cert
->Hdr
.dwLength
> context
->SecDir
->Size
) {
1022 perror(L
"Certificate list size is inconsistent with PE headers");
1023 return EFI_INVALID_PARAMETER
;
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
;
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.
1039 drain_openssl_errors();
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
);
1048 * Ensure that the binary isn't blacklisted
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
);
1058 * Check whether the binary is whitelisted in any of the firmware
1061 efi_status
= check_whitelist(cert
, sha256hash
, sha1hash
);
1062 if (EFI_ERROR(efi_status
)) {
1063 LogError(L
"check_whitelist(): %r\n", efi_status
);
1065 drain_openssl_errors();
1070 #if defined(ENABLE_SHIM_CERT)
1072 * Check against the shim build key
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()) {
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();
1090 LogError(L
"AuthenticodeVerify(shim_cert) failed\n");
1092 #endif /* defined(ENABLE_SHIM_CERT) */
1095 * And finally, check against shim's built-in key
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()) {
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();
1113 LogError(L
"AuthenticodeVerify(vendor_cert) failed\n");
1117 LogError(L
"Binary is not whitelisted\n");
1118 crypterr(EFI_SECURITY_VIOLATION
);
1120 efi_status
= EFI_SECURITY_VIOLATION
;
1125 * Read the binary header and grab appropriate information from it
1127 static EFI_STATUS
read_header(void *data
, unsigned int datasize
,
1128 PE_COFF_LOADER_IMAGE_CONTEXT
*context
)
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;
1135 if (datasize
< sizeof (PEHdr
->Pe32
)) {
1136 perror(L
"Invalid image\n");
1137 return EFI_UNSUPPORTED
;
1140 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
)
1141 PEHdr
= (EFI_IMAGE_OPTIONAL_HEADER_UNION
*)((char *)data
+ DosHdr
->e_lfanew
);
1143 if (!image_is_loadable(PEHdr
)) {
1144 perror(L
"Platform does not support this image\n");
1145 return EFI_UNSUPPORTED
;
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
);
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
);
1164 if (FileAlignment
% 2 != 0) {
1165 perror(L
"File Alignment is invalid (%d)\n", FileAlignment
);
1166 return EFI_UNSUPPORTED
;
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
;
1175 context
->NumberOfSections
= PEHdr
->Pe32
.FileHeader
.NumberOfSections
;
1177 if (EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES
< context
->NumberOfRvaAndSizes
) {
1178 perror(L
"Image header too small\n");
1179 return EFI_UNSUPPORTED
;
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
;
1190 SectionHeaderOffset
= DosHdr
->e_lfanew
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
;
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
;
1206 if ((((UINT8
*)PEHdr
- (UINT8
*)data
) + sizeof(EFI_IMAGE_OPTIONAL_HEADER_UNION
)) > datasize
) {
1207 perror(L
"Invalid image\n");
1208 return EFI_UNSUPPORTED
;
1211 if (PEHdr
->Te
.Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1212 perror(L
"Unsupported image type\n");
1213 return EFI_UNSUPPORTED
;
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
;
1221 context
->PEHdr
= PEHdr
;
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
];
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
];
1235 context
->FirstSection
= (EFI_IMAGE_SECTION_HEADER
*)((char *)PEHdr
+ PEHdr
->Pe32
.FileHeader
.SizeOfOptionalHeader
+ sizeof(UINT32
) + sizeof(EFI_IMAGE_FILE_HEADER
));
1237 if (context
->ImageSize
< context
->SizeOfHeaders
) {
1238 perror(L
"Invalid image\n");
1239 return EFI_UNSUPPORTED
;
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
;
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
;
1258 * Once the image has been loaded it needs to be validated and relocated
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
,
1266 EFI_STATUS efi_status
;
1269 EFI_IMAGE_SECTION_HEADER
*Section
;
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
];
1278 * The binary header contains relevant context and section pointers
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
);
1287 * We only need to verify the binary if we're in secure mode
1289 efi_status
= generate_hash(data
, datasize
, &context
, sha256hash
,
1291 if (EFI_ERROR(efi_status
))
1294 /* Measure the binary into the TPM */
1298 tpm_log_pe((EFI_PHYSICAL_ADDRESS
)(UINTN
)data
, datasize
, sha1hash
, 4);
1300 if (efi_status
!= EFI_SUCCESS
) {
1305 if (secure_mode ()) {
1306 efi_status
= verify_buffer(data
, datasize
, &context
,
1307 sha256hash
, sha1hash
);
1309 if (EFI_ERROR(efi_status
)) {
1310 console_error(L
"Verification failed", efi_status
);
1314 console_print(L
"Verification succeeded\n");
1318 /* The spec says, uselessly, of SectionAlignment:
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.
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.
1330 * We only support one page size, so if it's zero, nerf it to 4096.
1332 alignment
= context
.SectionAlignment
;
1336 alloc_size
= ALIGN_VALUE(context
.ImageSize
+ context
.SectionAlignment
,
1338 *alloc_pages
= alloc_size
/ PAGE_SIZE
;
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
;
1347 buffer
= (void *)ALIGN_VALUE((unsigned long)*alloc_address
, alignment
);
1349 CopyMem(buffer
, data
, context
.SizeOfHeaders
);
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
;
1359 char *RelocBase
, *RelocBaseEnd
;
1361 * These are relative virtual addresses, so we have to check them
1362 * against the image size, not the data size.
1364 RelocBase
= ImageAddress(buffer
, context
.ImageSize
,
1365 context
.RelocDir
->VirtualAddress
);
1367 * RelocBaseEnd here is the address of the last byte of the table
1369 RelocBaseEnd
= ImageAddress(buffer
, context
.ImageSize
,
1370 context
.RelocDir
->VirtualAddress
+
1371 context
.RelocDir
->Size
- 1);
1373 EFI_IMAGE_SECTION_HEADER
*RelocSection
= NULL
;
1376 * Copy the executable's sections to their desired offsets
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);
1387 perror(L
"Section %d has negative size\n", i
);
1388 gBS
->FreePages(*alloc_address
, *alloc_pages
);
1389 return EFI_UNSUPPORTED
;
1392 if (Section
->VirtualAddress
<= context
.EntryPoint
&&
1393 (Section
->VirtualAddress
+ Section
->SizeOfRawData
- 1)
1394 > context
.EntryPoint
)
1395 found_entry_point
++;
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) {
1401 perror(L
"Image has multiple relocation sections\n");
1402 return EFI_UNSUPPORTED
;
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
&&
1410 RelocBase
== base
&&
1411 RelocBaseEnd
== end
) {
1412 RelocSection
= Section
;
1416 if (Section
->Characteristics
& EFI_IMAGE_SCN_MEM_DISCARDABLE
) {
1421 perror(L
"Section %d has invalid base address\n", i
);
1422 return EFI_UNSUPPORTED
;
1425 perror(L
"Section %d has zero size\n", i
);
1426 return EFI_UNSUPPORTED
;
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
;
1436 if (Section
->Characteristics
& EFI_IMAGE_SCN_CNT_UNINITIALIZED_DATA
) {
1437 ZeroMem(base
, Section
->Misc
.VirtualSize
);
1439 if (Section
->PointerToRawData
< context
.SizeOfHeaders
) {
1440 perror(L
"Section %d is inside image headers\n", i
);
1441 return EFI_UNSUPPORTED
;
1444 if (Section
->SizeOfRawData
> 0)
1445 CopyMem(base
, data
+ Section
->PointerToRawData
,
1446 Section
->SizeOfRawData
);
1448 if (Section
->SizeOfRawData
< Section
->Misc
.VirtualSize
)
1449 ZeroMem(base
+ Section
->SizeOfRawData
,
1450 Section
->Misc
.VirtualSize
- Section
->SizeOfRawData
);
1454 if (context
.NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC
) {
1455 perror(L
"Image has no relocation entry\n");
1457 return EFI_UNSUPPORTED
;
1460 if (context
.RelocDir
->Size
&& RelocSection
) {
1462 * Run the relocation fixups
1464 efi_status
= relocate_coff(&context
, RelocSection
, data
,
1467 if (EFI_ERROR(efi_status
)) {
1468 perror(L
"Relocation failed: %r\n", efi_status
);
1475 * grub needs to know its location and size in memory, so fix up
1476 * the loaded image protocol values
1478 li
->ImageBase
= buffer
;
1479 li
->ImageSize
= context
.ImageSize
;
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
;
1487 if (!found_entry_point
) {
1488 perror(L
"Entry point is not within sections\n");
1489 return EFI_UNSUPPORTED
;
1491 if (found_entry_point
> 1) {
1492 perror(L
"%d sections contain entry point\n");
1493 return EFI_UNSUPPORTED
;
1500 should_use_fallback(EFI_HANDLE image_handle
)
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
;
1511 efi_status
= gBS
->HandleProtocol(image_handle
, &EFI_LOADED_IMAGE_GUID
,
1513 if (EFI_ERROR(efi_status
)) {
1514 perror(L
"Could not get image for bootx64.efi: %r\n",
1519 bootpath
= DevicePathToStr(li
->FilePath
);
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...
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))
1532 pathlen
= StrLen(bootpath
);
1533 if (pathlen
< 5 || StrCaseCmp(bootpath
+ pathlen
- 4, L
".EFI"))
1536 efi_status
= gBS
->HandleProtocol(li
->DeviceHandle
, &FileSystemProtocol
,
1538 if (EFI_ERROR(efi_status
)) {
1539 perror(L
"Could not get fio for li->DeviceHandle: %r\n",
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
);
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,
1575 * Generate the path of an executable given shim's path and the name
1578 static EFI_STATUS
generate_path_from_image_path(EFI_LOADED_IMAGE
*li
,
1582 EFI_DEVICE_PATH
*devpath
;
1585 unsigned int pathlen
= 0;
1586 EFI_STATUS efi_status
= EFI_SUCCESS
;
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.
1595 * If it is a full path, don't try to merge it with the directory
1596 * from our Loaded Image handle.
1598 if (StrSize(ImagePath
) > 5 && StrnCmp(ImagePath
, L
"\\EFI\\", 5) == 0) {
1599 *PathName
= StrDuplicate(ImagePath
);
1601 perror(L
"Failed to allocate path buffer\n");
1602 return EFI_OUT_OF_RESOURCES
;
1607 devpath
= li
->FilePath
;
1609 bootpath
= DevicePathToStr(devpath
);
1611 pathlen
= StrLen(bootpath
);
1614 * DevicePathToStr() concatenates two nodes with '/'.
1615 * Convert '/' to '\\'.
1617 for (i
= 0; i
< pathlen
; i
++) {
1618 if (bootpath
[i
] == '/')
1622 for (i
=pathlen
; i
>0; i
--) {
1623 if (bootpath
[i
] == '\\' && bootpath
[i
-1] == '\\')
1625 else if (last
== -1 && bootpath
[i
] == '\\')
1629 if (last
== -1 && bootpath
[0] == '\\')
1631 bootpath
[last
+1] = '\0';
1634 for (i
= 0, j
= 0; bootpath
[i
] != '\0'; i
++) {
1635 if (bootpath
[i
] != '/') {
1636 bootpath
[j
] = bootpath
[i
];
1643 while (*ImagePath
== '\\')
1646 *PathName
= AllocatePool(StrSize(bootpath
) + StrSize(ImagePath
));
1649 perror(L
"Failed to allocate path buffer\n");
1650 efi_status
= EFI_OUT_OF_RESOURCES
;
1654 *PathName
[0] = '\0';
1655 if (StrnCaseCmp(bootpath
, ImagePath
, StrLen(bootpath
)))
1656 StrCat(*PathName
, bootpath
);
1657 StrCat(*PathName
, ImagePath
);
1666 * Open the second stage bootloader and read it into a buffer
1668 static EFI_STATUS
load_image (EFI_LOADED_IMAGE
*li
, void **data
,
1669 int *datasize
, CHAR16
*PathName
)
1671 EFI_STATUS efi_status
;
1673 EFI_FILE_INFO
*fileinfo
= NULL
;
1674 EFI_FILE_IO_INTERFACE
*drive
;
1675 EFI_FILE
*root
, *grub
;
1676 UINTN buffersize
= sizeof(EFI_FILE_INFO
);
1678 device
= li
->DeviceHandle
;
1683 efi_status
= gBS
->HandleProtocol(device
, &EFI_SIMPLE_FILE_SYSTEM_GUID
,
1685 if (EFI_ERROR(efi_status
)) {
1686 perror(L
"Failed to find fs: %r\n", efi_status
);
1690 efi_status
= drive
->OpenVolume(drive
, &root
);
1691 if (EFI_ERROR(efi_status
)) {
1692 perror(L
"Failed to open fs: %r\n", efi_status
);
1697 * And then open the file
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
);
1705 fileinfo
= AllocatePool(buffersize
);
1708 perror(L
"Unable to allocate file info buffer\n");
1709 efi_status
= EFI_OUT_OF_RESOURCES
;
1714 * Find out how big the file is in order to allocate the storage
1717 efi_status
= grub
->GetInfo(grub
, &EFI_FILE_INFO_GUID
, &buffersize
,
1719 if (efi_status
== EFI_BUFFER_TOO_SMALL
) {
1721 fileinfo
= AllocatePool(buffersize
);
1723 perror(L
"Unable to allocate file info buffer\n");
1724 efi_status
= EFI_OUT_OF_RESOURCES
;
1727 efi_status
= grub
->GetInfo(grub
, &EFI_FILE_INFO_GUID
,
1728 &buffersize
, fileinfo
);
1731 if (EFI_ERROR(efi_status
)) {
1732 perror(L
"Unable to get file info: %r\n", efi_status
);
1736 buffersize
= fileinfo
->FileSize
;
1737 *data
= AllocatePool(buffersize
);
1739 perror(L
"Unable to allocate file buffer\n");
1740 efi_status
= EFI_OUT_OF_RESOURCES
;
1745 * Perform the actual read
1747 efi_status
= grub
->Read(grub
, &buffersize
, *data
);
1748 if (efi_status
== EFI_BUFFER_TOO_SMALL
) {
1750 *data
= AllocatePool(buffersize
);
1751 efi_status
= grub
->Read(grub
, &buffersize
, *data
);
1753 if (EFI_ERROR(efi_status
)) {
1754 perror(L
"Unexpected return from initial read: %r, buffersize %x\n",
1755 efi_status
, buffersize
);
1759 *datasize
= buffersize
;
1776 * Protocol entry point. If secure boot is enabled, verify that the provided
1777 * buffer is signed with a trusted key.
1779 EFI_STATUS
shim_verify (void *buffer
, UINT32 size
)
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
];
1786 if ((INT32
)size
< 0)
1787 return EFI_INVALID_PARAMETER
;
1789 loader_is_participating
= 1;
1792 efi_status
= read_header(buffer
, size
, &context
);
1793 if (EFI_ERROR(efi_status
))
1796 efi_status
= generate_hash(buffer
, size
, &context
,
1797 sha256hash
, sha1hash
);
1798 if (EFI_ERROR(efi_status
))
1801 /* Measure the binary into the TPM */
1805 tpm_log_pe((EFI_PHYSICAL_ADDRESS
)(UINTN
)buffer
, size
, sha1hash
, 4);
1807 if (EFI_ERROR(efi_status
))
1811 if (!secure_mode()) {
1812 efi_status
= EFI_SUCCESS
;
1816 efi_status
= verify_buffer(buffer
, size
, &context
,
1817 sha256hash
, sha1hash
);
1823 static EFI_STATUS
shim_hash (char *data
, int datasize
,
1824 PE_COFF_LOADER_IMAGE_CONTEXT
*context
,
1825 UINT8
*sha256hash
, UINT8
*sha1hash
)
1827 EFI_STATUS efi_status
;
1830 return EFI_INVALID_PARAMETER
;
1833 efi_status
= generate_hash(data
, datasize
, context
,
1834 sha256hash
, sha1hash
);
1840 static EFI_STATUS
shim_read_header(void *data
, unsigned int datasize
,
1841 PE_COFF_LOADER_IMAGE_CONTEXT
*context
)
1843 EFI_STATUS efi_status
;
1846 efi_status
= read_header(data
, datasize
, context
);
1853 * Load and run an EFI executable
1855 EFI_STATUS
start_image(EFI_HANDLE image_handle
, CHAR16
*ImagePath
)
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
;
1862 CHAR16
*PathName
= NULL
;
1863 void *sourcebuffer
= NULL
;
1864 UINT64 sourcesize
= 0;
1869 * We need to refer to the loaded image protocol on the running
1870 * binary in order to find our path
1872 efi_status
= gBS
->HandleProtocol(image_handle
, &EFI_LOADED_IMAGE_GUID
,
1874 if (EFI_ERROR(efi_status
)) {
1875 perror(L
"Unable to init protocol\n");
1880 * Build a new path from the existing one plus the executable name
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
,
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
;
1895 efi_status
= FetchNetbootimage(image_handle
, &sourcebuffer
,
1897 if (EFI_ERROR(efi_status
)) {
1898 perror(L
"Unable to fetch TFTP image: %r\n",
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
,
1909 if (EFI_ERROR(efi_status
)) {
1910 perror(L
"Unable to fetch HTTP image: %r\n",
1914 data
= sourcebuffer
;
1915 datasize
= sourcesize
;
1919 * Read the new executable off disk
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
);
1932 efi_status
= EFI_INVALID_PARAMETER
;
1937 * We need to modify the loaded image protocol entry before running
1938 * the new binary, so back it up
1940 CopyMem(&li_bak
, li
, sizeof(li_bak
));
1943 * Verify and, if appropriate, relocate and execute the executable
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
);
1951 CopyMem(li
, &li_bak
, sizeof(li_bak
));
1955 loader_is_participating
= 0;
1958 * The binary is trusted and relocated. Run it
1960 efi_status
= entry_point(image_handle
, systab
);
1963 * Restore our original loaded image values
1965 CopyMem(li
, &li_bak
, sizeof(li_bak
));
1977 * Load and run grub. If that fails because grub isn't trusted, load and
1980 EFI_STATUS
init_grub(EFI_HANDLE image_handle
)
1982 EFI_STATUS efi_status
;
1983 int use_fb
= should_use_fallback(image_handle
);
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
);
1995 efi_status
= start_image(image_handle
,
1996 use_fb
? FALLBACK
: second_stage
);
1999 if (EFI_ERROR(efi_status
)) {
2000 console_print(L
"start_image() returned %r\n", efi_status
);
2007 static inline EFI_STATUS
2008 get_load_option_optional_data(UINT8
*data
, UINTN data_size
,
2009 UINT8
**od
, UINTN
*ods
)
2012 * If it's not at least Attributes + FilePathListLength +
2013 * Description=L"" + 0x7fff0400 (EndEntrireDevicePath), it can't
2016 if (data_size
< (sizeof(UINT32
) + sizeof(UINT16
) + 2 + 4))
2017 return EFI_INVALID_PARAMETER
;
2019 UINT8
*cur
= data
+ sizeof(UINT32
);
2020 UINT16 fplistlen
= *(UINT16
*)cur
;
2022 * If there's not enough space for the file path list and the
2023 * smallest possible description (L""), it's not valid.
2025 if (fplistlen
> data_size
- (sizeof(UINT32
) + 2 + 4))
2026 return EFI_INVALID_PARAMETER
;
2028 cur
+= sizeof(UINT16
);
2029 UINTN limit
= data_size
- (cur
- data
) - fplistlen
;
2031 for (i
= 0; i
< limit
; i
++) {
2032 /* If the description isn't valid UCS2-LE, it's not valid. */
2035 return EFI_INVALID_PARAMETER
;
2036 } else if (cur
[i
] == 0) {
2037 /* we've found the end */
2039 if (i
>= limit
|| cur
[i
] != 0)
2040 return EFI_INVALID_PARAMETER
;
2046 return EFI_INVALID_PARAMETER
;
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.
2062 while (limit
- i
>= 4) {
2069 .subtype
= cur
[i
+1],
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.
2075 .len
= (cur
[i
+3] << 8) | cur
[i
+2],
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.
2083 if (dp
.len
< 4 || dp
.len
> limit
)
2084 return EFI_INVALID_PARAMETER
;
2087 * see if this is an EndEntire node...
2089 if (dp
.type
== 0x7f && dp
.subtype
== 0xff) {
2091 * if we've found the EndEntire node, it must be 4
2095 return EFI_INVALID_PARAMETER
;
2102 * It's just some random DP node; skip it.
2107 return EFI_INVALID_PARAMETER
;
2110 * if there's any space left, it's "optional data"
2117 static int is_our_path(EFI_LOADED_IMAGE
*li
, CHAR16
*path
, UINTN len
)
2119 CHAR16
*dppath
= NULL
;
2122 dppath
= DevicePathToStr(li
->FilePath
);
2126 dprint(L
"dppath: %s\n", dppath
);
2127 dprint(L
"path: %s\n", path
);
2128 if (StrnCaseCmp(dppath
, path
, len
))
2136 * Check the load options to specify the second stage loader
2138 EFI_STATUS
set_second_stage (EFI_HANDLE image_handle
)
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;
2148 second_stage
= DEFAULT_LOADER
;
2149 load_options
= NULL
;
2150 load_options_size
= 0;
2152 efi_status
= gBS
->HandleProtocol(image_handle
, &LoadedImageProtocol
,
2154 if (EFI_ERROR(efi_status
)) {
2155 perror (L
"Failed to get load options: %r\n", efi_status
);
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:
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.:.\...|
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:
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.|
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.
2192 * But then on some versions of BDS, we get:
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...|
2198 * which as you can see is one perfectly normal UCS2-EL string
2199 * containing the load option from the Boot#### variable.
2201 * We also sometimes find a guid or partial guid at the end, because
2202 * BDS will add that, but we ignore that here.
2206 * In either case, we've got to have at least a UCS2 NUL...
2208 if (li
->LoadOptionsSize
< 2)
2209 return EFI_BAD_BUFFER_SIZE
;
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.
2220 * Anyway, just nerf that out from the start. It's always just
2221 * garbage at the end.
2223 if (li
->LoadOptionsSize
> 16) {
2224 if (CompareGuid((EFI_GUID
*)(li
->LoadOptions
2225 + (li
->LoadOptionsSize
- 16)),
2227 li
->LoadOptionsSize
-= 16;
2231 * Apparently sometimes we get L"\0\0"? Which isn't useful at all.
2233 if (is_all_nuls(li
->LoadOptions
, li
->LoadOptionsSize
))
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.
2241 * If there are 3 strings, we're launched from the shell most likely,
2242 * But we actually only care about the second one.
2244 UINTN strings
= count_ucs2_strings(li
->LoadOptions
,
2245 li
->LoadOptionsSize
);
2247 * If it's not string data, try it as an EFI_LOAD_OPTION.
2251 * We at least didn't find /enough/ strings. See if it works
2252 * as an EFI_LOAD_OPTION.
2254 efi_status
= get_load_option_optional_data(li
->LoadOptions
,
2255 li
->LoadOptionsSize
,
2258 if (EFI_ERROR(efi_status
))
2262 } else if (strings
>= 2) {
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.
2270 UINT8
*cur
= li
->LoadOptions
;
2271 for (i
= 0; i
< li
->LoadOptionsSize
- 2; i
+= 2) {
2272 CHAR16 c
= (cur
[i
+1] << 8) | cur
[i
];
2274 start
= (CHAR16
*)&cur
[i
+2];
2275 remaining_size
= li
->LoadOptionsSize
- i
- 2;
2280 if (!start
|| remaining_size
<= 0 || start
[0] == L
'\0')
2283 for (i
= 0; start
[i
] != '\0'; i
++) {
2284 if (start
[i
] == L
' ')
2286 if (start
[i
] == L
'\0') {
2287 loader_len
= 2 * i
+ 2;
2292 remaining_size
-= loader_len
;
2294 /* only find one string */
2295 start
= li
->LoadOptions
;
2296 loader_len
= li
->LoadOptionsSize
;
2300 * Just to be sure all that math is right...
2302 if (loader_len
% 2 != 0)
2303 return EFI_INVALID_PARAMETER
;
2305 strings
= count_ucs2_strings((UINT8
*)start
, loader_len
);
2310 * And then I found a version of BDS that gives us our own path in
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...|
2318 * which is just cruel... So yeah, just don't use it.
2320 if (strings
== 1 && is_our_path(li
, start
, loader_len
))
2324 * Set up the name of the alternative loader and the LoadOptions for
2327 if (loader_len
> 0) {
2328 loader_str
= AllocatePool(loader_len
);
2330 perror(L
"Failed to allocate loader string\n");
2331 return EFI_OUT_OF_RESOURCES
;
2334 for (i
= 0; i
< loader_len
/ 2; i
++)
2335 loader_str
[i
] = start
[i
];
2336 loader_str
[loader_len
/2-1] = L
'\0';
2338 second_stage
= loader_str
;
2339 load_options
= remaining_size
? start
+ (loader_len
/2) : NULL
;
2340 load_options_size
= remaining_size
;
2347 ossl_malloc(size_t num
, const char *file
, int line
)
2349 return AllocatePool(num
);
2353 ossl_free(void *addr
, const char *file
, int line
)
2361 CRYPTO_set_mem_functions(ossl_malloc
, NULL
, ossl_free
);
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();
2386 static SHIM_LOCK shim_lock_interface
;
2387 static EFI_HANDLE shim_lock_handle
;
2390 install_shim_protocols(void)
2392 SHIM_LOCK
*shim_lock
;
2393 EFI_STATUS efi_status
;
2396 * Did another instance of shim earlier already install the
2397 * protocol? If so, get rid of it.
2399 * We have to uninstall shim's protocol here, because if we're
2400 * On the fallback.efi path, then our call pathway is:
2402 * shim->fallback->shim->grub
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.
2412 efi_status
= LibLocateProtocol(&SHIM_LOCK_GUID
, (VOID
**)&shim_lock
);
2413 if (!EFI_ERROR(efi_status
))
2414 uninstall_shim_protocols();
2417 * Install the protocol
2419 efi_status
= gBS
->InstallProtocolInterface(&shim_lock_handle
,
2421 EFI_NATIVE_INTERFACE
,
2422 &shim_lock_interface
);
2423 if (EFI_ERROR(efi_status
)) {
2424 console_error(L
"Could not install security protocol",
2432 #if defined(OVERRIDE_SECURITY_POLICY)
2434 * Install the security protocol hook
2436 security_policy_install(shim_verify
);
2443 uninstall_shim_protocols(void)
2446 * If we're back here then clean everything up before exiting
2448 gBS
->UninstallProtocolInterface(shim_lock_handle
, &SHIM_LOCK_GUID
,
2449 &shim_lock_interface
);
2454 #if defined(OVERRIDE_SECURITY_POLICY)
2456 * Clean up the security protocol hook
2458 security_policy_uninstall();
2466 dprint(L
"%a", shim_version
);
2468 /* Set the second stage loader */
2469 set_second_stage (global_image_handle
);
2471 if (secure_mode()) {
2472 if (vendor_cert_size
|| vendor_dbx_size
) {
2474 * If shim includes its own certificates then ensure
2475 * that anything it boots has performed some
2476 * validation of the next image.
2478 hook_system_services(systab
);
2479 loader_is_participating
= 0;
2485 return install_shim_protocols();
2492 * Remove our protocols
2494 uninstall_shim_protocols();
2496 if (secure_mode()) {
2499 * Remove our hooks from system services.
2501 unhook_system_services();
2506 * Free the space allocated for the alternative 2nd stage loader
2508 if (load_options_size
> 0 && second_stage
)
2509 FreePool(second_stage
);
2515 efi_main(EFI_HANDLE passed_image_handle
, EFI_SYSTEM_TABLE
*passed_systab
);
2518 __attribute__((__optimize__("0")))
2523 EFI_STATUS efi_status
;
2524 volatile register UINTN x
= 0;
2525 extern char _text
, _data
;
2530 efi_status
= get_variable(L
"SHIM_DEBUG", &data
, &dataSize
,
2532 if (EFI_ERROR(efi_status
)) {
2538 console_print(L
"add-symbol-file "DEBUGDIR
2539 L
"shim" EFI_ARCH L
".efi.debug 0x%08x -s .data 0x%08x\n",
2542 console_print(L
"Pausing for debugger attachment.\n");
2543 console_print(L
"To disable this, remove the EFI variable SHIM_DEBUG-%g .\n",
2547 /* Make this so it can't /totally/ DoS us. */
2548 #if defined(__x86_64__) || defined(__i386__) || defined(__i686__)
2549 if (x
> 4294967294ULL)
2551 __asm__
__volatile__("pause");
2552 #elif defined(__aarch64__)
2555 __asm__
__volatile__("wfi");
2566 efi_main (EFI_HANDLE passed_image_handle
, EFI_SYSTEM_TABLE
*passed_systab
)
2568 EFI_STATUS efi_status
;
2569 EFI_HANDLE image_handle
;
2571 verification_method
= VERIFIED_BY_NOTHING
;
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
;
2578 L
"import_mok_state() failed\n",
2579 L
"shim_int() failed\n",
2586 * Set up the shim lock protocol so that grub and MokManager can
2587 * call back in and use shim functions
2589 shim_lock_interface
.Verify
= shim_verify
;
2590 shim_lock_interface
.Hash
= shim_hash
;
2591 shim_lock_interface
.Context
= shim_read_header
;
2593 systab
= passed_systab
;
2594 image_handle
= global_image_handle
= passed_image_handle
;
2597 * Ensure that gnu-efi functions are available
2599 InitializeLib(image_handle
, systab
);
2604 * if SHIM_DEBUG is set, wait for a debugger to attach.
2609 * Before we do anything else, validate our non-volatile,
2610 * boot-services-only state variables are what we think they are.
2612 efi_status
= import_mok_state(image_handle
);
2613 if (EFI_ERROR(efi_status
)) {
2615 console_print(L
"Something has gone seriously wrong: %s: %r\n",
2616 msgs
[msg
], efi_status
);
2618 gRT
->ResetSystem(EfiResetShutdown
, EFI_SECURITY_VIOLATION
,
2622 efi_status
= shim_init();
2623 if (EFI_ERROR(efi_status
)) {
2629 * Tell the user that we're in insecure mode if necessary
2631 if (user_insecure_mode
) {
2632 console_print(L
"Booting in insecure mode\n");
2637 * Hand over control to the second stage bootloader
2639 efi_status
= init_grub(image_handle
);