Coverage Report

Created: 2026-03-11 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/u-boot/lib/efi_loader/efi_image_loader.c
Line
Count
Source
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
#define LOG_CATEGORY LOGC_EFI
11
12
#include <cpu_func.h>
13
#include <efi_loader.h>
14
#include <log.h>
15
#include <malloc.h>
16
#include <mapmem.h>
17
#include <pe.h>
18
#include <sort.h>
19
#include <crypto/mscode.h>
20
#include <crypto/pkcs7_parser.h>
21
#include <linux/err.h>
22
23
const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
24
const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
25
const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
26
const efi_guid_t efi_guid_loaded_image_device_path =
27
    EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
28
const efi_guid_t efi_simple_file_system_protocol_guid =
29
    EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
30
const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
31
32
static int machines[] = {
33
#if defined(__aarch64__)
34
  IMAGE_FILE_MACHINE_ARM64,
35
#elif defined(__arm__)
36
  IMAGE_FILE_MACHINE_ARM,
37
  IMAGE_FILE_MACHINE_THUMB,
38
  IMAGE_FILE_MACHINE_ARMNT,
39
#endif
40
41
#if defined(__x86_64__)
42
  IMAGE_FILE_MACHINE_AMD64,
43
#elif defined(__i386__)
44
  IMAGE_FILE_MACHINE_I386,
45
#endif
46
47
#if defined(__riscv) && (__riscv_xlen == 32)
48
  IMAGE_FILE_MACHINE_RISCV32,
49
#endif
50
51
#if defined(__riscv) && (__riscv_xlen == 64)
52
  IMAGE_FILE_MACHINE_RISCV64,
53
#endif
54
  0 };
55
56
/**
57
 * efi_print_image_info() - print information about a loaded image
58
 *
59
 * If the program counter is located within the image the offset to the base
60
 * address is shown.
61
 *
62
 * @obj:  EFI object
63
 * @image:  loaded image
64
 * @pc:   program counter (use NULL to suppress offset output)
65
 * Return:  status code
66
 */
67
static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
68
           struct efi_loaded_image *image,
69
           void *pc)
70
0
{
71
0
  printf("UEFI image");
72
0
  printf(" [0x%p:0x%p]",
73
0
         image->image_base, image->image_base + image->image_size - 1);
74
0
  if (pc && pc >= image->image_base &&
75
0
      pc < image->image_base + image->image_size)
76
0
    printf(" pc=0x%zx", pc - image->image_base);
77
0
  if (image->file_path)
78
0
    printf(" '%pD'", image->file_path);
79
0
  printf("\n");
80
0
  return EFI_SUCCESS;
81
0
}
82
83
/**
84
 * efi_print_image_infos() - print information about all loaded images
85
 *
86
 * @pc:   program counter (use NULL to suppress offset output)
87
 */
88
void efi_print_image_infos(void *pc)
89
0
{
90
0
  struct efi_object *efiobj;
91
0
  struct efi_handler *handler;
92
93
0
  list_for_each_entry(efiobj, &efi_obj_list, link) {
94
0
    list_for_each_entry(handler, &efiobj->protocols, link) {
95
0
      if (!guidcmp(&handler->guid, &efi_guid_loaded_image)) {
96
0
        efi_print_image_info(
97
0
          (struct efi_loaded_image_obj *)efiobj,
98
0
          handler->protocol_interface, pc);
99
0
      }
100
0
    }
101
0
  }
102
0
}
103
104
/**
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
 */
113
static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
114
      unsigned long rel_size, void *efi_reloc,
115
      unsigned long pref_address)
116
0
{
117
0
  unsigned long delta = (unsigned long)efi_reloc - pref_address;
118
0
  const IMAGE_BASE_RELOCATION *end;
119
0
  int i;
120
121
0
  if (delta == 0)
122
0
    return EFI_SUCCESS;
123
124
0
  end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
125
0
  while (rel + 1 < end && rel->SizeOfBlock) {
126
0
    const uint16_t *relocs = (const uint16_t *)(rel + 1);
127
0
    i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
128
0
    while (i--) {
129
0
      uint32_t offset = (uint32_t)(*relocs & 0xfff) +
130
0
            rel->VirtualAddress;
131
0
      int type = *relocs >> EFI_PAGE_SHIFT;
132
0
      uint64_t *x64 = efi_reloc + offset;
133
0
      uint32_t *x32 = efi_reloc + offset;
134
0
      uint16_t *x16 = efi_reloc + offset;
135
136
0
      switch (type) {
137
0
      case IMAGE_REL_BASED_ABSOLUTE:
138
0
        break;
139
0
      case IMAGE_REL_BASED_HIGH:
140
0
        *x16 += ((uint32_t)delta) >> 16;
141
0
        break;
142
0
      case IMAGE_REL_BASED_LOW:
143
0
        *x16 += (uint16_t)delta;
144
0
        break;
145
0
      case IMAGE_REL_BASED_HIGHLOW:
146
0
        *x32 += (uint32_t)delta;
147
0
        break;
148
0
      case IMAGE_REL_BASED_DIR64:
149
0
        *x64 += (uint64_t)delta;
150
0
        break;
151
#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) {
160
          log_err("Unsupported reloc offset\n");
161
          return EFI_LOAD_ERROR;
162
        }
163
        break;
164
#endif
165
0
      default:
166
0
        log_err("Unknown Relocation off %x type %x\n",
167
0
          offset, type);
168
0
        return EFI_LOAD_ERROR;
169
0
      }
170
0
      relocs++;
171
0
    }
172
0
    rel = (const IMAGE_BASE_RELOCATION *)relocs;
173
0
  }
174
0
  return EFI_SUCCESS;
175
0
}
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
0
{
189
0
  switch (image_type) {
190
0
  case IMAGE_SUBSYSTEM_EFI_APPLICATION:
191
0
    loaded_image_info->image_code_type = EFI_LOADER_CODE;
192
0
    loaded_image_info->image_data_type = EFI_LOADER_DATA;
193
0
    break;
194
0
  case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
195
0
    loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
196
0
    loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
197
0
    break;
198
0
  case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
199
0
  case IMAGE_SUBSYSTEM_EFI_ROM:
200
0
    loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
201
0
    loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
202
0
    break;
203
0
  default:
204
0
    log_err("invalid image type: %u\n", image_type);
205
    /* Let's assume it is an application */
206
0
    loaded_image_info->image_code_type = EFI_LOADER_CODE;
207
0
    loaded_image_info->image_data_type = EFI_LOADER_DATA;
208
0
    break;
209
0
  }
210
0
}
211
212
/**
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
 *
219
 * Take one entry of region \[@start, @end\[ and insert it into the list.
220
 *
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
 */
229
efi_status_t efi_image_region_add(struct efi_image_regions *regs,
230
          const void *start, const void *end,
231
          int nocheck)
232
0
{
233
0
  struct image_region *reg;
234
0
  int i, j;
235
236
0
  if (regs->num >= regs->max) {
237
0
    log_err("%s: no more room for regions\n", __func__);
238
0
    return EFI_OUT_OF_RESOURCES;
239
0
  }
240
241
0
  if (end < start)
242
0
    return EFI_INVALID_PARAMETER;
243
244
0
  for (i = 0; i < regs->num; i++) {
245
0
    reg = &regs->reg[i];
246
0
    if (nocheck)
247
0
      continue;
248
249
    /* new data after registered region */
250
0
    if (start >= reg->data + reg->size)
251
0
      continue;
252
253
    /* new data preceding registered region */
254
0
    if (end <= reg->data) {
255
0
      for (j = regs->num - 1; j >= i; j--)
256
0
        memcpy(&regs->reg[j + 1], &regs->reg[j],
257
0
               sizeof(*reg));
258
0
      break;
259
0
    }
260
261
    /* new data overlapping registered region */
262
0
    log_err("%s: new region already part of another\n", __func__);
263
0
    return EFI_INVALID_PARAMETER;
264
0
  }
265
266
0
  reg = &regs->reg[i];
267
0
  reg->data = start;
268
0
  reg->size = end - start;
269
0
  regs->num++;
270
271
0
  return EFI_SUCCESS;
272
0
}
273
274
/**
275
 * 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
278
 *
279
 * Compare the virtual addresses of two sections of an portable executable.
280
 * The arguments are defined as const void * to allow usage with qsort().
281
 *
282
 * 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.
285
 */
286
static int cmp_pe_section(const void *arg1, const void *arg2)
287
0
{
288
0
  const IMAGE_SECTION_HEADER *section1, *section2;
289
290
0
  section1 = *((const IMAGE_SECTION_HEADER **)arg1);
291
0
  section2 = *((const IMAGE_SECTION_HEADER **)arg2);
292
293
0
  if (section1->VirtualAddress < section2->VirtualAddress)
294
0
    return -1;
295
0
  else if (section1->VirtualAddress == section2->VirtualAddress)
296
0
    return 0;
297
0
  else
298
0
    return 1;
299
0
}
300
301
/**
302
 * 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
 */
311
void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
312
0
{
313
0
  size_t new_efi_size;
314
0
  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
0
  if (!IS_ALIGNED(*efi_size, 8)) {
321
0
    new_efi_size = ALIGN(*efi_size, 8);
322
0
    new_efi = calloc(new_efi_size, 1);
323
0
    if (!new_efi)
324
0
      return NULL;
325
0
    memcpy(new_efi, efi, *efi_size);
326
0
    *efi_size = new_efi_size;
327
0
    return new_efi;
328
0
  } else {
329
0
    return efi;
330
0
  }
331
0
}
332
333
/**
334
 * efi_image_parse() - parse a PE image
335
 * @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
 */
348
bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
349
         WIN_CERTIFICATE **auth, size_t *auth_len)
350
0
{
351
0
  struct efi_image_regions *regs;
352
0
  IMAGE_DOS_HEADER *dos;
353
0
  IMAGE_NT_HEADERS32 *nt;
354
0
  IMAGE_SECTION_HEADER *sections, **sorted;
355
0
  int num_regions, num_sections, i;
356
0
  int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
357
0
  u32 align, size, authsz, authoff;
358
0
  size_t bytes_hashed;
359
360
0
  dos = (void *)efi;
361
0
  nt = (void *)(efi + dos->e_lfanew);
362
0
  authoff = 0;
363
0
  authsz = 0;
364
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
0
  num_regions = 3; /* for header */
371
0
  num_regions += nt->FileHeader.NumberOfSections;
372
0
  num_regions++; /* for extra */
373
374
0
  regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
375
0
          1);
376
0
  if (!regs)
377
0
    goto err;
378
0
  regs->max = num_regions;
379
380
  /*
381
   * Collect data regions for hash calculation
382
   * 1. File headers
383
   */
384
0
  if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
385
0
    IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
386
0
    IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
387
388
    /* Skip CheckSum */
389
0
    efi_image_region_add(regs, efi, &opt->CheckSum, 0);
390
0
    if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
391
0
      efi_image_region_add(regs,
392
0
               &opt->Subsystem,
393
0
               efi + opt->SizeOfHeaders, 0);
394
0
    } else {
395
      /* Skip Certificates Table */
396
0
      efi_image_region_add(regs,
397
0
               &opt->Subsystem,
398
0
               &opt->DataDirectory[ctidx], 0);
399
0
      efi_image_region_add(regs,
400
0
               &opt->DataDirectory[ctidx] + 1,
401
0
               efi + opt->SizeOfHeaders, 0);
402
403
0
      authoff = opt->DataDirectory[ctidx].VirtualAddress;
404
0
      authsz = opt->DataDirectory[ctidx].Size;
405
0
    }
406
407
0
    bytes_hashed = opt->SizeOfHeaders;
408
0
    align = opt->FileAlignment;
409
0
  } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
410
0
    IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
411
412
    /* Skip CheckSum */
413
0
    efi_image_region_add(regs, efi, &opt->CheckSum, 0);
414
0
    if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
415
0
      efi_image_region_add(regs,
416
0
               &opt->Subsystem,
417
0
               efi + opt->SizeOfHeaders, 0);
418
0
    } else {
419
      /* Skip Certificates Table */
420
0
      efi_image_region_add(regs, &opt->Subsystem,
421
0
               &opt->DataDirectory[ctidx], 0);
422
0
      efi_image_region_add(regs,
423
0
               &opt->DataDirectory[ctidx] + 1,
424
0
               efi + opt->SizeOfHeaders, 0);
425
426
0
      authoff = opt->DataDirectory[ctidx].VirtualAddress;
427
0
      authsz = opt->DataDirectory[ctidx].Size;
428
0
    }
429
430
0
    bytes_hashed = opt->SizeOfHeaders;
431
0
    align = opt->FileAlignment;
432
0
  } else {
433
0
    log_err("%s: Invalid optional header magic %x\n", __func__,
434
0
      nt->OptionalHeader.Magic);
435
0
    goto err;
436
0
  }
437
438
  /* 2. Sections */
439
0
  num_sections = nt->FileHeader.NumberOfSections;
440
0
  sections = (void *)((uint8_t *)&nt->OptionalHeader +
441
0
          nt->FileHeader.SizeOfOptionalHeader);
442
0
  sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
443
0
  if (!sorted) {
444
0
    log_err("%s: Out of memory\n", __func__);
445
0
    goto err;
446
0
  }
447
448
  /*
449
   * Make sure the section list is in ascending order.
450
   */
451
0
  for (i = 0; i < num_sections; i++)
452
0
    sorted[i] = &sections[i];
453
0
  qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
454
455
0
  for (i = 0; i < num_sections; i++) {
456
0
    if (!sorted[i]->SizeOfRawData)
457
0
      continue;
458
459
0
    size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
460
0
    efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
461
0
             efi + sorted[i]->PointerToRawData + size,
462
0
             0);
463
0
    log_debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
464
0
        i, sorted[i]->Name,
465
0
        sorted[i]->PointerToRawData,
466
0
        sorted[i]->PointerToRawData + size,
467
0
        sorted[i]->VirtualAddress,
468
0
        sorted[i]->VirtualAddress
469
0
          + sorted[i]->Misc.VirtualSize);
470
471
0
    bytes_hashed += size;
472
0
  }
473
0
  free(sorted);
474
475
  /* 3. Extra data excluding Certificates Table */
476
0
  if (bytes_hashed + authsz < len) {
477
0
    log_debug("extra data for hash: %zu\n",
478
0
        len - (bytes_hashed + authsz));
479
0
    efi_image_region_add(regs, efi + bytes_hashed,
480
0
             efi + len - authsz, 0);
481
0
  }
482
483
  /* Return Certificates Table */
484
0
  if (authsz) {
485
0
    if (len < authoff + authsz) {
486
0
      log_err("%s: Size for auth too large: %u >= %zu\n",
487
0
        __func__, authsz, len - authoff);
488
0
      goto err;
489
0
    }
490
0
    if (authsz < sizeof(*auth)) {
491
0
      log_err("%s: Size for auth too small: %u < %zu\n",
492
0
        __func__, authsz, sizeof(*auth));
493
0
      goto err;
494
0
    }
495
0
    *auth = efi + authoff;
496
0
    *auth_len = authsz;
497
0
    log_debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff,
498
0
        authsz);
499
0
  } else {
500
0
    *auth = NULL;
501
0
    *auth_len = 0;
502
0
  }
503
504
0
  *regp = regs;
505
506
0
  return true;
507
508
0
err:
509
0
  free(regs);
510
511
0
  return false;
512
0
}
513
514
#ifdef CONFIG_EFI_SECURE_BOOT
515
/**
516
 * 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
 */
526
static bool efi_image_verify_digest(struct efi_image_regions *regs,
527
            struct pkcs7_message *msg)
528
0
{
529
0
  struct pefile_context ctx;
530
0
  void *hash;
531
0
  int hash_len, ret;
532
533
0
  const void *data;
534
0
  size_t data_len;
535
0
  size_t asn1hdrlen;
536
537
  /* get pkcs7's contentInfo */
538
0
  ret = pkcs7_get_content_data(msg, &data, &data_len, &asn1hdrlen);
539
0
  if (ret < 0 || !data)
540
0
    return false;
541
542
  /* parse data and retrieve a message digest into ctx */
543
0
  ret = mscode_parse(&ctx, data, data_len, asn1hdrlen);
544
0
  if (ret < 0)
545
0
    return false;
546
547
  /* calculate a hash value of PE image */
548
0
  hash = NULL;
549
0
  if (!efi_hash_regions(regs->reg, regs->num, &hash, ctx.digest_algo,
550
0
            &hash_len))
551
0
    return false;
552
553
  /* match the digest */
554
0
  if (ctx.digest_len != hash_len || memcmp(ctx.digest, hash, hash_len))
555
0
    return false;
556
557
0
  return true;
558
0
}
559
560
/**
561
 * efi_image_authenticate() - verify a signature of signed image
562
 * @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
 */
581
static bool efi_image_authenticate(void *efi, size_t efi_size)
582
0
{
583
0
  struct efi_image_regions *regs = NULL;
584
0
  WIN_CERTIFICATE *wincerts = NULL, *wincert;
585
0
  size_t wincerts_len;
586
0
  struct pkcs7_message *msg = NULL;
587
0
  struct efi_signature_store *db = NULL, *dbx = NULL;
588
0
  void *new_efi = NULL;
589
0
  u8 *auth, *wincerts_end;
590
0
  u64 new_efi_size = efi_size;
591
0
  size_t auth_size;
592
0
  bool ret = false;
593
594
0
  log_debug("%s: Enter, %d\n", __func__, ret);
595
596
0
  if (!efi_secure_boot_enabled())
597
0
    return true;
598
599
0
  new_efi = efi_prepare_aligned_image(efi, &new_efi_size);
600
0
  if (!new_efi)
601
0
    return false;
602
603
0
  if (!efi_image_parse(new_efi, new_efi_size, &regs, &wincerts,
604
0
           &wincerts_len)) {
605
0
    log_err("Parsing PE executable image failed\n");
606
0
    goto out;
607
0
  }
608
609
  /*
610
   * verify signature using db and dbx
611
   */
612
0
  db = efi_sigstore_parse_sigdb(u"db");
613
0
  if (!db) {
614
0
    log_err("Getting signature database(db) failed\n");
615
0
    goto out;
616
0
  }
617
618
0
  dbx = efi_sigstore_parse_sigdb(u"dbx");
619
0
  if (!dbx) {
620
0
    log_err("Getting signature database(dbx) failed\n");
621
0
    goto out;
622
0
  }
623
624
0
  if (efi_signature_lookup_digest(regs, dbx, true)) {
625
0
    log_debug("Image's digest was found in \"dbx\"\n");
626
0
    goto out;
627
0
  }
628
629
  /*
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
636
   *   - unless signature is rejected explicitly with its digest.
637
   */
638
639
0
  for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
640
0
       (u8 *)wincert < wincerts_end;
641
0
       wincert = (WIN_CERTIFICATE *)
642
0
      ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
643
0
    if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
644
0
      break;
645
646
0
    if (wincert->dwLength <= sizeof(*wincert)) {
647
0
      log_debug("dwLength too small: %u < %zu\n",
648
0
          wincert->dwLength, sizeof(*wincert));
649
0
      continue;
650
0
    }
651
652
0
    log_debug("WIN_CERTIFICATE_TYPE: 0x%x\n",
653
0
        wincert->wCertificateType);
654
655
0
    auth = (u8 *)wincert + sizeof(*wincert);
656
0
    auth_size = wincert->dwLength - sizeof(*wincert);
657
0
    if (wincert->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
658
0
      if (auth + sizeof(efi_guid_t) >= wincerts_end)
659
0
        break;
660
661
0
      if (auth_size <= sizeof(efi_guid_t)) {
662
0
        log_debug("dwLength too small: %u < %zu\n",
663
0
            wincert->dwLength, sizeof(*wincert));
664
0
        continue;
665
0
      }
666
0
      if (guidcmp(auth, &efi_guid_cert_type_pkcs7)) {
667
0
        log_debug("Certificate type not supported: %pUs\n",
668
0
            auth);
669
0
        ret = false;
670
0
        goto out;
671
0
      }
672
673
0
      auth += sizeof(efi_guid_t);
674
0
      auth_size -= sizeof(efi_guid_t);
675
0
    } else if (wincert->wCertificateType
676
0
        != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
677
0
      log_debug("Certificate type not supported\n");
678
0
      ret = false;
679
0
      goto out;
680
0
    }
681
682
0
    msg = pkcs7_parse_message(auth, auth_size);
683
0
    if (IS_ERR(msg)) {
684
0
      log_err("Parsing image's signature failed\n");
685
0
      msg = NULL;
686
0
      continue;
687
0
    }
688
689
    /*
690
     * verify signatures in pkcs7's signedInfos which are
691
     * to authenticate the integrity of pkcs7's contentInfo.
692
     *
693
     * 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
     */
711
    /* try black-list first */
712
0
    if (efi_signature_verify_one(regs, msg, dbx)) {
713
0
      ret = false;
714
0
      log_debug("Signature was rejected by \"dbx\"\n");
715
0
      goto out;
716
0
    }
717
718
0
    if (!efi_signature_check_signers(msg, dbx)) {
719
0
      ret = false;
720
0
      log_debug("Signer(s) in \"dbx\"\n");
721
0
      goto out;
722
0
    }
723
724
    /* try white-list */
725
0
    if (!efi_signature_verify(regs, msg, db, dbx)) {
726
0
      log_debug("Signature was not verified by \"db\"\n");
727
0
      continue;
728
0
    }
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
0
    if (efi_image_verify_digest(regs, msg)) {
735
0
      ret = true;
736
0
      continue;
737
0
    }
738
739
0
    log_debug("Message digest doesn't match\n");
740
0
  }
741
742
  /* last resort try the image sha256 hash in db */
743
0
  if (!ret && efi_signature_lookup_digest(regs, db, false))
744
0
    ret = true;
745
746
0
out:
747
0
  efi_sigstore_free(db);
748
0
  efi_sigstore_free(dbx);
749
0
  pkcs7_free_message(msg);
750
0
  free(regs);
751
0
  if (new_efi != efi)
752
0
    free(new_efi);
753
754
0
  log_debug("%s: Exit, %d\n", __func__, ret);
755
0
  return ret;
756
0
}
757
#else
758
static bool efi_image_authenticate(void *efi, size_t efi_size)
759
{
760
  return true;
761
}
762
#endif /* CONFIG_EFI_SECURE_BOOT */
763
764
/**
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
 */
772
efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
773
0
{
774
0
  IMAGE_DOS_HEADER *dos = buffer;
775
0
  IMAGE_NT_HEADERS32 *nt;
776
777
0
  if (size < sizeof(*dos))
778
0
    return EFI_INVALID_PARAMETER;
779
780
  /* Check for DOS magix */
781
0
  if (dos->e_magic != IMAGE_DOS_SIGNATURE)
782
0
    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
0
  if (size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32))
790
0
    return EFI_INVALID_PARAMETER;
791
0
  nt = (IMAGE_NT_HEADERS32 *)((u8 *)buffer + dos->e_lfanew);
792
793
  /* Check for PE-COFF magic */
794
0
  if (nt->Signature != IMAGE_NT_SIGNATURE)
795
0
    return EFI_INVALID_PARAMETER;
796
797
0
  if (nt_header)
798
0
    *nt_header = nt;
799
800
0
  return EFI_SUCCESS;
801
0
}
802
803
/**
804
 * 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
 */
812
static u32 section_size(IMAGE_SECTION_HEADER *sec)
813
0
{
814
0
  if (sec->Misc.VirtualSize)
815
0
    return sec->Misc.VirtualSize;
816
0
  else
817
0
    return sec->SizeOfRawData;
818
0
}
819
820
/**
821
 * efi_load_pe() - relocate EFI binary
822
 *
823
 * This function loads all sections from a PE binary into a newly reserved
824
 * 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
828
 * @efi_size:   size of @efi binary
829
 * @loaded_image_info:  loaded image protocol
830
 * Return:    status code
831
 */
832
efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
833
       void *efi, size_t efi_size,
834
       struct efi_loaded_image *loaded_image_info)
835
0
{
836
0
  IMAGE_NT_HEADERS32 *nt;
837
0
  IMAGE_DOS_HEADER *dos;
838
0
  IMAGE_SECTION_HEADER *sections;
839
0
  int num_sections;
840
0
  void *efi_reloc;
841
0
  int i;
842
0
  const IMAGE_BASE_RELOCATION *rel;
843
0
  unsigned long rel_size;
844
0
  int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
845
0
  uint64_t image_base;
846
0
  unsigned long virt_size = 0;
847
0
  int supported = 0;
848
0
  efi_status_t ret;
849
850
0
  ret = efi_check_pe(efi, efi_size, (void **)&nt);
851
0
  if (ret != EFI_SUCCESS) {
852
0
    log_err("Not a PE-COFF file\n");
853
0
    return EFI_LOAD_ERROR;
854
0
  }
855
856
0
  for (i = 0; machines[i]; i++)
857
0
    if (machines[i] == nt->FileHeader.Machine) {
858
0
      supported = 1;
859
0
      break;
860
0
    }
861
862
0
  if (!supported) {
863
0
    log_err("Machine type 0x%04x is not supported\n",
864
0
      nt->FileHeader.Machine);
865
0
    return EFI_LOAD_ERROR;
866
0
  }
867
868
0
  num_sections = nt->FileHeader.NumberOfSections;
869
0
  sections = (void *)&nt->OptionalHeader +
870
0
          nt->FileHeader.SizeOfOptionalHeader;
871
872
0
  if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
873
0
      - efi)) {
874
0
    log_err("Invalid number of sections: %d\n", num_sections);
875
0
    return EFI_LOAD_ERROR;
876
0
  }
877
878
  /* Authenticate an image */
879
0
  if (efi_image_authenticate(efi, efi_size)) {
880
0
    handle->auth_status = EFI_IMAGE_AUTH_PASSED;
881
0
  } else {
882
0
    handle->auth_status = EFI_IMAGE_AUTH_FAILED;
883
0
    log_err("Image not authenticated\n");
884
0
  }
885
886
  /* Calculate upper virtual address boundary */
887
0
  for (i = num_sections - 1; i >= 0; i--) {
888
0
    IMAGE_SECTION_HEADER *sec = &sections[i];
889
890
0
    virt_size = max_t(unsigned long, virt_size,
891
0
          sec->VirtualAddress + section_size(sec));
892
0
  }
893
894
  /* Read 32/64bit specific header bits */
895
0
  if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
896
0
    IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
897
0
    IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
898
0
    image_base = opt->ImageBase;
899
0
    efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
900
0
    handle->image_type = opt->Subsystem;
901
0
    efi_reloc = efi_alloc_aligned_pages(virt_size,
902
0
                loaded_image_info->image_code_type,
903
0
                opt->SectionAlignment);
904
0
    if (!efi_reloc) {
905
0
      log_err("Out of memory\n");
906
0
      ret = EFI_OUT_OF_RESOURCES;
907
0
      goto err;
908
0
    }
909
0
    handle->entry = efi_reloc + opt->AddressOfEntryPoint;
910
0
    rel_size = opt->DataDirectory[rel_idx].Size;
911
0
    rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
912
0
  } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
913
0
    IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
914
0
    image_base = opt->ImageBase;
915
0
    efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
916
0
    handle->image_type = opt->Subsystem;
917
0
    efi_reloc = efi_alloc_aligned_pages(virt_size,
918
0
                loaded_image_info->image_code_type,
919
0
                opt->SectionAlignment);
920
0
    if (!efi_reloc) {
921
0
      log_err("Out of memory\n");
922
0
      ret = EFI_OUT_OF_RESOURCES;
923
0
      goto err;
924
0
    }
925
0
    handle->entry = efi_reloc + opt->AddressOfEntryPoint;
926
0
    rel_size = opt->DataDirectory[rel_idx].Size;
927
0
    rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
928
0
  } else {
929
0
    log_err("Invalid optional header magic %x\n",
930
0
      nt->OptionalHeader.Magic);
931
0
    ret = EFI_LOAD_ERROR;
932
0
    goto err;
933
0
  }
934
935
0
#if IS_ENABLED(CONFIG_EFI_TCG2_PROTOCOL)
936
  /* Measure an PE/COFF image */
937
0
  ret = tcg2_measure_pe_image(efi, efi_size, handle, loaded_image_info);
938
0
  if (ret == EFI_SECURITY_VIOLATION) {
939
    /*
940
     * TCG2 Protocol is installed but no TPM device found,
941
     * this is not expected.
942
     */
943
0
    log_err("PE image measurement failed, no tpm device found\n");
944
0
    goto err;
945
0
  }
946
947
0
#endif
948
949
  /* Copy PE headers */
950
0
  memcpy(efi_reloc, efi,
951
0
         sizeof(*dos)
952
0
     + sizeof(*nt)
953
0
     + nt->FileHeader.SizeOfOptionalHeader
954
0
     + num_sections * sizeof(IMAGE_SECTION_HEADER));
955
956
  /* Load sections into RAM */
957
0
  for (i = num_sections - 1; i >= 0; i--) {
958
0
    IMAGE_SECTION_HEADER *sec = &sections[i];
959
0
    u32 copy_size = section_size(sec);
960
961
0
    if (copy_size > sec->SizeOfRawData) {
962
0
      copy_size = sec->SizeOfRawData;
963
0
      memset(efi_reloc + sec->VirtualAddress, 0,
964
0
             sec->Misc.VirtualSize);
965
0
    }
966
0
    memcpy(efi_reloc + sec->VirtualAddress,
967
0
           efi + sec->PointerToRawData,
968
0
           copy_size);
969
0
  }
970
971
  /* Run through relocations */
972
0
  if (efi_loader_relocate(rel, rel_size, efi_reloc,
973
0
        (unsigned long)image_base) != EFI_SUCCESS) {
974
0
    efi_free_pages((uintptr_t) efi_reloc,
975
0
             (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
976
0
    ret = EFI_LOAD_ERROR;
977
0
    goto err;
978
0
  }
979
980
  /* Flush cache */
981
0
  flush_cache(map_to_sysmem(efi_reloc),
982
0
        ALIGN(virt_size, EFI_CACHELINE_SIZE));
983
984
  /*
985
   * If on x86 a write affects a prefetched instruction,
986
   * the prefetch queue is invalidated.
987
   */
988
0
  if (!CONFIG_IS_ENABLED(X86))
989
0
    invalidate_icache_all();
990
991
  /* Populate the loaded image interface bits */
992
0
  loaded_image_info->image_base = efi_reloc;
993
0
  loaded_image_info->image_size = virt_size;
994
995
0
  if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
996
0
    return EFI_SUCCESS;
997
0
  else
998
0
    return EFI_SECURITY_VIOLATION;
999
1000
0
err:
1001
0
  return ret;
1002
0
}