]> Git Repo - u-boot.git/blame - lib/efi_loader/efi_image_loader.c
Merge patch series "api: Remove duplicate newlines"
[u-boot.git] / lib / efi_loader / efi_image_loader.c
CommitLineData
f739fcd8 1// SPDX-License-Identifier: GPL-2.0+
cb149c66
AG
2/*
3 * EFI image loader
4 *
5 * based partly on wine code
6 *
7 * Copyright (c) 2016 Alexander Graf
cb149c66
AG
8 */
9
24586059
HS
10#define LOG_CATEGORY LOGC_EFI
11
1eb69ae4 12#include <cpu_func.h>
cb149c66 13#include <efi_loader.h>
24586059 14#include <log.h>
4540dabd 15#include <malloc.h>
cb149c66 16#include <pe.h>
4540dabd 17#include <sort.h>
634f6b2f 18#include <crypto/mscode.h>
d7ca3ce3 19#include <crypto/pkcs7_parser.h>
6f146155 20#include <linux/err.h>
cb149c66 21
9975fe96 22const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
dec88e41
HS
23const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
24const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
25const efi_guid_t efi_guid_loaded_image_device_path =
26 EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
2a92080d
RC
27const efi_guid_t efi_simple_file_system_protocol_guid =
28 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
29const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
cb149c66 30
61a5ced6 31static int machines[] = {
b59f6971 32#if defined(__aarch64__)
61a5ced6 33 IMAGE_FILE_MACHINE_ARM64,
b59f6971 34#elif defined(__arm__)
61a5ced6
IG
35 IMAGE_FILE_MACHINE_ARM,
36 IMAGE_FILE_MACHINE_THUMB,
37 IMAGE_FILE_MACHINE_ARMNT,
38#endif
39
b59f6971 40#if defined(__x86_64__)
61a5ced6 41 IMAGE_FILE_MACHINE_AMD64,
b59f6971 42#elif defined(__i386__)
61a5ced6
IG
43 IMAGE_FILE_MACHINE_I386,
44#endif
45
b59f6971 46#if defined(__riscv) && (__riscv_xlen == 32)
61a5ced6
IG
47 IMAGE_FILE_MACHINE_RISCV32,
48#endif
49
b59f6971 50#if defined(__riscv) && (__riscv_xlen == 64)
61a5ced6
IG
51 IMAGE_FILE_MACHINE_RISCV64,
52#endif
53 0 };
54
1db561e1
HS
55/**
56 * efi_print_image_info() - print information about a loaded image
c9a63f44
HS
57 *
58 * If the program counter is located within the image the offset to the base
59 * address is shown.
60 *
c982874e 61 * @obj: EFI object
c9a63f44
HS
62 * @image: loaded image
63 * @pc: program counter (use NULL to suppress offset output)
1db561e1 64 * Return: status code
c9a63f44 65 */
c982874e
HS
66static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
67 struct efi_loaded_image *image,
68 void *pc)
c9a63f44 69{
c9a63f44
HS
70 printf("UEFI image");
71 printf(" [0x%p:0x%p]",
8458bf64
AT
72 image->image_base, image->image_base + image->image_size - 1);
73 if (pc && pc >= image->image_base &&
74 pc < image->image_base + image->image_size)
75 printf(" pc=0x%zx", pc - image->image_base);
c9a63f44
HS
76 if (image->file_path)
77 printf(" '%pD'", image->file_path);
78 printf("\n");
79 return EFI_SUCCESS;
80}
81
1db561e1
HS
82/**
83 * efi_print_image_infos() - print information about all loaded images
c9a63f44
HS
84 *
85 * @pc: program counter (use NULL to suppress offset output)
86 */
87void efi_print_image_infos(void *pc)
88{
89 struct efi_object *efiobj;
90 struct efi_handler *handler;
91
92 list_for_each_entry(efiobj, &efi_obj_list, link) {
93 list_for_each_entry(handler, &efiobj->protocols, link) {
66028930 94 if (!guidcmp(&handler->guid, &efi_guid_loaded_image)) {
c9a63f44 95 efi_print_image_info(
c982874e 96 (struct efi_loaded_image_obj *)efiobj,
c9a63f44
HS
97 handler->protocol_interface, pc);
98 }
99 }
100 }
101}
102
1db561e1
HS
103/**
104 * efi_loader_relocate() - relocate UEFI binary
105 *
106 * @rel: pointer to the relocation table
107 * @rel_size: size of the relocation table in bytes
108 * @efi_reloc: actual load address of the image
109 * @pref_address: preferred load address of the image
110 * Return: status code
111 */
da684a64 112static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
e2dc4229
IG
113 unsigned long rel_size, void *efi_reloc,
114 unsigned long pref_address)
cb149c66 115{
e2dc4229 116 unsigned long delta = (unsigned long)efi_reloc - pref_address;
cb149c66
AG
117 const IMAGE_BASE_RELOCATION *end;
118 int i;
119
e2dc4229
IG
120 if (delta == 0)
121 return EFI_SUCCESS;
122
cb149c66 123 end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
997fc12e 124 while (rel < end && rel->SizeOfBlock) {
cb149c66
AG
125 const uint16_t *relocs = (const uint16_t *)(rel + 1);
126 i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
127 while (i--) {
b1237c6e 128 uint32_t offset = (uint32_t)(*relocs & 0xfff) +
cb149c66
AG
129 rel->VirtualAddress;
130 int type = *relocs >> EFI_PAGE_SHIFT;
cb149c66
AG
131 uint64_t *x64 = efi_reloc + offset;
132 uint32_t *x32 = efi_reloc + offset;
133 uint16_t *x16 = efi_reloc + offset;
134
135 switch (type) {
136 case IMAGE_REL_BASED_ABSOLUTE:
137 break;
138 case IMAGE_REL_BASED_HIGH:
139 *x16 += ((uint32_t)delta) >> 16;
140 break;
141 case IMAGE_REL_BASED_LOW:
142 *x16 += (uint16_t)delta;
143 break;
144 case IMAGE_REL_BASED_HIGHLOW:
145 *x32 += (uint32_t)delta;
146 break;
147 case IMAGE_REL_BASED_DIR64:
148 *x64 += (uint64_t)delta;
149 break;
de452c04
AG
150#ifdef __riscv
151 case IMAGE_REL_BASED_RISCV_HI20:
152 *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
153 (*x32 & 0x00000fff);
154 break;
155 case IMAGE_REL_BASED_RISCV_LOW12I:
156 case IMAGE_REL_BASED_RISCV_LOW12S:
157 /* We know that we're 4k aligned */
158 if (delta & 0xfff) {
24586059 159 log_err("Unsupported reloc offset\n");
de452c04
AG
160 return EFI_LOAD_ERROR;
161 }
162 break;
163#endif
cb149c66 164 default:
24586059
HS
165 log_err("Unknown Relocation off %x type %x\n",
166 offset, type);
da684a64 167 return EFI_LOAD_ERROR;
cb149c66
AG
168 }
169 relocs++;
170 }
171 rel = (const IMAGE_BASE_RELOCATION *)relocs;
172 }
da684a64 173 return EFI_SUCCESS;
cb149c66
AG
174}
175
1db561e1
HS
176/**
177 * efi_set_code_and_data_type() - determine the memory types to be used for code
178 * and data.
36b41a3c 179 *
1db561e1
HS
180 * @loaded_image_info: image descriptor
181 * @image_type: field Subsystem of the optional header for
36b41a3c
HS
182 * Windows specific field
183 */
184static void efi_set_code_and_data_type(
185 struct efi_loaded_image *loaded_image_info,
186 uint16_t image_type)
187{
188 switch (image_type) {
189 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
190 loaded_image_info->image_code_type = EFI_LOADER_CODE;
191 loaded_image_info->image_data_type = EFI_LOADER_DATA;
192 break;
193 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
194 loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
195 loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
196 break;
197 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
268ec6e0 198 case IMAGE_SUBSYSTEM_EFI_ROM:
36b41a3c
HS
199 loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
200 loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
201 break;
202 default:
24586059 203 log_err("invalid image type: %u\n", image_type);
36b41a3c
HS
204 /* Let's assume it is an application */
205 loaded_image_info->image_code_type = EFI_LOADER_CODE;
206 loaded_image_info->image_data_type = EFI_LOADER_DATA;
207 break;
208 }
209}
210
f6081a8a
MK
211/**
212 * efi_image_region_add() - add an entry of region
213 * @regs: Pointer to array of regions
214 * @start: Start address of region (included)
215 * @end: End address of region (excluded)
216 * @nocheck: flag against overlapped regions
217 *
b95e5edc 218 * Take one entry of region \[@start, @end\[ and insert it into the list.
f6081a8a
MK
219 *
220 * * If @nocheck is false, the list will be sorted ascending by address.
221 * Overlapping entries will not be allowed.
222 *
223 * * If @nocheck is true, the list will be sorted ascending by sequence
224 * of adding the entries. Overlapping is allowed.
225 *
226 * Return: status code
227 */
228efi_status_t efi_image_region_add(struct efi_image_regions *regs,
229 const void *start, const void *end,
230 int nocheck)
231{
232 struct image_region *reg;
233 int i, j;
234
235 if (regs->num >= regs->max) {
b72d09fa 236 log_err("%s: no more room for regions\n", __func__);
f6081a8a
MK
237 return EFI_OUT_OF_RESOURCES;
238 }
239
240 if (end < start)
241 return EFI_INVALID_PARAMETER;
242
243 for (i = 0; i < regs->num; i++) {
244 reg = &regs->reg[i];
245 if (nocheck)
246 continue;
247
248 /* new data after registered region */
249 if (start >= reg->data + reg->size)
250 continue;
251
252 /* new data preceding registered region */
253 if (end <= reg->data) {
254 for (j = regs->num - 1; j >= i; j--)
255 memcpy(&regs->reg[j + 1], &regs->reg[j],
256 sizeof(*reg));
257 break;
258 }
259
260 /* new data overlapping registered region */
b72d09fa 261 log_err("%s: new region already part of another\n", __func__);
f6081a8a
MK
262 return EFI_INVALID_PARAMETER;
263 }
264
265 reg = &regs->reg[i];
266 reg->data = start;
267 reg->size = end - start;
268 regs->num++;
269
270 return EFI_SUCCESS;
271}
272
4540dabd 273/**
13f62d9f
HS
274 * cmp_pe_section() - compare virtual addresses of two PE image sections
275 * @arg1: pointer to pointer to first section header
276 * @arg2: pointer to pointer to second section header
4540dabd 277 *
13f62d9f
HS
278 * Compare the virtual addresses of two sections of an portable executable.
279 * The arguments are defined as const void * to allow usage with qsort().
4540dabd 280 *
13f62d9f
HS
281 * Return: -1 if the virtual address of arg1 is less than that of arg2,
282 * 0 if the virtual addresses are equal, 1 if the virtual address
283 * of arg1 is greater than that of arg2.
4540dabd
AT
284 */
285static int cmp_pe_section(const void *arg1, const void *arg2)
286{
287 const IMAGE_SECTION_HEADER *section1, *section2;
288
289 section1 = *((const IMAGE_SECTION_HEADER **)arg1);
290 section2 = *((const IMAGE_SECTION_HEADER **)arg2);
291
292 if (section1->VirtualAddress < section2->VirtualAddress)
293 return -1;
294 else if (section1->VirtualAddress == section2->VirtualAddress)
295 return 0;
296 else
297 return 1;
298}
299
163a0d7e
MK
300/**
301 * efi_prepare_aligned_image() - prepare 8-byte aligned image
302 * @efi: pointer to the EFI binary
303 * @efi_size: size of @efi binary
304 *
305 * If @efi is not 8-byte aligned, this function newly allocates
306 * the image buffer.
307 *
308 * Return: valid pointer to a image, return NULL if allocation fails.
309 */
310void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
311{
312 size_t new_efi_size;
313 void *new_efi;
314
315 /*
316 * Size must be 8-byte aligned and the trailing bytes must be
317 * zero'ed. Otherwise hash value may be incorrect.
318 */
319 if (!IS_ALIGNED(*efi_size, 8)) {
320 new_efi_size = ALIGN(*efi_size, 8);
321 new_efi = calloc(new_efi_size, 1);
322 if (!new_efi)
323 return NULL;
324 memcpy(new_efi, efi, *efi_size);
325 *efi_size = new_efi_size;
326 return new_efi;
327 } else {
328 return efi;
329 }
330}
331
4540dabd 332/**
4afceb4d 333 * efi_image_parse() - parse a PE image
4540dabd
AT
334 * @efi: Pointer to image
335 * @len: Size of @efi
336 * @regp: Pointer to a list of regions
337 * @auth: Pointer to a pointer to authentication data in PE
338 * @auth_len: Size of @auth
339 *
340 * Parse image binary in PE32(+) format, assuming that sanity of PE image
341 * has been checked by a caller.
342 * On success, an address of authentication data in @efi and its size will
343 * be returned in @auth and @auth_len, respectively.
344 *
345 * Return: true on success, false on error
346 */
347bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
348 WIN_CERTIFICATE **auth, size_t *auth_len)
349{
350 struct efi_image_regions *regs;
351 IMAGE_DOS_HEADER *dos;
352 IMAGE_NT_HEADERS32 *nt;
353 IMAGE_SECTION_HEADER *sections, **sorted;
354 int num_regions, num_sections, i;
355 int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
356 u32 align, size, authsz, authoff;
357 size_t bytes_hashed;
358
359 dos = (void *)efi;
360 nt = (void *)(efi + dos->e_lfanew);
eb537fd7
AT
361 authoff = 0;
362 authsz = 0;
4540dabd
AT
363
364 /*
365 * Count maximum number of regions to be digested.
366 * We don't have to have an exact number here.
367 * See efi_image_region_add()'s in parsing below.
368 */
369 num_regions = 3; /* for header */
370 num_regions += nt->FileHeader.NumberOfSections;
371 num_regions++; /* for extra */
372
373 regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
374 1);
375 if (!regs)
376 goto err;
377 regs->max = num_regions;
378
379 /*
380 * Collect data regions for hash calculation
381 * 1. File headers
382 */
383 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
384 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
385 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
386
387 /* Skip CheckSum */
388 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
389 if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
390 efi_image_region_add(regs,
52d7bfe7 391 &opt->Subsystem,
4540dabd
AT
392 efi + opt->SizeOfHeaders, 0);
393 } else {
394 /* Skip Certificates Table */
395 efi_image_region_add(regs,
52d7bfe7 396 &opt->Subsystem,
4540dabd
AT
397 &opt->DataDirectory[ctidx], 0);
398 efi_image_region_add(regs,
399 &opt->DataDirectory[ctidx] + 1,
400 efi + opt->SizeOfHeaders, 0);
eb537fd7
AT
401
402 authoff = opt->DataDirectory[ctidx].VirtualAddress;
403 authsz = opt->DataDirectory[ctidx].Size;
4540dabd
AT
404 }
405
406 bytes_hashed = opt->SizeOfHeaders;
407 align = opt->FileAlignment;
4540dabd
AT
408 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
409 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
410
eb537fd7 411 /* Skip CheckSum */
4540dabd 412 efi_image_region_add(regs, efi, &opt->CheckSum, 0);
eb537fd7
AT
413 if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
414 efi_image_region_add(regs,
415 &opt->Subsystem,
416 efi + opt->SizeOfHeaders, 0);
417 } else {
418 /* Skip Certificates Table */
419 efi_image_region_add(regs, &opt->Subsystem,
420 &opt->DataDirectory[ctidx], 0);
421 efi_image_region_add(regs,
422 &opt->DataDirectory[ctidx] + 1,
423 efi + opt->SizeOfHeaders, 0);
424
425 authoff = opt->DataDirectory[ctidx].VirtualAddress;
426 authsz = opt->DataDirectory[ctidx].Size;
427 }
4540dabd
AT
428
429 bytes_hashed = opt->SizeOfHeaders;
430 align = opt->FileAlignment;
4540dabd 431 } else {
b72d09fa
AT
432 log_err("%s: Invalid optional header magic %x\n", __func__,
433 nt->OptionalHeader.Magic);
4540dabd
AT
434 goto err;
435 }
436
437 /* 2. Sections */
438 num_sections = nt->FileHeader.NumberOfSections;
439 sections = (void *)((uint8_t *)&nt->OptionalHeader +
440 nt->FileHeader.SizeOfOptionalHeader);
441 sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
442 if (!sorted) {
b72d09fa 443 log_err("%s: Out of memory\n", __func__);
4540dabd
AT
444 goto err;
445 }
446
447 /*
448 * Make sure the section list is in ascending order.
449 */
450 for (i = 0; i < num_sections; i++)
451 sorted[i] = &sections[i];
452 qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
453
454 for (i = 0; i < num_sections; i++) {
455 if (!sorted[i]->SizeOfRawData)
456 continue;
457
458 size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
459 efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
460 efi + sorted[i]->PointerToRawData + size,
461 0);
b72d09fa 462 log_debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
1b6c0854
AT
463 i, sorted[i]->Name,
464 sorted[i]->PointerToRawData,
465 sorted[i]->PointerToRawData + size,
466 sorted[i]->VirtualAddress,
467 sorted[i]->VirtualAddress
468 + sorted[i]->Misc.VirtualSize);
4540dabd
AT
469
470 bytes_hashed += size;
471 }
472 free(sorted);
473
474 /* 3. Extra data excluding Certificates Table */
475 if (bytes_hashed + authsz < len) {
b72d09fa 476 log_debug("extra data for hash: %zu\n",
1b6c0854 477 len - (bytes_hashed + authsz));
4540dabd
AT
478 efi_image_region_add(regs, efi + bytes_hashed,
479 efi + len - authsz, 0);
480 }
481
482 /* Return Certificates Table */
483 if (authsz) {
484 if (len < authoff + authsz) {
b72d09fa
AT
485 log_err("%s: Size for auth too large: %u >= %zu\n",
486 __func__, authsz, len - authoff);
4540dabd
AT
487 goto err;
488 }
489 if (authsz < sizeof(*auth)) {
b72d09fa
AT
490 log_err("%s: Size for auth too small: %u < %zu\n",
491 __func__, authsz, sizeof(*auth));
4540dabd
AT
492 goto err;
493 }
494 *auth = efi + authoff;
495 *auth_len = authsz;
b72d09fa 496 log_debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff,
1b6c0854 497 authsz);
4540dabd
AT
498 } else {
499 *auth = NULL;
500 *auth_len = 0;
501 }
502
503 *regp = regs;
504
505 return true;
506
507err:
508 free(regs);
509
510 return false;
511}
512
f6081a8a 513#ifdef CONFIG_EFI_SECURE_BOOT
634f6b2f
AT
514/**
515 * efi_image_verify_digest - verify image's message digest
516 * @regs: Array of memory regions to digest
517 * @msg: Signature in pkcs7 structure
518 *
519 * @regs contains all the data in a PE image to digest. Calculate
520 * a hash value based on @regs and compare it with a messaged digest
521 * in the content (SpcPeImageData) of @msg's contentInfo.
522 *
523 * Return: true if verified, false if not
524 */
525static bool efi_image_verify_digest(struct efi_image_regions *regs,
526 struct pkcs7_message *msg)
527{
528 struct pefile_context ctx;
529 void *hash;
530 int hash_len, ret;
531
532 const void *data;
533 size_t data_len;
534 size_t asn1hdrlen;
535
536 /* get pkcs7's contentInfo */
537 ret = pkcs7_get_content_data(msg, &data, &data_len, &asn1hdrlen);
538 if (ret < 0 || !data)
539 return false;
540
541 /* parse data and retrieve a message digest into ctx */
542 ret = mscode_parse(&ctx, data, data_len, asn1hdrlen);
543 if (ret < 0)
544 return false;
545
546 /* calculate a hash value of PE image */
547 hash = NULL;
548 if (!efi_hash_regions(regs->reg, regs->num, &hash, ctx.digest_algo,
549 &hash_len))
550 return false;
551
552 /* match the digest */
553 if (ctx.digest_len != hash_len || memcmp(ctx.digest, hash, hash_len))
554 return false;
555
556 return true;
557}
558
4540dabd 559/**
4afceb4d 560 * efi_image_authenticate() - verify a signature of signed image
4540dabd
AT
561 * @efi: Pointer to image
562 * @efi_size: Size of @efi
563 *
564 * A signed image should have its signature stored in a table of its PE header.
565 * So if an image is signed and only if if its signature is verified using
566 * signature databases, an image is authenticated.
567 * If an image is not signed, its validity is checked by using
568 * efi_image_unsigned_authenticated().
569 * TODO:
570 * When AuditMode==0, if the image's signature is not found in
571 * the authorized database, or is found in the forbidden database,
572 * the image will not be started and instead, information about it
573 * will be placed in this table.
574 * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
575 * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
576 * in the certificate table of every image that is validated.
577 *
578 * Return: true if authenticated, false if not
579 */
580static bool efi_image_authenticate(void *efi, size_t efi_size)
581{
582 struct efi_image_regions *regs = NULL;
583 WIN_CERTIFICATE *wincerts = NULL, *wincert;
584 size_t wincerts_len;
585 struct pkcs7_message *msg = NULL;
586 struct efi_signature_store *db = NULL, *dbx = NULL;
4540dabd 587 void *new_efi = NULL;
1a44b705 588 u8 *auth, *wincerts_end;
82944538 589 u64 new_efi_size = efi_size;
163a0d7e 590 size_t auth_size;
4540dabd
AT
591 bool ret = false;
592
b72d09fa 593 log_debug("%s: Enter, %d\n", __func__, ret);
11bafb25 594
4540dabd
AT
595 if (!efi_secure_boot_enabled())
596 return true;
597
82944538 598 new_efi = efi_prepare_aligned_image(efi, &new_efi_size);
163a0d7e
MK
599 if (!new_efi)
600 return false;
4540dabd 601
82944538 602 if (!efi_image_parse(new_efi, new_efi_size, &regs, &wincerts,
4540dabd 603 &wincerts_len)) {
b72d09fa 604 log_err("Parsing PE executable image failed\n");
54cebe8a 605 goto out;
4540dabd
AT
606 }
607
608 /*
609 * verify signature using db and dbx
610 */
156ccbc3 611 db = efi_sigstore_parse_sigdb(u"db");
4540dabd 612 if (!db) {
b72d09fa 613 log_err("Getting signature database(db) failed\n");
54cebe8a 614 goto out;
4540dabd
AT
615 }
616
156ccbc3 617 dbx = efi_sigstore_parse_sigdb(u"dbx");
4540dabd 618 if (!dbx) {
b72d09fa 619 log_err("Getting signature database(dbx) failed\n");
54cebe8a 620 goto out;
4540dabd
AT
621 }
622
4b634313 623 if (efi_signature_lookup_digest(regs, dbx, true)) {
b72d09fa 624 log_debug("Image's digest was found in \"dbx\"\n");
54cebe8a 625 goto out;
52956e53
AT
626 }
627
11bafb25
AT
628 /*
629 * go through WIN_CERTIFICATE list
630 * NOTE:
631 * We may have multiple signatures either as WIN_CERTIFICATE's
632 * in PE header, or as pkcs7 SignerInfo's in SignedData.
633 * So the verification policy here is:
634 * - Success if, at least, one of signatures is verified
52956e53 635 * - unless signature is rejected explicitly with its digest.
11bafb25 636 */
52956e53 637
1a44b705
AT
638 for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
639 (u8 *)wincert < wincerts_end;
640 wincert = (WIN_CERTIFICATE *)
641 ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
642 if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
643 break;
644
645 if (wincert->dwLength <= sizeof(*wincert)) {
b72d09fa 646 log_debug("dwLength too small: %u < %zu\n",
1a44b705
AT
647 wincert->dwLength, sizeof(*wincert));
648 continue;
649 }
650
b72d09fa 651 log_debug("WIN_CERTIFICATE_TYPE: 0x%x\n",
1a44b705
AT
652 wincert->wCertificateType);
653
654 auth = (u8 *)wincert + sizeof(*wincert);
655 auth_size = wincert->dwLength - sizeof(*wincert);
656 if (wincert->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
657 if (auth + sizeof(efi_guid_t) >= wincerts_end)
658 break;
659
660 if (auth_size <= sizeof(efi_guid_t)) {
b72d09fa 661 log_debug("dwLength too small: %u < %zu\n",
1a44b705
AT
662 wincert->dwLength, sizeof(*wincert));
663 continue;
664 }
665 if (guidcmp(auth, &efi_guid_cert_type_pkcs7)) {
b72d09fa 666 log_debug("Certificate type not supported: %pUs\n",
1a44b705 667 auth);
54cebe8a
IA
668 ret = false;
669 goto out;
1a44b705
AT
670 }
671
672 auth += sizeof(efi_guid_t);
673 auth_size -= sizeof(efi_guid_t);
674 } else if (wincert->wCertificateType
675 != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
b72d09fa 676 log_debug("Certificate type not supported\n");
54cebe8a
IA
677 ret = false;
678 goto out;
4540dabd 679 }
1a44b705
AT
680
681 msg = pkcs7_parse_message(auth, auth_size);
6f146155 682 if (IS_ERR(msg)) {
b72d09fa 683 log_err("Parsing image's signature failed\n");
6f146155 684 msg = NULL;
1a44b705 685 continue;
4540dabd
AT
686 }
687
7926dfb5 688 /*
634f6b2f
AT
689 * verify signatures in pkcs7's signedInfos which are
690 * to authenticate the integrity of pkcs7's contentInfo.
691 *
7926dfb5
AT
692 * NOTE:
693 * UEFI specification defines two signature types possible
694 * in signature database:
695 * a. x509 certificate, where a signature in image is
696 * a message digest encrypted by RSA public key
697 * (EFI_CERT_X509_GUID)
698 * b. bare hash value of message digest
699 * (EFI_CERT_SHAxxx_GUID)
700 *
701 * efi_signature_verify() handles case (a), while
702 * efi_signature_lookup_digest() handles case (b).
703 *
704 * There is a third type:
705 * c. message digest of a certificate
706 * (EFI_CERT_X509_SHAAxxx_GUID)
707 * This type of signature is used only in revocation list
708 * (dbx) and handled as part of efi_signatgure_verify().
709 */
4540dabd 710 /* try black-list first */
11bafb25 711 if (efi_signature_verify_one(regs, msg, dbx)) {
54cebe8a 712 ret = false;
b72d09fa 713 log_debug("Signature was rejected by \"dbx\"\n");
54cebe8a 714 goto out;
4540dabd
AT
715 }
716
11bafb25 717 if (!efi_signature_check_signers(msg, dbx)) {
54cebe8a 718 ret = false;
b72d09fa 719 log_debug("Signer(s) in \"dbx\"\n");
54cebe8a 720 goto out;
4540dabd 721 }
7926dfb5
AT
722
723 /* try white-list */
634f6b2f
AT
724 if (!efi_signature_verify(regs, msg, db, dbx)) {
725 log_debug("Signature was not verified by \"db\"\n");
726 continue;
727 }
728
729 /*
730 * now calculate an image's hash value and compare it with
731 * a messaged digest embedded in pkcs7's contentInfo
732 */
733 if (efi_image_verify_digest(regs, msg)) {
52956e53 734 ret = true;
54cebe8a 735 continue;
52956e53 736 }
7926dfb5 737
634f6b2f 738 log_debug("Message digest doesn't match\n");
54cebe8a 739 }
7926dfb5 740
54cebe8a
IA
741 /* last resort try the image sha256 hash in db */
742 if (!ret && efi_signature_lookup_digest(regs, db, false))
743 ret = true;
4540dabd 744
54cebe8a 745out:
4540dabd
AT
746 efi_sigstore_free(db);
747 efi_sigstore_free(dbx);
748 pkcs7_free_message(msg);
749 free(regs);
163a0d7e
MK
750 if (new_efi != efi)
751 free(new_efi);
4540dabd 752
b72d09fa 753 log_debug("%s: Exit, %d\n", __func__, ret);
4540dabd
AT
754 return ret;
755}
756#else
757static bool efi_image_authenticate(void *efi, size_t efi_size)
758{
759 return true;
760}
761#endif /* CONFIG_EFI_SECURE_BOOT */
762
5dad05a0
HS
763/**
764 * efi_check_pe() - check if a memory buffer contains a PE-COFF image
765 *
766 * @buffer: buffer to check
767 * @size: size of buffer
768 * @nt_header: on return pointer to NT header of PE-COFF image
769 * Return: EFI_SUCCESS if the buffer contains a PE-COFF image
770 */
771efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
772{
773 IMAGE_DOS_HEADER *dos = buffer;
774 IMAGE_NT_HEADERS32 *nt;
775
776 if (size < sizeof(*dos))
777 return EFI_INVALID_PARAMETER;
778
779 /* Check for DOS magix */
780 if (dos->e_magic != IMAGE_DOS_SIGNATURE)
781 return EFI_INVALID_PARAMETER;
782
783 /*
784 * Check if the image section header fits into the file. Knowing that at
785 * least one section header follows we only need to check for the length
786 * of the 64bit header which is longer than the 32bit header.
787 */
788 if (size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32))
789 return EFI_INVALID_PARAMETER;
790 nt = (IMAGE_NT_HEADERS32 *)((u8 *)buffer + dos->e_lfanew);
791
792 /* Check for PE-COFF magic */
793 if (nt->Signature != IMAGE_NT_SIGNATURE)
794 return EFI_INVALID_PARAMETER;
795
796 if (nt_header)
797 *nt_header = nt;
798
799 return EFI_SUCCESS;
800}
801
1ea133ac
HS
802/**
803 * section_size() - determine size of section
804 *
805 * The size of a section in memory if normally given by VirtualSize.
806 * If VirtualSize is not provided, use SizeOfRawData.
807 *
808 * @sec: section header
809 * Return: size of section in memory
810 */
811static u32 section_size(IMAGE_SECTION_HEADER *sec)
812{
813 if (sec->Misc.VirtualSize)
814 return sec->Misc.VirtualSize;
815 else
816 return sec->SizeOfRawData;
817}
818
8f7e2b29
HS
819/**
820 * efi_load_pe() - relocate EFI binary
821 *
cb149c66 822 * This function loads all sections from a PE binary into a newly reserved
8f7e2b29
HS
823 * piece of memory. On success the entry point is returned as handle->entry.
824 *
825 * @handle: loaded image handle
826 * @efi: pointer to the EFI binary
4540dabd 827 * @efi_size: size of @efi binary
8f7e2b29
HS
828 * @loaded_image_info: loaded image protocol
829 * Return: status code
cb149c66 830 */
4540dabd
AT
831efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
832 void *efi, size_t efi_size,
8f7e2b29 833 struct efi_loaded_image *loaded_image_info)
cb149c66
AG
834{
835 IMAGE_NT_HEADERS32 *nt;
836 IMAGE_DOS_HEADER *dos;
837 IMAGE_SECTION_HEADER *sections;
838 int num_sections;
839 void *efi_reloc;
840 int i;
841 const IMAGE_BASE_RELOCATION *rel;
842 unsigned long rel_size;
843 int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
e2dc4229 844 uint64_t image_base;
cb149c66 845 unsigned long virt_size = 0;
61a5ced6 846 int supported = 0;
4540dabd
AT
847 efi_status_t ret;
848
5dad05a0
HS
849 ret = efi_check_pe(efi, efi_size, (void **)&nt);
850 if (ret != EFI_SUCCESS) {
851 log_err("Not a PE-COFF file\n");
852 return EFI_LOAD_ERROR;
cb149c66
AG
853 }
854
61a5ced6
IG
855 for (i = 0; machines[i]; i++)
856 if (machines[i] == nt->FileHeader.Machine) {
857 supported = 1;
858 break;
859 }
860
861 if (!supported) {
24586059
HS
862 log_err("Machine type 0x%04x is not supported\n",
863 nt->FileHeader.Machine);
5dad05a0 864 return EFI_LOAD_ERROR;
61a5ced6
IG
865 }
866
cb149c66
AG
867 num_sections = nt->FileHeader.NumberOfSections;
868 sections = (void *)&nt->OptionalHeader +
869 nt->FileHeader.SizeOfOptionalHeader;
870
4540dabd
AT
871 if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
872 - efi)) {
24586059 873 log_err("Invalid number of sections: %d\n", num_sections);
5dad05a0 874 return EFI_LOAD_ERROR;
4540dabd
AT
875 }
876
877 /* Authenticate an image */
0f7878b8 878 if (efi_image_authenticate(efi, efi_size)) {
4540dabd 879 handle->auth_status = EFI_IMAGE_AUTH_PASSED;
0f7878b8 880 } else {
4540dabd 881 handle->auth_status = EFI_IMAGE_AUTH_FAILED;
0f7878b8
HS
882 log_err("Image not authenticated\n");
883 }
4540dabd
AT
884
885 /* Calculate upper virtual address boundary */
cb149c66
AG
886 for (i = num_sections - 1; i >= 0; i--) {
887 IMAGE_SECTION_HEADER *sec = &sections[i];
1ea133ac 888
cb149c66 889 virt_size = max_t(unsigned long, virt_size,
1ea133ac 890 sec->VirtualAddress + section_size(sec));
cb149c66
AG
891 }
892
893 /* Read 32/64bit specific header bits */
61a5ced6 894 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
cb149c66
AG
895 IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
896 IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
e2dc4229 897 image_base = opt->ImageBase;
36b41a3c 898 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
126a43f1 899 handle->image_type = opt->Subsystem;
ebdea88d
IA
900 efi_reloc = efi_alloc_aligned_pages(virt_size,
901 loaded_image_info->image_code_type,
902 opt->SectionAlignment);
cb149c66 903 if (!efi_reloc) {
24586059 904 log_err("Out of memory\n");
4540dabd
AT
905 ret = EFI_OUT_OF_RESOURCES;
906 goto err;
cb149c66 907 }
8f7e2b29 908 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
cb149c66
AG
909 rel_size = opt->DataDirectory[rel_idx].Size;
910 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
61a5ced6 911 } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
cb149c66 912 IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
e2dc4229 913 image_base = opt->ImageBase;
36b41a3c 914 efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
126a43f1 915 handle->image_type = opt->Subsystem;
ebdea88d
IA
916 efi_reloc = efi_alloc_aligned_pages(virt_size,
917 loaded_image_info->image_code_type,
918 opt->SectionAlignment);
cb149c66 919 if (!efi_reloc) {
24586059 920 log_err("Out of memory\n");
4540dabd
AT
921 ret = EFI_OUT_OF_RESOURCES;
922 goto err;
cb149c66 923 }
8f7e2b29 924 handle->entry = efi_reloc + opt->AddressOfEntryPoint;
cb149c66
AG
925 rel_size = opt->DataDirectory[rel_idx].Size;
926 rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
927 } else {
24586059
HS
928 log_err("Invalid optional header magic %x\n",
929 nt->OptionalHeader.Magic);
4540dabd
AT
930 ret = EFI_LOAD_ERROR;
931 goto err;
cb149c66
AG
932 }
933
07754cb0 934#if IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)
163a0d7e 935 /* Measure an PE/COFF image */
f9b51dcf
MK
936 ret = tcg2_measure_pe_image(efi, efi_size, handle, loaded_image_info);
937 if (ret == EFI_SECURITY_VIOLATION) {
938 /*
939 * TCG2 Protocol is installed but no TPM device found,
940 * this is not expected.
941 */
942 log_err("PE image measurement failed, no tpm device found\n");
943 goto err;
944 }
945
163a0d7e
MK
946#endif
947
8458bf64 948 /* Copy PE headers */
4540dabd
AT
949 memcpy(efi_reloc, efi,
950 sizeof(*dos)
951 + sizeof(*nt)
952 + nt->FileHeader.SizeOfOptionalHeader
953 + num_sections * sizeof(IMAGE_SECTION_HEADER));
8458bf64 954
cb149c66
AG
955 /* Load sections into RAM */
956 for (i = num_sections - 1; i >= 0; i--) {
957 IMAGE_SECTION_HEADER *sec = &sections[i];
1ea133ac
HS
958 u32 copy_size = section_size(sec);
959
960 if (copy_size > sec->SizeOfRawData) {
961 copy_size = sec->SizeOfRawData;
962 memset(efi_reloc + sec->VirtualAddress, 0,
963 sec->Misc.VirtualSize);
964 }
cb149c66
AG
965 memcpy(efi_reloc + sec->VirtualAddress,
966 efi + sec->PointerToRawData,
1ea133ac 967 copy_size);
cb149c66
AG
968 }
969
970 /* Run through relocations */
e2dc4229
IG
971 if (efi_loader_relocate(rel, rel_size, efi_reloc,
972 (unsigned long)image_base) != EFI_SUCCESS) {
da684a64
HS
973 efi_free_pages((uintptr_t) efi_reloc,
974 (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
4540dabd
AT
975 ret = EFI_LOAD_ERROR;
976 goto err;
da684a64 977 }
cb149c66
AG
978
979 /* Flush cache */
d0d90993 980 flush_cache((ulong)efi_reloc,
89aea436 981 ALIGN(virt_size, EFI_CACHELINE_SIZE));
19d41f49
HS
982
983 /*
984 * If on x86 a write affects a prefetched instruction,
985 * the prefetch queue is invalidated.
986 */
987 if (!CONFIG_IS_ENABLED(X86))
988 invalidate_icache_all();
cb149c66
AG
989
990 /* Populate the loaded image interface bits */
8458bf64
AT
991 loaded_image_info->image_base = efi_reloc;
992 loaded_image_info->image_size = virt_size;
cb149c66 993
4540dabd
AT
994 if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
995 return EFI_SUCCESS;
996 else
997 return EFI_SECURITY_VIOLATION;
998
999err:
1000 return ret;
cb149c66 1001}
This page took 0.322052 seconds and 4 git commands to generate.