1 // SPDX-License-Identifier: GPL-2.0+
5 * based partly on wine code
7 * Copyright (c) 2016 Alexander Graf
12 #include <efi_loader.h>
16 #include "../lib/crypto/pkcs7_parser.h"
18 const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
19 const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
20 const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
21 const efi_guid_t efi_guid_loaded_image_device_path =
22 EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
23 const efi_guid_t efi_simple_file_system_protocol_guid =
24 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
25 const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
27 static int machines[] = {
28 #if defined(__aarch64__)
29 IMAGE_FILE_MACHINE_ARM64,
30 #elif defined(__arm__)
31 IMAGE_FILE_MACHINE_ARM,
32 IMAGE_FILE_MACHINE_THUMB,
33 IMAGE_FILE_MACHINE_ARMNT,
36 #if defined(__x86_64__)
37 IMAGE_FILE_MACHINE_AMD64,
38 #elif defined(__i386__)
39 IMAGE_FILE_MACHINE_I386,
42 #if defined(__riscv) && (__riscv_xlen == 32)
43 IMAGE_FILE_MACHINE_RISCV32,
46 #if defined(__riscv) && (__riscv_xlen == 64)
47 IMAGE_FILE_MACHINE_RISCV64,
52 * efi_print_image_info() - print information about a loaded image
54 * If the program counter is located within the image the offset to the base
58 * @image: loaded image
59 * @pc: program counter (use NULL to suppress offset output)
62 static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
63 struct efi_loaded_image *image,
67 printf(" [0x%p:0x%p]",
68 image->image_base, image->image_base + image->image_size - 1);
69 if (pc && pc >= image->image_base &&
70 pc < image->image_base + image->image_size)
71 printf(" pc=0x%zx", pc - image->image_base);
73 printf(" '%pD'", image->file_path);
79 * efi_print_image_infos() - print information about all loaded images
81 * @pc: program counter (use NULL to suppress offset output)
83 void efi_print_image_infos(void *pc)
85 struct efi_object *efiobj;
86 struct efi_handler *handler;
88 list_for_each_entry(efiobj, &efi_obj_list, link) {
89 list_for_each_entry(handler, &efiobj->protocols, link) {
90 if (!guidcmp(handler->guid, &efi_guid_loaded_image)) {
92 (struct efi_loaded_image_obj *)efiobj,
93 handler->protocol_interface, pc);
100 * efi_loader_relocate() - relocate UEFI binary
102 * @rel: pointer to the relocation table
103 * @rel_size: size of the relocation table in bytes
104 * @efi_reloc: actual load address of the image
105 * @pref_address: preferred load address of the image
106 * Return: status code
108 static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
109 unsigned long rel_size, void *efi_reloc,
110 unsigned long pref_address)
112 unsigned long delta = (unsigned long)efi_reloc - pref_address;
113 const IMAGE_BASE_RELOCATION *end;
119 end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
120 while (rel < end && rel->SizeOfBlock) {
121 const uint16_t *relocs = (const uint16_t *)(rel + 1);
122 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
124 uint32_t offset = (uint32_t)(*relocs & 0xfff) +
126 int type = *relocs >> EFI_PAGE_SHIFT;
127 uint64_t *x64 = efi_reloc + offset;
128 uint32_t *x32 = efi_reloc + offset;
129 uint16_t *x16 = efi_reloc + offset;
132 case IMAGE_REL_BASED_ABSOLUTE:
134 case IMAGE_REL_BASED_HIGH:
135 *x16 += ((uint32_t)delta) >> 16;
137 case IMAGE_REL_BASED_LOW:
138 *x16 += (uint16_t)delta;
140 case IMAGE_REL_BASED_HIGHLOW:
141 *x32 += (uint32_t)delta;
143 case IMAGE_REL_BASED_DIR64:
144 *x64 += (uint64_t)delta;
147 case IMAGE_REL_BASED_RISCV_HI20:
148 *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
151 case IMAGE_REL_BASED_RISCV_LOW12I:
152 case IMAGE_REL_BASED_RISCV_LOW12S:
153 /* We know that we're 4k aligned */
155 printf("Unsupported reloc offset\n");
156 return EFI_LOAD_ERROR;
161 printf("Unknown Relocation off %x type %x\n",
163 return EFI_LOAD_ERROR;
167 rel = (const IMAGE_BASE_RELOCATION *)relocs;
172 void __weak invalidate_icache_all(void)
174 /* If the system doesn't support icache_all flush, cross our fingers */
178 * efi_set_code_and_data_type() - determine the memory types to be used for code
181 * @loaded_image_info: image descriptor
182 * @image_type: field Subsystem of the optional header for
183 * Windows specific field
185 static void efi_set_code_and_data_type(
186 struct efi_loaded_image *loaded_image_info,
189 switch (image_type) {
190 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
191 loaded_image_info->image_code_type = EFI_LOADER_CODE;
192 loaded_image_info->image_data_type = EFI_LOADER_DATA;
194 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
195 loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
196 loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
198 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
199 case IMAGE_SUBSYSTEM_EFI_ROM:
200 loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
201 loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
204 printf("%s: invalid image type: %u\n", __func__, image_type);
205 /* Let's assume it is an application */
206 loaded_image_info->image_code_type = EFI_LOADER_CODE;
207 loaded_image_info->image_data_type = EFI_LOADER_DATA;
212 #ifdef CONFIG_EFI_SECURE_BOOT
214 * cmp_pe_section - compare two sections
215 * @arg1: Pointer to pointer to first section
216 * @arg2: Pointer to pointer to second section
218 * Compare two sections in PE image.
220 * Return: -1, 0, 1 respectively if arg1 < arg2, arg1 == arg2 or
223 static int cmp_pe_section(const void *arg1, const void *arg2)
225 const IMAGE_SECTION_HEADER *section1, *section2;
227 section1 = *((const IMAGE_SECTION_HEADER **)arg1);
228 section2 = *((const IMAGE_SECTION_HEADER **)arg2);
230 if (section1->VirtualAddress < section2->VirtualAddress)
232 else if (section1->VirtualAddress == section2->VirtualAddress)
239 * efi_image_parse - parse a PE image
240 * @efi: Pointer to image
242 * @regp: Pointer to a list of regions
243 * @auth: Pointer to a pointer to authentication data in PE
244 * @auth_len: Size of @auth
246 * Parse image binary in PE32(+) format, assuming that sanity of PE image
247 * has been checked by a caller.
248 * On success, an address of authentication data in @efi and its size will
249 * be returned in @auth and @auth_len, respectively.
251 * Return: true on success, false on error
253 bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
254 WIN_CERTIFICATE **auth, size_t *auth_len)
256 struct efi_image_regions *regs;
257 IMAGE_DOS_HEADER *dos;
258 IMAGE_NT_HEADERS32 *nt;
259 IMAGE_SECTION_HEADER *sections, **sorted;
260 int num_regions, num_sections, i;
261 int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
262 u32 align, size, authsz, authoff;
266 nt = (void *)(efi + dos->e_lfanew);
269 * Count maximum number of regions to be digested.
270 * We don't have to have an exact number here.
271 * See efi_image_region_add()'s in parsing below.
273 num_regions = 3; /* for header */
274 num_regions += nt->FileHeader.NumberOfSections;
275 num_regions++; /* for extra */
277 regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
281 regs->max = num_regions;
284 * Collect data regions for hash calculation
287 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
288 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
289 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
292 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
293 if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
294 efi_image_region_add(regs,
296 efi + opt->SizeOfHeaders, 0);
298 /* Skip Certificates Table */
299 efi_image_region_add(regs,
301 &opt->DataDirectory[ctidx], 0);
302 efi_image_region_add(regs,
303 &opt->DataDirectory[ctidx] + 1,
304 efi + opt->SizeOfHeaders, 0);
307 bytes_hashed = opt->SizeOfHeaders;
308 align = opt->FileAlignment;
309 authoff = opt->DataDirectory[ctidx].VirtualAddress;
310 authsz = opt->DataDirectory[ctidx].Size;
311 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
312 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
314 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
315 efi_image_region_add(regs, &opt->CheckSum + 1,
316 &opt->DataDirectory[ctidx], 0);
317 efi_image_region_add(regs, &opt->DataDirectory[ctidx] + 1,
318 efi + opt->SizeOfHeaders, 0);
320 bytes_hashed = opt->SizeOfHeaders;
321 align = opt->FileAlignment;
322 authoff = opt->DataDirectory[ctidx].VirtualAddress;
323 authsz = opt->DataDirectory[ctidx].Size;
325 debug("%s: Invalid optional header magic %x\n", __func__,
326 nt->OptionalHeader.Magic);
331 num_sections = nt->FileHeader.NumberOfSections;
332 sections = (void *)((uint8_t *)&nt->OptionalHeader +
333 nt->FileHeader.SizeOfOptionalHeader);
334 sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
336 debug("%s: Out of memory\n", __func__);
341 * Make sure the section list is in ascending order.
343 for (i = 0; i < num_sections; i++)
344 sorted[i] = §ions[i];
345 qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
347 for (i = 0; i < num_sections; i++) {
348 if (!sorted[i]->SizeOfRawData)
351 size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
352 efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
353 efi + sorted[i]->PointerToRawData + size,
355 debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
357 sorted[i]->PointerToRawData,
358 sorted[i]->PointerToRawData + size,
359 sorted[i]->VirtualAddress,
360 sorted[i]->VirtualAddress
361 + sorted[i]->Misc.VirtualSize);
363 bytes_hashed += size;
367 /* 3. Extra data excluding Certificates Table */
368 if (bytes_hashed + authsz < len) {
369 debug("extra data for hash: %lu\n",
370 len - (bytes_hashed + authsz));
371 efi_image_region_add(regs, efi + bytes_hashed,
372 efi + len - authsz, 0);
375 /* Return Certificates Table */
377 if (len < authoff + authsz) {
378 debug("%s: Size for auth too large: %u >= %zu\n",
379 __func__, authsz, len - authoff);
382 if (authsz < sizeof(*auth)) {
383 debug("%s: Size for auth too small: %u < %zu\n",
384 __func__, authsz, sizeof(*auth));
387 *auth = efi + authoff;
389 debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff, authsz);
406 * efi_image_unsigned_authenticate - authenticate unsigned image with
408 * @regs: List of regions to be verified
410 * If an image is not signed, it doesn't have a signature. In this case,
411 * its message digest is calculated and it will be compared with one of
412 * hash values stored in signature databases.
414 * Return: true if authenticated, false if not
416 static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs)
418 struct efi_signature_store *db = NULL, *dbx = NULL;
421 dbx = efi_sigstore_parse_sigdb(L"dbx");
423 debug("Getting signature database(dbx) failed\n");
427 db = efi_sigstore_parse_sigdb(L"db");
429 debug("Getting signature database(db) failed\n");
433 /* try black-list first */
434 if (efi_signature_verify_with_sigdb(regs, NULL, dbx, NULL)) {
435 debug("Image is not signed and rejected by \"dbx\"\n");
440 if (efi_signature_verify_with_sigdb(regs, NULL, db, NULL))
443 debug("Image is not signed and not found in \"db\" or \"dbx\"\n");
446 efi_sigstore_free(db);
447 efi_sigstore_free(dbx);
453 * efi_image_authenticate - verify a signature of signed image
454 * @efi: Pointer to image
455 * @efi_size: Size of @efi
457 * A signed image should have its signature stored in a table of its PE header.
458 * So if an image is signed and only if if its signature is verified using
459 * signature databases, an image is authenticated.
460 * If an image is not signed, its validity is checked by using
461 * efi_image_unsigned_authenticated().
463 * When AuditMode==0, if the image's signature is not found in
464 * the authorized database, or is found in the forbidden database,
465 * the image will not be started and instead, information about it
466 * will be placed in this table.
467 * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
468 * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
469 * in the certificate table of every image that is validated.
471 * Return: true if authenticated, false if not
473 static bool efi_image_authenticate(void *efi, size_t efi_size)
475 struct efi_image_regions *regs = NULL;
476 WIN_CERTIFICATE *wincerts = NULL, *wincert;
478 struct pkcs7_message *msg = NULL;
479 struct efi_signature_store *db = NULL, *dbx = NULL;
480 struct x509_certificate *cert = NULL;
481 void *new_efi = NULL;
485 if (!efi_secure_boot_enabled())
489 * Size must be 8-byte aligned and the trailing bytes must be
490 * zero'ed. Otherwise hash value may be incorrect.
492 if (efi_size & 0x7) {
493 new_efi_size = (efi_size + 0x7) & ~0x7ULL;
494 new_efi = calloc(new_efi_size, 1);
497 memcpy(new_efi, efi, efi_size);
499 efi_size = new_efi_size;
502 if (!efi_image_parse(efi, efi_size, ®s, &wincerts,
504 debug("Parsing PE executable image failed\n");
509 /* The image is not signed */
510 ret = efi_image_unsigned_authenticate(regs);
516 * verify signature using db and dbx
518 db = efi_sigstore_parse_sigdb(L"db");
520 debug("Getting signature database(db) failed\n");
524 dbx = efi_sigstore_parse_sigdb(L"dbx");
526 debug("Getting signature database(dbx) failed\n");
530 /* go through WIN_CERTIFICATE list */
531 for (wincert = wincerts;
532 (void *)wincert < (void *)wincerts + wincerts_len;
533 wincert = (void *)wincert + ALIGN(wincert->dwLength, 8)) {
534 if (wincert->dwLength < sizeof(*wincert)) {
535 debug("%s: dwLength too small: %u < %zu\n",
536 __func__, wincert->dwLength, sizeof(*wincert));
539 msg = pkcs7_parse_message((void *)wincert + sizeof(*wincert),
540 wincert->dwLength - sizeof(*wincert));
542 debug("Parsing image's signature failed\n");
546 /* try black-list first */
547 if (efi_signature_verify_with_sigdb(regs, msg, dbx, NULL)) {
548 debug("Signature was rejected by \"dbx\"\n");
552 if (!efi_signature_verify_signers(msg, dbx)) {
553 debug("Signer was rejected by \"dbx\"\n");
560 if (!efi_signature_verify_with_sigdb(regs, msg, db, &cert)) {
561 debug("Verifying signature with \"db\" failed\n");
567 if (!efi_signature_verify_cert(cert, dbx)) {
568 debug("Certificate was rejected by \"dbx\"\n");
576 x509_free_certificate(cert);
577 efi_sigstore_free(db);
578 efi_sigstore_free(dbx);
579 pkcs7_free_message(msg);
586 static bool efi_image_authenticate(void *efi, size_t efi_size)
590 #endif /* CONFIG_EFI_SECURE_BOOT */
593 * efi_load_pe() - relocate EFI binary
595 * This function loads all sections from a PE binary into a newly reserved
596 * piece of memory. On success the entry point is returned as handle->entry.
598 * @handle: loaded image handle
599 * @efi: pointer to the EFI binary
600 * @efi_size: size of @efi binary
601 * @loaded_image_info: loaded image protocol
602 * Return: status code
604 efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
605 void *efi, size_t efi_size,
606 struct efi_loaded_image *loaded_image_info)
608 IMAGE_NT_HEADERS32 *nt;
609 IMAGE_DOS_HEADER *dos;
610 IMAGE_SECTION_HEADER *sections;
614 const IMAGE_BASE_RELOCATION *rel;
615 unsigned long rel_size;
616 int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
618 unsigned long virt_size = 0;
622 /* Sanity check for a file header */
623 if (efi_size < sizeof(*dos)) {
624 printf("%s: Truncated DOS Header\n", __func__);
625 ret = EFI_LOAD_ERROR;
630 if (dos->e_magic != IMAGE_DOS_SIGNATURE) {
631 printf("%s: Invalid DOS Signature\n", __func__);
632 ret = EFI_LOAD_ERROR;
636 /* assume sizeof(IMAGE_NT_HEADERS32) <= sizeof(IMAGE_NT_HEADERS64) */
637 if (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32)) {
638 printf("%s: Invalid offset for Extended Header\n", __func__);
639 ret = EFI_LOAD_ERROR;
643 nt = (void *) ((char *)efi + dos->e_lfanew);
644 if ((nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) &&
645 (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS64))) {
646 printf("%s: Invalid offset for Extended Header\n", __func__);
647 ret = EFI_LOAD_ERROR;
651 if (nt->Signature != IMAGE_NT_SIGNATURE) {
652 printf("%s: Invalid NT Signature\n", __func__);
653 ret = EFI_LOAD_ERROR;
657 for (i = 0; machines[i]; i++)
658 if (machines[i] == nt->FileHeader.Machine) {
664 printf("%s: Machine type 0x%04x is not supported\n",
665 __func__, nt->FileHeader.Machine);
666 ret = EFI_LOAD_ERROR;
670 num_sections = nt->FileHeader.NumberOfSections;
671 sections = (void *)&nt->OptionalHeader +
672 nt->FileHeader.SizeOfOptionalHeader;
674 if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
676 printf("%s: Invalid number of sections: %d\n",
677 __func__, num_sections);
678 ret = EFI_LOAD_ERROR;
682 /* Authenticate an image */
683 if (efi_image_authenticate(efi, efi_size))
684 handle->auth_status = EFI_IMAGE_AUTH_PASSED;
686 handle->auth_status = EFI_IMAGE_AUTH_FAILED;
688 /* Calculate upper virtual address boundary */
689 for (i = num_sections - 1; i >= 0; i--) {
690 IMAGE_SECTION_HEADER *sec = §ions[i];
691 virt_size = max_t(unsigned long, virt_size,
692 sec->VirtualAddress + sec->Misc.VirtualSize);
695 /* Read 32/64bit specific header bits */
696 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
697 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
698 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
699 image_base = opt->ImageBase;
700 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
701 handle->image_type = opt->Subsystem;
702 efi_reloc = efi_alloc(virt_size,
703 loaded_image_info->image_code_type);
705 printf("%s: Could not allocate %lu bytes\n",
706 __func__, virt_size);
707 ret = EFI_OUT_OF_RESOURCES;
710 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
711 rel_size = opt->DataDirectory[rel_idx].Size;
712 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
713 virt_size = ALIGN(virt_size, opt->SectionAlignment);
714 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
715 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
716 image_base = opt->ImageBase;
717 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
718 handle->image_type = opt->Subsystem;
719 efi_reloc = efi_alloc(virt_size,
720 loaded_image_info->image_code_type);
722 printf("%s: Could not allocate %lu bytes\n",
723 __func__, virt_size);
724 ret = EFI_OUT_OF_RESOURCES;
727 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
728 rel_size = opt->DataDirectory[rel_idx].Size;
729 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
730 virt_size = ALIGN(virt_size, opt->SectionAlignment);
732 printf("%s: Invalid optional header magic %x\n", __func__,
733 nt->OptionalHeader.Magic);
734 ret = EFI_LOAD_ERROR;
738 /* Copy PE headers */
739 memcpy(efi_reloc, efi,
742 + nt->FileHeader.SizeOfOptionalHeader
743 + num_sections * sizeof(IMAGE_SECTION_HEADER));
745 /* Load sections into RAM */
746 for (i = num_sections - 1; i >= 0; i--) {
747 IMAGE_SECTION_HEADER *sec = §ions[i];
748 memset(efi_reloc + sec->VirtualAddress, 0,
749 sec->Misc.VirtualSize);
750 memcpy(efi_reloc + sec->VirtualAddress,
751 efi + sec->PointerToRawData,
755 /* Run through relocations */
756 if (efi_loader_relocate(rel, rel_size, efi_reloc,
757 (unsigned long)image_base) != EFI_SUCCESS) {
758 efi_free_pages((uintptr_t) efi_reloc,
759 (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
760 ret = EFI_LOAD_ERROR;
765 flush_cache((ulong)efi_reloc,
766 ALIGN(virt_size, EFI_CACHELINE_SIZE));
767 invalidate_icache_all();
769 /* Populate the loaded image interface bits */
770 loaded_image_info->image_base = efi_reloc;
771 loaded_image_info->image_size = virt_size;
773 if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
776 return EFI_SECURITY_VIOLATION;