efi_image_loader.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. /**
  200. * efi_image_region_add() - add an entry of region
  201. * @regs: Pointer to array of regions
  202. * @start: Start address of region (included)
  203. * @end: End address of region (excluded)
  204. * @nocheck: flag against overlapped regions
  205. *
  206. * Take one entry of region \[@start, @end\[ and insert it into the list.
  207. *
  208. * * If @nocheck is false, the list will be sorted ascending by address.
  209. * Overlapping entries will not be allowed.
  210. *
  211. * * If @nocheck is true, the list will be sorted ascending by sequence
  212. * of adding the entries. Overlapping is allowed.
  213. *
  214. * Return: status code
  215. */
  216. efi_status_t efi_image_region_add(struct efi_image_regions *regs,
  217. const void *start, const void *end,
  218. int nocheck)
  219. {
  220. struct image_region *reg;
  221. int i, j;
  222. if (regs->num >= regs->max) {
  223. EFI_PRINT("%s: no more room for regions\n", __func__);
  224. return EFI_OUT_OF_RESOURCES;
  225. }
  226. if (end < start)
  227. return EFI_INVALID_PARAMETER;
  228. for (i = 0; i < regs->num; i++) {
  229. reg = &regs->reg[i];
  230. if (nocheck)
  231. continue;
  232. /* new data after registered region */
  233. if (start >= reg->data + reg->size)
  234. continue;
  235. /* new data preceding registered region */
  236. if (end <= reg->data) {
  237. for (j = regs->num - 1; j >= i; j--)
  238. memcpy(&regs->reg[j + 1], &regs->reg[j],
  239. sizeof(*reg));
  240. break;
  241. }
  242. /* new data overlapping registered region */
  243. EFI_PRINT("%s: new region already part of another\n", __func__);
  244. return EFI_INVALID_PARAMETER;
  245. }
  246. reg = &regs->reg[i];
  247. reg->data = start;
  248. reg->size = end - start;
  249. regs->num++;
  250. return EFI_SUCCESS;
  251. }
  252. /**
  253. * cmp_pe_section() - compare virtual addresses of two PE image sections
  254. * @arg1: pointer to pointer to first section header
  255. * @arg2: pointer to pointer to second section header
  256. *
  257. * Compare the virtual addresses of two sections of an portable executable.
  258. * The arguments are defined as const void * to allow usage with qsort().
  259. *
  260. * Return: -1 if the virtual address of arg1 is less than that of arg2,
  261. * 0 if the virtual addresses are equal, 1 if the virtual address
  262. * of arg1 is greater than that of arg2.
  263. */
  264. static int cmp_pe_section(const void *arg1, const void *arg2)
  265. {
  266. const IMAGE_SECTION_HEADER *section1, *section2;
  267. section1 = *((const IMAGE_SECTION_HEADER **)arg1);
  268. section2 = *((const IMAGE_SECTION_HEADER **)arg2);
  269. if (section1->VirtualAddress < section2->VirtualAddress)
  270. return -1;
  271. else if (section1->VirtualAddress == section2->VirtualAddress)
  272. return 0;
  273. else
  274. return 1;
  275. }
  276. /**
  277. * efi_prepare_aligned_image() - prepare 8-byte aligned image
  278. * @efi: pointer to the EFI binary
  279. * @efi_size: size of @efi binary
  280. *
  281. * If @efi is not 8-byte aligned, this function newly allocates
  282. * the image buffer.
  283. *
  284. * Return: valid pointer to a image, return NULL if allocation fails.
  285. */
  286. void *efi_prepare_aligned_image(void *efi, u64 *efi_size)
  287. {
  288. size_t new_efi_size;
  289. void *new_efi;
  290. /*
  291. * Size must be 8-byte aligned and the trailing bytes must be
  292. * zero'ed. Otherwise hash value may be incorrect.
  293. */
  294. if (!IS_ALIGNED(*efi_size, 8)) {
  295. new_efi_size = ALIGN(*efi_size, 8);
  296. new_efi = calloc(new_efi_size, 1);
  297. if (!new_efi)
  298. return NULL;
  299. memcpy(new_efi, efi, *efi_size);
  300. *efi_size = new_efi_size;
  301. return new_efi;
  302. } else {
  303. return efi;
  304. }
  305. }
  306. /**
  307. * efi_image_parse() - parse a PE image
  308. * @efi: Pointer to image
  309. * @len: Size of @efi
  310. * @regp: Pointer to a list of regions
  311. * @auth: Pointer to a pointer to authentication data in PE
  312. * @auth_len: Size of @auth
  313. *
  314. * Parse image binary in PE32(+) format, assuming that sanity of PE image
  315. * has been checked by a caller.
  316. * On success, an address of authentication data in @efi and its size will
  317. * be returned in @auth and @auth_len, respectively.
  318. *
  319. * Return: true on success, false on error
  320. */
  321. bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
  322. WIN_CERTIFICATE **auth, size_t *auth_len)
  323. {
  324. struct efi_image_regions *regs;
  325. IMAGE_DOS_HEADER *dos;
  326. IMAGE_NT_HEADERS32 *nt;
  327. IMAGE_SECTION_HEADER *sections, **sorted;
  328. int num_regions, num_sections, i;
  329. int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY;
  330. u32 align, size, authsz, authoff;
  331. size_t bytes_hashed;
  332. dos = (void *)efi;
  333. nt = (void *)(efi + dos->e_lfanew);
  334. authoff = 0;
  335. authsz = 0;
  336. /*
  337. * Count maximum number of regions to be digested.
  338. * We don't have to have an exact number here.
  339. * See efi_image_region_add()'s in parsing below.
  340. */
  341. num_regions = 3; /* for header */
  342. num_regions += nt->FileHeader.NumberOfSections;
  343. num_regions++; /* for extra */
  344. regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions,
  345. 1);
  346. if (!regs)
  347. goto err;
  348. regs->max = num_regions;
  349. /*
  350. * Collect data regions for hash calculation
  351. * 1. File headers
  352. */
  353. if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  354. IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
  355. IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
  356. /* Skip CheckSum */
  357. efi_image_region_add(regs, efi, &opt->CheckSum, 0);
  358. if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
  359. efi_image_region_add(regs,
  360. &opt->Subsystem,
  361. efi + opt->SizeOfHeaders, 0);
  362. } else {
  363. /* Skip Certificates Table */
  364. efi_image_region_add(regs,
  365. &opt->Subsystem,
  366. &opt->DataDirectory[ctidx], 0);
  367. efi_image_region_add(regs,
  368. &opt->DataDirectory[ctidx] + 1,
  369. efi + opt->SizeOfHeaders, 0);
  370. authoff = opt->DataDirectory[ctidx].VirtualAddress;
  371. authsz = opt->DataDirectory[ctidx].Size;
  372. }
  373. bytes_hashed = opt->SizeOfHeaders;
  374. align = opt->FileAlignment;
  375. } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  376. IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
  377. /* Skip CheckSum */
  378. efi_image_region_add(regs, efi, &opt->CheckSum, 0);
  379. if (nt->OptionalHeader.NumberOfRvaAndSizes <= ctidx) {
  380. efi_image_region_add(regs,
  381. &opt->Subsystem,
  382. efi + opt->SizeOfHeaders, 0);
  383. } else {
  384. /* Skip Certificates Table */
  385. efi_image_region_add(regs, &opt->Subsystem,
  386. &opt->DataDirectory[ctidx], 0);
  387. efi_image_region_add(regs,
  388. &opt->DataDirectory[ctidx] + 1,
  389. efi + opt->SizeOfHeaders, 0);
  390. authoff = opt->DataDirectory[ctidx].VirtualAddress;
  391. authsz = opt->DataDirectory[ctidx].Size;
  392. }
  393. bytes_hashed = opt->SizeOfHeaders;
  394. align = opt->FileAlignment;
  395. } else {
  396. EFI_PRINT("%s: Invalid optional header magic %x\n", __func__,
  397. nt->OptionalHeader.Magic);
  398. goto err;
  399. }
  400. /* 2. Sections */
  401. num_sections = nt->FileHeader.NumberOfSections;
  402. sections = (void *)((uint8_t *)&nt->OptionalHeader +
  403. nt->FileHeader.SizeOfOptionalHeader);
  404. sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections);
  405. if (!sorted) {
  406. EFI_PRINT("%s: Out of memory\n", __func__);
  407. goto err;
  408. }
  409. /*
  410. * Make sure the section list is in ascending order.
  411. */
  412. for (i = 0; i < num_sections; i++)
  413. sorted[i] = &sections[i];
  414. qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section);
  415. for (i = 0; i < num_sections; i++) {
  416. if (!sorted[i]->SizeOfRawData)
  417. continue;
  418. size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1);
  419. efi_image_region_add(regs, efi + sorted[i]->PointerToRawData,
  420. efi + sorted[i]->PointerToRawData + size,
  421. 0);
  422. EFI_PRINT("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n",
  423. i, sorted[i]->Name,
  424. sorted[i]->PointerToRawData,
  425. sorted[i]->PointerToRawData + size,
  426. sorted[i]->VirtualAddress,
  427. sorted[i]->VirtualAddress
  428. + sorted[i]->Misc.VirtualSize);
  429. bytes_hashed += size;
  430. }
  431. free(sorted);
  432. /* 3. Extra data excluding Certificates Table */
  433. if (bytes_hashed + authsz < len) {
  434. EFI_PRINT("extra data for hash: %zu\n",
  435. len - (bytes_hashed + authsz));
  436. efi_image_region_add(regs, efi + bytes_hashed,
  437. efi + len - authsz, 0);
  438. }
  439. /* Return Certificates Table */
  440. if (authsz) {
  441. if (len < authoff + authsz) {
  442. EFI_PRINT("%s: Size for auth too large: %u >= %zu\n",
  443. __func__, authsz, len - authoff);
  444. goto err;
  445. }
  446. if (authsz < sizeof(*auth)) {
  447. EFI_PRINT("%s: Size for auth too small: %u < %zu\n",
  448. __func__, authsz, sizeof(*auth));
  449. goto err;
  450. }
  451. *auth = efi + authoff;
  452. *auth_len = authsz;
  453. EFI_PRINT("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff,
  454. authsz);
  455. } else {
  456. *auth = NULL;
  457. *auth_len = 0;
  458. }
  459. *regp = regs;
  460. return true;
  461. err:
  462. free(regs);
  463. return false;
  464. }
  465. #ifdef CONFIG_EFI_SECURE_BOOT
  466. /**
  467. * efi_image_unsigned_authenticate() - authenticate unsigned image with
  468. * SHA256 hash
  469. * @regs: List of regions to be verified
  470. *
  471. * If an image is not signed, it doesn't have a signature. In this case,
  472. * its message digest is calculated and it will be compared with one of
  473. * hash values stored in signature databases.
  474. *
  475. * Return: true if authenticated, false if not
  476. */
  477. static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs)
  478. {
  479. struct efi_signature_store *db = NULL, *dbx = NULL;
  480. bool ret = false;
  481. dbx = efi_sigstore_parse_sigdb(L"dbx");
  482. if (!dbx) {
  483. EFI_PRINT("Getting signature database(dbx) failed\n");
  484. goto out;
  485. }
  486. db = efi_sigstore_parse_sigdb(L"db");
  487. if (!db) {
  488. EFI_PRINT("Getting signature database(db) failed\n");
  489. goto out;
  490. }
  491. /* try black-list first */
  492. if (efi_signature_lookup_digest(regs, dbx)) {
  493. EFI_PRINT("Image is not signed and its digest found in \"dbx\"\n");
  494. goto out;
  495. }
  496. /* try white-list */
  497. if (efi_signature_lookup_digest(regs, db))
  498. ret = true;
  499. else
  500. EFI_PRINT("Image is not signed and its digest not found in \"db\" or \"dbx\"\n");
  501. out:
  502. efi_sigstore_free(db);
  503. efi_sigstore_free(dbx);
  504. return ret;
  505. }
  506. /**
  507. * efi_image_authenticate() - verify a signature of signed image
  508. * @efi: Pointer to image
  509. * @efi_size: Size of @efi
  510. *
  511. * A signed image should have its signature stored in a table of its PE header.
  512. * So if an image is signed and only if if its signature is verified using
  513. * signature databases, an image is authenticated.
  514. * If an image is not signed, its validity is checked by using
  515. * efi_image_unsigned_authenticated().
  516. * TODO:
  517. * When AuditMode==0, if the image's signature is not found in
  518. * the authorized database, or is found in the forbidden database,
  519. * the image will not be started and instead, information about it
  520. * will be placed in this table.
  521. * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created
  522. * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found
  523. * in the certificate table of every image that is validated.
  524. *
  525. * Return: true if authenticated, false if not
  526. */
  527. static bool efi_image_authenticate(void *efi, size_t efi_size)
  528. {
  529. struct efi_image_regions *regs = NULL;
  530. WIN_CERTIFICATE *wincerts = NULL, *wincert;
  531. size_t wincerts_len;
  532. struct pkcs7_message *msg = NULL;
  533. struct efi_signature_store *db = NULL, *dbx = NULL;
  534. void *new_efi = NULL;
  535. u8 *auth, *wincerts_end;
  536. size_t auth_size;
  537. bool ret = false;
  538. EFI_PRINT("%s: Enter, %d\n", __func__, ret);
  539. if (!efi_secure_boot_enabled())
  540. return true;
  541. new_efi = efi_prepare_aligned_image(efi, (u64 *)&efi_size);
  542. if (!new_efi)
  543. return false;
  544. if (!efi_image_parse(new_efi, efi_size, &regs, &wincerts,
  545. &wincerts_len)) {
  546. EFI_PRINT("Parsing PE executable image failed\n");
  547. goto err;
  548. }
  549. if (!wincerts) {
  550. /* The image is not signed */
  551. ret = efi_image_unsigned_authenticate(regs);
  552. goto err;
  553. }
  554. /*
  555. * verify signature using db and dbx
  556. */
  557. db = efi_sigstore_parse_sigdb(L"db");
  558. if (!db) {
  559. EFI_PRINT("Getting signature database(db) failed\n");
  560. goto err;
  561. }
  562. dbx = efi_sigstore_parse_sigdb(L"dbx");
  563. if (!dbx) {
  564. EFI_PRINT("Getting signature database(dbx) failed\n");
  565. goto err;
  566. }
  567. if (efi_signature_lookup_digest(regs, dbx)) {
  568. EFI_PRINT("Image's digest was found in \"dbx\"\n");
  569. goto err;
  570. }
  571. /*
  572. * go through WIN_CERTIFICATE list
  573. * NOTE:
  574. * We may have multiple signatures either as WIN_CERTIFICATE's
  575. * in PE header, or as pkcs7 SignerInfo's in SignedData.
  576. * So the verification policy here is:
  577. * - Success if, at least, one of signatures is verified
  578. * - unless signature is rejected explicitly with its digest.
  579. */
  580. for (wincert = wincerts, wincerts_end = (u8 *)wincerts + wincerts_len;
  581. (u8 *)wincert < wincerts_end;
  582. wincert = (WIN_CERTIFICATE *)
  583. ((u8 *)wincert + ALIGN(wincert->dwLength, 8))) {
  584. if ((u8 *)wincert + sizeof(*wincert) >= wincerts_end)
  585. break;
  586. if (wincert->dwLength <= sizeof(*wincert)) {
  587. EFI_PRINT("dwLength too small: %u < %zu\n",
  588. wincert->dwLength, sizeof(*wincert));
  589. continue;
  590. }
  591. EFI_PRINT("WIN_CERTIFICATE_TYPE: 0x%x\n",
  592. wincert->wCertificateType);
  593. auth = (u8 *)wincert + sizeof(*wincert);
  594. auth_size = wincert->dwLength - sizeof(*wincert);
  595. if (wincert->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
  596. if (auth + sizeof(efi_guid_t) >= wincerts_end)
  597. break;
  598. if (auth_size <= sizeof(efi_guid_t)) {
  599. EFI_PRINT("dwLength too small: %u < %zu\n",
  600. wincert->dwLength, sizeof(*wincert));
  601. continue;
  602. }
  603. if (guidcmp(auth, &efi_guid_cert_type_pkcs7)) {
  604. EFI_PRINT("Certificate type not supported: %pUs\n",
  605. auth);
  606. continue;
  607. }
  608. auth += sizeof(efi_guid_t);
  609. auth_size -= sizeof(efi_guid_t);
  610. } else if (wincert->wCertificateType
  611. != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
  612. EFI_PRINT("Certificate type not supported\n");
  613. continue;
  614. }
  615. msg = pkcs7_parse_message(auth, auth_size);
  616. if (IS_ERR(msg)) {
  617. EFI_PRINT("Parsing image's signature failed\n");
  618. msg = NULL;
  619. continue;
  620. }
  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. EFI_PRINT("Signature was rejected by \"dbx\"\n");
  643. continue;
  644. }
  645. if (!efi_signature_check_signers(msg, dbx)) {
  646. EFI_PRINT("Signer(s) in \"dbx\"\n");
  647. continue;
  648. }
  649. /* try white-list */
  650. if (efi_signature_verify(regs, msg, db, dbx)) {
  651. ret = true;
  652. break;
  653. }
  654. EFI_PRINT("Signature was not verified by \"db\"\n");
  655. if (efi_signature_lookup_digest(regs, db)) {
  656. ret = true;
  657. break;
  658. }
  659. EFI_PRINT("Image's digest was not found in \"db\" or \"dbx\"\n");
  660. }
  661. err:
  662. efi_sigstore_free(db);
  663. efi_sigstore_free(dbx);
  664. pkcs7_free_message(msg);
  665. free(regs);
  666. if (new_efi != efi)
  667. free(new_efi);
  668. EFI_PRINT("%s: Exit, %d\n", __func__, ret);
  669. return ret;
  670. }
  671. #else
  672. static bool efi_image_authenticate(void *efi, size_t efi_size)
  673. {
  674. return true;
  675. }
  676. #endif /* CONFIG_EFI_SECURE_BOOT */
  677. /**
  678. * efi_check_pe() - check if a memory buffer contains a PE-COFF image
  679. *
  680. * @buffer: buffer to check
  681. * @size: size of buffer
  682. * @nt_header: on return pointer to NT header of PE-COFF image
  683. * Return: EFI_SUCCESS if the buffer contains a PE-COFF image
  684. */
  685. efi_status_t efi_check_pe(void *buffer, size_t size, void **nt_header)
  686. {
  687. IMAGE_DOS_HEADER *dos = buffer;
  688. IMAGE_NT_HEADERS32 *nt;
  689. if (size < sizeof(*dos))
  690. return EFI_INVALID_PARAMETER;
  691. /* Check for DOS magix */
  692. if (dos->e_magic != IMAGE_DOS_SIGNATURE)
  693. return EFI_INVALID_PARAMETER;
  694. /*
  695. * Check if the image section header fits into the file. Knowing that at
  696. * least one section header follows we only need to check for the length
  697. * of the 64bit header which is longer than the 32bit header.
  698. */
  699. if (size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32))
  700. return EFI_INVALID_PARAMETER;
  701. nt = (IMAGE_NT_HEADERS32 *)((u8 *)buffer + dos->e_lfanew);
  702. /* Check for PE-COFF magic */
  703. if (nt->Signature != IMAGE_NT_SIGNATURE)
  704. return EFI_INVALID_PARAMETER;
  705. if (nt_header)
  706. *nt_header = nt;
  707. return EFI_SUCCESS;
  708. }
  709. /**
  710. * section_size() - determine size of section
  711. *
  712. * The size of a section in memory if normally given by VirtualSize.
  713. * If VirtualSize is not provided, use SizeOfRawData.
  714. *
  715. * @sec: section header
  716. * Return: size of section in memory
  717. */
  718. static u32 section_size(IMAGE_SECTION_HEADER *sec)
  719. {
  720. if (sec->Misc.VirtualSize)
  721. return sec->Misc.VirtualSize;
  722. else
  723. return sec->SizeOfRawData;
  724. }
  725. /**
  726. * efi_load_pe() - relocate EFI binary
  727. *
  728. * This function loads all sections from a PE binary into a newly reserved
  729. * piece of memory. On success the entry point is returned as handle->entry.
  730. *
  731. * @handle: loaded image handle
  732. * @efi: pointer to the EFI binary
  733. * @efi_size: size of @efi binary
  734. * @loaded_image_info: loaded image protocol
  735. * Return: status code
  736. */
  737. efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
  738. void *efi, size_t efi_size,
  739. struct efi_loaded_image *loaded_image_info)
  740. {
  741. IMAGE_NT_HEADERS32 *nt;
  742. IMAGE_DOS_HEADER *dos;
  743. IMAGE_SECTION_HEADER *sections;
  744. int num_sections;
  745. void *efi_reloc;
  746. int i;
  747. const IMAGE_BASE_RELOCATION *rel;
  748. unsigned long rel_size;
  749. int rel_idx = IMAGE_DIRECTORY_ENTRY_BASERELOC;
  750. uint64_t image_base;
  751. unsigned long virt_size = 0;
  752. int supported = 0;
  753. efi_status_t ret;
  754. ret = efi_check_pe(efi, efi_size, (void **)&nt);
  755. if (ret != EFI_SUCCESS) {
  756. log_err("Not a PE-COFF file\n");
  757. return EFI_LOAD_ERROR;
  758. }
  759. for (i = 0; machines[i]; i++)
  760. if (machines[i] == nt->FileHeader.Machine) {
  761. supported = 1;
  762. break;
  763. }
  764. if (!supported) {
  765. log_err("Machine type 0x%04x is not supported\n",
  766. nt->FileHeader.Machine);
  767. return EFI_LOAD_ERROR;
  768. }
  769. num_sections = nt->FileHeader.NumberOfSections;
  770. sections = (void *)&nt->OptionalHeader +
  771. nt->FileHeader.SizeOfOptionalHeader;
  772. if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections
  773. - efi)) {
  774. log_err("Invalid number of sections: %d\n", num_sections);
  775. return EFI_LOAD_ERROR;
  776. }
  777. /* Authenticate an image */
  778. if (efi_image_authenticate(efi, efi_size)) {
  779. handle->auth_status = EFI_IMAGE_AUTH_PASSED;
  780. } else {
  781. handle->auth_status = EFI_IMAGE_AUTH_FAILED;
  782. log_err("Image not authenticated\n");
  783. }
  784. /* Calculate upper virtual address boundary */
  785. for (i = num_sections - 1; i >= 0; i--) {
  786. IMAGE_SECTION_HEADER *sec = &sections[i];
  787. virt_size = max_t(unsigned long, virt_size,
  788. sec->VirtualAddress + section_size(sec));
  789. }
  790. /* Read 32/64bit specific header bits */
  791. if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  792. IMAGE_NT_HEADERS64 *nt64 = (void *)nt;
  793. IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader;
  794. image_base = opt->ImageBase;
  795. efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
  796. handle->image_type = opt->Subsystem;
  797. efi_reloc = efi_alloc_aligned_pages(virt_size,
  798. loaded_image_info->image_code_type,
  799. opt->SectionAlignment);
  800. if (!efi_reloc) {
  801. log_err("Out of memory\n");
  802. ret = EFI_OUT_OF_RESOURCES;
  803. goto err;
  804. }
  805. handle->entry = efi_reloc + opt->AddressOfEntryPoint;
  806. rel_size = opt->DataDirectory[rel_idx].Size;
  807. rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
  808. } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  809. IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader;
  810. image_base = opt->ImageBase;
  811. efi_set_code_and_data_type(loaded_image_info, opt->Subsystem);
  812. handle->image_type = opt->Subsystem;
  813. efi_reloc = efi_alloc_aligned_pages(virt_size,
  814. loaded_image_info->image_code_type,
  815. opt->SectionAlignment);
  816. if (!efi_reloc) {
  817. log_err("Out of memory\n");
  818. ret = EFI_OUT_OF_RESOURCES;
  819. goto err;
  820. }
  821. handle->entry = efi_reloc + opt->AddressOfEntryPoint;
  822. rel_size = opt->DataDirectory[rel_idx].Size;
  823. rel = efi_reloc + opt->DataDirectory[rel_idx].VirtualAddress;
  824. } else {
  825. log_err("Invalid optional header magic %x\n",
  826. nt->OptionalHeader.Magic);
  827. ret = EFI_LOAD_ERROR;
  828. goto err;
  829. }
  830. #if CONFIG_IS_ENABLED(EFI_TCG2_PROTOCOL)
  831. /* Measure an PE/COFF image */
  832. ret = tcg2_measure_pe_image(efi, efi_size, handle, loaded_image_info);
  833. if (ret == EFI_SECURITY_VIOLATION) {
  834. /*
  835. * TCG2 Protocol is installed but no TPM device found,
  836. * this is not expected.
  837. */
  838. log_err("PE image measurement failed, no tpm device found\n");
  839. goto err;
  840. }
  841. #endif
  842. /* Copy PE headers */
  843. memcpy(efi_reloc, efi,
  844. sizeof(*dos)
  845. + sizeof(*nt)
  846. + nt->FileHeader.SizeOfOptionalHeader
  847. + num_sections * sizeof(IMAGE_SECTION_HEADER));
  848. /* Load sections into RAM */
  849. for (i = num_sections - 1; i >= 0; i--) {
  850. IMAGE_SECTION_HEADER *sec = &sections[i];
  851. u32 copy_size = section_size(sec);
  852. if (copy_size > sec->SizeOfRawData) {
  853. copy_size = sec->SizeOfRawData;
  854. memset(efi_reloc + sec->VirtualAddress, 0,
  855. sec->Misc.VirtualSize);
  856. }
  857. memcpy(efi_reloc + sec->VirtualAddress,
  858. efi + sec->PointerToRawData,
  859. copy_size);
  860. }
  861. /* Run through relocations */
  862. if (efi_loader_relocate(rel, rel_size, efi_reloc,
  863. (unsigned long)image_base) != EFI_SUCCESS) {
  864. efi_free_pages((uintptr_t) efi_reloc,
  865. (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT);
  866. ret = EFI_LOAD_ERROR;
  867. goto err;
  868. }
  869. /* Flush cache */
  870. flush_cache((ulong)efi_reloc,
  871. ALIGN(virt_size, EFI_CACHELINE_SIZE));
  872. invalidate_icache_all();
  873. /* Populate the loaded image interface bits */
  874. loaded_image_info->image_base = efi_reloc;
  875. loaded_image_info->image_size = virt_size;
  876. if (handle->auth_status == EFI_IMAGE_AUTH_PASSED)
  877. return EFI_SUCCESS;
  878. else
  879. return EFI_SECURITY_VIOLATION;
  880. err:
  881. return ret;
  882. }