efi_image_loader.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. authoff = 0;
  251. authsz = 0;
  252. /*
  253. * Count maximum number of regions to be digested.
  254. * We don't have to have an exact number here.
  255. * See efi_image_region_add()'s in parsing below.
  256. */
  257. num_regions = 3; /* for header */
  258. num_regions += nt->FileHeader.NumberOfSections;
  259. num_regions++; /* for extra */
  260. regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
  261. 1);
  262. if (!regs)
  263. goto err;
  264. regs->max = num_regions;
  265. /*
  266. * Collect data regions for hash calculation
  267. * 1. File headers
  268. */
  269. if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  270. IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
  271. IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
  272. /* Skip CheckSum */
  273. efi_image_region_add(regs, efi, &opt->CheckSum, 0);
  274. if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
  275. efi_image_region_add(regs,
  276. &opt->Subsystem,
  277. efi + opt->SizeOfHeaders, 0);
  278. } else {
  279. /* Skip Certificates Table */
  280. efi_image_region_add(regs,
  281. &opt->Subsystem,
  282. &opt->DataDirectory[ctidx], 0);
  283. efi_image_region_add(regs,
  284. &opt->DataDirectory[ctidx] + 1,
  285. efi + opt->SizeOfHeaders, 0);
  286. authoff = opt->DataDirectory[ctidx].VirtualAddress;
  287. authsz = opt->DataDirectory[ctidx].Size;
  288. }
  289. bytes_hashed = opt->SizeOfHeaders;
  290. align = opt->FileAlignment;
  291. } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  292. IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
  293. /* Skip CheckSum */
  294. efi_image_region_add(regs, efi, &opt->CheckSum, 0);
  295. if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
  296. efi_image_region_add(regs,
  297. &opt->Subsystem,
  298. efi + opt->SizeOfHeaders, 0);
  299. } else {
  300. /* Skip Certificates Table */
  301. efi_image_region_add(regs, &opt->Subsystem,
  302. &opt->DataDirectory[ctidx], 0);
  303. efi_image_region_add(regs,
  304. &opt->DataDirectory[ctidx] + 1,
  305. efi + opt->SizeOfHeaders, 0);
  306. authoff = opt->DataDirectory[ctidx].VirtualAddress;
  307. authsz = opt->DataDirectory[ctidx].Size;
  308. }
  309. bytes_hashed = opt->SizeOfHeaders;
  310. align = opt->FileAlignment;
  311. } else {
  312. EFI_PRINT("%s: Invalid optional header magic %x\n", __func__,
  313. nt->OptionalHeader.Magic);
  314. goto err;
  315. }
  316. /* 2. Sections */
  317. num_sections = nt->FileHeader.NumberOfSections;
  318. sections = (void *)((uint8_t *)&nt->OptionalHeader +
  319. nt->FileHeader.SizeOfOptionalHeader);
  320. sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
  321. if (!sorted) {
  322. EFI_PRINT("%s: Out of memory\n", __func__);
  323. goto err;
  324. }
  325. /*
  326. * Make sure the section list is in ascending order.
  327. */
  328. for (i = 0; i < num_sections; i++)
  329. sorted[i] = &sections[i];
  330. qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
  331. for (i = 0; i < num_sections; i++) {
  332. if (!sorted[i]->SizeOfRawData)
  333. continue;
  334. size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
  335. efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
  336. efi + sorted[i]->PointerToRawData + size,
  337. 0);
  338. EFI_PRINT("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
  339. i, sorted[i]->Name,
  340. sorted[i]->PointerToRawData,
  341. sorted[i]->PointerToRawData + size,
  342. sorted[i]->VirtualAddress,
  343. sorted[i]->VirtualAddress
  344. + sorted[i]->Misc.VirtualSize);
  345. bytes_hashed += size;
  346. }
  347. free(sorted);
  348. /* 3. Extra data excluding Certificates Table */
  349. if (bytes_hashed + authsz < len) {
  350. EFI_PRINT("extra data for hash: %zu\n",
  351. len - (bytes_hashed + authsz));
  352. efi_image_region_add(regs, efi + bytes_hashed,
  353. efi + len - authsz, 0);
  354. }
  355. /* Return Certificates Table */
  356. if (authsz) {
  357. if (len < authoff + authsz) {
  358. EFI_PRINT("%s: Size for auth too large: %u >= %zu\n",
  359. __func__, authsz, len - authoff);
  360. goto err;
  361. }
  362. if (authsz < sizeof(*auth)) {
  363. EFI_PRINT("%s: Size for auth too small: %u < %zu\n",
  364. __func__, authsz, sizeof(*auth));
  365. goto err;
  366. }
  367. *auth = efi + authoff;
  368. *auth_len = authsz;
  369. EFI_PRINT("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff,
  370. authsz);
  371. } else {
  372. *auth = NULL;
  373. *auth_len = 0;
  374. }
  375. *regp = regs;
  376. return true;
  377. err:
  378. free(regs);
  379. return false;
  380. }
  381. /**
  382. * efi_image_unsigned_authenticate() - authenticate unsigned image with
  383. * SHA256 hash
  384. * @regs: List of regions to be verified
  385. *
  386. * If an image is not signed, it doesn't have a signature. In this case,
  387. * its message digest is calculated and it will be compared with one of
  388. * hash values stored in signature databases.
  389. *
  390. * Return: true if authenticated, false if not
  391. */
  392. static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs)
  393. {
  394. struct efi_signature_store *db = NULL, *dbx = NULL;
  395. bool ret = false;
  396. dbx = efi_sigstore_parse_sigdb(L"dbx");
  397. if (!dbx) {
  398. EFI_PRINT("Getting signature database(dbx) failed\n");
  399. goto out;
  400. }
  401. db = efi_sigstore_parse_sigdb(L"db");
  402. if (!db) {
  403. EFI_PRINT("Getting signature database(db) failed\n");
  404. goto out;
  405. }
  406. /* try black-list first */
  407. if (efi_signature_lookup_digest(regs, dbx)) {
  408. EFI_PRINT("Image is not signed and its digest found in \"dbx\"\n");
  409. goto out;
  410. }
  411. /* try white-list */
  412. if (efi_signature_lookup_digest(regs, db))
  413. ret = true;
  414. else
  415. EFI_PRINT("Image is not signed and its digest not found in \"db\" or \"dbx\"\n");
  416. out:
  417. efi_sigstore_free(db);
  418. efi_sigstore_free(dbx);
  419. return ret;
  420. }
  421. /**
  422. * efi_image_authenticate() - verify a signature of signed image
  423. * @efi: Pointer to image
  424. * @efi_size: Size of @efi
  425. *
  426. * A signed image should have its signature stored in a table of its PE header.
  427. * So if an image is signed and only if if its signature is verified using
  428. * signature databases, an image is authenticated.
  429. * If an image is not signed, its validity is checked by using
  430. * efi_image_unsigned_authenticated().
  431. * TODO:
  432. * When AuditMode==0, if the image's signature is not found in
  433. * the authorized database, or is found in the forbidden database,
  434. * the image will not be started and instead, information about it
  435. * will be placed in this table.
  436. * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
  437. * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
  438. * in the certificate table of every image that is validated.
  439. *
  440. * Return: true if authenticated, false if not
  441. */
  442. static bool efi_image_authenticate(void *efi, size_t efi_size)
  443. {
  444. struct efi_image_regions *regs = NULL;
  445. WIN_CERTIFICATE *wincerts = NULL, *wincert;
  446. size_t wincerts_len;
  447. struct pkcs7_message *msg = NULL;
  448. struct efi_signature_store *db = NULL, *dbx = NULL;
  449. void *new_efi = NULL;
  450. u8 *auth, *wincerts_end;
  451. size_t new_efi_size, auth_size;
  452. bool ret = false;
  453. debug("%s: Enter, %d\n", __func__, ret);
  454. if (!efi_secure_boot_enabled())
  455. return true;
  456. /*
  457. * Size must be 8-byte aligned and the trailing bytes must be
  458. * zero'ed. Otherwise hash value may be incorrect.
  459. */
  460. if (efi_size & 0x7) {
  461. new_efi_size = (efi_size + 0x7) & ~0x7ULL;
  462. new_efi = calloc(new_efi_size, 1);
  463. if (!new_efi)
  464. return false;
  465. memcpy(new_efi, efi, efi_size);
  466. efi = new_efi;
  467. efi_size = new_efi_size;
  468. }
  469. if (!efi_image_parse(efi, efi_size, &regs, &wincerts,
  470. &wincerts_len)) {
  471. EFI_PRINT("Parsing PE executable image failed\n");
  472. goto err;
  473. }
  474. if (!wincerts) {
  475. /* The image is not signed */
  476. ret = efi_image_unsigned_authenticate(regs);
  477. goto err;
  478. }
  479. /*
  480. * verify signature using db and dbx
  481. */
  482. db = efi_sigstore_parse_sigdb(L"db");
  483. if (!db) {
  484. EFI_PRINT("Getting signature database(db) failed\n");
  485. goto err;
  486. }
  487. dbx = efi_sigstore_parse_sigdb(L"dbx");
  488. if (!dbx) {
  489. EFI_PRINT("Getting signature database(dbx) failed\n");
  490. goto err;
  491. }
  492. /*
  493. * go through WIN_CERTIFICATE list
  494. * NOTE:
  495. * We may have multiple signatures either as WIN_CERTIFICATE's
  496. * in PE header, or as pkcs7 SignerInfo's in SignedData.
  497. * So the verification policy here is:
  498. * - Success if, at least, one of signatures is verified
  499. * - unless
  500. * any of signatures is rejected explicitly, or
  501. * none of digest algorithms are supported
  502. */
  503. for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
  504. (u8 *)wincert < wincerts_end;
  505. wincert = (WIN_CERTIFICATE *)
  506. ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
  507. if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
  508. break;
  509. if (wincert->dwLength <= sizeof(*wincert)) {
  510. EFI_PRINT("dwLength too small: %u < %zu\n",
  511. wincert->dwLength, sizeof(*wincert));
  512. continue;
  513. }
  514. EFI_PRINT("WIN_CERTIFICATE_TYPE: 0x%x\n",
  515. wincert->wCertificateType);
  516. auth = (u8 *)wincert + sizeof(*wincert);
  517. auth_size = wincert->dwLength - sizeof(*wincert);
  518. if (wincert->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
  519. if (auth + sizeof(efi_guid_t) >= wincerts_end)
  520. break;
  521. if (auth_size <= sizeof(efi_guid_t)) {
  522. EFI_PRINT("dwLength too small: %u < %zu\n",
  523. wincert->dwLength, sizeof(*wincert));
  524. continue;
  525. }
  526. if (guidcmp(auth, &efi_guid_cert_type_pkcs7)) {
  527. EFI_PRINT("Certificate type not supported: %pUl\n",
  528. auth);
  529. continue;
  530. }
  531. auth += sizeof(efi_guid_t);
  532. auth_size -= sizeof(efi_guid_t);
  533. } else if (wincert->wCertificateType
  534. != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
  535. EFI_PRINT("Certificate type not supported\n");
  536. continue;
  537. }
  538. msg = pkcs7_parse_message(auth, auth_size);
  539. if (IS_ERR(msg)) {
  540. EFI_PRINT("Parsing image's signature failed\n");
  541. msg = NULL;
  542. continue;
  543. }
  544. /*
  545. * NOTE:
  546. * UEFI specification defines two signature types possible
  547. * in signature database:
  548. * a. x509 certificate, where a signature in image is
  549. * a message digest encrypted by RSA public key
  550. * (EFI_CERT_X509_GUID)
  551. * b. bare hash value of message digest
  552. * (EFI_CERT_SHAxxx_GUID)
  553. *
  554. * efi_signature_verify() handles case (a), while
  555. * efi_signature_lookup_digest() handles case (b).
  556. *
  557. * There is a third type:
  558. * c. message digest of a certificate
  559. * (EFI_CERT_X509_SHAAxxx_GUID)
  560. * This type of signature is used only in revocation list
  561. * (dbx) and handled as part of efi_signatgure_verify().
  562. */
  563. /* try black-list first */
  564. if (efi_signature_verify_one(regs, msg, dbx)) {
  565. EFI_PRINT("Signature was rejected by \"dbx\"\n");
  566. goto err;
  567. }
  568. if (!efi_signature_check_signers(msg, dbx)) {
  569. EFI_PRINT("Signer(s) in \"dbx\"\n");
  570. goto err;
  571. }
  572. if (efi_signature_lookup_digest(regs, dbx)) {
  573. EFI_PRINT("Image's digest was found in \"dbx\"\n");
  574. goto err;
  575. }
  576. /* try white-list */
  577. if (efi_signature_verify_with_sigdb(regs, msg, db, dbx))
  578. continue;
  579. debug("Signature was not verified by \"db\"\n");
  580. if (efi_signature_lookup_digest(regs, db))
  581. continue;
  582. debug("Image's digest was not found in \"db\" or \"dbx\"\n");
  583. goto err;
  584. }
  585. ret = true;
  586. err:
  587. efi_sigstore_free(db);
  588. efi_sigstore_free(dbx);
  589. pkcs7_free_message(msg);
  590. free(regs);
  591. free(new_efi);
  592. debug("%s: Exit, %d\n", __func__, ret);
  593. return ret;
  594. }
  595. #else
  596. static bool efi_image_authenticate(void *efi, size_t efi_size)
  597. {
  598. return true;
  599. }
  600. #endif /* CONFIG_EFI_SECURE_BOOT */
  601. /**
  602. * efi_load_pe() - relocate EFI binary
  603. *
  604. * This function loads all sections from a PE binary into a newly reserved
  605. * piece of memory. On success the entry point is returned as handle->entry.
  606. *
  607. * @handle: loaded image handle
  608. * @efi: pointer to the EFI binary
  609. * @efi_size: size of @efi binary
  610. * @loaded_image_info: loaded image protocol
  611. * Return: status code
  612. */
  613. efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
  614. void *efi, size_t efi_size,
  615. struct efi_loaded_image *loaded_image_info)
  616. {
  617. IMAGE_NT_HEADERS32 *nt;
  618. IMAGE_DOS_HEADER *dos;
  619. IMAGE_SECTION_HEADER *sections;
  620. int num_sections;
  621. void *efi_reloc;
  622. int i;
  623. const IMAGE_BASE_RELOCATION *rel;
  624. unsigned long rel_size;
  625. int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
  626. uint64_t image_base;
  627. unsigned long virt_size = 0;
  628. int supported = 0;
  629. efi_status_t ret;
  630. /* Sanity check for a file header */
  631. if (efi_size < sizeof(*dos)) {
  632. printf("%s: Truncated DOS Header\n", __func__);
  633. ret = EFI_LOAD_ERROR;
  634. goto err;
  635. }
  636. dos = efi;
  637. if (dos->e_magic != IMAGE_DOS_SIGNATURE) {
  638. printf("%s: Invalid DOS Signature\n", __func__);
  639. ret = EFI_LOAD_ERROR;
  640. goto err;
  641. }
  642. /*
  643. * Check if the image section header fits into the file. Knowing that at
  644. * least one section header follows we only need to check for the length
  645. * of the 64bit header which is longer than the 32bit header.
  646. */
  647. if (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS64)) {
  648. printf("%s: Invalid offset for Extended Header\n", __func__);
  649. ret = EFI_LOAD_ERROR;
  650. goto err;
  651. }
  652. nt = (void *) ((char *)efi + dos->e_lfanew);
  653. if (nt->Signature != IMAGE_NT_SIGNATURE) {
  654. printf("%s: Invalid NT Signature\n", __func__);
  655. ret = EFI_LOAD_ERROR;
  656. goto err;
  657. }
  658. for (i = 0; machines[i]; i++)
  659. if (machines[i] == nt->FileHeader.Machine) {
  660. supported = 1;
  661. break;
  662. }
  663. if (!supported) {
  664. printf("%s: Machine type 0x%04x is not supported\n",
  665. __func__, nt->FileHeader.Machine);
  666. ret = EFI_LOAD_ERROR;
  667. goto err;
  668. }
  669. num_sections = nt->FileHeader.NumberOfSections;
  670. sections = (void *)&nt->OptionalHeader +
  671. nt->FileHeader.SizeOfOptionalHeader;
  672. if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
  673. - efi)) {
  674. printf("%s: Invalid number of sections: %d\n",
  675. __func__, num_sections);
  676. ret = EFI_LOAD_ERROR;
  677. goto err;
  678. }
  679. /* Authenticate an image */
  680. if (efi_image_authenticate(efi, efi_size))
  681. handle->auth_status = EFI_IMAGE_AUTH_PASSED;
  682. else
  683. handle->auth_status = EFI_IMAGE_AUTH_FAILED;
  684. /* Calculate upper virtual address boundary */
  685. for (i = num_sections - 1; i >= 0; i--) {
  686. IMAGE_SECTION_HEADER *sec = &sections[i];
  687. virt_size = max_t(unsigned long, virt_size,
  688. sec->VirtualAddress + sec->Misc.VirtualSize);
  689. }
  690. /* Read 32/64bit specific header bits */
  691. if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  692. IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
  693. IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
  694. image_base = opt->ImageBase;
  695. efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
  696. handle->image_type = opt->Subsystem;
  697. efi_reloc = efi_alloc(virt_size,
  698. loaded_image_info->image_code_type);
  699. if (!efi_reloc) {
  700. printf("%s: Could not allocate %lu bytes\n",
  701. __func__, virt_size);
  702. ret = EFI_OUT_OF_RESOURCES;
  703. goto err;
  704. }
  705. handle->entry = efi_reloc + opt->AddressOfEntryPoint;
  706. rel_size = opt->DataDirectory[rel_idx].Size;
  707. rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
  708. virt_size = ALIGN(virt_size, opt->SectionAlignment);
  709. } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  710. IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
  711. image_base = opt->ImageBase;
  712. efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
  713. handle->image_type = opt->Subsystem;
  714. efi_reloc = efi_alloc(virt_size,
  715. loaded_image_info->image_code_type);
  716. if (!efi_reloc) {
  717. printf("%s: Could not allocate %lu bytes\n",
  718. __func__, virt_size);
  719. ret = EFI_OUT_OF_RESOURCES;
  720. goto err;
  721. }
  722. handle->entry = efi_reloc + opt->AddressOfEntryPoint;
  723. rel_size = opt->DataDirectory[rel_idx].Size;
  724. rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
  725. virt_size = ALIGN(virt_size, opt->SectionAlignment);
  726. } else {
  727. printf("%s: Invalid optional header magic %x\n", __func__,
  728. nt->OptionalHeader.Magic);
  729. ret = EFI_LOAD_ERROR;
  730. goto err;
  731. }
  732. /* Copy PE headers */
  733. memcpy(efi_reloc, efi,
  734. sizeof(*dos)
  735. + sizeof(*nt)
  736. + nt->FileHeader.SizeOfOptionalHeader
  737. + num_sections * sizeof(IMAGE_SECTION_HEADER));
  738. /* Load sections into RAM */
  739. for (i = num_sections - 1; i >= 0; i--) {
  740. IMAGE_SECTION_HEADER *sec = &sections[i];
  741. memset(efi_reloc + sec->VirtualAddress, 0,
  742. sec->Misc.VirtualSize);
  743. memcpy(efi_reloc + sec->VirtualAddress,
  744. efi + sec->PointerToRawData,
  745. sec->SizeOfRawData);
  746. }
  747. /* Run through relocations */
  748. if (efi_loader_relocate(rel, rel_size, efi_reloc,
  749. (unsigned long)image_base) != EFI_SUCCESS) {
  750. efi_free_pages((uintptr_t) efi_reloc,
  751. (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
  752. ret = EFI_LOAD_ERROR;
  753. goto err;
  754. }
  755. /* Flush cache */
  756. flush_cache((ulong)efi_reloc,
  757. ALIGN(virt_size, EFI_CACHELINE_SIZE));
  758. invalidate_icache_all();
  759. /* Populate the loaded image interface bits */
  760. loaded_image_info->image_base = efi_reloc;
  761. loaded_image_info->image_size = virt_size;
  762. if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
  763. return EFI_SUCCESS;
  764. else
  765. return EFI_SECURITY_VIOLATION;
  766. err:
  767. return ret;
  768. }