2 The library instance provides security service of TPM measure boot.
4 Caution: This file requires additional review when modified.
5 This library will have external input - PE/COFF image and GPT partition.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
9 DxeTpmMeasureBootLibImageRead() function will make sure the PE/COFF image content
10 read is within the image buffer.
12 TcgMeasurePeImage() function will accept untrusted PE/COFF image and validate its
13 data structure within this image buffer before use.
15 TcgMeasureGptTable() function will receive untrusted GPT partition table, and parse
16 partition data carefully.
18 Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
19 This program and the accompanying materials
20 are licensed and made available under the terms and conditions of the BSD License
21 which accompanies this distribution. The full text of the license may be found at
22 http://opensource.org/licenses/bsd-license.php
24 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
25 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
31 #include <Protocol/TcgService.h>
32 #include <Protocol/BlockIo.h>
33 #include <Protocol/DiskIo.h>
34 #include <Protocol/FirmwareVolumeBlock.h>
36 #include <Guid/MeasuredFvHob.h>
38 #include <Library/BaseLib.h>
39 #include <Library/DebugLib.h>
40 #include <Library/BaseMemoryLib.h>
41 #include <Library/MemoryAllocationLib.h>
42 #include <Library/DevicePathLib.h>
43 #include <Library/UefiBootServicesTableLib.h>
44 #include <Library/BaseCryptLib.h>
45 #include <Library/PeCoffLib.h>
46 #include <Library/SecurityManagementLib.h>
47 #include <Library/HobLib.h>
50 // Flag to check GPT partition. It only need be measured once.
52 BOOLEAN mMeasureGptTableFlag
= FALSE
;
53 UINTN mMeasureGptCount
= 0;
57 // Measured FV handle cache
59 EFI_HANDLE mCacheMeasuredHandle
= NULL
;
60 MEASURED_HOB_DATA
*mMeasuredHobData
= NULL
;
63 Reads contents of a PE/COFF image in memory buffer.
65 Caution: This function may receive untrusted input.
66 PE/COFF image is external input, so this function will make sure the PE/COFF image content
67 read is within the image buffer.
69 @param FileHandle Pointer to the file handle to read the PE/COFF image.
70 @param FileOffset Offset into the PE/COFF image to begin the read operation.
71 @param ReadSize On input, the size in bytes of the requested read operation.
72 On output, the number of bytes actually read.
73 @param Buffer Output buffer that contains the data read from the PE/COFF image.
75 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
79 DxeTpmMeasureBootLibImageRead (
82 IN OUT UINTN
*ReadSize
,
88 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
89 return EFI_INVALID_PARAMETER
;
92 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
93 return EFI_INVALID_PARAMETER
;
96 EndPosition
= FileOffset
+ *ReadSize
;
97 if (EndPosition
> mTpmImageSize
) {
98 *ReadSize
= (UINT32
)(mTpmImageSize
- FileOffset
);
101 if (FileOffset
>= mTpmImageSize
) {
105 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
111 Measure GPT table data into TPM log.
113 Caution: This function may receive untrusted input.
114 The GPT partition table is external input, so this function should parse partition data carefully.
116 @param TcgProtocol Pointer to the located TCG protocol instance.
117 @param GptHandle Handle that GPT partition was installed.
119 @retval EFI_SUCCESS Successfully measure GPT table.
120 @retval EFI_UNSUPPORTED Not support GPT table on the given handle.
121 @retval EFI_DEVICE_ERROR Can't get GPT table because device error.
122 @retval EFI_OUT_OF_RESOURCES No enough resource to measure GPT table.
123 @retval other error value
128 IN EFI_TCG_PROTOCOL
*TcgProtocol
,
129 IN EFI_HANDLE GptHandle
133 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
134 EFI_DISK_IO_PROTOCOL
*DiskIo
;
135 EFI_PARTITION_TABLE_HEADER
*PrimaryHeader
;
136 EFI_PARTITION_ENTRY
*PartitionEntry
;
138 UINTN NumberOfPartition
;
140 TCG_PCR_EVENT
*TcgEvent
;
141 EFI_GPT_DATA
*GptData
;
144 EFI_PHYSICAL_ADDRESS EventLogLastEntry
;
146 if (mMeasureGptCount
> 0) {
150 Status
= gBS
->HandleProtocol (GptHandle
, &gEfiBlockIoProtocolGuid
, (VOID
**)&BlockIo
);
151 if (EFI_ERROR (Status
)) {
152 return EFI_UNSUPPORTED
;
154 Status
= gBS
->HandleProtocol (GptHandle
, &gEfiDiskIoProtocolGuid
, (VOID
**)&DiskIo
);
155 if (EFI_ERROR (Status
)) {
156 return EFI_UNSUPPORTED
;
159 // Read the EFI Partition Table Header
161 PrimaryHeader
= (EFI_PARTITION_TABLE_HEADER
*) AllocatePool (BlockIo
->Media
->BlockSize
);
162 if (PrimaryHeader
== NULL
) {
163 return EFI_OUT_OF_RESOURCES
;
165 Status
= DiskIo
->ReadDisk (
167 BlockIo
->Media
->MediaId
,
168 1 * BlockIo
->Media
->BlockSize
,
169 BlockIo
->Media
->BlockSize
,
170 (UINT8
*)PrimaryHeader
172 if (EFI_ERROR (Status
)) {
173 DEBUG ((EFI_D_ERROR
, "Failed to Read Partition Table Header!\n"));
174 FreePool (PrimaryHeader
);
175 return EFI_DEVICE_ERROR
;
178 // Read the partition entry.
180 EntryPtr
= (UINT8
*)AllocatePool (PrimaryHeader
->NumberOfPartitionEntries
* PrimaryHeader
->SizeOfPartitionEntry
);
181 if (EntryPtr
== NULL
) {
182 FreePool (PrimaryHeader
);
183 return EFI_OUT_OF_RESOURCES
;
185 Status
= DiskIo
->ReadDisk (
187 BlockIo
->Media
->MediaId
,
188 MultU64x32(PrimaryHeader
->PartitionEntryLBA
, BlockIo
->Media
->BlockSize
),
189 PrimaryHeader
->NumberOfPartitionEntries
* PrimaryHeader
->SizeOfPartitionEntry
,
192 if (EFI_ERROR (Status
)) {
193 FreePool (PrimaryHeader
);
195 return EFI_DEVICE_ERROR
;
199 // Count the valid partition
201 PartitionEntry
= (EFI_PARTITION_ENTRY
*)EntryPtr
;
202 NumberOfPartition
= 0;
203 for (Index
= 0; Index
< PrimaryHeader
->NumberOfPartitionEntries
; Index
++) {
204 if (!IsZeroGuid (&PartitionEntry
->PartitionTypeGUID
)) {
207 PartitionEntry
= (EFI_PARTITION_ENTRY
*)((UINT8
*)PartitionEntry
+ PrimaryHeader
->SizeOfPartitionEntry
);
211 // Prepare Data for Measurement
213 EventSize
= (UINT32
)(sizeof (EFI_GPT_DATA
) - sizeof (GptData
->Partitions
)
214 + NumberOfPartition
* PrimaryHeader
->SizeOfPartitionEntry
);
215 TcgEvent
= (TCG_PCR_EVENT
*) AllocateZeroPool (EventSize
+ sizeof (TCG_PCR_EVENT_HDR
));
216 if (TcgEvent
== NULL
) {
217 FreePool (PrimaryHeader
);
219 return EFI_OUT_OF_RESOURCES
;
222 TcgEvent
->PCRIndex
= 5;
223 TcgEvent
->EventType
= EV_EFI_GPT_EVENT
;
224 TcgEvent
->EventSize
= EventSize
;
225 GptData
= (EFI_GPT_DATA
*) TcgEvent
->Event
;
228 // Copy the EFI_PARTITION_TABLE_HEADER and NumberOfPartition
230 CopyMem ((UINT8
*)GptData
, (UINT8
*)PrimaryHeader
, sizeof (EFI_PARTITION_TABLE_HEADER
));
231 GptData
->NumberOfPartitions
= NumberOfPartition
;
233 // Copy the valid partition entry
235 PartitionEntry
= (EFI_PARTITION_ENTRY
*)EntryPtr
;
236 NumberOfPartition
= 0;
237 for (Index
= 0; Index
< PrimaryHeader
->NumberOfPartitionEntries
; Index
++) {
238 if (!IsZeroGuid (&PartitionEntry
->PartitionTypeGUID
)) {
240 (UINT8
*)&GptData
->Partitions
+ NumberOfPartition
* PrimaryHeader
->SizeOfPartitionEntry
,
241 (UINT8
*)PartitionEntry
,
242 PrimaryHeader
->SizeOfPartitionEntry
246 PartitionEntry
=(EFI_PARTITION_ENTRY
*)((UINT8
*)PartitionEntry
+ PrimaryHeader
->SizeOfPartitionEntry
);
250 // Measure the GPT data
253 Status
= TcgProtocol
->HashLogExtendEvent (
255 (EFI_PHYSICAL_ADDRESS
) (UINTN
) (VOID
*) GptData
,
256 (UINT64
) TcgEvent
->EventSize
,
262 if (!EFI_ERROR (Status
)) {
266 FreePool (PrimaryHeader
);
274 Measure PE image into TPM log based on the authenticode image hashing in
275 PE/COFF Specification 8.0 Appendix A.
277 Caution: This function may receive untrusted input.
278 PE/COFF image is external input, so this function will validate its data structure
279 within this image buffer before use.
281 Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
282 its caller function DxeTpmMeasureBootHandler().
284 @param[in] TcgProtocol Pointer to the located TCG protocol instance.
285 @param[in] ImageAddress Start address of image buffer.
286 @param[in] ImageSize Image size
287 @param[in] LinkTimeBase Address that the image is loaded into memory.
288 @param[in] ImageType Image subsystem type.
289 @param[in] FilePath File path is corresponding to the input image.
291 @retval EFI_SUCCESS Successfully measure image.
292 @retval EFI_OUT_OF_RESOURCES No enough resource to measure image.
293 @retval EFI_UNSUPPORTED ImageType is unsupported or PE image is mal-format.
294 @retval other error value
300 IN EFI_TCG_PROTOCOL
*TcgProtocol
,
301 IN EFI_PHYSICAL_ADDRESS ImageAddress
,
303 IN UINTN LinkTimeBase
,
305 IN EFI_DEVICE_PATH_PROTOCOL
*FilePath
309 TCG_PCR_EVENT
*TcgEvent
;
310 EFI_IMAGE_LOAD_EVENT
*ImageLoad
;
314 EFI_IMAGE_DOS_HEADER
*DosHdr
;
315 UINT32 PeCoffHeaderOffset
;
316 EFI_IMAGE_SECTION_HEADER
*Section
;
319 UINTN SumOfBytesHashed
;
320 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
326 EFI_PHYSICAL_ADDRESS EventLogLastEntry
;
327 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr
;
328 UINT32 NumberOfRvaAndSizes
;
332 Status
= EFI_UNSUPPORTED
;
334 SectionHeader
= NULL
;
336 FilePathSize
= (UINT32
) GetDevicePathSize (FilePath
);
339 // Determine destination PCR by BootPolicy
341 EventSize
= sizeof (*ImageLoad
) - sizeof (ImageLoad
->DevicePath
) + FilePathSize
;
342 TcgEvent
= AllocateZeroPool (EventSize
+ sizeof (TCG_PCR_EVENT
));
343 if (TcgEvent
== NULL
) {
344 return EFI_OUT_OF_RESOURCES
;
347 TcgEvent
->EventSize
= EventSize
;
348 ImageLoad
= (EFI_IMAGE_LOAD_EVENT
*) TcgEvent
->Event
;
351 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION
:
352 TcgEvent
->EventType
= EV_EFI_BOOT_SERVICES_APPLICATION
;
353 TcgEvent
->PCRIndex
= 4;
355 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER
:
356 TcgEvent
->EventType
= EV_EFI_BOOT_SERVICES_DRIVER
;
357 TcgEvent
->PCRIndex
= 2;
359 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER
:
360 TcgEvent
->EventType
= EV_EFI_RUNTIME_SERVICES_DRIVER
;
361 TcgEvent
->PCRIndex
= 2;
366 "TcgMeasurePeImage: Unknown subsystem type %d",
372 ImageLoad
->ImageLocationInMemory
= ImageAddress
;
373 ImageLoad
->ImageLengthInMemory
= ImageSize
;
374 ImageLoad
->ImageLinkTimeAddress
= LinkTimeBase
;
375 ImageLoad
->LengthOfDevicePath
= FilePathSize
;
376 if ((FilePath
!= NULL
) && (FilePathSize
!= 0)) {
377 CopyMem (ImageLoad
->DevicePath
, FilePath
, FilePathSize
);
381 // Check PE/COFF image
383 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) (UINTN
) ImageAddress
;
384 PeCoffHeaderOffset
= 0;
385 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
386 PeCoffHeaderOffset
= DosHdr
->e_lfanew
;
389 Hdr
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*)((UINT8
*) (UINTN
) ImageAddress
+ PeCoffHeaderOffset
);
390 if (Hdr
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
395 // PE/COFF Image Measurement
397 // NOTE: The following codes/steps are based upon the authenticode image hashing in
398 // PE/COFF Specification 8.0 Appendix A.
402 // 1. Load the image header into memory.
404 // 2. Initialize a SHA hash context.
405 CtxSize
= Sha1GetContextSize ();
406 Sha1Ctx
= AllocatePool (CtxSize
);
407 if (Sha1Ctx
== NULL
) {
408 Status
= EFI_OUT_OF_RESOURCES
;
412 HashStatus
= Sha1Init (Sha1Ctx
);
418 // Measuring PE/COFF Image Header;
419 // But CheckSum field and SECURITY data directory (certificate) are excluded
421 if (Hdr
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& Hdr
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
423 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
424 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
425 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
426 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
428 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
431 // Get the magic value from the PE/COFF Optional Header
433 Magic
= Hdr
.Pe32
->OptionalHeader
.Magic
;
437 // 3. Calculate the distance from the base of the image header to the image checksum address.
438 // 4. Hash the image header from its base to beginning of the image checksum.
440 HashBase
= (UINT8
*) (UINTN
) ImageAddress
;
441 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
445 NumberOfRvaAndSizes
= Hdr
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
446 HashSize
= (UINTN
) ((UINT8
*)(&Hdr
.Pe32
->OptionalHeader
.CheckSum
) - HashBase
);
451 NumberOfRvaAndSizes
= Hdr
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
452 HashSize
= (UINTN
) ((UINT8
*)(&Hdr
.Pe32Plus
->OptionalHeader
.CheckSum
) - HashBase
);
455 HashStatus
= Sha1Update (Sha1Ctx
, HashBase
, HashSize
);
461 // 5. Skip over the image checksum (it occupies a single ULONG).
463 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
465 // 6. Since there is no Cert Directory in optional header, hash everything
466 // from the end of the checksum to the end of image header.
468 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
472 HashBase
= (UINT8
*) &Hdr
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
473 HashSize
= Hdr
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- ImageAddress
);
478 HashBase
= (UINT8
*) &Hdr
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
479 HashSize
= Hdr
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- ImageAddress
);
483 HashStatus
= Sha1Update (Sha1Ctx
, HashBase
, HashSize
);
490 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
492 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
496 HashBase
= (UINT8
*) &Hdr
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
497 HashSize
= (UINTN
) ((UINT8
*)(&Hdr
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
502 HashBase
= (UINT8
*) &Hdr
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
503 HashSize
= (UINTN
) ((UINT8
*)(&Hdr
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
507 HashStatus
= Sha1Update (Sha1Ctx
, HashBase
, HashSize
);
514 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
515 // 9. Hash everything from the end of the Cert Directory to the end of image header.
517 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
521 HashBase
= (UINT8
*) &Hdr
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
522 HashSize
= Hdr
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- ImageAddress
);
527 HashBase
= (UINT8
*) &Hdr
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
528 HashSize
= Hdr
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- ImageAddress
);
532 HashStatus
= Sha1Update (Sha1Ctx
, HashBase
, HashSize
);
540 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header
542 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
546 SumOfBytesHashed
= Hdr
.Pe32
->OptionalHeader
.SizeOfHeaders
;
551 SumOfBytesHashed
= Hdr
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
555 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
556 // structures in the image. The 'NumberOfSections' field of the image
557 // header indicates how big the table should be. Do not include any
558 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
560 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * Hdr
.Pe32
->FileHeader
.NumberOfSections
);
561 if (SectionHeader
== NULL
) {
562 Status
= EFI_OUT_OF_RESOURCES
;
567 // 12. Using the 'PointerToRawData' in the referenced section headers as
568 // a key, arrange the elements in the table in ascending order. In other
569 // words, sort the section headers according to the disk-file offset of
572 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
573 (UINT8
*) (UINTN
) ImageAddress
+
576 sizeof(EFI_IMAGE_FILE_HEADER
) +
577 Hdr
.Pe32
->FileHeader
.SizeOfOptionalHeader
579 for (Index
= 0; Index
< Hdr
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
581 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
582 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof(EFI_IMAGE_SECTION_HEADER
));
585 CopyMem (&SectionHeader
[Pos
], Section
, sizeof(EFI_IMAGE_SECTION_HEADER
));
590 // 13. Walk through the sorted table, bring the corresponding section
591 // into memory, and hash the entire section (using the 'SizeOfRawData'
592 // field in the section header to determine the amount of data to hash).
593 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
594 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
596 for (Index
= 0; Index
< Hdr
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
597 Section
= (EFI_IMAGE_SECTION_HEADER
*) &SectionHeader
[Index
];
598 if (Section
->SizeOfRawData
== 0) {
601 HashBase
= (UINT8
*) (UINTN
) ImageAddress
+ Section
->PointerToRawData
;
602 HashSize
= (UINTN
) Section
->SizeOfRawData
;
604 HashStatus
= Sha1Update (Sha1Ctx
, HashBase
, HashSize
);
609 SumOfBytesHashed
+= HashSize
;
613 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
614 // data in the file that needs to be added to the hash. This data begins
615 // at file offset SUM_OF_BYTES_HASHED and its length is:
616 // FileSize - (CertDirectory->Size)
618 if (ImageSize
> SumOfBytesHashed
) {
619 HashBase
= (UINT8
*) (UINTN
) ImageAddress
+ SumOfBytesHashed
;
621 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
624 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
628 CertSize
= Hdr
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
633 CertSize
= Hdr
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
637 if (ImageSize
> CertSize
+ SumOfBytesHashed
) {
638 HashSize
= (UINTN
) (ImageSize
- CertSize
- SumOfBytesHashed
);
640 HashStatus
= Sha1Update (Sha1Ctx
, HashBase
, HashSize
);
644 } else if (ImageSize
< CertSize
+ SumOfBytesHashed
) {
650 // 17. Finalize the SHA hash.
652 HashStatus
= Sha1Final (Sha1Ctx
, (UINT8
*) &TcgEvent
->Digest
);
661 Status
= TcgProtocol
->HashLogExtendEvent (
663 (EFI_PHYSICAL_ADDRESS
) (UINTN
) (VOID
*) NULL
,
670 if (Status
== EFI_OUT_OF_RESOURCES
) {
672 // Out of resource here means the image is hashed and its result is extended to PCR.
673 // But the event log cann't be saved since log area is full.
674 // Just return EFI_SUCCESS in order not to block the image load.
676 Status
= EFI_SUCCESS
;
682 if (SectionHeader
!= NULL
) {
683 FreePool (SectionHeader
);
686 if (Sha1Ctx
!= NULL
) {
693 The security handler is used to abstract platform-specific policy
694 from the DXE core response to an attempt to use a file that returns a
695 given status for the authentication check from the section extraction protocol.
697 The possible responses in a given SAP implementation may include locking
698 flash upon failure to authenticate, attestation logging for all signed drivers,
699 and other exception operations. The File parameter allows for possible logging
700 within the SAP of the driver.
702 If File is NULL, then EFI_INVALID_PARAMETER is returned.
704 If the file specified by File with an authentication status specified by
705 AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.
707 If the file specified by File with an authentication status specified by
708 AuthenticationStatus is not safe for the DXE Core to use under any circumstances,
709 then EFI_ACCESS_DENIED is returned.
711 If the file specified by File with an authentication status specified by
712 AuthenticationStatus is not safe for the DXE Core to use right now, but it
713 might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is
716 @param[in] AuthenticationStatus This is the authentication status returned
717 from the securitymeasurement services for the
719 @param[in] File This is a pointer to the device path of the file that is
720 being dispatched. This will optionally be used for logging.
721 @param[in] FileBuffer File buffer matches the input file device path.
722 @param[in] FileSize Size of File buffer matches the input file device path.
723 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
725 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
726 FileBuffer did authenticate, and the platform policy dictates
727 that the DXE Foundation may use the file.
728 @retval other error value
732 DxeTpmMeasureBootHandler (
733 IN UINT32 AuthenticationStatus
,
734 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
737 IN BOOLEAN BootPolicy
740 EFI_TCG_PROTOCOL
*TcgProtocol
;
742 TCG_EFI_BOOT_SERVICE_CAPABILITY ProtocolCapability
;
743 UINT32 TCGFeatureFlags
;
744 EFI_PHYSICAL_ADDRESS EventLogLocation
;
745 EFI_PHYSICAL_ADDRESS EventLogLastEntry
;
746 EFI_DEVICE_PATH_PROTOCOL
*DevicePathNode
;
747 EFI_DEVICE_PATH_PROTOCOL
*OrigDevicePathNode
;
749 EFI_HANDLE TempHandle
;
750 BOOLEAN ApplicationRequired
;
751 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
752 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
*FvbProtocol
;
753 EFI_PHYSICAL_ADDRESS FvAddress
;
756 Status
= gBS
->LocateProtocol (&gEfiTcgProtocolGuid
, NULL
, (VOID
**) &TcgProtocol
);
757 if (EFI_ERROR (Status
)) {
759 // TCG protocol is not installed. So, TPM is not present.
760 // Don't do any measurement, and directly return EFI_SUCCESS.
765 ProtocolCapability
.Size
= (UINT8
) sizeof (ProtocolCapability
);
766 Status
= TcgProtocol
->StatusCheck (
773 if (EFI_ERROR (Status
) || ProtocolCapability
.TPMDeactivatedFlag
|| (!ProtocolCapability
.TPMPresentFlag
)) {
775 // TPM device doesn't work or activate.
781 // Copy File Device Path
783 OrigDevicePathNode
= DuplicateDevicePath (File
);
786 // 1. Check whether this device path support BlockIo protocol.
787 // Is so, this device path may be a GPT device path.
789 DevicePathNode
= OrigDevicePathNode
;
790 Status
= gBS
->LocateDevicePath (&gEfiBlockIoProtocolGuid
, &DevicePathNode
, &Handle
);
791 if (!EFI_ERROR (Status
) && !mMeasureGptTableFlag
) {
793 // Find the gpt partion on the given devicepath
795 DevicePathNode
= OrigDevicePathNode
;
796 ASSERT (DevicePathNode
!= NULL
);
797 while (!IsDevicePathEnd (DevicePathNode
)) {
799 // Find the Gpt partition
801 if (DevicePathType (DevicePathNode
) == MEDIA_DEVICE_PATH
&&
802 DevicePathSubType (DevicePathNode
) == MEDIA_HARDDRIVE_DP
) {
804 // Check whether it is a gpt partition or not
806 if (((HARDDRIVE_DEVICE_PATH
*) DevicePathNode
)->MBRType
== MBR_TYPE_EFI_PARTITION_TABLE_HEADER
&&
807 ((HARDDRIVE_DEVICE_PATH
*) DevicePathNode
)->SignatureType
== SIGNATURE_TYPE_GUID
) {
810 // Change the partition device path to its parent device path (disk) and get the handle.
812 DevicePathNode
->Type
= END_DEVICE_PATH_TYPE
;
813 DevicePathNode
->SubType
= END_ENTIRE_DEVICE_PATH_SUBTYPE
;
814 DevicePathNode
= OrigDevicePathNode
;
815 Status
= gBS
->LocateDevicePath (
816 &gEfiDiskIoProtocolGuid
,
820 if (!EFI_ERROR (Status
)) {
824 Status
= TcgMeasureGptTable (TcgProtocol
, Handle
);
825 if (!EFI_ERROR (Status
)) {
827 // GPT disk check done.
829 mMeasureGptTableFlag
= TRUE
;
832 FreePool (OrigDevicePathNode
);
833 OrigDevicePathNode
= DuplicateDevicePath (File
);
834 ASSERT (OrigDevicePathNode
!= NULL
);
838 DevicePathNode
= NextDevicePathNode (DevicePathNode
);
843 // 2. Measure PE image.
845 ApplicationRequired
= FALSE
;
848 // Check whether this device path support FVB protocol.
850 DevicePathNode
= OrigDevicePathNode
;
851 Status
= gBS
->LocateDevicePath (&gEfiFirmwareVolumeBlockProtocolGuid
, &DevicePathNode
, &Handle
);
852 if (!EFI_ERROR (Status
)) {
854 // Don't check FV image, and directly return EFI_SUCCESS.
855 // It can be extended to the specific FV authentication according to the different requirement.
857 if (IsDevicePathEnd (DevicePathNode
)) {
861 // The PE image from unmeasured Firmware volume need be measured
862 // The PE image from measured Firmware volume will be mearsured according to policy below.
863 // If it is driver, do not measure
864 // If it is application, still measure.
866 ApplicationRequired
= TRUE
;
868 if (mCacheMeasuredHandle
!= Handle
&& mMeasuredHobData
!= NULL
) {
870 // Search for Root FV of this PE image
874 Status
= gBS
->HandleProtocol(
876 &gEfiFirmwareVolumeBlockProtocolGuid
,
879 TempHandle
= FvbProtocol
->ParentHandle
;
880 } while (!EFI_ERROR(Status
) && FvbProtocol
->ParentHandle
!= NULL
);
883 // Search in measured FV Hob
885 Status
= FvbProtocol
->GetPhysicalAddress(FvbProtocol
, &FvAddress
);
886 if (EFI_ERROR(Status
)){
890 ApplicationRequired
= FALSE
;
892 for (Index
= 0; Index
< mMeasuredHobData
->Num
; Index
++) {
893 if(mMeasuredHobData
->MeasuredFvBuf
[Index
].BlobBase
== FvAddress
) {
895 // Cache measured FV for next measurement
897 mCacheMeasuredHandle
= Handle
;
898 ApplicationRequired
= TRUE
;
906 // File is not found.
908 if (FileBuffer
== NULL
) {
909 Status
= EFI_SECURITY_VIOLATION
;
913 mTpmImageSize
= FileSize
;
914 mFileBuffer
= FileBuffer
;
919 DevicePathNode
= OrigDevicePathNode
;
920 ZeroMem (&ImageContext
, sizeof (ImageContext
));
921 ImageContext
.Handle
= (VOID
*) FileBuffer
;
922 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeTpmMeasureBootLibImageRead
;
925 // Get information about the image being loaded
927 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
928 if (EFI_ERROR (Status
)) {
930 // The information can't be got from the invalid PeImage
936 // Measure only application if Application flag is set
937 // Measure drivers and applications if Application flag is not set
939 if ((!ApplicationRequired
) ||
940 (ApplicationRequired
&& ImageContext
.ImageType
== EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION
)) {
942 // Print the image path to be measured.
946 ToText
= ConvertDevicePathToText (
951 if (ToText
!= NULL
) {
952 DEBUG ((DEBUG_INFO
, "The measured image path is %s.\n", ToText
));
958 // Measure PE image into TPM log.
960 Status
= TcgMeasurePeImage (
962 (EFI_PHYSICAL_ADDRESS
) (UINTN
) FileBuffer
,
964 (UINTN
) ImageContext
.ImageAddress
,
965 ImageContext
.ImageType
,
971 // Done, free the allocated resource.
974 if (OrigDevicePathNode
!= NULL
) {
975 FreePool (OrigDevicePathNode
);
982 Register the security handler to provide TPM measure boot service.
984 @param ImageHandle ImageHandle of the loaded driver.
985 @param SystemTable Pointer to the EFI System Table.
987 @retval EFI_SUCCESS Register successfully.
988 @retval EFI_OUT_OF_RESOURCES No enough memory to register this handler.
992 DxeTpmMeasureBootLibConstructor (
993 IN EFI_HANDLE ImageHandle
,
994 IN EFI_SYSTEM_TABLE
*SystemTable
997 EFI_HOB_GUID_TYPE
*GuidHob
;
1001 GuidHob
= GetFirstGuidHob (&gMeasuredFvHobGuid
);
1003 if (GuidHob
!= NULL
) {
1004 mMeasuredHobData
= GET_GUID_HOB_DATA (GuidHob
);
1007 return RegisterSecurity2Handler (
1008 DxeTpmMeasureBootHandler
,
1009 EFI_AUTH_OPERATION_MEASURE_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED