efi_image_loader.c 27 KB

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