DxeTpmMeasureBootLib.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. /** @file
  2. The library instance provides security service of TPM measure boot.
  3. Caution: This file requires additional review when modified.
  4. This library will have external input - PE/COFF image and GPT partition.
  5. This external input must be validated carefully to avoid security issue like
  6. buffer overflow, integer overflow.
  7. DxeTpmMeasureBootLibImageRead() function will make sure the PE/COFF image content
  8. read is within the image buffer.
  9. TcgMeasurePeImage() function will accept untrusted PE/COFF image and validate its
  10. data structure within this image buffer before use.
  11. TcgMeasureGptTable() function will receive untrusted GPT partition table, and parse
  12. partition data carefully.
  13. Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
  14. SPDX-License-Identifier: BSD-2-Clause-Patent
  15. **/
  16. #include <PiDxe.h>
  17. #include <Protocol/TcgService.h>
  18. #include <Protocol/BlockIo.h>
  19. #include <Protocol/DiskIo.h>
  20. #include <Protocol/FirmwareVolumeBlock.h>
  21. #include <Guid/MeasuredFvHob.h>
  22. #include <Library/BaseLib.h>
  23. #include <Library/DebugLib.h>
  24. #include <Library/BaseMemoryLib.h>
  25. #include <Library/MemoryAllocationLib.h>
  26. #include <Library/DevicePathLib.h>
  27. #include <Library/UefiBootServicesTableLib.h>
  28. #include <Library/BaseCryptLib.h>
  29. #include <Library/PeCoffLib.h>
  30. #include <Library/SecurityManagementLib.h>
  31. #include <Library/HobLib.h>
  32. //
  33. // Flag to check GPT partition. It only need be measured once.
  34. //
  35. BOOLEAN mMeasureGptTableFlag = FALSE;
  36. UINTN mMeasureGptCount = 0;
  37. VOID *mFileBuffer;
  38. UINTN mTpmImageSize;
  39. //
  40. // Measured FV handle cache
  41. //
  42. EFI_HANDLE mCacheMeasuredHandle = NULL;
  43. MEASURED_HOB_DATA *mMeasuredHobData = NULL;
  44. /**
  45. Reads contents of a PE/COFF image in memory buffer.
  46. Caution: This function may receive untrusted input.
  47. PE/COFF image is external input, so this function will make sure the PE/COFF image content
  48. read is within the image buffer.
  49. @param FileHandle Pointer to the file handle to read the PE/COFF image.
  50. @param FileOffset Offset into the PE/COFF image to begin the read operation.
  51. @param ReadSize On input, the size in bytes of the requested read operation.
  52. On output, the number of bytes actually read.
  53. @param Buffer Output buffer that contains the data read from the PE/COFF image.
  54. @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
  55. **/
  56. EFI_STATUS
  57. EFIAPI
  58. DxeTpmMeasureBootLibImageRead (
  59. IN VOID *FileHandle,
  60. IN UINTN FileOffset,
  61. IN OUT UINTN *ReadSize,
  62. OUT VOID *Buffer
  63. )
  64. {
  65. UINTN EndPosition;
  66. if ((FileHandle == NULL) || (ReadSize == NULL) || (Buffer == NULL)) {
  67. return EFI_INVALID_PARAMETER;
  68. }
  69. if (MAX_ADDRESS - FileOffset < *ReadSize) {
  70. return EFI_INVALID_PARAMETER;
  71. }
  72. EndPosition = FileOffset + *ReadSize;
  73. if (EndPosition > mTpmImageSize) {
  74. *ReadSize = (UINT32)(mTpmImageSize - FileOffset);
  75. }
  76. if (FileOffset >= mTpmImageSize) {
  77. *ReadSize = 0;
  78. }
  79. CopyMem (Buffer, (UINT8 *)((UINTN)FileHandle + FileOffset), *ReadSize);
  80. return EFI_SUCCESS;
  81. }
  82. /**
  83. Measure GPT table data into TPM log.
  84. Caution: This function may receive untrusted input.
  85. The GPT partition table is external input, so this function should parse partition data carefully.
  86. @param TcgProtocol Pointer to the located TCG protocol instance.
  87. @param GptHandle Handle that GPT partition was installed.
  88. @retval EFI_SUCCESS Successfully measure GPT table.
  89. @retval EFI_UNSUPPORTED Not support GPT table on the given handle.
  90. @retval EFI_DEVICE_ERROR Can't get GPT table because device error.
  91. @retval EFI_OUT_OF_RESOURCES No enough resource to measure GPT table.
  92. @retval other error value
  93. **/
  94. EFI_STATUS
  95. EFIAPI
  96. TcgMeasureGptTable (
  97. IN EFI_TCG_PROTOCOL *TcgProtocol,
  98. IN EFI_HANDLE GptHandle
  99. )
  100. {
  101. EFI_STATUS Status;
  102. EFI_BLOCK_IO_PROTOCOL *BlockIo;
  103. EFI_DISK_IO_PROTOCOL *DiskIo;
  104. EFI_PARTITION_TABLE_HEADER *PrimaryHeader;
  105. EFI_PARTITION_ENTRY *PartitionEntry;
  106. UINT8 *EntryPtr;
  107. UINTN NumberOfPartition;
  108. UINT32 Index;
  109. TCG_PCR_EVENT *TcgEvent;
  110. EFI_GPT_DATA *GptData;
  111. UINT32 EventSize;
  112. UINT32 EventNumber;
  113. EFI_PHYSICAL_ADDRESS EventLogLastEntry;
  114. if (mMeasureGptCount > 0) {
  115. return EFI_SUCCESS;
  116. }
  117. Status = gBS->HandleProtocol (GptHandle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo);
  118. if (EFI_ERROR (Status)) {
  119. return EFI_UNSUPPORTED;
  120. }
  121. Status = gBS->HandleProtocol (GptHandle, &gEfiDiskIoProtocolGuid, (VOID **)&DiskIo);
  122. if (EFI_ERROR (Status)) {
  123. return EFI_UNSUPPORTED;
  124. }
  125. //
  126. // Read the EFI Partition Table Header
  127. //
  128. PrimaryHeader = (EFI_PARTITION_TABLE_HEADER *)AllocatePool (BlockIo->Media->BlockSize);
  129. if (PrimaryHeader == NULL) {
  130. return EFI_OUT_OF_RESOURCES;
  131. }
  132. Status = DiskIo->ReadDisk (
  133. DiskIo,
  134. BlockIo->Media->MediaId,
  135. 1 * BlockIo->Media->BlockSize,
  136. BlockIo->Media->BlockSize,
  137. (UINT8 *)PrimaryHeader
  138. );
  139. if (EFI_ERROR (Status)) {
  140. DEBUG ((DEBUG_ERROR, "Failed to Read Partition Table Header!\n"));
  141. FreePool (PrimaryHeader);
  142. return EFI_DEVICE_ERROR;
  143. }
  144. //
  145. // Read the partition entry.
  146. //
  147. EntryPtr = (UINT8 *)AllocatePool (PrimaryHeader->NumberOfPartitionEntries * PrimaryHeader->SizeOfPartitionEntry);
  148. if (EntryPtr == NULL) {
  149. FreePool (PrimaryHeader);
  150. return EFI_OUT_OF_RESOURCES;
  151. }
  152. Status = DiskIo->ReadDisk (
  153. DiskIo,
  154. BlockIo->Media->MediaId,
  155. MultU64x32 (PrimaryHeader->PartitionEntryLBA, BlockIo->Media->BlockSize),
  156. PrimaryHeader->NumberOfPartitionEntries * PrimaryHeader->SizeOfPartitionEntry,
  157. EntryPtr
  158. );
  159. if (EFI_ERROR (Status)) {
  160. FreePool (PrimaryHeader);
  161. FreePool (EntryPtr);
  162. return EFI_DEVICE_ERROR;
  163. }
  164. //
  165. // Count the valid partition
  166. //
  167. PartitionEntry = (EFI_PARTITION_ENTRY *)EntryPtr;
  168. NumberOfPartition = 0;
  169. for (Index = 0; Index < PrimaryHeader->NumberOfPartitionEntries; Index++) {
  170. if (!IsZeroGuid (&PartitionEntry->PartitionTypeGUID)) {
  171. NumberOfPartition++;
  172. }
  173. PartitionEntry = (EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);
  174. }
  175. //
  176. // Prepare Data for Measurement
  177. //
  178. EventSize = (UINT32)(sizeof (EFI_GPT_DATA) - sizeof (GptData->Partitions)
  179. + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry);
  180. TcgEvent = (TCG_PCR_EVENT *)AllocateZeroPool (EventSize + sizeof (TCG_PCR_EVENT_HDR));
  181. if (TcgEvent == NULL) {
  182. FreePool (PrimaryHeader);
  183. FreePool (EntryPtr);
  184. return EFI_OUT_OF_RESOURCES;
  185. }
  186. TcgEvent->PCRIndex = 5;
  187. TcgEvent->EventType = EV_EFI_GPT_EVENT;
  188. TcgEvent->EventSize = EventSize;
  189. GptData = (EFI_GPT_DATA *)TcgEvent->Event;
  190. //
  191. // Copy the EFI_PARTITION_TABLE_HEADER and NumberOfPartition
  192. //
  193. CopyMem ((UINT8 *)GptData, (UINT8 *)PrimaryHeader, sizeof (EFI_PARTITION_TABLE_HEADER));
  194. GptData->NumberOfPartitions = NumberOfPartition;
  195. //
  196. // Copy the valid partition entry
  197. //
  198. PartitionEntry = (EFI_PARTITION_ENTRY *)EntryPtr;
  199. NumberOfPartition = 0;
  200. for (Index = 0; Index < PrimaryHeader->NumberOfPartitionEntries; Index++) {
  201. if (!IsZeroGuid (&PartitionEntry->PartitionTypeGUID)) {
  202. CopyMem (
  203. (UINT8 *)&GptData->Partitions + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry,
  204. (UINT8 *)PartitionEntry,
  205. PrimaryHeader->SizeOfPartitionEntry
  206. );
  207. NumberOfPartition++;
  208. }
  209. PartitionEntry = (EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);
  210. }
  211. //
  212. // Measure the GPT data
  213. //
  214. EventNumber = 1;
  215. Status = TcgProtocol->HashLogExtendEvent (
  216. TcgProtocol,
  217. (EFI_PHYSICAL_ADDRESS)(UINTN)(VOID *)GptData,
  218. (UINT64)TcgEvent->EventSize,
  219. TPM_ALG_SHA,
  220. TcgEvent,
  221. &EventNumber,
  222. &EventLogLastEntry
  223. );
  224. if (!EFI_ERROR (Status)) {
  225. mMeasureGptCount++;
  226. }
  227. FreePool (PrimaryHeader);
  228. FreePool (EntryPtr);
  229. FreePool (TcgEvent);
  230. return Status;
  231. }
  232. /**
  233. Measure PE image into TPM log based on the authenticode image hashing in
  234. PE/COFF Specification 8.0 Appendix A.
  235. Caution: This function may receive untrusted input.
  236. PE/COFF image is external input, so this function will validate its data structure
  237. within this image buffer before use.
  238. Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
  239. its caller function DxeTpmMeasureBootHandler().
  240. @param[in] TcgProtocol Pointer to the located TCG protocol instance.
  241. @param[in] ImageAddress Start address of image buffer.
  242. @param[in] ImageSize Image size
  243. @param[in] LinkTimeBase Address that the image is loaded into memory.
  244. @param[in] ImageType Image subsystem type.
  245. @param[in] FilePath File path is corresponding to the input image.
  246. @retval EFI_SUCCESS Successfully measure image.
  247. @retval EFI_OUT_OF_RESOURCES No enough resource to measure image.
  248. @retval EFI_UNSUPPORTED ImageType is unsupported or PE image is mal-format.
  249. @retval other error value
  250. **/
  251. EFI_STATUS
  252. EFIAPI
  253. TcgMeasurePeImage (
  254. IN EFI_TCG_PROTOCOL *TcgProtocol,
  255. IN EFI_PHYSICAL_ADDRESS ImageAddress,
  256. IN UINTN ImageSize,
  257. IN UINTN LinkTimeBase,
  258. IN UINT16 ImageType,
  259. IN EFI_DEVICE_PATH_PROTOCOL *FilePath
  260. )
  261. {
  262. EFI_STATUS Status;
  263. TCG_PCR_EVENT *TcgEvent;
  264. EFI_IMAGE_LOAD_EVENT *ImageLoad;
  265. UINT32 FilePathSize;
  266. VOID *Sha1Ctx;
  267. UINTN CtxSize;
  268. EFI_IMAGE_DOS_HEADER *DosHdr;
  269. UINT32 PeCoffHeaderOffset;
  270. EFI_IMAGE_SECTION_HEADER *Section;
  271. UINT8 *HashBase;
  272. UINTN HashSize;
  273. UINTN SumOfBytesHashed;
  274. EFI_IMAGE_SECTION_HEADER *SectionHeader;
  275. UINTN Index;
  276. UINTN Pos;
  277. UINT32 EventSize;
  278. UINT32 EventNumber;
  279. EFI_PHYSICAL_ADDRESS EventLogLastEntry;
  280. EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
  281. UINT32 NumberOfRvaAndSizes;
  282. BOOLEAN HashStatus;
  283. UINT32 CertSize;
  284. Status = EFI_UNSUPPORTED;
  285. ImageLoad = NULL;
  286. SectionHeader = NULL;
  287. Sha1Ctx = NULL;
  288. FilePathSize = (UINT32)GetDevicePathSize (FilePath);
  289. //
  290. // Determine destination PCR by BootPolicy
  291. //
  292. EventSize = sizeof (*ImageLoad) - sizeof (ImageLoad->DevicePath) + FilePathSize;
  293. TcgEvent = AllocateZeroPool (EventSize + sizeof (TCG_PCR_EVENT));
  294. if (TcgEvent == NULL) {
  295. return EFI_OUT_OF_RESOURCES;
  296. }
  297. TcgEvent->EventSize = EventSize;
  298. ImageLoad = (EFI_IMAGE_LOAD_EVENT *)TcgEvent->Event;
  299. switch (ImageType) {
  300. case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
  301. TcgEvent->EventType = EV_EFI_BOOT_SERVICES_APPLICATION;
  302. TcgEvent->PCRIndex = 4;
  303. break;
  304. case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
  305. TcgEvent->EventType = EV_EFI_BOOT_SERVICES_DRIVER;
  306. TcgEvent->PCRIndex = 2;
  307. break;
  308. case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
  309. TcgEvent->EventType = EV_EFI_RUNTIME_SERVICES_DRIVER;
  310. TcgEvent->PCRIndex = 2;
  311. break;
  312. default:
  313. DEBUG ((
  314. DEBUG_ERROR,
  315. "TcgMeasurePeImage: Unknown subsystem type %d",
  316. ImageType
  317. ));
  318. goto Finish;
  319. }
  320. ImageLoad->ImageLocationInMemory = ImageAddress;
  321. ImageLoad->ImageLengthInMemory = ImageSize;
  322. ImageLoad->ImageLinkTimeAddress = LinkTimeBase;
  323. ImageLoad->LengthOfDevicePath = FilePathSize;
  324. if ((FilePath != NULL) && (FilePathSize != 0)) {
  325. CopyMem (ImageLoad->DevicePath, FilePath, FilePathSize);
  326. }
  327. //
  328. // Check PE/COFF image
  329. //
  330. DosHdr = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress;
  331. PeCoffHeaderOffset = 0;
  332. if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
  333. PeCoffHeaderOffset = DosHdr->e_lfanew;
  334. }
  335. Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset);
  336. if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
  337. goto Finish;
  338. }
  339. //
  340. // PE/COFF Image Measurement
  341. //
  342. // NOTE: The following codes/steps are based upon the authenticode image hashing in
  343. // PE/COFF Specification 8.0 Appendix A.
  344. //
  345. //
  346. // 1. Load the image header into memory.
  347. // 2. Initialize a SHA hash context.
  348. CtxSize = Sha1GetContextSize ();
  349. Sha1Ctx = AllocatePool (CtxSize);
  350. if (Sha1Ctx == NULL) {
  351. Status = EFI_OUT_OF_RESOURCES;
  352. goto Finish;
  353. }
  354. HashStatus = Sha1Init (Sha1Ctx);
  355. if (!HashStatus) {
  356. goto Finish;
  357. }
  358. //
  359. // Measuring PE/COFF Image Header;
  360. // But CheckSum field and SECURITY data directory (certificate) are excluded
  361. //
  362. //
  363. // 3. Calculate the distance from the base of the image header to the image checksum address.
  364. // 4. Hash the image header from its base to beginning of the image checksum.
  365. //
  366. HashBase = (UINT8 *)(UINTN)ImageAddress;
  367. if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  368. //
  369. // Use PE32 offset
  370. //
  371. NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
  372. HashSize = (UINTN)(&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN)HashBase;
  373. } else {
  374. //
  375. // Use PE32+ offset
  376. //
  377. NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
  378. HashSize = (UINTN)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - (UINTN)HashBase;
  379. }
  380. HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
  381. if (!HashStatus) {
  382. goto Finish;
  383. }
  384. //
  385. // 5. Skip over the image checksum (it occupies a single ULONG).
  386. //
  387. if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
  388. //
  389. // 6. Since there is no Cert Directory in optional header, hash everything
  390. // from the end of the checksum to the end of image header.
  391. //
  392. if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  393. //
  394. // Use PE32 offset.
  395. //
  396. HashBase = (UINT8 *)&Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
  397. HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
  398. } else {
  399. //
  400. // Use PE32+ offset.
  401. //
  402. HashBase = (UINT8 *)&Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
  403. HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
  404. }
  405. if (HashSize != 0) {
  406. HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
  407. if (!HashStatus) {
  408. goto Finish;
  409. }
  410. }
  411. } else {
  412. //
  413. // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
  414. //
  415. if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  416. //
  417. // Use PE32 offset
  418. //
  419. HashBase = (UINT8 *)&Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
  420. HashSize = (UINTN)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN)HashBase;
  421. } else {
  422. //
  423. // Use PE32+ offset
  424. //
  425. HashBase = (UINT8 *)&Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
  426. HashSize = (UINTN)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN)HashBase;
  427. }
  428. if (HashSize != 0) {
  429. HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
  430. if (!HashStatus) {
  431. goto Finish;
  432. }
  433. }
  434. //
  435. // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
  436. // 9. Hash everything from the end of the Cert Directory to the end of image header.
  437. //
  438. if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  439. //
  440. // Use PE32 offset
  441. //
  442. HashBase = (UINT8 *)&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
  443. HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
  444. } else {
  445. //
  446. // Use PE32+ offset
  447. //
  448. HashBase = (UINT8 *)&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
  449. HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
  450. }
  451. if (HashSize != 0) {
  452. HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
  453. if (!HashStatus) {
  454. goto Finish;
  455. }
  456. }
  457. }
  458. //
  459. // 10. Set the SUM_OF_BYTES_HASHED to the size of the header
  460. //
  461. if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  462. //
  463. // Use PE32 offset
  464. //
  465. SumOfBytesHashed = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
  466. } else {
  467. //
  468. // Use PE32+ offset
  469. //
  470. SumOfBytesHashed = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
  471. }
  472. //
  473. // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
  474. // structures in the image. The 'NumberOfSections' field of the image
  475. // header indicates how big the table should be. Do not include any
  476. // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
  477. //
  478. SectionHeader = (EFI_IMAGE_SECTION_HEADER *)AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * Hdr.Pe32->FileHeader.NumberOfSections);
  479. if (SectionHeader == NULL) {
  480. Status = EFI_OUT_OF_RESOURCES;
  481. goto Finish;
  482. }
  483. //
  484. // 12. Using the 'PointerToRawData' in the referenced section headers as
  485. // a key, arrange the elements in the table in ascending order. In other
  486. // words, sort the section headers according to the disk-file offset of
  487. // the section.
  488. //
  489. Section = (EFI_IMAGE_SECTION_HEADER *)(
  490. (UINT8 *)(UINTN)ImageAddress +
  491. PeCoffHeaderOffset +
  492. sizeof (UINT32) +
  493. sizeof (EFI_IMAGE_FILE_HEADER) +
  494. Hdr.Pe32->FileHeader.SizeOfOptionalHeader
  495. );
  496. for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
  497. Pos = Index;
  498. while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
  499. CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
  500. Pos--;
  501. }
  502. CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
  503. Section += 1;
  504. }
  505. //
  506. // 13. Walk through the sorted table, bring the corresponding section
  507. // into memory, and hash the entire section (using the 'SizeOfRawData'
  508. // field in the section header to determine the amount of data to hash).
  509. // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
  510. // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
  511. //
  512. for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
  513. Section = (EFI_IMAGE_SECTION_HEADER *)&SectionHeader[Index];
  514. if (Section->SizeOfRawData == 0) {
  515. continue;
  516. }
  517. HashBase = (UINT8 *)(UINTN)ImageAddress + Section->PointerToRawData;
  518. HashSize = (UINTN)Section->SizeOfRawData;
  519. HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
  520. if (!HashStatus) {
  521. goto Finish;
  522. }
  523. SumOfBytesHashed += HashSize;
  524. }
  525. //
  526. // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
  527. // data in the file that needs to be added to the hash. This data begins
  528. // at file offset SUM_OF_BYTES_HASHED and its length is:
  529. // FileSize - (CertDirectory->Size)
  530. //
  531. if (ImageSize > SumOfBytesHashed) {
  532. HashBase = (UINT8 *)(UINTN)ImageAddress + SumOfBytesHashed;
  533. if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
  534. CertSize = 0;
  535. } else {
  536. if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  537. //
  538. // Use PE32 offset.
  539. //
  540. CertSize = Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
  541. } else {
  542. //
  543. // Use PE32+ offset.
  544. //
  545. CertSize = Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
  546. }
  547. }
  548. if (ImageSize > CertSize + SumOfBytesHashed) {
  549. HashSize = (UINTN)(ImageSize - CertSize - SumOfBytesHashed);
  550. HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
  551. if (!HashStatus) {
  552. goto Finish;
  553. }
  554. } else if (ImageSize < CertSize + SumOfBytesHashed) {
  555. goto Finish;
  556. }
  557. }
  558. //
  559. // 17. Finalize the SHA hash.
  560. //
  561. HashStatus = Sha1Final (Sha1Ctx, (UINT8 *)&TcgEvent->Digest);
  562. if (!HashStatus) {
  563. goto Finish;
  564. }
  565. //
  566. // Log the PE data
  567. //
  568. EventNumber = 1;
  569. Status = TcgProtocol->HashLogExtendEvent (
  570. TcgProtocol,
  571. (EFI_PHYSICAL_ADDRESS)(UINTN)(VOID *)NULL,
  572. 0,
  573. TPM_ALG_SHA,
  574. TcgEvent,
  575. &EventNumber,
  576. &EventLogLastEntry
  577. );
  578. if (Status == EFI_OUT_OF_RESOURCES) {
  579. //
  580. // Out of resource here means the image is hashed and its result is extended to PCR.
  581. // But the event log can't be saved since log area is full.
  582. // Just return EFI_SUCCESS in order not to block the image load.
  583. //
  584. Status = EFI_SUCCESS;
  585. }
  586. Finish:
  587. FreePool (TcgEvent);
  588. if (SectionHeader != NULL) {
  589. FreePool (SectionHeader);
  590. }
  591. if (Sha1Ctx != NULL ) {
  592. FreePool (Sha1Ctx);
  593. }
  594. return Status;
  595. }
  596. /**
  597. The security handler is used to abstract platform-specific policy
  598. from the DXE core response to an attempt to use a file that returns a
  599. given status for the authentication check from the section extraction protocol.
  600. The possible responses in a given SAP implementation may include locking
  601. flash upon failure to authenticate, attestation logging for all signed drivers,
  602. and other exception operations. The File parameter allows for possible logging
  603. within the SAP of the driver.
  604. If the file specified by File with an authentication status specified by
  605. AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.
  606. If the file specified by File with an authentication status specified by
  607. AuthenticationStatus is not safe for the DXE Core to use under any circumstances,
  608. then EFI_ACCESS_DENIED is returned.
  609. If the file specified by File with an authentication status specified by
  610. AuthenticationStatus is not safe for the DXE Core to use right now, but it
  611. might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is
  612. returned.
  613. If check image specified by FileBuffer and File is NULL meanwhile, return EFI_ACCESS_DENIED.
  614. @param[in] AuthenticationStatus This is the authentication status returned
  615. from the securitymeasurement services for the
  616. input file.
  617. @param[in] File This is a pointer to the device path of the file that is
  618. being dispatched. This will optionally be used for logging.
  619. @param[in] FileBuffer File buffer matches the input file device path.
  620. @param[in] FileSize Size of File buffer matches the input file device path.
  621. @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
  622. @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
  623. FileBuffer did authenticate, and the platform policy dictates
  624. that the DXE Foundation may use the file.
  625. @retval other error value
  626. **/
  627. EFI_STATUS
  628. EFIAPI
  629. DxeTpmMeasureBootHandler (
  630. IN UINT32 AuthenticationStatus,
  631. IN CONST EFI_DEVICE_PATH_PROTOCOL *File OPTIONAL,
  632. IN VOID *FileBuffer,
  633. IN UINTN FileSize,
  634. IN BOOLEAN BootPolicy
  635. )
  636. {
  637. EFI_TCG_PROTOCOL *TcgProtocol;
  638. EFI_STATUS Status;
  639. TCG_EFI_BOOT_SERVICE_CAPABILITY ProtocolCapability;
  640. UINT32 TCGFeatureFlags;
  641. EFI_PHYSICAL_ADDRESS EventLogLocation;
  642. EFI_PHYSICAL_ADDRESS EventLogLastEntry;
  643. EFI_DEVICE_PATH_PROTOCOL *DevicePathNode;
  644. EFI_DEVICE_PATH_PROTOCOL *OrigDevicePathNode;
  645. EFI_HANDLE Handle;
  646. EFI_HANDLE TempHandle;
  647. BOOLEAN ApplicationRequired;
  648. PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
  649. EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;
  650. EFI_PHYSICAL_ADDRESS FvAddress;
  651. UINT32 Index;
  652. Status = gBS->LocateProtocol (&gEfiTcgProtocolGuid, NULL, (VOID **)&TcgProtocol);
  653. if (EFI_ERROR (Status)) {
  654. //
  655. // TCG protocol is not installed. So, TPM is not present.
  656. // Don't do any measurement, and directly return EFI_SUCCESS.
  657. //
  658. return EFI_SUCCESS;
  659. }
  660. ProtocolCapability.Size = (UINT8)sizeof (ProtocolCapability);
  661. Status = TcgProtocol->StatusCheck (
  662. TcgProtocol,
  663. &ProtocolCapability,
  664. &TCGFeatureFlags,
  665. &EventLogLocation,
  666. &EventLogLastEntry
  667. );
  668. if (EFI_ERROR (Status) || ProtocolCapability.TPMDeactivatedFlag || (!ProtocolCapability.TPMPresentFlag)) {
  669. //
  670. // TPM device doesn't work or activate.
  671. //
  672. return EFI_SUCCESS;
  673. }
  674. //
  675. // Copy File Device Path
  676. //
  677. OrigDevicePathNode = DuplicateDevicePath (File);
  678. //
  679. // 1. Check whether this device path support BlockIo protocol.
  680. // Is so, this device path may be a GPT device path.
  681. //
  682. DevicePathNode = OrigDevicePathNode;
  683. Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &DevicePathNode, &Handle);
  684. if (!EFI_ERROR (Status) && !mMeasureGptTableFlag) {
  685. //
  686. // Find the gpt partition on the given devicepath
  687. //
  688. DevicePathNode = OrigDevicePathNode;
  689. ASSERT (DevicePathNode != NULL);
  690. while (!IsDevicePathEnd (DevicePathNode)) {
  691. //
  692. // Find the Gpt partition
  693. //
  694. if ((DevicePathType (DevicePathNode) == MEDIA_DEVICE_PATH) &&
  695. (DevicePathSubType (DevicePathNode) == MEDIA_HARDDRIVE_DP))
  696. {
  697. //
  698. // Check whether it is a gpt partition or not
  699. //
  700. if ((((HARDDRIVE_DEVICE_PATH *)DevicePathNode)->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER) &&
  701. (((HARDDRIVE_DEVICE_PATH *)DevicePathNode)->SignatureType == SIGNATURE_TYPE_GUID))
  702. {
  703. //
  704. // Change the partition device path to its parent device path (disk) and get the handle.
  705. //
  706. DevicePathNode->Type = END_DEVICE_PATH_TYPE;
  707. DevicePathNode->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
  708. DevicePathNode = OrigDevicePathNode;
  709. Status = gBS->LocateDevicePath (
  710. &gEfiDiskIoProtocolGuid,
  711. &DevicePathNode,
  712. &Handle
  713. );
  714. if (!EFI_ERROR (Status)) {
  715. //
  716. // Measure GPT disk.
  717. //
  718. Status = TcgMeasureGptTable (TcgProtocol, Handle);
  719. if (!EFI_ERROR (Status)) {
  720. //
  721. // GPT disk check done.
  722. //
  723. mMeasureGptTableFlag = TRUE;
  724. }
  725. }
  726. FreePool (OrigDevicePathNode);
  727. OrigDevicePathNode = DuplicateDevicePath (File);
  728. ASSERT (OrigDevicePathNode != NULL);
  729. break;
  730. }
  731. }
  732. DevicePathNode = NextDevicePathNode (DevicePathNode);
  733. }
  734. }
  735. //
  736. // 2. Measure PE image.
  737. //
  738. ApplicationRequired = FALSE;
  739. //
  740. // Check whether this device path support FVB protocol.
  741. //
  742. DevicePathNode = OrigDevicePathNode;
  743. Status = gBS->LocateDevicePath (&gEfiFirmwareVolumeBlockProtocolGuid, &DevicePathNode, &Handle);
  744. if (!EFI_ERROR (Status)) {
  745. //
  746. // Don't check FV image, and directly return EFI_SUCCESS.
  747. // It can be extended to the specific FV authentication according to the different requirement.
  748. //
  749. if (IsDevicePathEnd (DevicePathNode)) {
  750. return EFI_SUCCESS;
  751. }
  752. //
  753. // The PE image from unmeasured Firmware volume need be measured
  754. // The PE image from measured Firmware volume will be measured according to policy below.
  755. // If it is driver, do not measure
  756. // If it is application, still measure.
  757. //
  758. ApplicationRequired = TRUE;
  759. if ((mCacheMeasuredHandle != Handle) && (mMeasuredHobData != NULL)) {
  760. //
  761. // Search for Root FV of this PE image
  762. //
  763. TempHandle = Handle;
  764. do {
  765. Status = gBS->HandleProtocol (
  766. TempHandle,
  767. &gEfiFirmwareVolumeBlockProtocolGuid,
  768. (VOID **)&FvbProtocol
  769. );
  770. TempHandle = FvbProtocol->ParentHandle;
  771. } while (!EFI_ERROR (Status) && FvbProtocol->ParentHandle != NULL);
  772. //
  773. // Search in measured FV Hob
  774. //
  775. Status = FvbProtocol->GetPhysicalAddress (FvbProtocol, &FvAddress);
  776. if (EFI_ERROR (Status)) {
  777. return Status;
  778. }
  779. ApplicationRequired = FALSE;
  780. for (Index = 0; Index < mMeasuredHobData->Num; Index++) {
  781. if (mMeasuredHobData->MeasuredFvBuf[Index].BlobBase == FvAddress) {
  782. //
  783. // Cache measured FV for next measurement
  784. //
  785. mCacheMeasuredHandle = Handle;
  786. ApplicationRequired = TRUE;
  787. break;
  788. }
  789. }
  790. }
  791. }
  792. //
  793. // File is not found.
  794. //
  795. if (FileBuffer == NULL) {
  796. Status = EFI_SECURITY_VIOLATION;
  797. goto Finish;
  798. }
  799. mTpmImageSize = FileSize;
  800. mFileBuffer = FileBuffer;
  801. //
  802. // Measure PE Image
  803. //
  804. DevicePathNode = OrigDevicePathNode;
  805. ZeroMem (&ImageContext, sizeof (ImageContext));
  806. ImageContext.Handle = (VOID *)FileBuffer;
  807. ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)DxeTpmMeasureBootLibImageRead;
  808. //
  809. // Get information about the image being loaded
  810. //
  811. Status = PeCoffLoaderGetImageInfo (&ImageContext);
  812. if (EFI_ERROR (Status)) {
  813. //
  814. // Check for invalid parameters.
  815. //
  816. if (File == NULL) {
  817. return EFI_ACCESS_DENIED;
  818. }
  819. //
  820. // The information can't be got from the invalid PeImage
  821. //
  822. goto Finish;
  823. }
  824. //
  825. // Measure only application if Application flag is set
  826. // Measure drivers and applications if Application flag is not set
  827. //
  828. if ((!ApplicationRequired) ||
  829. (ApplicationRequired && (ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)))
  830. {
  831. //
  832. // Print the image path to be measured.
  833. //
  834. DEBUG_CODE_BEGIN ();
  835. CHAR16 *ToText;
  836. ToText = ConvertDevicePathToText (
  837. DevicePathNode,
  838. FALSE,
  839. TRUE
  840. );
  841. if (ToText != NULL) {
  842. DEBUG ((DEBUG_INFO, "The measured image path is %s.\n", ToText));
  843. FreePool (ToText);
  844. }
  845. DEBUG_CODE_END ();
  846. //
  847. // Measure PE image into TPM log.
  848. //
  849. Status = TcgMeasurePeImage (
  850. TcgProtocol,
  851. (EFI_PHYSICAL_ADDRESS)(UINTN)FileBuffer,
  852. FileSize,
  853. (UINTN)ImageContext.ImageAddress,
  854. ImageContext.ImageType,
  855. DevicePathNode
  856. );
  857. }
  858. //
  859. // Done, free the allocated resource.
  860. //
  861. Finish:
  862. if (OrigDevicePathNode != NULL) {
  863. FreePool (OrigDevicePathNode);
  864. }
  865. return Status;
  866. }
  867. /**
  868. Register the security handler to provide TPM measure boot service.
  869. @param ImageHandle ImageHandle of the loaded driver.
  870. @param SystemTable Pointer to the EFI System Table.
  871. @retval EFI_SUCCESS Register successfully.
  872. @retval EFI_OUT_OF_RESOURCES No enough memory to register this handler.
  873. **/
  874. EFI_STATUS
  875. EFIAPI
  876. DxeTpmMeasureBootLibConstructor (
  877. IN EFI_HANDLE ImageHandle,
  878. IN EFI_SYSTEM_TABLE *SystemTable
  879. )
  880. {
  881. EFI_HOB_GUID_TYPE *GuidHob;
  882. GuidHob = NULL;
  883. GuidHob = GetFirstGuidHob (&gMeasuredFvHobGuid);
  884. if (GuidHob != NULL) {
  885. mMeasuredHobData = GET_GUID_HOB_DATA (GuidHob);
  886. }
  887. return RegisterSecurity2Handler (
  888. DxeTpmMeasureBootHandler,
  889. EFI_AUTH_OPERATION_MEASURE_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
  890. );
  891. }