Home | History | Annotate | Download | only in DxeTpm2MeasureBootLib
      1 /** @file
      2   The library instance provides security service of TPM2 measure boot.
      3 
      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.
      8 
      9   DxeTpm2MeasureBootLibImageRead() function will make sure the PE/COFF image content
     10   read is within the image buffer.
     11 
     12   Tcg2MeasurePeImage() function will accept untrusted PE/COFF image and validate its
     13   data structure within this image buffer before use.
     14 
     15   Tcg2MeasureGptTable() function will receive untrusted GPT partition table, and parse
     16   partition data carefully.
     17 
     18 Copyright (c) 2013 - 2015, Intel Corporation. All rights reserved.<BR>
     19 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
     20 This program and the accompanying materials
     21 are licensed and made available under the terms and conditions of the BSD License
     22 which accompanies this distribution.  The full text of the license may be found at
     23 http://opensource.org/licenses/bsd-license.php
     24 
     25 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
     26 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
     27 
     28 **/
     29 
     30 #include <PiDxe.h>
     31 
     32 #include <Protocol/Tcg2Protocol.h>
     33 #include <Protocol/BlockIo.h>
     34 #include <Protocol/DiskIo.h>
     35 #include <Protocol/DevicePathToText.h>
     36 #include <Protocol/FirmwareVolumeBlock.h>
     37 
     38 #include <Guid/MeasuredFvHob.h>
     39 #include <Guid/ZeroGuid.h>
     40 
     41 #include <Library/BaseLib.h>
     42 #include <Library/DebugLib.h>
     43 #include <Library/BaseMemoryLib.h>
     44 #include <Library/MemoryAllocationLib.h>
     45 #include <Library/DevicePathLib.h>
     46 #include <Library/UefiBootServicesTableLib.h>
     47 #include <Library/BaseCryptLib.h>
     48 #include <Library/PeCoffLib.h>
     49 #include <Library/SecurityManagementLib.h>
     50 #include <Library/HobLib.h>
     51 
     52 //
     53 // Flag to check GPT partition. It only need be measured once.
     54 //
     55 BOOLEAN                           mTcg2MeasureGptTableFlag = FALSE;
     56 UINTN                             mTcg2MeasureGptCount = 0;
     57 VOID                              *mTcg2FileBuffer;
     58 UINTN                             mTcg2ImageSize;
     59 //
     60 // Measured FV handle cache
     61 //
     62 EFI_HANDLE                        mTcg2CacheMeasuredHandle  = NULL;
     63 MEASURED_HOB_DATA                 *mTcg2MeasuredHobData     = NULL;
     64 
     65 /**
     66   Reads contents of a PE/COFF image in memory buffer.
     67 
     68   Caution: This function may receive untrusted input.
     69   PE/COFF image is external input, so this function will make sure the PE/COFF image content
     70   read is within the image buffer.
     71 
     72   @param  FileHandle      Pointer to the file handle to read the PE/COFF image.
     73   @param  FileOffset      Offset into the PE/COFF image to begin the read operation.
     74   @param  ReadSize        On input, the size in bytes of the requested read operation.
     75                           On output, the number of bytes actually read.
     76   @param  Buffer          Output buffer that contains the data read from the PE/COFF image.
     77 
     78   @retval EFI_SUCCESS     The specified portion of the PE/COFF image was read and the size
     79 **/
     80 EFI_STATUS
     81 EFIAPI
     82 DxeTpm2MeasureBootLibImageRead (
     83   IN     VOID    *FileHandle,
     84   IN     UINTN   FileOffset,
     85   IN OUT UINTN   *ReadSize,
     86   OUT    VOID    *Buffer
     87   )
     88 {
     89   UINTN               EndPosition;
     90 
     91   if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {
     92     return EFI_INVALID_PARAMETER;
     93   }
     94 
     95   if (MAX_ADDRESS - FileOffset < *ReadSize) {
     96     return EFI_INVALID_PARAMETER;
     97   }
     98 
     99   EndPosition = FileOffset + *ReadSize;
    100   if (EndPosition > mTcg2ImageSize) {
    101     *ReadSize = (UINT32)(mTcg2ImageSize - FileOffset);
    102   }
    103 
    104   if (FileOffset >= mTcg2ImageSize) {
    105     *ReadSize = 0;
    106   }
    107 
    108   CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);
    109 
    110   return EFI_SUCCESS;
    111 }
    112 
    113 /**
    114   Measure GPT table data into TPM log.
    115 
    116   Caution: This function may receive untrusted input.
    117   The GPT partition table is external input, so this function should parse partition data carefully.
    118 
    119   @param Tcg2Protocol            Pointer to the located TCG2 protocol instance.
    120   @param GptHandle               Handle that GPT partition was installed.
    121 
    122   @retval EFI_SUCCESS            Successfully measure GPT table.
    123   @retval EFI_UNSUPPORTED        Not support GPT table on the given handle.
    124   @retval EFI_DEVICE_ERROR       Can't get GPT table because device error.
    125   @retval EFI_OUT_OF_RESOURCES   No enough resource to measure GPT table.
    126   @retval other error value
    127 **/
    128 EFI_STATUS
    129 EFIAPI
    130 Tcg2MeasureGptTable (
    131   IN  EFI_TCG2_PROTOCOL  *Tcg2Protocol,
    132   IN  EFI_HANDLE         GptHandle
    133   )
    134 {
    135   EFI_STATUS                        Status;
    136   EFI_BLOCK_IO_PROTOCOL             *BlockIo;
    137   EFI_DISK_IO_PROTOCOL              *DiskIo;
    138   EFI_PARTITION_TABLE_HEADER        *PrimaryHeader;
    139   EFI_PARTITION_ENTRY               *PartitionEntry;
    140   UINT8                             *EntryPtr;
    141   UINTN                             NumberOfPartition;
    142   UINT32                            Index;
    143   EFI_TCG2_EVENT                    *Tcg2Event;
    144   EFI_GPT_DATA                      *GptData;
    145   UINT32                            EventSize;
    146 
    147   if (mTcg2MeasureGptCount > 0) {
    148     return EFI_SUCCESS;
    149   }
    150 
    151   Status = gBS->HandleProtocol (GptHandle, &gEfiBlockIoProtocolGuid, (VOID**)&BlockIo);
    152   if (EFI_ERROR (Status)) {
    153     return EFI_UNSUPPORTED;
    154   }
    155   Status = gBS->HandleProtocol (GptHandle, &gEfiDiskIoProtocolGuid, (VOID**)&DiskIo);
    156   if (EFI_ERROR (Status)) {
    157     return EFI_UNSUPPORTED;
    158   }
    159   //
    160   // Read the EFI Partition Table Header
    161   //
    162   PrimaryHeader = (EFI_PARTITION_TABLE_HEADER *) AllocatePool (BlockIo->Media->BlockSize);
    163   if (PrimaryHeader == NULL) {
    164     return EFI_OUT_OF_RESOURCES;
    165   }
    166   Status = DiskIo->ReadDisk (
    167                      DiskIo,
    168                      BlockIo->Media->MediaId,
    169                      1 * BlockIo->Media->BlockSize,
    170                      BlockIo->Media->BlockSize,
    171                      (UINT8 *)PrimaryHeader
    172                      );
    173   if (EFI_ERROR (Status)) {
    174     DEBUG ((EFI_D_ERROR, "Failed to Read Partition Table Header!\n"));
    175     FreePool (PrimaryHeader);
    176     return EFI_DEVICE_ERROR;
    177   }
    178   //
    179   // Read the partition entry.
    180   //
    181   EntryPtr = (UINT8 *)AllocatePool (PrimaryHeader->NumberOfPartitionEntries * PrimaryHeader->SizeOfPartitionEntry);
    182   if (EntryPtr == NULL) {
    183     FreePool (PrimaryHeader);
    184     return EFI_OUT_OF_RESOURCES;
    185   }
    186   Status = DiskIo->ReadDisk (
    187                      DiskIo,
    188                      BlockIo->Media->MediaId,
    189                      MultU64x32(PrimaryHeader->PartitionEntryLBA, BlockIo->Media->BlockSize),
    190                      PrimaryHeader->NumberOfPartitionEntries * PrimaryHeader->SizeOfPartitionEntry,
    191                      EntryPtr
    192                      );
    193   if (EFI_ERROR (Status)) {
    194     FreePool (PrimaryHeader);
    195     FreePool (EntryPtr);
    196     return EFI_DEVICE_ERROR;
    197   }
    198 
    199   //
    200   // Count the valid partition
    201   //
    202   PartitionEntry    = (EFI_PARTITION_ENTRY *)EntryPtr;
    203   NumberOfPartition = 0;
    204   for (Index = 0; Index < PrimaryHeader->NumberOfPartitionEntries; Index++) {
    205     if (!CompareGuid (&PartitionEntry->PartitionTypeGUID, &gZeroGuid)) {
    206       NumberOfPartition++;
    207     }
    208     PartitionEntry = (EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);
    209   }
    210 
    211   //
    212   // Prepare Data for Measurement
    213   //
    214   EventSize = (UINT32)(sizeof (EFI_GPT_DATA) - sizeof (GptData->Partitions)
    215                         + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry);
    216   Tcg2Event = (EFI_TCG2_EVENT *) AllocateZeroPool (EventSize + sizeof (EFI_TCG2_EVENT) - sizeof(Tcg2Event->Event));
    217   if (Tcg2Event == NULL) {
    218     FreePool (PrimaryHeader);
    219     FreePool (EntryPtr);
    220     return EFI_OUT_OF_RESOURCES;
    221   }
    222 
    223   Tcg2Event->Size = EventSize + sizeof (EFI_TCG2_EVENT) - sizeof(Tcg2Event->Event);
    224   Tcg2Event->Header.HeaderSize    = sizeof(EFI_TCG2_EVENT_HEADER);
    225   Tcg2Event->Header.HeaderVersion = EFI_TCG2_EVENT_HEADER_VERSION;
    226   Tcg2Event->Header.PCRIndex      = 5;
    227   Tcg2Event->Header.EventType     = EV_EFI_GPT_EVENT;
    228   GptData = (EFI_GPT_DATA *) Tcg2Event->Event;
    229 
    230   //
    231   // Copy the EFI_PARTITION_TABLE_HEADER and NumberOfPartition
    232   //
    233   CopyMem ((UINT8 *)GptData, (UINT8*)PrimaryHeader, sizeof (EFI_PARTITION_TABLE_HEADER));
    234   GptData->NumberOfPartitions = NumberOfPartition;
    235   //
    236   // Copy the valid partition entry
    237   //
    238   PartitionEntry    = (EFI_PARTITION_ENTRY*)EntryPtr;
    239   NumberOfPartition = 0;
    240   for (Index = 0; Index < PrimaryHeader->NumberOfPartitionEntries; Index++) {
    241     if (!CompareGuid (&PartitionEntry->PartitionTypeGUID, &gZeroGuid)) {
    242       CopyMem (
    243         (UINT8 *)&GptData->Partitions + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry,
    244         (UINT8 *)PartitionEntry,
    245         PrimaryHeader->SizeOfPartitionEntry
    246         );
    247       NumberOfPartition++;
    248     }
    249     PartitionEntry =(EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);
    250   }
    251 
    252   //
    253   // Measure the GPT data
    254   //
    255   Status = Tcg2Protocol->HashLogExtendEvent (
    256              Tcg2Protocol,
    257              0,
    258              (EFI_PHYSICAL_ADDRESS) (UINTN) (VOID *) GptData,
    259              (UINT64) EventSize,
    260              Tcg2Event
    261              );
    262   if (!EFI_ERROR (Status)) {
    263     mTcg2MeasureGptCount++;
    264   }
    265 
    266   FreePool (PrimaryHeader);
    267   FreePool (EntryPtr);
    268   FreePool (Tcg2Event);
    269 
    270   return Status;
    271 }
    272 
    273 /**
    274   Measure PE image into TPM log based on the authenticode image hashing in
    275   PE/COFF Specification 8.0 Appendix A.
    276 
    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.
    280 
    281   @param[in] Tcg2Protocol   Pointer to the located TCG2 protocol instance.
    282   @param[in] ImageAddress   Start address of image buffer.
    283   @param[in] ImageSize      Image size
    284   @param[in] LinkTimeBase   Address that the image is loaded into memory.
    285   @param[in] ImageType      Image subsystem type.
    286   @param[in] FilePath       File path is corresponding to the input image.
    287 
    288   @retval EFI_SUCCESS            Successfully measure image.
    289   @retval EFI_OUT_OF_RESOURCES   No enough resource to measure image.
    290   @retval EFI_UNSUPPORTED        ImageType is unsupported or PE image is mal-format.
    291   @retval other error value
    292 
    293 **/
    294 EFI_STATUS
    295 EFIAPI
    296 Tcg2MeasurePeImage (
    297   IN  EFI_TCG2_PROTOCOL         *Tcg2Protocol,
    298   IN  EFI_PHYSICAL_ADDRESS      ImageAddress,
    299   IN  UINTN                     ImageSize,
    300   IN  UINTN                     LinkTimeBase,
    301   IN  UINT16                    ImageType,
    302   IN  EFI_DEVICE_PATH_PROTOCOL  *FilePath
    303   )
    304 {
    305   EFI_STATUS                        Status;
    306   EFI_TCG2_EVENT                    *Tcg2Event;
    307   EFI_IMAGE_LOAD_EVENT              *ImageLoad;
    308   UINT32                            FilePathSize;
    309   UINT32                            EventSize;
    310 
    311   Status        = EFI_UNSUPPORTED;
    312   ImageLoad     = NULL;
    313   FilePathSize  = (UINT32) GetDevicePathSize (FilePath);
    314 
    315   //
    316   // Determine destination PCR by BootPolicy
    317   //
    318   EventSize = sizeof (*ImageLoad) - sizeof (ImageLoad->DevicePath) + FilePathSize;
    319   Tcg2Event = AllocateZeroPool (EventSize + sizeof (EFI_TCG2_EVENT) - sizeof(Tcg2Event->Event));
    320   if (Tcg2Event == NULL) {
    321     return EFI_OUT_OF_RESOURCES;
    322   }
    323 
    324   Tcg2Event->Size = EventSize + sizeof (EFI_TCG2_EVENT) - sizeof(Tcg2Event->Event);
    325   Tcg2Event->Header.HeaderSize    = sizeof(EFI_TCG2_EVENT_HEADER);
    326   Tcg2Event->Header.HeaderVersion = EFI_TCG2_EVENT_HEADER_VERSION;
    327   ImageLoad           = (EFI_IMAGE_LOAD_EVENT *) Tcg2Event->Event;
    328 
    329   switch (ImageType) {
    330     case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
    331       Tcg2Event->Header.EventType = EV_EFI_BOOT_SERVICES_APPLICATION;
    332       Tcg2Event->Header.PCRIndex  = 4;
    333       break;
    334     case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
    335       Tcg2Event->Header.EventType = EV_EFI_BOOT_SERVICES_DRIVER;
    336       Tcg2Event->Header.PCRIndex  = 2;
    337       break;
    338     case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
    339       Tcg2Event->Header.EventType = EV_EFI_RUNTIME_SERVICES_DRIVER;
    340       Tcg2Event->Header.PCRIndex  = 2;
    341       break;
    342     default:
    343       DEBUG ((
    344         EFI_D_ERROR,
    345         "Tcg2MeasurePeImage: Unknown subsystem type %d",
    346         ImageType
    347         ));
    348       goto Finish;
    349   }
    350 
    351   ImageLoad->ImageLocationInMemory = ImageAddress;
    352   ImageLoad->ImageLengthInMemory   = ImageSize;
    353   ImageLoad->ImageLinkTimeAddress  = LinkTimeBase;
    354   ImageLoad->LengthOfDevicePath    = FilePathSize;
    355   if ((FilePath != NULL) && (FilePathSize != 0)) {
    356     CopyMem (ImageLoad->DevicePath, FilePath, FilePathSize);
    357   }
    358 
    359   //
    360   // Log the PE data
    361   //
    362   Status = Tcg2Protocol->HashLogExtendEvent (
    363              Tcg2Protocol,
    364              PE_COFF_IMAGE,
    365              ImageAddress,
    366              ImageSize,
    367              Tcg2Event
    368              );
    369   if (Status == EFI_VOLUME_FULL) {
    370     //
    371     // Volume full here means the image is hashed and its result is extended to PCR.
    372     // But the event log cann't be saved since log area is full.
    373     // Just return EFI_SUCCESS in order not to block the image load.
    374     //
    375     Status = EFI_SUCCESS;
    376   }
    377 
    378 Finish:
    379   FreePool (Tcg2Event);
    380 
    381   return Status;
    382 }
    383 
    384 /**
    385   The security handler is used to abstract platform-specific policy
    386   from the DXE core response to an attempt to use a file that returns a
    387   given status for the authentication check from the section extraction protocol.
    388 
    389   The possible responses in a given SAP implementation may include locking
    390   flash upon failure to authenticate, attestation logging for all signed drivers,
    391   and other exception operations.  The File parameter allows for possible logging
    392   within the SAP of the driver.
    393 
    394   If File is NULL, then EFI_INVALID_PARAMETER is returned.
    395 
    396   If the file specified by File with an authentication status specified by
    397   AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.
    398 
    399   If the file specified by File with an authentication status specified by
    400   AuthenticationStatus is not safe for the DXE Core to use under any circumstances,
    401   then EFI_ACCESS_DENIED is returned.
    402 
    403   If the file specified by File with an authentication status specified by
    404   AuthenticationStatus is not safe for the DXE Core to use right now, but it
    405   might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is
    406   returned.
    407 
    408   @param[in]      AuthenticationStatus  This is the authentication status returned
    409                                         from the securitymeasurement services for the
    410                                         input file.
    411   @param[in]      File       This is a pointer to the device path of the file that is
    412                              being dispatched. This will optionally be used for logging.
    413   @param[in]      FileBuffer File buffer matches the input file device path.
    414   @param[in]      FileSize   Size of File buffer matches the input file device path.
    415   @param[in]      BootPolicy A boot policy that was used to call LoadImage() UEFI service.
    416 
    417   @retval EFI_SUCCESS             The file specified by DevicePath and non-NULL
    418                                   FileBuffer did authenticate, and the platform policy dictates
    419                                   that the DXE Foundation may use the file.
    420   @retval other error value
    421 **/
    422 EFI_STATUS
    423 EFIAPI
    424 DxeTpm2MeasureBootHandler (
    425   IN  UINT32                           AuthenticationStatus,
    426   IN  CONST EFI_DEVICE_PATH_PROTOCOL   *File,
    427   IN  VOID                             *FileBuffer,
    428   IN  UINTN                            FileSize,
    429   IN  BOOLEAN                          BootPolicy
    430   )
    431 {
    432   EFI_TCG2_PROTOCOL                   *Tcg2Protocol;
    433   EFI_STATUS                          Status;
    434   EFI_TCG2_BOOT_SERVICE_CAPABILITY    ProtocolCapability;
    435   EFI_DEVICE_PATH_PROTOCOL            *DevicePathNode;
    436   EFI_DEVICE_PATH_PROTOCOL            *OrigDevicePathNode;
    437   EFI_HANDLE                          Handle;
    438   EFI_HANDLE                          TempHandle;
    439   BOOLEAN                             ApplicationRequired;
    440   PE_COFF_LOADER_IMAGE_CONTEXT        ImageContext;
    441   EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *FvbProtocol;
    442   EFI_PHYSICAL_ADDRESS                FvAddress;
    443   UINT32                              Index;
    444 
    445   Status = gBS->LocateProtocol (&gEfiTcg2ProtocolGuid, NULL, (VOID **) &Tcg2Protocol);
    446   if (EFI_ERROR (Status)) {
    447     //
    448     // Tcg2 protocol is not installed. So, TPM2 is not present.
    449     // Don't do any measurement, and directly return EFI_SUCCESS.
    450     //
    451     DEBUG ((EFI_D_VERBOSE, "DxeTpm2MeasureBootHandler - Tcg2 - %r\n", Status));
    452     return EFI_SUCCESS;
    453   }
    454 
    455   ProtocolCapability.Size = (UINT8) sizeof (ProtocolCapability);
    456   Status = Tcg2Protocol->GetCapability (
    457                            Tcg2Protocol,
    458                            &ProtocolCapability
    459                            );
    460   if (EFI_ERROR (Status) || (!ProtocolCapability.TPMPresentFlag)) {
    461     //
    462     // TPM device doesn't work or activate.
    463     //
    464     DEBUG ((EFI_D_ERROR, "DxeTpm2MeasureBootHandler (%r) - TPMPresentFlag - %x\n", Status, ProtocolCapability.TPMPresentFlag));
    465     return EFI_SUCCESS;
    466   }
    467 
    468   //
    469   // Copy File Device Path
    470   //
    471   OrigDevicePathNode = DuplicateDevicePath (File);
    472 
    473   //
    474   // 1. Check whether this device path support BlockIo protocol.
    475   // Is so, this device path may be a GPT device path.
    476   //
    477   DevicePathNode = OrigDevicePathNode;
    478   Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &DevicePathNode, &Handle);
    479   if (!EFI_ERROR (Status) && !mTcg2MeasureGptTableFlag) {
    480     //
    481     // Find the gpt partion on the given devicepath
    482     //
    483     DevicePathNode = OrigDevicePathNode;
    484     ASSERT (DevicePathNode != NULL);
    485     while (!IsDevicePathEnd (DevicePathNode)) {
    486       //
    487       // Find the Gpt partition
    488       //
    489       if (DevicePathType (DevicePathNode) == MEDIA_DEVICE_PATH &&
    490             DevicePathSubType (DevicePathNode) == MEDIA_HARDDRIVE_DP) {
    491         //
    492         // Check whether it is a gpt partition or not
    493         //
    494         if (((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER &&
    495             ((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->SignatureType == SIGNATURE_TYPE_GUID) {
    496 
    497           //
    498           // Change the partition device path to its parent device path (disk) and get the handle.
    499           //
    500           DevicePathNode->Type    = END_DEVICE_PATH_TYPE;
    501           DevicePathNode->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
    502           DevicePathNode          = OrigDevicePathNode;
    503           Status = gBS->LocateDevicePath (
    504                          &gEfiDiskIoProtocolGuid,
    505                          &DevicePathNode,
    506                          &Handle
    507                          );
    508           if (!EFI_ERROR (Status)) {
    509             //
    510             // Measure GPT disk.
    511             //
    512             Status = Tcg2MeasureGptTable (Tcg2Protocol, Handle);
    513             DEBUG ((EFI_D_INFO, "DxeTpm2MeasureBootHandler - Tcg2MeasureGptTable - %r\n", Status));
    514             if (!EFI_ERROR (Status)) {
    515               //
    516               // GPT disk check done.
    517               //
    518               mTcg2MeasureGptTableFlag = TRUE;
    519             }
    520           }
    521           FreePool (OrigDevicePathNode);
    522           OrigDevicePathNode = DuplicateDevicePath (File);
    523           ASSERT (OrigDevicePathNode != NULL);
    524           break;
    525         }
    526       }
    527       DevicePathNode    = NextDevicePathNode (DevicePathNode);
    528     }
    529   }
    530 
    531   //
    532   // 2. Measure PE image.
    533   //
    534   ApplicationRequired = FALSE;
    535 
    536   //
    537   // Check whether this device path support FVB protocol.
    538   //
    539   DevicePathNode = OrigDevicePathNode;
    540   Status = gBS->LocateDevicePath (&gEfiFirmwareVolumeBlockProtocolGuid, &DevicePathNode, &Handle);
    541   if (!EFI_ERROR (Status)) {
    542     //
    543     // Don't check FV image, and directly return EFI_SUCCESS.
    544     // It can be extended to the specific FV authentication according to the different requirement.
    545     //
    546     if (IsDevicePathEnd (DevicePathNode)) {
    547       return EFI_SUCCESS;
    548     }
    549     //
    550     // The PE image from unmeasured Firmware volume need be measured
    551     // The PE image from measured Firmware volume will be mearsured according to policy below.
    552     //   If it is driver, do not measure
    553     //   If it is application, still measure.
    554     //
    555     ApplicationRequired = TRUE;
    556 
    557     if (mTcg2CacheMeasuredHandle != Handle && mTcg2MeasuredHobData != NULL) {
    558       //
    559       // Search for Root FV of this PE image
    560       //
    561       TempHandle = Handle;
    562       do {
    563         Status = gBS->HandleProtocol(
    564                         TempHandle,
    565                         &gEfiFirmwareVolumeBlockProtocolGuid,
    566                         (VOID**)&FvbProtocol
    567                         );
    568         TempHandle = FvbProtocol->ParentHandle;
    569       } while (!EFI_ERROR(Status) && FvbProtocol->ParentHandle != NULL);
    570 
    571       //
    572       // Search in measured FV Hob
    573       //
    574       Status = FvbProtocol->GetPhysicalAddress(FvbProtocol, &FvAddress);
    575       if (EFI_ERROR(Status)){
    576         return Status;
    577       }
    578 
    579       ApplicationRequired = FALSE;
    580 
    581       for (Index = 0; Index < mTcg2MeasuredHobData->Num; Index++) {
    582         if(mTcg2MeasuredHobData->MeasuredFvBuf[Index].BlobBase == FvAddress) {
    583           //
    584           // Cache measured FV for next measurement
    585           //
    586           mTcg2CacheMeasuredHandle = Handle;
    587           ApplicationRequired  = TRUE;
    588           break;
    589         }
    590       }
    591     }
    592   }
    593 
    594   //
    595   // File is not found.
    596   //
    597   if (FileBuffer == NULL) {
    598     Status = EFI_SECURITY_VIOLATION;
    599     goto Finish;
    600   }
    601 
    602   mTcg2ImageSize  = FileSize;
    603   mTcg2FileBuffer = FileBuffer;
    604 
    605   //
    606   // Measure PE Image
    607   //
    608   DevicePathNode = OrigDevicePathNode;
    609   ZeroMem (&ImageContext, sizeof (ImageContext));
    610   ImageContext.Handle    = (VOID *) FileBuffer;
    611   ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeTpm2MeasureBootLibImageRead;
    612 
    613   //
    614   // Get information about the image being loaded
    615   //
    616   Status = PeCoffLoaderGetImageInfo (&ImageContext);
    617   if (EFI_ERROR (Status)) {
    618     //
    619     // The information can't be got from the invalid PeImage
    620     //
    621     goto Finish;
    622   }
    623 
    624   //
    625   // Measure only application if Application flag is set
    626   // Measure drivers and applications if Application flag is not set
    627   //
    628   if ((!ApplicationRequired) ||
    629         (ApplicationRequired && ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) {
    630     //
    631     // Print the image path to be measured.
    632     //
    633     DEBUG_CODE_BEGIN ();
    634       CHAR16                            *ToText;
    635       ToText = ConvertDevicePathToText (
    636                  DevicePathNode,
    637                  FALSE,
    638                  TRUE
    639                  );
    640       if (ToText != NULL) {
    641         DEBUG ((DEBUG_INFO, "The measured image path is %s.\n", ToText));
    642         FreePool (ToText);
    643       }
    644     DEBUG_CODE_END ();
    645 
    646     //
    647     // Measure PE image into TPM log.
    648     //
    649     Status = Tcg2MeasurePeImage (
    650                Tcg2Protocol,
    651                (EFI_PHYSICAL_ADDRESS) (UINTN) FileBuffer,
    652                FileSize,
    653                (UINTN) ImageContext.ImageAddress,
    654                ImageContext.ImageType,
    655                DevicePathNode
    656                );
    657     DEBUG ((EFI_D_INFO, "DxeTpm2MeasureBootHandler - Tcg2MeasurePeImage - %r\n", Status));
    658   }
    659 
    660   //
    661   // Done, free the allocated resource.
    662   //
    663 Finish:
    664   if (OrigDevicePathNode != NULL) {
    665     FreePool (OrigDevicePathNode);
    666   }
    667 
    668   DEBUG ((EFI_D_INFO, "DxeTpm2MeasureBootHandler - %r\n", Status));
    669 
    670   return Status;
    671 }
    672 
    673 /**
    674   Register the security handler to provide TPM measure boot service.
    675 
    676   @param  ImageHandle  ImageHandle of the loaded driver.
    677   @param  SystemTable  Pointer to the EFI System Table.
    678 
    679   @retval  EFI_SUCCESS            Register successfully.
    680   @retval  EFI_OUT_OF_RESOURCES   No enough memory to register this handler.
    681 **/
    682 EFI_STATUS
    683 EFIAPI
    684 DxeTpm2MeasureBootLibConstructor (
    685   IN EFI_HANDLE        ImageHandle,
    686   IN EFI_SYSTEM_TABLE  *SystemTable
    687   )
    688 {
    689   EFI_HOB_GUID_TYPE  *GuidHob;
    690 
    691   GuidHob = NULL;
    692 
    693   GuidHob = GetFirstGuidHob (&gMeasuredFvHobGuid);
    694 
    695   if (GuidHob != NULL) {
    696     mTcg2MeasuredHobData = GET_GUID_HOB_DATA (GuidHob);
    697   }
    698 
    699   return RegisterSecurity2Handler (
    700           DxeTpm2MeasureBootHandler,
    701           EFI_AUTH_OPERATION_MEASURE_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
    702           );
    703 }
    704