efi_image_loader.c 22 KB

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