blob: d002eb0c7440755974336037948143471cfe92a6 [file] [log] [blame]
Tom Rini70df9d62018-05-07 17:02:21 -04001// SPDX-License-Identifier: GPL-2.0+
Alexander Graf4e0c1c12016-03-04 01:09:58 +01002/*
3 * EFI image loader
4 *
5 * based partly on wine code
6 *
7 * Copyright (c) 2016 Alexander Graf
Alexander Graf4e0c1c12016-03-04 01:09:58 +01008 */
9
Heinrich Schuchardteb676572020-08-25 17:51:20 +000010#define LOG_CATEGORY LOGC_EFI
11
Simon Glass63334482019-11-14 12:57:39 -070012#include <cpu_func.h>
Alexander Graf4e0c1c12016-03-04 01:09:58 +010013#include <efi_loader.h>
Heinrich Schuchardteb676572020-08-25 17:51:20 +000014#include <log.h>
AKASHI Takahiro0e104e32020-04-14 11:51:44 +090015#include <malloc.h>
Simon Glass567b62c2024-11-27 11:17:19 -060016#include <mapmem.h>
Alexander Graf4e0c1c12016-03-04 01:09:58 +010017#include <pe.h>
AKASHI Takahiro0e104e32020-04-14 11:51:44 +090018#include <sort.h>
AKASHI Takahiroe669c2d2022-07-05 14:48:14 +090019#include <crypto/mscode.h>
Heinrich Schuchardt2aa09422020-05-07 17:57:43 +020020#include <crypto/pkcs7_parser.h>
Patrick Wildtfbc745c2020-05-07 02:17:14 +020021#include <linux/err.h>
Alexander Graf4e0c1c12016-03-04 01:09:58 +010022
Rob Clarkc84c1102017-09-13 18:05:38 -040023const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
Heinrich Schuchardt788ad412019-04-20 07:39:11 +020024const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
25const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
26const efi_guid_t efi_guid_loaded_image_device_path =
27 EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
Rob Clark53142032017-09-13 18:05:34 -040028const efi_guid_t efi_simple_file_system_protocol_guid =
29 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
30const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
Alexander Graf4e0c1c12016-03-04 01:09:58 +010031
Ivan Gorinov749d5c12018-04-05 18:32:06 -070032static int machines[] = {
Alexander Graf8aec3082018-06-18 17:22:57 +020033#if defined(__aarch64__)
Ivan Gorinov749d5c12018-04-05 18:32:06 -070034 IMAGE_FILE_MACHINE_ARM64,
Alexander Graf8aec3082018-06-18 17:22:57 +020035#elif defined(__arm__)
Ivan Gorinov749d5c12018-04-05 18:32:06 -070036 IMAGE_FILE_MACHINE_ARM,
37 IMAGE_FILE_MACHINE_THUMB,
38 IMAGE_FILE_MACHINE_ARMNT,
39#endif
40
Alexander Graf8aec3082018-06-18 17:22:57 +020041#if defined(__x86_64__)
Ivan Gorinov749d5c12018-04-05 18:32:06 -070042 IMAGE_FILE_MACHINE_AMD64,
Alexander Graf8aec3082018-06-18 17:22:57 +020043#elif defined(__i386__)
Ivan Gorinov749d5c12018-04-05 18:32:06 -070044 IMAGE_FILE_MACHINE_I386,
45#endif
46
Alexander Graf8aec3082018-06-18 17:22:57 +020047#if defined(__riscv) && (__riscv_xlen == 32)
Ivan Gorinov749d5c12018-04-05 18:32:06 -070048 IMAGE_FILE_MACHINE_RISCV32,
49#endif
50
Alexander Graf8aec3082018-06-18 17:22:57 +020051#if defined(__riscv) && (__riscv_xlen == 64)
Ivan Gorinov749d5c12018-04-05 18:32:06 -070052 IMAGE_FILE_MACHINE_RISCV64,
53#endif
54 0 };
55
Heinrich Schuchardt0fcdb7a2019-02-16 15:22:13 +010056/**
57 * efi_print_image_info() - print information about a loaded image
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020058 *
59 * If the program counter is located within the image the offset to the base
60 * address is shown.
61 *
Heinrich Schuchardt3c3a7352018-09-23 17:21:51 +020062 * @obj: EFI object
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020063 * @image: loaded image
64 * @pc: program counter (use NULL to suppress offset output)
Heinrich Schuchardt0fcdb7a2019-02-16 15:22:13 +010065 * Return: status code
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020066 */
Heinrich Schuchardt3c3a7352018-09-23 17:21:51 +020067static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
68 struct efi_loaded_image *image,
69 void *pc)
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020070{
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020071 printf("UEFI image");
72 printf(" [0x%p:0x%p]",
AKASHI Takahiro068879a2018-10-11 04:09:58 -070073 image->image_base, image->image_base + image->image_size - 1);
74 if (pc && pc >= image->image_base &&
75 pc < image->image_base + image->image_size)
76 printf(" pc=0x%zx", pc - image->image_base);
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020077 if (image->file_path)
78 printf(" '%pD'", image->file_path);
79 printf("\n");
80 return EFI_SUCCESS;
81}
82
Heinrich Schuchardt0fcdb7a2019-02-16 15:22:13 +010083/**
84 * efi_print_image_infos() - print information about all loaded images
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020085 *
86 * @pc: program counter (use NULL to suppress offset output)
87 */
88void efi_print_image_infos(void *pc)
89{
90 struct efi_object *efiobj;
91 struct efi_handler *handler;
92
93 list_for_each_entry(efiobj, &efi_obj_list, link) {
94 list_for_each_entry(handler, &efiobj->protocols, link) {
Heinrich Schuchardt2a22db92022-03-09 19:56:23 +010095 if (!guidcmp(&handler->guid, &efi_guid_loaded_image)) {
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020096 efi_print_image_info(
Heinrich Schuchardt3c3a7352018-09-23 17:21:51 +020097 (struct efi_loaded_image_obj *)efiobj,
Heinrich Schuchardt83d96b72018-04-05 11:56:21 +020098 handler->protocol_interface, pc);
99 }
100 }
101 }
102}
103
Heinrich Schuchardt0fcdb7a2019-02-16 15:22:13 +0100104/**
105 * efi_loader_relocate() - relocate UEFI binary
106 *
107 * @rel: pointer to the relocation table
108 * @rel_size: size of the relocation table in bytes
109 * @efi_reloc: actual load address of the image
110 * @pref_address: preferred load address of the image
111 * Return: status code
112 */
xypron.glpk@gmx.de6ec97d22017-07-04 00:12:58 +0200113static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700114 unsigned long rel_size, void *efi_reloc,
115 unsigned long pref_address)
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100116{
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700117 unsigned long delta = (unsigned long)efi_reloc - pref_address;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100118 const IMAGE_BASE_RELOCATION *end;
119 int i;
120
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700121 if (delta == 0)
122 return EFI_SUCCESS;
123
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100124 end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
Aleksandar Gerasimovski255c9492024-11-29 21:09:44 +0000125 while (rel + 1 < end && rel->SizeOfBlock) {
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100126 const uint16_t *relocs = (const uint16_t *)(rel + 1);
127 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
128 while (i--) {
Alexander Graf07032252016-08-18 23:45:18 +0200129 uint32_t offset = (uint32_t)(*relocs & 0xfff) +
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100130 rel->VirtualAddress;
131 int type = *relocs >> EFI_PAGE_SHIFT;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100132 uint64_t *x64 = efi_reloc + offset;
133 uint32_t *x32 = efi_reloc + offset;
134 uint16_t *x16 = efi_reloc + offset;
135
136 switch (type) {
137 case IMAGE_REL_BASED_ABSOLUTE:
138 break;
139 case IMAGE_REL_BASED_HIGH:
140 *x16 += ((uint32_t)delta) >> 16;
141 break;
142 case IMAGE_REL_BASED_LOW:
143 *x16 += (uint16_t)delta;
144 break;
145 case IMAGE_REL_BASED_HIGHLOW:
146 *x32 += (uint32_t)delta;
147 break;
148 case IMAGE_REL_BASED_DIR64:
149 *x64 += (uint64_t)delta;
150 break;
Alexander Graf71f91202018-06-05 19:20:32 +0200151#ifdef __riscv
152 case IMAGE_REL_BASED_RISCV_HI20:
153 *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
154 (*x32 & 0x00000fff);
155 break;
156 case IMAGE_REL_BASED_RISCV_LOW12I:
157 case IMAGE_REL_BASED_RISCV_LOW12S:
158 /* We know that we're 4k aligned */
159 if (delta & 0xfff) {
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000160 log_err("Unsupported reloc offset\n");
Alexander Graf71f91202018-06-05 19:20:32 +0200161 return EFI_LOAD_ERROR;
162 }
163 break;
164#endif
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100165 default:
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000166 log_err("Unknown Relocation off %x type %x\n",
167 offset, type);
xypron.glpk@gmx.de6ec97d22017-07-04 00:12:58 +0200168 return EFI_LOAD_ERROR;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100169 }
170 relocs++;
171 }
172 rel = (const IMAGE_BASE_RELOCATION *)relocs;
173 }
xypron.glpk@gmx.de6ec97d22017-07-04 00:12:58 +0200174 return EFI_SUCCESS;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100175}
176
Heinrich Schuchardt0fcdb7a2019-02-16 15:22:13 +0100177/**
178 * efi_set_code_and_data_type() - determine the memory types to be used for code
179 * and data.
Heinrich Schuchardtfaef0e72018-01-19 20:24:41 +0100180 *
Heinrich Schuchardt0fcdb7a2019-02-16 15:22:13 +0100181 * @loaded_image_info: image descriptor
182 * @image_type: field Subsystem of the optional header for
Heinrich Schuchardtfaef0e72018-01-19 20:24:41 +0100183 * Windows specific field
184 */
185static 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:
Heinrich Schuchardt467fd7a2018-01-31 18:45:35 +0000199 case IMAGE_SUBSYSTEM_EFI_ROM:
Heinrich Schuchardtfaef0e72018-01-19 20:24:41 +0100200 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:
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000204 log_err("invalid image type: %u\n", image_type);
Heinrich Schuchardtfaef0e72018-01-19 20:24:41 +0100205 /* 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
Masahisa Kojima915e4272021-05-14 09:53:36 +0900212/**
213 * efi_image_region_add() - add an entry of region
214 * @regs: Pointer to array of regions
215 * @start: Start address of region (included)
216 * @end: End address of region (excluded)
217 * @nocheck: flag against overlapped regions
218 *
Heinrich Schuchardt0ab00372021-06-09 00:21:24 +0200219 * Take one entry of region \[@start, @end\[ and insert it into the list.
Masahisa Kojima915e4272021-05-14 09:53:36 +0900220 *
221 * * If @nocheck is false, the list will be sorted ascending by address.
222 * Overlapping entries will not be allowed.
223 *
224 * * If @nocheck is true, the list will be sorted ascending by sequence
225 * of adding the entries. Overlapping is allowed.
226 *
227 * Return: status code
228 */
229efi_status_t efi_image_region_add(struct efi_image_regions *regs,
230 const void *start, const void *end,
231 int nocheck)
232{
233 struct image_region *reg;
234 int i, j;
235
236 if (regs->num >= regs->max) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900237 log_err("%s: no more room for regions\n", __func__);
Masahisa Kojima915e4272021-05-14 09:53:36 +0900238 return EFI_OUT_OF_RESOURCES;
239 }
240
241 if (end < start)
242 return EFI_INVALID_PARAMETER;
243
244 for (i = 0; i < regs->num; i++) {
245 reg = &regs->reg[i];
246 if (nocheck)
247 continue;
248
249 /* new data after registered region */
250 if (start >= reg->data + reg->size)
251 continue;
252
253 /* new data preceding registered region */
254 if (end <= reg->data) {
255 for (j = regs->num - 1; j >= i; j--)
256 memcpy(&regs->reg[j + 1], &regs->reg[j],
257 sizeof(*reg));
258 break;
259 }
260
261 /* new data overlapping registered region */
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900262 log_err("%s: new region already part of another\n", __func__);
Masahisa Kojima915e4272021-05-14 09:53:36 +0900263 return EFI_INVALID_PARAMETER;
264 }
265
266 reg = &regs->reg[i];
267 reg->data = start;
268 reg->size = end - start;
269 regs->num++;
270
271 return EFI_SUCCESS;
272}
273
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900274/**
Heinrich Schuchardt72bc7142020-05-30 06:44:48 +0200275 * cmp_pe_section() - compare virtual addresses of two PE image sections
276 * @arg1: pointer to pointer to first section header
277 * @arg2: pointer to pointer to second section header
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900278 *
Heinrich Schuchardt72bc7142020-05-30 06:44:48 +0200279 * Compare the virtual addresses of two sections of an portable executable.
280 * The arguments are defined as const void * to allow usage with qsort().
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900281 *
Heinrich Schuchardt72bc7142020-05-30 06:44:48 +0200282 * Return: -1 if the virtual address of arg1 is less than that of arg2,
283 * 0 if the virtual addresses are equal, 1 if the virtual address
284 * of arg1 is greater than that of arg2.
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900285 */
286static int cmp_pe_section(const void *arg1, const void *arg2)
287{
288 const IMAGE_SECTION_HEADER *section1, *section2;
289
290 section1 = *((const IMAGE_SECTION_HEADER **)arg1);
291 section2 = *((const IMAGE_SECTION_HEADER **)arg2);
292
293 if (section1->VirtualAddress < section2->VirtualAddress)
294 return -1;
295 else if (section1->VirtualAddress == section2->VirtualAddress)
296 return 0;
297 else
298 return 1;
299}
300
301/**
Masahisa Kojima70be5a62021-05-26 12:09:58 +0900302 * efi_prepare_aligned_image() - prepare 8-byte aligned image
303 * @efi: pointer to the EFI binary
304 * @efi_size: size of @efi binary
305 *
306 * If @efi is not 8-byte aligned, this function newly allocates
307 * the image buffer.
308 *
309 * Return: valid pointer to a image, return NULL if allocation fails.
310 */
311void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
312{
313 size_t new_efi_size;
314 void *new_efi;
315
316 /*
317 * Size must be 8-byte aligned and the trailing bytes must be
318 * zero'ed. Otherwise hash value may be incorrect.
319 */
320 if (!IS_ALIGNED(*efi_size, 8)) {
321 new_efi_size = ALIGN(*efi_size, 8);
322 new_efi = calloc(new_efi_size, 1);
323 if (!new_efi)
324 return NULL;
325 memcpy(new_efi, efi, *efi_size);
326 *efi_size = new_efi_size;
327 return new_efi;
328 } else {
329 return efi;
330 }
331}
332
333/**
Heinrich Schuchardtda6d6072020-05-30 05:48:08 +0200334 * efi_image_parse() - parse a PE image
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900335 * @efi: Pointer to image
336 * @len: Size of @efi
337 * @regp: Pointer to a list of regions
338 * @auth: Pointer to a pointer to authentication data in PE
339 * @auth_len: Size of @auth
340 *
341 * Parse image binary in PE32(+) format, assuming that sanity of PE image
342 * has been checked by a caller.
343 * On success, an address of authentication data in @efi and its size will
344 * be returned in @auth and @auth_len, respectively.
345 *
346 * Return: true on success, false on error
347 */
348bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
349 WIN_CERTIFICATE **auth, size_t *auth_len)
350{
351 struct efi_image_regions *regs;
352 IMAGE_DOS_HEADER *dos;
353 IMAGE_NT_HEADERS32 *nt;
354 IMAGE_SECTION_HEADER *sections, **sorted;
355 int num_regions, num_sections, i;
356 int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
357 u32 align, size, authsz, authoff;
358 size_t bytes_hashed;
359
360 dos = (void *)efi;
361 nt = (void *)(efi + dos->e_lfanew);
AKASHI Takahiro0d5eba42020-07-08 14:01:53 +0900362 authoff = 0;
363 authsz = 0;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900364
365 /*
366 * Count maximum number of regions to be digested.
367 * We don't have to have an exact number here.
368 * See efi_image_region_add()'s in parsing below.
369 */
370 num_regions = 3; /* for header */
371 num_regions += nt->FileHeader.NumberOfSections;
372 num_regions++; /* for extra */
373
374 regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
375 1);
376 if (!regs)
377 goto err;
378 regs->max = num_regions;
379
380 /*
381 * Collect data regions for hash calculation
382 * 1. File headers
383 */
384 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
385 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
386 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
387
388 /* Skip CheckSum */
389 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
390 if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
391 efi_image_region_add(regs,
AKASHI Takahirob69546f2020-05-08 14:51:59 +0900392 &opt->Subsystem,
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900393 efi + opt->SizeOfHeaders, 0);
394 } else {
395 /* Skip Certificates Table */
396 efi_image_region_add(regs,
AKASHI Takahirob69546f2020-05-08 14:51:59 +0900397 &opt->Subsystem,
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900398 &opt->DataDirectory[ctidx], 0);
399 efi_image_region_add(regs,
400 &opt->DataDirectory[ctidx] + 1,
401 efi + opt->SizeOfHeaders, 0);
AKASHI Takahiro0d5eba42020-07-08 14:01:53 +0900402
403 authoff = opt->DataDirectory[ctidx].VirtualAddress;
404 authsz = opt->DataDirectory[ctidx].Size;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900405 }
406
407 bytes_hashed = opt->SizeOfHeaders;
408 align = opt->FileAlignment;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900409 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
410 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
411
AKASHI Takahiro0d5eba42020-07-08 14:01:53 +0900412 /* Skip CheckSum */
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900413 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
AKASHI Takahiro0d5eba42020-07-08 14:01:53 +0900414 if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
415 efi_image_region_add(regs,
416 &opt->Subsystem,
417 efi + opt->SizeOfHeaders, 0);
418 } else {
419 /* Skip Certificates Table */
420 efi_image_region_add(regs, &opt->Subsystem,
421 &opt->DataDirectory[ctidx], 0);
422 efi_image_region_add(regs,
423 &opt->DataDirectory[ctidx] + 1,
424 efi + opt->SizeOfHeaders, 0);
425
426 authoff = opt->DataDirectory[ctidx].VirtualAddress;
427 authsz = opt->DataDirectory[ctidx].Size;
428 }
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900429
430 bytes_hashed = opt->SizeOfHeaders;
431 align = opt->FileAlignment;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900432 } else {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900433 log_err("%s: Invalid optional header magic %x\n", __func__,
434 nt->OptionalHeader.Magic);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900435 goto err;
436 }
437
438 /* 2. Sections */
439 num_sections = nt->FileHeader.NumberOfSections;
440 sections = (void *)((uint8_t *)&nt->OptionalHeader +
441 nt->FileHeader.SizeOfOptionalHeader);
442 sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
443 if (!sorted) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900444 log_err("%s: Out of memory\n", __func__);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900445 goto err;
446 }
447
448 /*
449 * Make sure the section list is in ascending order.
450 */
451 for (i = 0; i < num_sections; i++)
452 sorted[i] = &sections[i];
453 qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
454
455 for (i = 0; i < num_sections; i++) {
456 if (!sorted[i]->SizeOfRawData)
457 continue;
458
459 size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
460 efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
461 efi + sorted[i]->PointerToRawData + size,
462 0);
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900463 log_debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
AKASHI Takahirocb0b4112020-06-09 14:09:35 +0900464 i, sorted[i]->Name,
465 sorted[i]->PointerToRawData,
466 sorted[i]->PointerToRawData + size,
467 sorted[i]->VirtualAddress,
468 sorted[i]->VirtualAddress
469 + sorted[i]->Misc.VirtualSize);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900470
471 bytes_hashed += size;
472 }
473 free(sorted);
474
475 /* 3. Extra data excluding Certificates Table */
476 if (bytes_hashed + authsz < len) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900477 log_debug("extra data for hash: %zu\n",
AKASHI Takahirocb0b4112020-06-09 14:09:35 +0900478 len - (bytes_hashed + authsz));
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900479 efi_image_region_add(regs, efi + bytes_hashed,
480 efi + len - authsz, 0);
481 }
482
483 /* Return Certificates Table */
484 if (authsz) {
485 if (len < authoff + authsz) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900486 log_err("%s: Size for auth too large: %u >= %zu\n",
487 __func__, authsz, len - authoff);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900488 goto err;
489 }
490 if (authsz < sizeof(*auth)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900491 log_err("%s: Size for auth too small: %u < %zu\n",
492 __func__, authsz, sizeof(*auth));
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900493 goto err;
494 }
495 *auth = efi + authoff;
496 *auth_len = authsz;
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900497 log_debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff,
AKASHI Takahirocb0b4112020-06-09 14:09:35 +0900498 authsz);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900499 } else {
500 *auth = NULL;
501 *auth_len = 0;
502 }
503
504 *regp = regs;
505
506 return true;
507
508err:
509 free(regs);
510
511 return false;
512}
513
Masahisa Kojima915e4272021-05-14 09:53:36 +0900514#ifdef CONFIG_EFI_SECURE_BOOT
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900515/**
AKASHI Takahiroe669c2d2022-07-05 14:48:14 +0900516 * efi_image_verify_digest - verify image's message digest
517 * @regs: Array of memory regions to digest
518 * @msg: Signature in pkcs7 structure
519 *
520 * @regs contains all the data in a PE image to digest. Calculate
521 * a hash value based on @regs and compare it with a messaged digest
522 * in the content (SpcPeImageData) of @msg's contentInfo.
523 *
524 * Return: true if verified, false if not
525 */
526static bool efi_image_verify_digest(struct efi_image_regions *regs,
527 struct pkcs7_message *msg)
528{
529 struct pefile_context ctx;
530 void *hash;
531 int hash_len, ret;
532
533 const void *data;
534 size_t data_len;
535 size_t asn1hdrlen;
536
537 /* get pkcs7's contentInfo */
538 ret = pkcs7_get_content_data(msg, &data, &data_len, &asn1hdrlen);
539 if (ret < 0 || !data)
540 return false;
541
542 /* parse data and retrieve a message digest into ctx */
543 ret = mscode_parse(&ctx, data, data_len, asn1hdrlen);
544 if (ret < 0)
545 return false;
546
547 /* calculate a hash value of PE image */
548 hash = NULL;
549 if (!efi_hash_regions(regs->reg, regs->num, &hash, ctx.digest_algo,
550 &hash_len))
551 return false;
552
553 /* match the digest */
554 if (ctx.digest_len != hash_len || memcmp(ctx.digest, hash, hash_len))
555 return false;
556
557 return true;
558}
559
560/**
Heinrich Schuchardtda6d6072020-05-30 05:48:08 +0200561 * efi_image_authenticate() - verify a signature of signed image
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900562 * @efi: Pointer to image
563 * @efi_size: Size of @efi
564 *
565 * A signed image should have its signature stored in a table of its PE header.
566 * So if an image is signed and only if if its signature is verified using
567 * signature databases, an image is authenticated.
568 * If an image is not signed, its validity is checked by using
569 * efi_image_unsigned_authenticated().
570 * TODO:
571 * When AuditMode==0, if the image's signature is not found in
572 * the authorized database, or is found in the forbidden database,
573 * the image will not be started and instead, information about it
574 * will be placed in this table.
575 * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
576 * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
577 * in the certificate table of every image that is validated.
578 *
579 * Return: true if authenticated, false if not
580 */
581static bool efi_image_authenticate(void *efi, size_t efi_size)
582{
583 struct efi_image_regions *regs = NULL;
584 WIN_CERTIFICATE *wincerts = NULL, *wincert;
585 size_t wincerts_len;
586 struct pkcs7_message *msg = NULL;
587 struct efi_signature_store *db = NULL, *dbx = NULL;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900588 void *new_efi = NULL;
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900589 u8 *auth, *wincerts_end;
Dan Carpenter0c5ff7e2023-07-26 09:54:52 +0300590 u64 new_efi_size = efi_size;
Masahisa Kojima70be5a62021-05-26 12:09:58 +0900591 size_t auth_size;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900592 bool ret = false;
593
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900594 log_debug("%s: Enter, %d\n", __func__, ret);
AKASHI Takahiro4154b642020-07-08 14:01:56 +0900595
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900596 if (!efi_secure_boot_enabled())
597 return true;
598
Dan Carpenter0c5ff7e2023-07-26 09:54:52 +0300599 new_efi = efi_prepare_aligned_image(efi, &new_efi_size);
Masahisa Kojima70be5a62021-05-26 12:09:58 +0900600 if (!new_efi)
601 return false;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900602
Dan Carpenter0c5ff7e2023-07-26 09:54:52 +0300603 if (!efi_image_parse(new_efi, new_efi_size, &regs, &wincerts,
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900604 &wincerts_len)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900605 log_err("Parsing PE executable image failed\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200606 goto out;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900607 }
608
609 /*
610 * verify signature using db and dbx
611 */
Simon Glass90975372022-01-23 12:55:12 -0700612 db = efi_sigstore_parse_sigdb(u"db");
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900613 if (!db) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900614 log_err("Getting signature database(db) failed\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200615 goto out;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900616 }
617
Simon Glass90975372022-01-23 12:55:12 -0700618 dbx = efi_sigstore_parse_sigdb(u"dbx");
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900619 if (!dbx) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900620 log_err("Getting signature database(dbx) failed\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200621 goto out;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900622 }
623
Ilias Apalodimas71eae982022-01-29 00:20:31 +0200624 if (efi_signature_lookup_digest(regs, dbx, true)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900625 log_debug("Image's digest was found in \"dbx\"\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200626 goto out;
AKASHI Takahiro16411802020-08-14 14:39:23 +0900627 }
628
AKASHI Takahiro4154b642020-07-08 14:01:56 +0900629 /*
630 * go through WIN_CERTIFICATE list
631 * NOTE:
632 * We may have multiple signatures either as WIN_CERTIFICATE's
633 * in PE header, or as pkcs7 SignerInfo's in SignedData.
634 * So the verification policy here is:
635 * - Success if, at least, one of signatures is verified
AKASHI Takahiro16411802020-08-14 14:39:23 +0900636 * - unless signature is rejected explicitly with its digest.
AKASHI Takahiro4154b642020-07-08 14:01:56 +0900637 */
AKASHI Takahiro16411802020-08-14 14:39:23 +0900638
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900639 for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
640 (u8 *)wincert < wincerts_end;
641 wincert = (WIN_CERTIFICATE *)
642 ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
643 if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
644 break;
645
646 if (wincert->dwLength <= sizeof(*wincert)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900647 log_debug("dwLength too small: %u < %zu\n",
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900648 wincert->dwLength, sizeof(*wincert));
649 continue;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900650 }
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900651
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900652 log_debug("WIN_CERTIFICATE_TYPE: 0x%x\n",
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900653 wincert->wCertificateType);
654
655 auth = (u8 *)wincert + sizeof(*wincert);
656 auth_size = wincert->dwLength - sizeof(*wincert);
657 if (wincert->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
658 if (auth + sizeof(efi_guid_t) >= wincerts_end)
659 break;
660
661 if (auth_size <= sizeof(efi_guid_t)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900662 log_debug("dwLength too small: %u < %zu\n",
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900663 wincert->dwLength, sizeof(*wincert));
664 continue;
665 }
666 if (guidcmp(auth, &efi_guid_cert_type_pkcs7)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900667 log_debug("Certificate type not supported: %pUs\n",
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900668 auth);
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200669 ret = false;
670 goto out;
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900671 }
672
673 auth += sizeof(efi_guid_t);
674 auth_size -= sizeof(efi_guid_t);
675 } else if (wincert->wCertificateType
676 != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900677 log_debug("Certificate type not supported\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200678 ret = false;
679 goto out;
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900680 }
681
682 msg = pkcs7_parse_message(auth, auth_size);
Patrick Wildtfbc745c2020-05-07 02:17:14 +0200683 if (IS_ERR(msg)) {
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900684 log_err("Parsing image's signature failed\n");
Patrick Wildtfbc745c2020-05-07 02:17:14 +0200685 msg = NULL;
AKASHI Takahiroeab12752020-07-08 14:01:52 +0900686 continue;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900687 }
688
AKASHI Takahirode924072020-07-08 14:01:57 +0900689 /*
AKASHI Takahiroe669c2d2022-07-05 14:48:14 +0900690 * verify signatures in pkcs7's signedInfos which are
691 * to authenticate the integrity of pkcs7's contentInfo.
692 *
AKASHI Takahirode924072020-07-08 14:01:57 +0900693 * NOTE:
694 * UEFI specification defines two signature types possible
695 * in signature database:
696 * a. x509 certificate, where a signature in image is
697 * a message digest encrypted by RSA public key
698 * (EFI_CERT_X509_GUID)
699 * b. bare hash value of message digest
700 * (EFI_CERT_SHAxxx_GUID)
701 *
702 * efi_signature_verify() handles case (a), while
703 * efi_signature_lookup_digest() handles case (b).
704 *
705 * There is a third type:
706 * c. message digest of a certificate
707 * (EFI_CERT_X509_SHAAxxx_GUID)
708 * This type of signature is used only in revocation list
709 * (dbx) and handled as part of efi_signatgure_verify().
710 */
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900711 /* try black-list first */
AKASHI Takahiro4154b642020-07-08 14:01:56 +0900712 if (efi_signature_verify_one(regs, msg, dbx)) {
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200713 ret = false;
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900714 log_debug("Signature was rejected by \"dbx\"\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200715 goto out;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900716 }
717
AKASHI Takahiro4154b642020-07-08 14:01:56 +0900718 if (!efi_signature_check_signers(msg, dbx)) {
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200719 ret = false;
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900720 log_debug("Signer(s) in \"dbx\"\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200721 goto out;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900722 }
AKASHI Takahirode924072020-07-08 14:01:57 +0900723
724 /* try white-list */
AKASHI Takahiroe669c2d2022-07-05 14:48:14 +0900725 if (!efi_signature_verify(regs, msg, db, dbx)) {
726 log_debug("Signature was not verified by \"db\"\n");
727 continue;
728 }
729
730 /*
731 * now calculate an image's hash value and compare it with
732 * a messaged digest embedded in pkcs7's contentInfo
733 */
734 if (efi_image_verify_digest(regs, msg)) {
AKASHI Takahiro16411802020-08-14 14:39:23 +0900735 ret = true;
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200736 continue;
AKASHI Takahiro16411802020-08-14 14:39:23 +0900737 }
AKASHI Takahirode924072020-07-08 14:01:57 +0900738
AKASHI Takahiroe669c2d2022-07-05 14:48:14 +0900739 log_debug("Message digest doesn't match\n");
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200740 }
AKASHI Takahirode924072020-07-08 14:01:57 +0900741
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200742 /* last resort try the image sha256 hash in db */
743 if (!ret && efi_signature_lookup_digest(regs, db, false))
744 ret = true;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900745
Ilias Apalodimase9b36622022-02-11 09:37:49 +0200746out:
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900747 efi_sigstore_free(db);
748 efi_sigstore_free(dbx);
749 pkcs7_free_message(msg);
750 free(regs);
Masahisa Kojima70be5a62021-05-26 12:09:58 +0900751 if (new_efi != efi)
752 free(new_efi);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900753
AKASHI Takahiroe2761e22022-07-05 14:48:13 +0900754 log_debug("%s: Exit, %d\n", __func__, ret);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900755 return ret;
756}
757#else
758static bool efi_image_authenticate(void *efi, size_t efi_size)
759{
760 return true;
761}
762#endif /* CONFIG_EFI_SECURE_BOOT */
763
Heinrich Schuchardtad6e0f72021-01-12 12:40:32 +0100764/**
765 * efi_check_pe() - check if a memory buffer contains a PE-COFF image
766 *
767 * @buffer: buffer to check
768 * @size: size of buffer
769 * @nt_header: on return pointer to NT header of PE-COFF image
770 * Return: EFI_SUCCESS if the buffer contains a PE-COFF image
771 */
772efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
773{
774 IMAGE_DOS_HEADER *dos = buffer;
775 IMAGE_NT_HEADERS32 *nt;
776
777 if (size < sizeof(*dos))
778 return EFI_INVALID_PARAMETER;
779
780 /* Check for DOS magix */
781 if (dos->e_magic != IMAGE_DOS_SIGNATURE)
782 return EFI_INVALID_PARAMETER;
783
784 /*
785 * Check if the image section header fits into the file. Knowing that at
786 * least one section header follows we only need to check for the length
787 * of the 64bit header which is longer than the 32bit header.
788 */
789 if (size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32))
790 return EFI_INVALID_PARAMETER;
791 nt = (IMAGE_NT_HEADERS32 *)((u8 *)buffer + dos->e_lfanew);
792
793 /* Check for PE-COFF magic */
794 if (nt->Signature != IMAGE_NT_SIGNATURE)
795 return EFI_INVALID_PARAMETER;
796
797 if (nt_header)
798 *nt_header = nt;
799
800 return EFI_SUCCESS;
801}
802
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100803/**
Heinrich Schuchardtcd86dc92021-08-29 11:52:44 +0200804 * section_size() - determine size of section
805 *
806 * The size of a section in memory if normally given by VirtualSize.
807 * If VirtualSize is not provided, use SizeOfRawData.
808 *
809 * @sec: section header
810 * Return: size of section in memory
811 */
812static u32 section_size(IMAGE_SECTION_HEADER *sec)
813{
814 if (sec->Misc.VirtualSize)
815 return sec->Misc.VirtualSize;
816 else
817 return sec->SizeOfRawData;
818}
819
820/**
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100821 * efi_load_pe() - relocate EFI binary
822 *
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100823 * This function loads all sections from a PE binary into a newly reserved
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100824 * piece of memory. On success the entry point is returned as handle->entry.
825 *
826 * @handle: loaded image handle
827 * @efi: pointer to the EFI binary
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900828 * @efi_size: size of @efi binary
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100829 * @loaded_image_info: loaded image protocol
830 * Return: status code
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100831 */
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900832efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
833 void *efi, size_t efi_size,
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100834 struct efi_loaded_image *loaded_image_info)
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100835{
836 IMAGE_NT_HEADERS32 *nt;
837 IMAGE_DOS_HEADER *dos;
838 IMAGE_SECTION_HEADER *sections;
839 int num_sections;
840 void *efi_reloc;
841 int i;
842 const IMAGE_BASE_RELOCATION *rel;
843 unsigned long rel_size;
844 int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700845 uint64_t image_base;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100846 unsigned long virt_size = 0;
Ivan Gorinov749d5c12018-04-05 18:32:06 -0700847 int supported = 0;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900848 efi_status_t ret;
849
Heinrich Schuchardtad6e0f72021-01-12 12:40:32 +0100850 ret = efi_check_pe(efi, efi_size, (void **)&nt);
851 if (ret != EFI_SUCCESS) {
852 log_err("Not a PE-COFF file\n");
853 return EFI_LOAD_ERROR;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100854 }
855
Ivan Gorinov749d5c12018-04-05 18:32:06 -0700856 for (i = 0; machines[i]; i++)
857 if (machines[i] == nt->FileHeader.Machine) {
858 supported = 1;
859 break;
860 }
861
862 if (!supported) {
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000863 log_err("Machine type 0x%04x is not supported\n",
864 nt->FileHeader.Machine);
Heinrich Schuchardtad6e0f72021-01-12 12:40:32 +0100865 return EFI_LOAD_ERROR;
Ivan Gorinov749d5c12018-04-05 18:32:06 -0700866 }
867
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100868 num_sections = nt->FileHeader.NumberOfSections;
869 sections = (void *)&nt->OptionalHeader +
870 nt->FileHeader.SizeOfOptionalHeader;
871
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900872 if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
873 - efi)) {
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000874 log_err("Invalid number of sections: %d\n", num_sections);
Heinrich Schuchardtad6e0f72021-01-12 12:40:32 +0100875 return EFI_LOAD_ERROR;
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900876 }
877
878 /* Authenticate an image */
Heinrich Schuchardt74a84142020-08-27 17:51:32 +0200879 if (efi_image_authenticate(efi, efi_size)) {
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900880 handle->auth_status = EFI_IMAGE_AUTH_PASSED;
Heinrich Schuchardt74a84142020-08-27 17:51:32 +0200881 } else {
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900882 handle->auth_status = EFI_IMAGE_AUTH_FAILED;
Heinrich Schuchardt74a84142020-08-27 17:51:32 +0200883 log_err("Image not authenticated\n");
884 }
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900885
886 /* Calculate upper virtual address boundary */
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100887 for (i = num_sections - 1; i >= 0; i--) {
888 IMAGE_SECTION_HEADER *sec = &sections[i];
Heinrich Schuchardtcd86dc92021-08-29 11:52:44 +0200889
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100890 virt_size = max_t(unsigned long, virt_size,
Heinrich Schuchardtcd86dc92021-08-29 11:52:44 +0200891 sec->VirtualAddress + section_size(sec));
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100892 }
893
894 /* Read 32/64bit specific header bits */
Ivan Gorinov749d5c12018-04-05 18:32:06 -0700895 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100896 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
897 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700898 image_base = opt->ImageBase;
Heinrich Schuchardtfaef0e72018-01-19 20:24:41 +0100899 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
Heinrich Schuchardt37587522019-05-01 20:07:04 +0200900 handle->image_type = opt->Subsystem;
Ilias Apalodimas6e01c232021-10-11 15:10:23 +0300901 efi_reloc = efi_alloc_aligned_pages(virt_size,
902 loaded_image_info->image_code_type,
903 opt->SectionAlignment);
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100904 if (!efi_reloc) {
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000905 log_err("Out of memory\n");
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900906 ret = EFI_OUT_OF_RESOURCES;
907 goto err;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100908 }
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100909 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100910 rel_size = opt->DataDirectory[rel_idx].Size;
911 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
Ivan Gorinov749d5c12018-04-05 18:32:06 -0700912 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100913 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700914 image_base = opt->ImageBase;
Heinrich Schuchardtfaef0e72018-01-19 20:24:41 +0100915 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
Heinrich Schuchardt37587522019-05-01 20:07:04 +0200916 handle->image_type = opt->Subsystem;
Ilias Apalodimas6e01c232021-10-11 15:10:23 +0300917 efi_reloc = efi_alloc_aligned_pages(virt_size,
918 loaded_image_info->image_code_type,
919 opt->SectionAlignment);
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100920 if (!efi_reloc) {
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000921 log_err("Out of memory\n");
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900922 ret = EFI_OUT_OF_RESOURCES;
923 goto err;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100924 }
Heinrich Schuchardt408fbcc2018-12-26 12:49:09 +0100925 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100926 rel_size = opt->DataDirectory[rel_idx].Size;
927 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
928 } else {
Heinrich Schuchardteb676572020-08-25 17:51:20 +0000929 log_err("Invalid optional header magic %x\n",
930 nt->OptionalHeader.Magic);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900931 ret = EFI_LOAD_ERROR;
932 goto err;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100933 }
934
Simon Glass75be05f2023-02-05 15:39:46 -0700935#if IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)
Masahisa Kojima70be5a62021-05-26 12:09:58 +0900936 /* Measure an PE/COFF image */
Masahisa Kojima38155ea2021-12-07 14:15:33 +0900937 ret = tcg2_measure_pe_image(efi, efi_size, handle, loaded_image_info);
938 if (ret == EFI_SECURITY_VIOLATION) {
939 /*
940 * TCG2 Protocol is installed but no TPM device found,
941 * this is not expected.
942 */
943 log_err("PE image measurement failed, no tpm device found\n");
944 goto err;
945 }
946
Masahisa Kojima70be5a62021-05-26 12:09:58 +0900947#endif
948
AKASHI Takahiro068879a2018-10-11 04:09:58 -0700949 /* Copy PE headers */
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900950 memcpy(efi_reloc, efi,
951 sizeof(*dos)
952 + sizeof(*nt)
953 + nt->FileHeader.SizeOfOptionalHeader
954 + num_sections * sizeof(IMAGE_SECTION_HEADER));
AKASHI Takahiro068879a2018-10-11 04:09:58 -0700955
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100956 /* Load sections into RAM */
957 for (i = num_sections - 1; i >= 0; i--) {
958 IMAGE_SECTION_HEADER *sec = &sections[i];
Heinrich Schuchardtcd86dc92021-08-29 11:52:44 +0200959 u32 copy_size = section_size(sec);
960
961 if (copy_size > sec->SizeOfRawData) {
962 copy_size = sec->SizeOfRawData;
963 memset(efi_reloc + sec->VirtualAddress, 0,
964 sec->Misc.VirtualSize);
965 }
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100966 memcpy(efi_reloc + sec->VirtualAddress,
967 efi + sec->PointerToRawData,
Heinrich Schuchardtcd86dc92021-08-29 11:52:44 +0200968 copy_size);
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100969 }
970
971 /* Run through relocations */
Ivan Gorinovc7270bc2018-05-02 16:36:02 -0700972 if (efi_loader_relocate(rel, rel_size, efi_reloc,
973 (unsigned long)image_base) != EFI_SUCCESS) {
xypron.glpk@gmx.de6ec97d22017-07-04 00:12:58 +0200974 efi_free_pages((uintptr_t) efi_reloc,
975 (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900976 ret = EFI_LOAD_ERROR;
977 goto err;
xypron.glpk@gmx.de6ec97d22017-07-04 00:12:58 +0200978 }
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100979
980 /* Flush cache */
Simon Glass567b62c2024-11-27 11:17:19 -0600981 flush_cache(map_to_sysmem(efi_reloc),
Alexander Graf59254d62018-04-23 07:59:47 +0200982 ALIGN(virt_size, EFI_CACHELINE_SIZE));
Heinrich Schuchardt3a67d132024-06-16 19:31:05 +0200983
984 /*
985 * If on x86 a write affects a prefetched instruction,
986 * the prefetch queue is invalidated.
987 */
988 if (!CONFIG_IS_ENABLED(X86))
989 invalidate_icache_all();
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100990
991 /* Populate the loaded image interface bits */
AKASHI Takahiro068879a2018-10-11 04:09:58 -0700992 loaded_image_info->image_base = efi_reloc;
993 loaded_image_info->image_size = virt_size;
Alexander Graf4e0c1c12016-03-04 01:09:58 +0100994
AKASHI Takahiro0e104e32020-04-14 11:51:44 +0900995 if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
996 return EFI_SUCCESS;
997 else
998 return EFI_SECURITY_VIOLATION;
999
1000err:
1001 return ret;
Alexander Graf4e0c1c12016-03-04 01:09:58 +01001002}