efi_image_loader.c 24 KB

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