efi_loader: image_loader: support image authentication
[oweals/u-boot.git] / lib / efi_loader / efi_image_loader.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI image loader
4  *
5  *  based partly on wine code
6  *
7  *  Copyright (c) 2016 Alexander Graf
8  */
9
10 #include <common.h>
11 #include <cpu_func.h>
12 #include <efi_loader.h>
13 #include <malloc.h>
14 #include <pe.h>
15 #include <sort.h>
16 #include "../lib/crypto/pkcs7_parser.h"
17
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;
26
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,
34 #endif
35
36 #if defined(__x86_64__)
37         IMAGE_FILE_MACHINE_AMD64,
38 #elif defined(__i386__)
39         IMAGE_FILE_MACHINE_I386,
40 #endif
41
42 #if defined(__riscv) && (__riscv_xlen == 32)
43         IMAGE_FILE_MACHINE_RISCV32,
44 #endif
45
46 #if defined(__riscv) && (__riscv_xlen == 64)
47         IMAGE_FILE_MACHINE_RISCV64,
48 #endif
49         0 };
50
51 /**
52  * efi_print_image_info() - print information about a loaded image
53  *
54  * If the program counter is located within the image the offset to the base
55  * address is shown.
56  *
57  * @obj:        EFI object
58  * @image:      loaded image
59  * @pc:         program counter (use NULL to suppress offset output)
60  * Return:      status code
61  */
62 static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
63                                          struct efi_loaded_image *image,
64                                          void *pc)
65 {
66         printf("UEFI 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);
72         if (image->file_path)
73                 printf(" '%pD'", image->file_path);
74         printf("\n");
75         return EFI_SUCCESS;
76 }
77
78 /**
79  * efi_print_image_infos() - print information about all loaded images
80  *
81  * @pc:         program counter (use NULL to suppress offset output)
82  */
83 void efi_print_image_infos(void *pc)
84 {
85         struct efi_object *efiobj;
86         struct efi_handler *handler;
87
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)) {
91                                 efi_print_image_info(
92                                         (struct efi_loaded_image_obj *)efiobj,
93                                         handler->protocol_interface, pc);
94                         }
95                 }
96         }
97 }
98
99 /**
100  * efi_loader_relocate() - relocate UEFI binary
101  *
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
107  */
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)
111 {
112         unsigned long delta = (unsigned long)efi_reloc - pref_address;
113         const IMAGE_BASE_RELOCATION *end;
114         int i;
115
116         if (delta == 0)
117                 return EFI_SUCCESS;
118
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);
123                 while (i--) {
124                         uint32_t offset = (uint32_t)(*relocs & 0xfff) +
125                                           rel->VirtualAddress;
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;
130
131                         switch (type) {
132                         case IMAGE_REL_BASED_ABSOLUTE:
133                                 break;
134                         case IMAGE_REL_BASED_HIGH:
135                                 *x16 += ((uint32_t)delta) >> 16;
136                                 break;
137                         case IMAGE_REL_BASED_LOW:
138                                 *x16 += (uint16_t)delta;
139                                 break;
140                         case IMAGE_REL_BASED_HIGHLOW:
141                                 *x32 += (uint32_t)delta;
142                                 break;
143                         case IMAGE_REL_BASED_DIR64:
144                                 *x64 += (uint64_t)delta;
145                                 break;
146 #ifdef __riscv
147                         case IMAGE_REL_BASED_RISCV_HI20:
148                                 *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
149                                         (*x32 & 0x00000fff);
150                                 break;
151                         case IMAGE_REL_BASED_RISCV_LOW12I:
152                         case IMAGE_REL_BASED_RISCV_LOW12S:
153                                 /* We know that we're 4k aligned */
154                                 if (delta & 0xfff) {
155                                         printf("Unsupported reloc offset\n");
156                                         return EFI_LOAD_ERROR;
157                                 }
158                                 break;
159 #endif
160                         default:
161                                 printf("Unknown Relocation off %x type %x\n",
162                                        offset, type);
163                                 return EFI_LOAD_ERROR;
164                         }
165                         relocs++;
166                 }
167                 rel = (const IMAGE_BASE_RELOCATION *)relocs;
168         }
169         return EFI_SUCCESS;
170 }
171
172 void __weak invalidate_icache_all(void)
173 {
174         /* If the system doesn't support icache_all flush, cross our fingers */
175 }
176
177 /**
178  * efi_set_code_and_data_type() - determine the memory types to be used for code
179  *                                and data.
180  *
181  * @loaded_image_info:  image descriptor
182  * @image_type:         field Subsystem of the optional header for
183  *                      Windows specific field
184  */
185 static void efi_set_code_and_data_type(
186                         struct efi_loaded_image *loaded_image_info,
187                         uint16_t image_type)
188 {
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;
193                 break;
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;
197                 break;
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;
202                 break;
203         default:
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;
208                 break;
209         }
210 }
211
212 #ifdef CONFIG_EFI_SECURE_BOOT
213 /**
214  * cmp_pe_section - compare two sections
215  * @arg1:       Pointer to pointer to first section
216  * @arg2:       Pointer to pointer to second section
217  *
218  * Compare two sections in PE image.
219  *
220  * Return:      -1, 0, 1 respectively if arg1 < arg2, arg1 == arg2 or
221  *              arg1 > arg2
222  */
223 static int cmp_pe_section(const void *arg1, const void *arg2)
224 {
225         const IMAGE_SECTION_HEADER *section1, *section2;
226
227         section1 = *((const IMAGE_SECTION_HEADER **)arg1);
228         section2 = *((const IMAGE_SECTION_HEADER **)arg2);
229
230         if (section1->VirtualAddress < section2->VirtualAddress)
231                 return -1;
232         else if (section1->VirtualAddress == section2->VirtualAddress)
233                 return 0;
234         else
235                 return 1;
236 }
237
238 /**
239  * efi_image_parse - parse a PE image
240  * @efi:        Pointer to image
241  * @len:        Size of @efi
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
245  *
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.
250  *
251  * Return:      true on success, false on error
252  */
253 bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
254                      WIN_CERTIFICATE **auth, size_t *auth_len)
255 {
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;
263         size_t bytes_hashed;
264
265         dos = (void *)efi;
266         nt = (void *)(efi + dos->e_lfanew);
267
268         /*
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.
272          */
273         num_regions = 3; /* for header */
274         num_regions += nt->FileHeader.NumberOfSections;
275         num_regions++; /* for extra */
276
277         regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
278                       1);
279         if (!regs)
280                 goto err;
281         regs->max = num_regions;
282
283         /*
284          * Collect data regions for hash calculation
285          * 1. File headers
286          */
287         if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
288                 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
289                 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
290
291                 /* Skip CheckSum */
292                 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
293                 if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
294                         efi_image_region_add(regs,
295                                              &opt->CheckSum + 1,
296                                              efi + opt->SizeOfHeaders, 0);
297                 } else {
298                         /* Skip Certificates Table */
299                         efi_image_region_add(regs,
300                                              &opt->CheckSum + 1,
301                                              &opt->DataDirectory[ctidx], 0);
302                         efi_image_region_add(regs,
303                                              &opt->DataDirectory[ctidx] + 1,
304                                              efi + opt->SizeOfHeaders, 0);
305                 }
306
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;
313
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);
319
320                 bytes_hashed = opt->SizeOfHeaders;
321                 align = opt->FileAlignment;
322                 authoff = opt->DataDirectory[ctidx].VirtualAddress;
323                 authsz = opt->DataDirectory[ctidx].Size;
324         } else {
325                 debug("%s: Invalid optional header magic %x\n", __func__,
326                       nt->OptionalHeader.Magic);
327                 goto err;
328         }
329
330         /* 2. Sections */
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);
335         if (!sorted) {
336                 debug("%s: Out of memory\n", __func__);
337                 goto err;
338         }
339
340         /*
341          * Make sure the section list is in ascending order.
342          */
343         for (i = 0; i < num_sections; i++)
344                 sorted[i] = &sections[i];
345         qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
346
347         for (i = 0; i < num_sections; i++) {
348                 if (!sorted[i]->SizeOfRawData)
349                         continue;
350
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,
354                                      0);
355                 debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
356                       i, sorted[i]->Name,
357                       sorted[i]->PointerToRawData,
358                       sorted[i]->PointerToRawData + size,
359                       sorted[i]->VirtualAddress,
360                       sorted[i]->VirtualAddress
361                         + sorted[i]->Misc.VirtualSize);
362
363                 bytes_hashed += size;
364         }
365         free(sorted);
366
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);
373         }
374
375         /* Return Certificates Table */
376         if (authsz) {
377                 if (len < authoff + authsz) {
378                         debug("%s: Size for auth too large: %u >= %zu\n",
379                               __func__, authsz, len - authoff);
380                         goto err;
381                 }
382                 if (authsz < sizeof(*auth)) {
383                         debug("%s: Size for auth too small: %u < %zu\n",
384                               __func__, authsz, sizeof(*auth));
385                         goto err;
386                 }
387                 *auth = efi + authoff;
388                 *auth_len = authsz;
389                 debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff, authsz);
390         } else {
391                 *auth = NULL;
392                 *auth_len = 0;
393         }
394
395         *regp = regs;
396
397         return true;
398
399 err:
400         free(regs);
401
402         return false;
403 }
404
405 /**
406  * efi_image_unsigned_authenticate - authenticate unsigned image with
407  * SHA256 hash
408  * @regs:       List of regions to be verified
409  *
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.
413  *
414  * Return:      true if authenticated, false if not
415  */
416 static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs)
417 {
418         struct efi_signature_store *db = NULL, *dbx = NULL;
419         bool ret = false;
420
421         dbx = efi_sigstore_parse_sigdb(L"dbx");
422         if (!dbx) {
423                 debug("Getting signature database(dbx) failed\n");
424                 goto out;
425         }
426
427         db = efi_sigstore_parse_sigdb(L"db");
428         if (!db) {
429                 debug("Getting signature database(db) failed\n");
430                 goto out;
431         }
432
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");
436                 goto out;
437         }
438
439         /* try white-list */
440         if (efi_signature_verify_with_sigdb(regs, NULL, db, NULL))
441                 ret = true;
442         else
443                 debug("Image is not signed and not found in \"db\" or \"dbx\"\n");
444
445 out:
446         efi_sigstore_free(db);
447         efi_sigstore_free(dbx);
448
449         return ret;
450 }
451
452 /**
453  * efi_image_authenticate - verify a signature of signed image
454  * @efi:        Pointer to image
455  * @efi_size:   Size of @efi
456  *
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().
462  * TODO:
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.
470  *
471  * Return:      true if authenticated, false if not
472  */
473 static bool efi_image_authenticate(void *efi, size_t efi_size)
474 {
475         struct efi_image_regions *regs = NULL;
476         WIN_CERTIFICATE *wincerts = NULL, *wincert;
477         size_t wincerts_len;
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;
482         size_t new_efi_size;
483         bool ret = false;
484
485         if (!efi_secure_boot_enabled())
486                 return true;
487
488         /*
489          * Size must be 8-byte aligned and the trailing bytes must be
490          * zero'ed. Otherwise hash value may be incorrect.
491          */
492         if (efi_size & 0x7) {
493                 new_efi_size = (efi_size + 0x7) & ~0x7ULL;
494                 new_efi = calloc(new_efi_size, 1);
495                 if (!new_efi)
496                         return false;
497                 memcpy(new_efi, efi, efi_size);
498                 efi = new_efi;
499                 efi_size = new_efi_size;
500         }
501
502         if (!efi_image_parse(efi, efi_size, &regs, &wincerts,
503                              &wincerts_len)) {
504                 debug("Parsing PE executable image failed\n");
505                 goto err;
506         }
507
508         if (!wincerts) {
509                 /* The image is not signed */
510                 ret = efi_image_unsigned_authenticate(regs);
511
512                 goto err;
513         }
514
515         /*
516          * verify signature using db and dbx
517          */
518         db = efi_sigstore_parse_sigdb(L"db");
519         if (!db) {
520                 debug("Getting signature database(db) failed\n");
521                 goto err;
522         }
523
524         dbx = efi_sigstore_parse_sigdb(L"dbx");
525         if (!dbx) {
526                 debug("Getting signature database(dbx) failed\n");
527                 goto err;
528         }
529
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));
537                         goto err;
538                 }
539                 msg = pkcs7_parse_message((void *)wincert + sizeof(*wincert),
540                                           wincert->dwLength - sizeof(*wincert));
541                 if (!msg) {
542                         debug("Parsing image's signature failed\n");
543                         goto err;
544                 }
545
546                 /* try black-list first */
547                 if (efi_signature_verify_with_sigdb(regs, msg, dbx, NULL)) {
548                         debug("Signature was rejected by \"dbx\"\n");
549                         goto err;
550                 }
551
552                 if (!efi_signature_verify_signers(msg, dbx)) {
553                         debug("Signer was rejected by \"dbx\"\n");
554                         goto err;
555                 } else {
556                         ret = true;
557                 }
558
559                 /* try white-list */
560                 if (!efi_signature_verify_with_sigdb(regs, msg, db, &cert)) {
561                         debug("Verifying signature with \"db\" failed\n");
562                         goto err;
563                 } else {
564                         ret = true;
565                 }
566
567                 if (!efi_signature_verify_cert(cert, dbx)) {
568                         debug("Certificate was rejected by \"dbx\"\n");
569                         goto err;
570                 } else {
571                         ret = true;
572                 }
573         }
574
575 err:
576         x509_free_certificate(cert);
577         efi_sigstore_free(db);
578         efi_sigstore_free(dbx);
579         pkcs7_free_message(msg);
580         free(regs);
581         free(new_efi);
582
583         return ret;
584 }
585 #else
586 static bool efi_image_authenticate(void *efi, size_t efi_size)
587 {
588         return true;
589 }
590 #endif /* CONFIG_EFI_SECURE_BOOT */
591
592 /**
593  * efi_load_pe() - relocate EFI binary
594  *
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.
597  *
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
603  */
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)
607 {
608         IMAGE_NT_HEADERS32 *nt;
609         IMAGE_DOS_HEADER *dos;
610         IMAGE_SECTION_HEADER *sections;
611         int num_sections;
612         void *efi_reloc;
613         int i;
614         const IMAGE_BASE_RELOCATION *rel;
615         unsigned long rel_size;
616         int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
617         uint64_t image_base;
618         unsigned long virt_size = 0;
619         int supported = 0;
620         efi_status_t ret;
621
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;
626                 goto err;
627         }
628
629         dos = efi;
630         if (dos->e_magic != IMAGE_DOS_SIGNATURE) {
631                 printf("%s: Invalid DOS Signature\n", __func__);
632                 ret = EFI_LOAD_ERROR;
633                 goto err;
634         }
635
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;
640                 goto err;
641         }
642
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;
648                 goto err;
649         }
650
651         if (nt->Signature != IMAGE_NT_SIGNATURE) {
652                 printf("%s: Invalid NT Signature\n", __func__);
653                 ret = EFI_LOAD_ERROR;
654                 goto err;
655         }
656
657         for (i = 0; machines[i]; i++)
658                 if (machines[i] == nt->FileHeader.Machine) {
659                         supported = 1;
660                         break;
661                 }
662
663         if (!supported) {
664                 printf("%s: Machine type 0x%04x is not supported\n",
665                        __func__, nt->FileHeader.Machine);
666                 ret = EFI_LOAD_ERROR;
667                 goto err;
668         }
669
670         num_sections = nt->FileHeader.NumberOfSections;
671         sections = (void *)&nt->OptionalHeader +
672                             nt->FileHeader.SizeOfOptionalHeader;
673
674         if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
675                         - efi)) {
676                 printf("%s: Invalid number of sections: %d\n",
677                        __func__, num_sections);
678                 ret = EFI_LOAD_ERROR;
679                 goto err;
680         }
681
682         /* Authenticate an image */
683         if (efi_image_authenticate(efi, efi_size))
684                 handle->auth_status = EFI_IMAGE_AUTH_PASSED;
685         else
686                 handle->auth_status = EFI_IMAGE_AUTH_FAILED;
687
688         /* Calculate upper virtual address boundary */
689         for (i = num_sections - 1; i >= 0; i--) {
690                 IMAGE_SECTION_HEADER *sec = &sections[i];
691                 virt_size = max_t(unsigned long, virt_size,
692                                   sec->VirtualAddress + sec->Misc.VirtualSize);
693         }
694
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);
704                 if (!efi_reloc) {
705                         printf("%s: Could not allocate %lu bytes\n",
706                                __func__, virt_size);
707                         ret = EFI_OUT_OF_RESOURCES;
708                         goto err;
709                 }
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);
721                 if (!efi_reloc) {
722                         printf("%s: Could not allocate %lu bytes\n",
723                                __func__, virt_size);
724                         ret = EFI_OUT_OF_RESOURCES;
725                         goto err;
726                 }
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);
731         } else {
732                 printf("%s: Invalid optional header magic %x\n", __func__,
733                        nt->OptionalHeader.Magic);
734                 ret = EFI_LOAD_ERROR;
735                 goto err;
736         }
737
738         /* Copy PE headers */
739         memcpy(efi_reloc, efi,
740                sizeof(*dos)
741                  + sizeof(*nt)
742                  + nt->FileHeader.SizeOfOptionalHeader
743                  + num_sections * sizeof(IMAGE_SECTION_HEADER));
744
745         /* Load sections into RAM */
746         for (i = num_sections - 1; i >= 0; i--) {
747                 IMAGE_SECTION_HEADER *sec = &sections[i];
748                 memset(efi_reloc + sec->VirtualAddress, 0,
749                        sec->Misc.VirtualSize);
750                 memcpy(efi_reloc + sec->VirtualAddress,
751                        efi + sec->PointerToRawData,
752                        sec->SizeOfRawData);
753         }
754
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;
761                 goto err;
762         }
763
764         /* Flush cache */
765         flush_cache((ulong)efi_reloc,
766                     ALIGN(virt_size, EFI_CACHELINE_SIZE));
767         invalidate_icache_all();
768
769         /* Populate the loaded image interface bits */
770         loaded_image_info->image_base = efi_reloc;
771         loaded_image_info->image_size = virt_size;
772
773         if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
774                 return EFI_SUCCESS;
775         else
776                 return EFI_SECURITY_VIOLATION;
777
778 err:
779         return ret;
780 }