efi_image_loader.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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. #include <common.h>
  10. #include <cpu_func.h>
  11. #include <efi_loader.h>
  12. #include <malloc.h>
  13. #include <pe.h>
  14. #include <sort.h>
  15. #include "crypto/pkcs7_parser.h"
  16. const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID;
  17. const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID;
  18. const efi_guid_t efi_guid_loaded_image = EFI_LOADED_IMAGE_PROTOCOL_GUID;
  19. const efi_guid_t efi_guid_loaded_image_device_path =
  20. EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID;
  21. const efi_guid_t efi_simple_file_system_protocol_guid =
  22. EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
  23. const efi_guid_t efi_file_info_guid = EFI_FILE_INFO_GUID;
  24. static int machines[] = {
  25. #if defined(__aarch64__)
  26. IMAGE_FILE_MACHINE_ARM64,
  27. #elif defined(__arm__)
  28. IMAGE_FILE_MACHINE_ARM,
  29. IMAGE_FILE_MACHINE_THUMB,
  30. IMAGE_FILE_MACHINE_ARMNT,
  31. #endif
  32. #if defined(__x86_64__)
  33. IMAGE_FILE_MACHINE_AMD64,
  34. #elif defined(__i386__)
  35. IMAGE_FILE_MACHINE_I386,
  36. #endif
  37. #if defined(__riscv) && (__riscv_xlen == 32)
  38. IMAGE_FILE_MACHINE_RISCV32,
  39. #endif
  40. #if defined(__riscv) && (__riscv_xlen == 64)
  41. IMAGE_FILE_MACHINE_RISCV64,
  42. #endif
  43. 0 };
  44. /**
  45. * efi_print_image_info() - print information about a loaded image
  46. *
  47. * If the program counter is located within the image the offset to the base
  48. * address is shown.
  49. *
  50. * @obj: EFI object
  51. * @image: loaded image
  52. * @pc: program counter (use NULL to suppress offset output)
  53. * Return: status code
  54. */
  55. static efi_status_t efi_print_image_info(struct efi_loaded_image_obj *obj,
  56. struct efi_loaded_image *image,
  57. void *pc)
  58. {
  59. printf("UEFI image");
  60. printf(" [0x%p:0x%p]",
  61. image->image_base, image->image_base + image->image_size - 1);
  62. if (pc && pc >= image->image_base &&
  63. pc < image->image_base + image->image_size)
  64. printf(" pc=0x%zx", pc - image->image_base);
  65. if (image->file_path)
  66. printf(" '%pD'", image->file_path);
  67. printf("\n");
  68. return EFI_SUCCESS;
  69. }
  70. /**
  71. * efi_print_image_infos() - print information about all loaded images
  72. *
  73. * @pc: program counter (use NULL to suppress offset output)
  74. */
  75. void efi_print_image_infos(void *pc)
  76. {
  77. struct efi_object *efiobj;
  78. struct efi_handler *handler;
  79. list_for_each_entry(efiobj, &efi_obj_list, link) {
  80. list_for_each_entry(handler, &efiobj->protocols, link) {
  81. if (!guidcmp(handler->guid, &efi_guid_loaded_image)) {
  82. efi_print_image_info(
  83. (struct efi_loaded_image_obj *)efiobj,
  84. handler->protocol_interface, pc);
  85. }
  86. }
  87. }
  88. }
  89. /**
  90. * efi_loader_relocate() - relocate UEFI binary
  91. *
  92. * @rel: pointer to the relocation table
  93. * @rel_size: size of the relocation table in bytes
  94. * @efi_reloc: actual load address of the image
  95. * @pref_address: preferred load address of the image
  96. * Return: status code
  97. */
  98. static efi_status_t efi_loader_relocate(const IMAGE_BASE_RELOCATION *rel,
  99. unsigned long rel_size, void *efi_reloc,
  100. unsigned long pref_address)
  101. {
  102. unsigned long delta = (unsigned long)efi_reloc - pref_address;
  103. const IMAGE_BASE_RELOCATION *end;
  104. int i;
  105. if (delta == 0)
  106. return EFI_SUCCESS;
  107. end = (const IMAGE_BASE_RELOCATION *)((const char *)rel + rel_size);
  108. while (rel < end && rel->SizeOfBlock) {
  109. const uint16_t *relocs = (const uint16_t *)(rel + 1);
  110. i = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(uint16_t);
  111. while (i--) {
  112. uint32_t offset = (uint32_t)(*relocs & 0xfff) +
  113. rel->VirtualAddress;
  114. int type = *relocs >> EFI_PAGE_SHIFT;
  115. uint64_t *x64 = efi_reloc + offset;
  116. uint32_t *x32 = efi_reloc + offset;
  117. uint16_t *x16 = efi_reloc + offset;
  118. switch (type) {
  119. case IMAGE_REL_BASED_ABSOLUTE:
  120. break;
  121. case IMAGE_REL_BASED_HIGH:
  122. *x16 += ((uint32_t)delta) >> 16;
  123. break;
  124. case IMAGE_REL_BASED_LOW:
  125. *x16 += (uint16_t)delta;
  126. break;
  127. case IMAGE_REL_BASED_HIGHLOW:
  128. *x32 += (uint32_t)delta;
  129. break;
  130. case IMAGE_REL_BASED_DIR64:
  131. *x64 += (uint64_t)delta;
  132. break;
  133. #ifdef __riscv
  134. case IMAGE_REL_BASED_RISCV_HI20:
  135. *x32 = ((*x32 & 0xfffff000) + (uint32_t)delta) |
  136. (*x32 & 0x00000fff);
  137. break;
  138. case IMAGE_REL_BASED_RISCV_LOW12I:
  139. case IMAGE_REL_BASED_RISCV_LOW12S:
  140. /* We know that we're 4k aligned */
  141. if (delta & 0xfff) {
  142. printf("Unsupported reloc offset\n");
  143. return EFI_LOAD_ERROR;
  144. }
  145. break;
  146. #endif
  147. default:
  148. printf("Unknown Relocation off %x type %x\n",
  149. offset, type);
  150. return EFI_LOAD_ERROR;
  151. }
  152. relocs++;
  153. }
  154. rel = (const IMAGE_BASE_RELOCATION *)relocs;
  155. }
  156. return EFI_SUCCESS;
  157. }
  158. void __weak invalidate_icache_all(void)
  159. {
  160. /* If the system doesn't support icache_all flush, cross our fingers */
  161. }
  162. /**
  163. * efi_set_code_and_data_type() - determine the memory types to be used for code
  164. * and data.
  165. *
  166. * @loaded_image_info: image descriptor
  167. * @image_type: field Subsystem of the optional header for
  168. * Windows specific field
  169. */
  170. static void efi_set_code_and_data_type(
  171. struct efi_loaded_image *loaded_image_info,
  172. uint16_t image_type)
  173. {
  174. switch (image_type) {
  175. case IMAGE_SUBSYSTEM_EFI_APPLICATION:
  176. loaded_image_info->image_code_type = EFI_LOADER_CODE;
  177. loaded_image_info->image_data_type = EFI_LOADER_DATA;
  178. break;
  179. case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
  180. loaded_image_info->image_code_type = EFI_BOOT_SERVICES_CODE;
  181. loaded_image_info->image_data_type = EFI_BOOT_SERVICES_DATA;
  182. break;
  183. case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
  184. case IMAGE_SUBSYSTEM_EFI_ROM:
  185. loaded_image_info->image_code_type = EFI_RUNTIME_SERVICES_CODE;
  186. loaded_image_info->image_data_type = EFI_RUNTIME_SERVICES_DATA;
  187. break;
  188. default:
  189. printf("%s: invalid image type: %u\n", __func__, image_type);
  190. /* Let's assume it is an application */
  191. loaded_image_info->image_code_type = EFI_LOADER_CODE;
  192. loaded_image_info->image_data_type = EFI_LOADER_DATA;
  193. break;
  194. }
  195. }
  196. #ifdef CONFIG_EFI_SECURE_BOOT
  197. /**
  198. * cmp_pe_section - compare two sections
  199. * @arg1: Pointer to pointer to first section
  200. * @arg2: Pointer to pointer to second section
  201. *
  202. * Compare two sections in PE image.
  203. *
  204. * Return: -1, 0, 1 respectively if arg1 < arg2, arg1 == arg2 or
  205. * arg1 > arg2
  206. */
  207. static int cmp_pe_section(const void *arg1, const void *arg2)
  208. {
  209. const IMAGE_SECTION_HEADER *section1, *section2;
  210. section1 = *((const IMAGE_SECTION_HEADER **)arg1);
  211. section2 = *((const IMAGE_SECTION_HEADER **)arg2);
  212. if (section1->VirtualAddress < section2->VirtualAddress)
  213. return -1;
  214. else if (section1->VirtualAddress == section2->VirtualAddress)
  215. return 0;
  216. else
  217. return 1;
  218. }
  219. /**
  220. * efi_image_parse - parse a PE image
  221. * @efi: Pointer to image
  222. * @len: Size of @efi
  223. * @regp: Pointer to a list of regions
  224. * @auth: Pointer to a pointer to authentication data in PE
  225. * @auth_len: Size of @auth
  226. *
  227. * Parse image binary in PE32(+) format, assuming that sanity of PE image
  228. * has been checked by a caller.
  229. * On success, an address of authentication data in @efi and its size will
  230. * be returned in @auth and @auth_len, respectively.
  231. *
  232. * Return: true on success, false on error
  233. */
  234. bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
  235. WIN_CERTIFICATE **auth, size_t *auth_len)
  236. {
  237. struct efi_image_regions *regs;
  238. IMAGE_DOS_HEADER *dos;
  239. IMAGE_NT_HEADERS32 *nt;
  240. IMAGE_SECTION_HEADER *sections, **sorted;
  241. int num_regions, num_sections, i;
  242. int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
  243. u32 align, size, authsz, authoff;
  244. size_t bytes_hashed;
  245. dos = (void *)efi;
  246. nt = (void *)(efi + dos->e_lfanew);
  247. /*
  248. * Count maximum number of regions to be digested.
  249. * We don't have to have an exact number here.
  250. * See efi_image_region_add()'s in parsing below.
  251. */
  252. num_regions = 3; /* for header */
  253. num_regions += nt->FileHeader.NumberOfSections;
  254. num_regions++; /* for extra */
  255. regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
  256. 1);
  257. if (!regs)
  258. goto err;
  259. regs->max = num_regions;
  260. /*
  261. * Collect data regions for hash calculation
  262. * 1. File headers
  263. */
  264. if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  265. IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
  266. IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
  267. /* Skip CheckSum */
  268. efi_image_region_add(regs, efi, &opt->CheckSum, 0);
  269. if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
  270. efi_image_region_add(regs,
  271. &opt->CheckSum + 1,
  272. efi + opt->SizeOfHeaders, 0);
  273. } else {
  274. /* Skip Certificates Table */
  275. efi_image_region_add(regs,
  276. &opt->CheckSum + 1,
  277. &opt->DataDirectory[ctidx], 0);
  278. efi_image_region_add(regs,
  279. &opt->DataDirectory[ctidx] + 1,
  280. efi + opt->SizeOfHeaders, 0);
  281. }
  282. bytes_hashed = opt->SizeOfHeaders;
  283. align = opt->FileAlignment;
  284. authoff = opt->DataDirectory[ctidx].VirtualAddress;
  285. authsz = opt->DataDirectory[ctidx].Size;
  286. } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  287. IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
  288. efi_image_region_add(regs, efi, &opt->CheckSum, 0);
  289. efi_image_region_add(regs, &opt->CheckSum + 1,
  290. &opt->DataDirectory[ctidx], 0);
  291. efi_image_region_add(regs, &opt->DataDirectory[ctidx] + 1,
  292. efi + opt->SizeOfHeaders, 0);
  293. bytes_hashed = opt->SizeOfHeaders;
  294. align = opt->FileAlignment;
  295. authoff = opt->DataDirectory[ctidx].VirtualAddress;
  296. authsz = opt->DataDirectory[ctidx].Size;
  297. } else {
  298. debug("%s: Invalid optional header magic %x\n", __func__,
  299. nt->OptionalHeader.Magic);
  300. goto err;
  301. }
  302. /* 2. Sections */
  303. num_sections = nt->FileHeader.NumberOfSections;
  304. sections = (void *)((uint8_t *)&nt->OptionalHeader +
  305. nt->FileHeader.SizeOfOptionalHeader);
  306. sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
  307. if (!sorted) {
  308. debug("%s: Out of memory\n", __func__);
  309. goto err;
  310. }
  311. /*
  312. * Make sure the section list is in ascending order.
  313. */
  314. for (i = 0; i < num_sections; i++)
  315. sorted[i] = &sections[i];
  316. qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
  317. for (i = 0; i < num_sections; i++) {
  318. if (!sorted[i]->SizeOfRawData)
  319. continue;
  320. size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
  321. efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
  322. efi + sorted[i]->PointerToRawData + size,
  323. 0);
  324. debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
  325. i, sorted[i]->Name,
  326. sorted[i]->PointerToRawData,
  327. sorted[i]->PointerToRawData + size,
  328. sorted[i]->VirtualAddress,
  329. sorted[i]->VirtualAddress
  330. + sorted[i]->Misc.VirtualSize);
  331. bytes_hashed += size;
  332. }
  333. free(sorted);
  334. /* 3. Extra data excluding Certificates Table */
  335. if (bytes_hashed + authsz < len) {
  336. debug("extra data for hash: %lu\n",
  337. len - (bytes_hashed + authsz));
  338. efi_image_region_add(regs, efi + bytes_hashed,
  339. efi + len - authsz, 0);
  340. }
  341. /* Return Certificates Table */
  342. if (authsz) {
  343. if (len < authoff + authsz) {
  344. debug("%s: Size for auth too large: %u >= %zu\n",
  345. __func__, authsz, len - authoff);
  346. goto err;
  347. }
  348. if (authsz < sizeof(*auth)) {
  349. debug("%s: Size for auth too small: %u < %zu\n",
  350. __func__, authsz, sizeof(*auth));
  351. goto err;
  352. }
  353. *auth = efi + authoff;
  354. *auth_len = authsz;
  355. debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff, authsz);
  356. } else {
  357. *auth = NULL;
  358. *auth_len = 0;
  359. }
  360. *regp = regs;
  361. return true;
  362. err:
  363. free(regs);
  364. return false;
  365. }
  366. /**
  367. * efi_image_unsigned_authenticate - authenticate unsigned image with
  368. * SHA256 hash
  369. * @regs: List of regions to be verified
  370. *
  371. * If an image is not signed, it doesn't have a signature. In this case,
  372. * its message digest is calculated and it will be compared with one of
  373. * hash values stored in signature databases.
  374. *
  375. * Return: true if authenticated, false if not
  376. */
  377. static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs)
  378. {
  379. struct efi_signature_store *db = NULL, *dbx = NULL;
  380. bool ret = false;
  381. dbx = efi_sigstore_parse_sigdb(L"dbx");
  382. if (!dbx) {
  383. debug("Getting signature database(dbx) failed\n");
  384. goto out;
  385. }
  386. db = efi_sigstore_parse_sigdb(L"db");
  387. if (!db) {
  388. debug("Getting signature database(db) failed\n");
  389. goto out;
  390. }
  391. /* try black-list first */
  392. if (efi_signature_verify_with_sigdb(regs, NULL, dbx, NULL)) {
  393. debug("Image is not signed and rejected by \"dbx\"\n");
  394. goto out;
  395. }
  396. /* try white-list */
  397. if (efi_signature_verify_with_sigdb(regs, NULL, db, NULL))
  398. ret = true;
  399. else
  400. debug("Image is not signed and not found in \"db\" or \"dbx\"\n");
  401. out:
  402. efi_sigstore_free(db);
  403. efi_sigstore_free(dbx);
  404. return ret;
  405. }
  406. /**
  407. * efi_image_authenticate - verify a signature of signed image
  408. * @efi: Pointer to image
  409. * @efi_size: Size of @efi
  410. *
  411. * A signed image should have its signature stored in a table of its PE header.
  412. * So if an image is signed and only if if its signature is verified using
  413. * signature databases, an image is authenticated.
  414. * If an image is not signed, its validity is checked by using
  415. * efi_image_unsigned_authenticated().
  416. * TODO:
  417. * When AuditMode==0, if the image's signature is not found in
  418. * the authorized database, or is found in the forbidden database,
  419. * the image will not be started and instead, information about it
  420. * will be placed in this table.
  421. * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
  422. * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
  423. * in the certificate table of every image that is validated.
  424. *
  425. * Return: true if authenticated, false if not
  426. */
  427. static bool efi_image_authenticate(void *efi, size_t efi_size)
  428. {
  429. struct efi_image_regions *regs = NULL;
  430. WIN_CERTIFICATE *wincerts = NULL, *wincert;
  431. size_t wincerts_len;
  432. struct pkcs7_message *msg = NULL;
  433. struct efi_signature_store *db = NULL, *dbx = NULL;
  434. struct x509_certificate *cert = NULL;
  435. void *new_efi = NULL;
  436. size_t new_efi_size;
  437. bool ret = false;
  438. if (!efi_secure_boot_enabled())
  439. return true;
  440. /*
  441. * Size must be 8-byte aligned and the trailing bytes must be
  442. * zero'ed. Otherwise hash value may be incorrect.
  443. */
  444. if (efi_size & 0x7) {
  445. new_efi_size = (efi_size + 0x7) & ~0x7ULL;
  446. new_efi = calloc(new_efi_size, 1);
  447. if (!new_efi)
  448. return false;
  449. memcpy(new_efi, efi, efi_size);
  450. efi = new_efi;
  451. efi_size = new_efi_size;
  452. }
  453. if (!efi_image_parse(efi, efi_size, &regs, &wincerts,
  454. &wincerts_len)) {
  455. debug("Parsing PE executable image failed\n");
  456. goto err;
  457. }
  458. if (!wincerts) {
  459. /* The image is not signed */
  460. ret = efi_image_unsigned_authenticate(regs);
  461. goto err;
  462. }
  463. /*
  464. * verify signature using db and dbx
  465. */
  466. db = efi_sigstore_parse_sigdb(L"db");
  467. if (!db) {
  468. debug("Getting signature database(db) failed\n");
  469. goto err;
  470. }
  471. dbx = efi_sigstore_parse_sigdb(L"dbx");
  472. if (!dbx) {
  473. debug("Getting signature database(dbx) failed\n");
  474. goto err;
  475. }
  476. /* go through WIN_CERTIFICATE list */
  477. for (wincert = wincerts;
  478. (void *)wincert < (void *)wincerts + wincerts_len;
  479. wincert = (void *)wincert + ALIGN(wincert->dwLength, 8)) {
  480. if (wincert->dwLength < sizeof(*wincert)) {
  481. debug("%s: dwLength too small: %u < %zu\n",
  482. __func__, wincert->dwLength, sizeof(*wincert));
  483. goto err;
  484. }
  485. msg = pkcs7_parse_message((void *)wincert + sizeof(*wincert),
  486. wincert->dwLength - sizeof(*wincert));
  487. if (!msg) {
  488. debug("Parsing image's signature failed\n");
  489. goto err;
  490. }
  491. /* try black-list first */
  492. if (efi_signature_verify_with_sigdb(regs, msg, dbx, NULL)) {
  493. debug("Signature was rejected by \"dbx\"\n");
  494. goto err;
  495. }
  496. if (!efi_signature_verify_signers(msg, dbx)) {
  497. debug("Signer was rejected by \"dbx\"\n");
  498. goto err;
  499. } else {
  500. ret = true;
  501. }
  502. /* try white-list */
  503. if (!efi_signature_verify_with_sigdb(regs, msg, db, &cert)) {
  504. debug("Verifying signature with \"db\" failed\n");
  505. goto err;
  506. } else {
  507. ret = true;
  508. }
  509. if (!efi_signature_verify_cert(cert, dbx)) {
  510. debug("Certificate was rejected by \"dbx\"\n");
  511. goto err;
  512. } else {
  513. ret = true;
  514. }
  515. }
  516. err:
  517. x509_free_certificate(cert);
  518. efi_sigstore_free(db);
  519. efi_sigstore_free(dbx);
  520. pkcs7_free_message(msg);
  521. free(regs);
  522. free(new_efi);
  523. return ret;
  524. }
  525. #else
  526. static bool efi_image_authenticate(void *efi, size_t efi_size)
  527. {
  528. return true;
  529. }
  530. #endif /* CONFIG_EFI_SECURE_BOOT */
  531. /**
  532. * efi_load_pe() - relocate EFI binary
  533. *
  534. * This function loads all sections from a PE binary into a newly reserved
  535. * piece of memory. On success the entry point is returned as handle->entry.
  536. *
  537. * @handle: loaded image handle
  538. * @efi: pointer to the EFI binary
  539. * @efi_size: size of @efi binary
  540. * @loaded_image_info: loaded image protocol
  541. * Return: status code
  542. */
  543. efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
  544. void *efi, size_t efi_size,
  545. struct efi_loaded_image *loaded_image_info)
  546. {
  547. IMAGE_NT_HEADERS32 *nt;
  548. IMAGE_DOS_HEADER *dos;
  549. IMAGE_SECTION_HEADER *sections;
  550. int num_sections;
  551. void *efi_reloc;
  552. int i;
  553. const IMAGE_BASE_RELOCATION *rel;
  554. unsigned long rel_size;
  555. int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
  556. uint64_t image_base;
  557. unsigned long virt_size = 0;
  558. int supported = 0;
  559. efi_status_t ret;
  560. /* Sanity check for a file header */
  561. if (efi_size < sizeof(*dos)) {
  562. printf("%s: Truncated DOS Header\n", __func__);
  563. ret = EFI_LOAD_ERROR;
  564. goto err;
  565. }
  566. dos = efi;
  567. if (dos->e_magic != IMAGE_DOS_SIGNATURE) {
  568. printf("%s: Invalid DOS Signature\n", __func__);
  569. ret = EFI_LOAD_ERROR;
  570. goto err;
  571. }
  572. /* assume sizeof(IMAGE_NT_HEADERS32) <= sizeof(IMAGE_NT_HEADERS64) */
  573. if (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32)) {
  574. printf("%s: Invalid offset for Extended Header\n", __func__);
  575. ret = EFI_LOAD_ERROR;
  576. goto err;
  577. }
  578. nt = (void *) ((char *)efi + dos->e_lfanew);
  579. if ((nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) &&
  580. (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS64))) {
  581. printf("%s: Invalid offset for Extended Header\n", __func__);
  582. ret = EFI_LOAD_ERROR;
  583. goto err;
  584. }
  585. if (nt->Signature != IMAGE_NT_SIGNATURE) {
  586. printf("%s: Invalid NT Signature\n", __func__);
  587. ret = EFI_LOAD_ERROR;
  588. goto err;
  589. }
  590. for (i = 0; machines[i]; i++)
  591. if (machines[i] == nt->FileHeader.Machine) {
  592. supported = 1;
  593. break;
  594. }
  595. if (!supported) {
  596. printf("%s: Machine type 0x%04x is not supported\n",
  597. __func__, nt->FileHeader.Machine);
  598. ret = EFI_LOAD_ERROR;
  599. goto err;
  600. }
  601. num_sections = nt->FileHeader.NumberOfSections;
  602. sections = (void *)&nt->OptionalHeader +
  603. nt->FileHeader.SizeOfOptionalHeader;
  604. if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
  605. - efi)) {
  606. printf("%s: Invalid number of sections: %d\n",
  607. __func__, num_sections);
  608. ret = EFI_LOAD_ERROR;
  609. goto err;
  610. }
  611. /* Authenticate an image */
  612. if (efi_image_authenticate(efi, efi_size))
  613. handle->auth_status = EFI_IMAGE_AUTH_PASSED;
  614. else
  615. handle->auth_status = EFI_IMAGE_AUTH_FAILED;
  616. /* Calculate upper virtual address boundary */
  617. for (i = num_sections - 1; i >= 0; i--) {
  618. IMAGE_SECTION_HEADER *sec = &sections[i];
  619. virt_size = max_t(unsigned long, virt_size,
  620. sec->VirtualAddress + sec->Misc.VirtualSize);
  621. }
  622. /* Read 32/64bit specific header bits */
  623. if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  624. IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
  625. IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
  626. image_base = opt->ImageBase;
  627. efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
  628. handle->image_type = opt->Subsystem;
  629. efi_reloc = efi_alloc(virt_size,
  630. loaded_image_info->image_code_type);
  631. if (!efi_reloc) {
  632. printf("%s: Could not allocate %lu bytes\n",
  633. __func__, virt_size);
  634. ret = EFI_OUT_OF_RESOURCES;
  635. goto err;
  636. }
  637. handle->entry = efi_reloc + opt->AddressOfEntryPoint;
  638. rel_size = opt->DataDirectory[rel_idx].Size;
  639. rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
  640. virt_size = ALIGN(virt_size, opt->SectionAlignment);
  641. } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  642. IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
  643. image_base = opt->ImageBase;
  644. efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
  645. handle->image_type = opt->Subsystem;
  646. efi_reloc = efi_alloc(virt_size,
  647. loaded_image_info->image_code_type);
  648. if (!efi_reloc) {
  649. printf("%s: Could not allocate %lu bytes\n",
  650. __func__, virt_size);
  651. ret = EFI_OUT_OF_RESOURCES;
  652. goto err;
  653. }
  654. handle->entry = efi_reloc + opt->AddressOfEntryPoint;
  655. rel_size = opt->DataDirectory[rel_idx].Size;
  656. rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
  657. virt_size = ALIGN(virt_size, opt->SectionAlignment);
  658. } else {
  659. printf("%s: Invalid optional header magic %x\n", __func__,
  660. nt->OptionalHeader.Magic);
  661. ret = EFI_LOAD_ERROR;
  662. goto err;
  663. }
  664. /* Copy PE headers */
  665. memcpy(efi_reloc, efi,
  666. sizeof(*dos)
  667. + sizeof(*nt)
  668. + nt->FileHeader.SizeOfOptionalHeader
  669. + num_sections * sizeof(IMAGE_SECTION_HEADER));
  670. /* Load sections into RAM */
  671. for (i = num_sections - 1; i >= 0; i--) {
  672. IMAGE_SECTION_HEADER *sec = &sections[i];
  673. memset(efi_reloc + sec->VirtualAddress, 0,
  674. sec->Misc.VirtualSize);
  675. memcpy(efi_reloc + sec->VirtualAddress,
  676. efi + sec->PointerToRawData,
  677. sec->SizeOfRawData);
  678. }
  679. /* Run through relocations */
  680. if (efi_loader_relocate(rel, rel_size, efi_reloc,
  681. (unsigned long)image_base) != EFI_SUCCESS) {
  682. efi_free_pages((uintptr_t) efi_reloc,
  683. (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
  684. ret = EFI_LOAD_ERROR;
  685. goto err;
  686. }
  687. /* Flush cache */
  688. flush_cache((ulong)efi_reloc,
  689. ALIGN(virt_size, EFI_CACHELINE_SIZE));
  690. invalidate_icache_all();
  691. /* Populate the loaded image interface bits */
  692. loaded_image_info->image_base = efi_reloc;
  693. loaded_image_info->image_size = virt_size;
  694. if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
  695. return EFI_SUCCESS;
  696. else
  697. return EFI_SECURITY_VIOLATION;
  698. err:
  699. return ret;
  700. }