2 Implement image verification services for secure boot service
4 Caution: This file requires additional review when modified.
5 This library will have external input - PE/COFF image.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
9 DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content
10 read is within the image buffer.
12 DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept
13 untrusted PE/COFF image and validate its data structure within this image buffer before use.
15 Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
16 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
17 This program and the accompanying materials
18 are licensed and made available under the terms and conditions of the BSD License
19 which accompanies this distribution. The full text of the license may be found at
20 http://opensource.org/licenses/bsd-license.php
22 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
23 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
27 #include "DxeImageVerificationLib.h"
30 // Caution: This is used by a function which may receive untrusted input.
31 // These global variables hold PE/COFF image data, and they should be validated before use.
33 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
34 UINT32 mPeCoffHeaderOffset
;
38 // Information on current PE/COFF image
41 UINT8
*mImageBase
= NULL
;
42 UINT8 mImageDigest
[MAX_DIGEST_SIZE
];
43 UINTN mImageDigestSize
;
46 // Notify string for authorization UI.
48 CHAR16 mNotifyString1
[MAX_NOTIFY_STRING_LEN
] = L
"Image verification pass but not found in authorized database!";
49 CHAR16 mNotifyString2
[MAX_NOTIFY_STRING_LEN
] = L
"Launch this image anyway? (Yes/Defer/No)";
51 // Public Exponent of RSA Key.
53 CONST UINT8 mRsaE
[] = { 0x01, 0x00, 0x01 };
57 // OID ASN.1 Value for Hash Algorithms
59 UINT8 mHashOidValue
[] = {
60 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
61 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
64 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
67 HASH_TABLE mHash
[] = {
68 { L
"SHA1", 20, &mHashOidValue
[0], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
69 { L
"SHA224", 28, &mHashOidValue
[5], 9, NULL
, NULL
, NULL
, NULL
},
70 { L
"SHA256", 32, &mHashOidValue
[14], 9, Sha256GetContextSize
, Sha256Init
, Sha256Update
, Sha256Final
},
71 { L
"SHA384", 48, &mHashOidValue
[23], 9, Sha384GetContextSize
, Sha384Init
, Sha384Update
, Sha384Final
},
72 { L
"SHA512", 64, &mHashOidValue
[32], 9, Sha512GetContextSize
, Sha512Init
, Sha512Update
, Sha512Final
}
75 EFI_STRING mHashTypeStr
;
78 SecureBoot Hook for processing image verification.
80 @param[in] VariableName Name of Variable to be found.
81 @param[in] VendorGuid Variable vendor GUID.
82 @param[in] DataSize Size of Data found. If size is less than the
83 data, this value contains the required size.
84 @param[in] Data Data pointer.
90 IN CHAR16
*VariableName
,
91 IN EFI_GUID
*VendorGuid
,
97 Reads contents of a PE/COFF image in memory buffer.
99 Caution: This function may receive untrusted input.
100 PE/COFF image is external input, so this function will make sure the PE/COFF image content
101 read is within the image buffer.
103 @param FileHandle Pointer to the file handle to read the PE/COFF image.
104 @param FileOffset Offset into the PE/COFF image to begin the read operation.
105 @param ReadSize On input, the size in bytes of the requested read operation.
106 On output, the number of bytes actually read.
107 @param Buffer Output buffer that contains the data read from the PE/COFF image.
109 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
113 DxeImageVerificationLibImageRead (
116 IN OUT UINTN
*ReadSize
,
122 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
123 return EFI_INVALID_PARAMETER
;
126 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
127 return EFI_INVALID_PARAMETER
;
130 EndPosition
= FileOffset
+ *ReadSize
;
131 if (EndPosition
> mImageSize
) {
132 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
135 if (FileOffset
>= mImageSize
) {
139 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
148 @param[in] File This is a pointer to the device path of the file that is
151 @return UINT32 Image Type
156 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
160 EFI_HANDLE DeviceHandle
;
161 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
162 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
165 return IMAGE_UNKNOWN
;
169 // First check to see if File is from a Firmware Volume
172 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
173 Status
= gBS
->LocateDevicePath (
174 &gEfiFirmwareVolume2ProtocolGuid
,
178 if (!EFI_ERROR (Status
)) {
179 Status
= gBS
->OpenProtocol (
181 &gEfiFirmwareVolume2ProtocolGuid
,
185 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
187 if (!EFI_ERROR (Status
)) {
188 return IMAGE_FROM_FV
;
193 // Next check to see if File is from a Block I/O device
196 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
197 Status
= gBS
->LocateDevicePath (
198 &gEfiBlockIoProtocolGuid
,
202 if (!EFI_ERROR (Status
)) {
204 Status
= gBS
->OpenProtocol (
206 &gEfiBlockIoProtocolGuid
,
210 EFI_OPEN_PROTOCOL_GET_PROTOCOL
212 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
213 if (BlockIo
->Media
!= NULL
) {
214 if (BlockIo
->Media
->RemovableMedia
) {
216 // Block I/O is present and specifies the media is removable
218 return IMAGE_FROM_REMOVABLE_MEDIA
;
221 // Block I/O is present and specifies the media is not removable
223 return IMAGE_FROM_FIXED_MEDIA
;
230 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
231 // the device path supports the Simple File System Protocol.
234 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
235 Status
= gBS
->LocateDevicePath (
236 &gEfiSimpleFileSystemProtocolGuid
,
240 if (!EFI_ERROR (Status
)) {
242 // Simple File System is present without Block I/O, so assume media is fixed.
244 return IMAGE_FROM_FIXED_MEDIA
;
248 // File is not from an FV, Block I/O or Simple File System, so the only options
249 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
251 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
252 while (!IsDevicePathEndType (TempDevicePath
)) {
253 switch (DevicePathType (TempDevicePath
)) {
255 case MEDIA_DEVICE_PATH
:
256 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
257 return IMAGE_FROM_OPTION_ROM
;
261 case MESSAGING_DEVICE_PATH
:
262 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
263 return IMAGE_FROM_REMOVABLE_MEDIA
;
270 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
272 return IMAGE_UNKNOWN
;
276 Calculate hash of Pe/Coff image based on the authenticode image hashing in
277 PE/COFF Specification 8.0 Appendix A
279 Caution: This function may receive untrusted input.
280 PE/COFF image is external input, so this function will validate its data structure
281 within this image buffer before use.
283 @param[in] HashAlg Hash algorithm type.
285 @retval TRUE Successfully hash image.
286 @retval FALSE Fail in hash image.
296 EFI_IMAGE_SECTION_HEADER
*Section
;
301 UINTN SumOfBytesHashed
;
302 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
306 UINT32 NumberOfRvaAndSizes
;
309 SectionHeader
= NULL
;
312 if ((HashAlg
>= HASHALG_MAX
)) {
317 // Initialize context of hash.
319 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
323 mImageDigestSize
= SHA1_DIGEST_SIZE
;
324 mCertType
= gEfiCertSha1Guid
;
328 mImageDigestSize
= SHA256_DIGEST_SIZE
;
329 mCertType
= gEfiCertSha256Guid
;
333 mImageDigestSize
= SHA384_DIGEST_SIZE
;
334 mCertType
= gEfiCertSha384Guid
;
338 mImageDigestSize
= SHA512_DIGEST_SIZE
;
339 mCertType
= gEfiCertSha512Guid
;
346 mHashTypeStr
= mHash
[HashAlg
].Name
;
347 CtxSize
= mHash
[HashAlg
].GetContextSize();
349 HashCtx
= AllocatePool (CtxSize
);
350 if (HashCtx
== NULL
) {
354 // 1. Load the image header into memory.
356 // 2. Initialize a SHA hash context.
357 Status
= mHash
[HashAlg
].HashInit(HashCtx
);
364 // Measuring PE/COFF Image Header;
365 // But CheckSum field and SECURITY data directory (certificate) are excluded
367 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
369 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
370 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
371 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
372 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
374 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
377 // Get the magic value from the PE/COFF Optional Header
379 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
383 // 3. Calculate the distance from the base of the image header to the image checksum address.
384 // 4. Hash the image header from its base to beginning of the image checksum.
386 HashBase
= mImageBase
;
387 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
391 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - HashBase
);
392 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
393 } else if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
397 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - HashBase
);
398 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
401 // Invalid header magic number.
407 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
413 // 5. Skip over the image checksum (it occupies a single ULONG).
415 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
417 // 6. Since there is no Cert Directory in optional header, hash everything
418 // from the end of the checksum to the end of image header.
420 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
424 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
425 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
430 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
431 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
435 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
442 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
444 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
448 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
449 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
454 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
455 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
459 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
466 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
467 // 9. Hash everything from the end of the Cert Directory to the end of image header.
469 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
473 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
474 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
479 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
480 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
484 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
492 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
494 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
498 SumOfBytesHashed
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
;
503 SumOfBytesHashed
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
507 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
509 mPeCoffHeaderOffset
+
511 sizeof (EFI_IMAGE_FILE_HEADER
) +
512 mNtHeader
.Pe32
->FileHeader
.SizeOfOptionalHeader
516 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
517 // structures in the image. The 'NumberOfSections' field of the image
518 // header indicates how big the table should be. Do not include any
519 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
521 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * mNtHeader
.Pe32
->FileHeader
.NumberOfSections
);
522 if (SectionHeader
== NULL
) {
527 // 12. Using the 'PointerToRawData' in the referenced section headers as
528 // a key, arrange the elements in the table in ascending order. In other
529 // words, sort the section headers according to the disk-file offset of
532 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
534 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
535 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
538 CopyMem (&SectionHeader
[Pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
543 // 13. Walk through the sorted table, bring the corresponding section
544 // into memory, and hash the entire section (using the 'SizeOfRawData'
545 // field in the section header to determine the amount of data to hash).
546 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
547 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
549 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
550 Section
= &SectionHeader
[Index
];
551 if (Section
->SizeOfRawData
== 0) {
554 HashBase
= mImageBase
+ Section
->PointerToRawData
;
555 HashSize
= (UINTN
) Section
->SizeOfRawData
;
557 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
562 SumOfBytesHashed
+= HashSize
;
566 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
567 // data in the file that needs to be added to the hash. This data begins
568 // at file offset SUM_OF_BYTES_HASHED and its length is:
569 // FileSize - (CertDirectory->Size)
571 if (mImageSize
> SumOfBytesHashed
) {
572 HashBase
= mImageBase
+ SumOfBytesHashed
;
574 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
577 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
581 CertSize
= mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
586 CertSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
590 if (mImageSize
> CertSize
+ SumOfBytesHashed
) {
591 HashSize
= (UINTN
) (mImageSize
- CertSize
- SumOfBytesHashed
);
593 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
597 } else if (mImageSize
< CertSize
+ SumOfBytesHashed
) {
603 Status
= mHash
[HashAlg
].HashFinal(HashCtx
, mImageDigest
);
606 if (HashCtx
!= NULL
) {
609 if (SectionHeader
!= NULL
) {
610 FreePool (SectionHeader
);
616 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
617 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
620 Caution: This function may receive untrusted input.
621 PE/COFF image is external input, so this function will validate its data structure
622 within this image buffer before use.
624 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
625 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
627 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
628 @retval EFI_SUCCESS Hash successfully.
634 IN UINTN AuthDataSize
639 for (Index
= 0; Index
< HASHALG_MAX
; Index
++) {
641 // Check the Hash algorithm in PE/COFF Authenticode.
642 // According to PKCS#7 Definition:
643 // SignedData ::= SEQUENCE {
645 // digestAlgorithms DigestAlgorithmIdentifiers,
646 // contentInfo ContentInfo,
648 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
649 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
650 // Fixed offset (+32) is calculated based on two bytes of length encoding.
652 if ((*(AuthData
+ 1) & TWO_BYTE_ENCODE
) != TWO_BYTE_ENCODE
) {
654 // Only support two bytes of Long Form of Length Encoding.
659 if (AuthDataSize
< 32 + mHash
[Index
].OidLength
) {
660 return EFI_UNSUPPORTED
;
663 if (CompareMem (AuthData
+ 32, mHash
[Index
].OidValue
, mHash
[Index
].OidLength
) == 0) {
668 if (Index
== HASHALG_MAX
) {
669 return EFI_UNSUPPORTED
;
673 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
675 if (!HashPeImage(Index
)) {
676 return EFI_UNSUPPORTED
;
684 Returns the size of a given image execution info table in bytes.
686 This function returns the size, in bytes, of the image execution info table specified by
687 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
689 @param ImageExeInfoTable A pointer to a image execution info table structure.
691 @retval 0 If ImageExeInfoTable is NULL.
692 @retval Others The size of a image execution info table in bytes.
696 GetImageExeInfoTableSize (
697 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
701 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoItem
;
704 if (ImageExeInfoTable
== NULL
) {
708 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoTable
+ sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
));
709 TotalSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
710 for (Index
= 0; Index
< ImageExeInfoTable
->NumberOfImages
; Index
++) {
711 TotalSize
+= ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
);
712 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoItem
+ ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
));
719 Create an Image Execution Information Table entry and add it to system configuration table.
721 @param[in] Action Describes the action taken by the firmware regarding this image.
722 @param[in] Name Input a null-terminated, user-friendly name.
723 @param[in] DevicePath Input device path pointer.
724 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
725 @param[in] SignatureSize Size of signature.
730 IN EFI_IMAGE_EXECUTION_ACTION Action
,
731 IN CHAR16
*Name OPTIONAL
,
732 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
,
733 IN EFI_SIGNATURE_LIST
*Signature OPTIONAL
,
734 IN UINTN SignatureSize
737 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
738 EFI_IMAGE_EXECUTION_INFO_TABLE
*NewImageExeInfoTable
;
739 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoEntry
;
740 UINTN ImageExeInfoTableSize
;
741 UINTN NewImageExeInfoEntrySize
;
743 UINTN DevicePathSize
;
746 ImageExeInfoTable
= NULL
;
747 NewImageExeInfoTable
= NULL
;
748 ImageExeInfoEntry
= NULL
;
752 if (DevicePath
== NULL
) {
757 NameStringLen
= StrSize (Name
);
759 NameStringLen
= sizeof (CHAR16
);
762 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
763 if (ImageExeInfoTable
!= NULL
) {
765 // The table has been found!
766 // We must enlarge the table to accomodate the new exe info entry.
768 ImageExeInfoTableSize
= GetImageExeInfoTableSize (ImageExeInfoTable
);
772 // We should create a new table to append to the configuration table.
774 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
777 DevicePathSize
= GetDevicePathSize (DevicePath
);
780 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
782 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
784 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
785 if (NewImageExeInfoTable
== NULL
) {
789 if (ImageExeInfoTable
!= NULL
) {
790 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
792 NewImageExeInfoTable
->NumberOfImages
= 0;
794 NewImageExeInfoTable
->NumberOfImages
++;
795 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
797 // Update new item's information.
799 WriteUnaligned32 ((UINT32
*) ImageExeInfoEntry
, Action
);
800 WriteUnaligned32 ((UINT32
*) ((UINT8
*) ImageExeInfoEntry
+ sizeof (EFI_IMAGE_EXECUTION_ACTION
)), (UINT32
) NewImageExeInfoEntrySize
);
802 NameStr
= (CHAR16
*)(ImageExeInfoEntry
+ 1);
804 CopyMem ((UINT8
*) NameStr
, Name
, NameStringLen
);
806 ZeroMem ((UINT8
*) NameStr
, sizeof (CHAR16
));
810 (UINT8
*) NameStr
+ NameStringLen
,
814 if (Signature
!= NULL
) {
816 (UINT8
*) NameStr
+ NameStringLen
+ DevicePathSize
,
822 // Update/replace the image execution table.
824 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
827 // Free Old table data!
829 if (ImageExeInfoTable
!= NULL
) {
830 FreePool (ImageExeInfoTable
);
835 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
837 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
838 @param[in] CertSize Size of X.509 Certificate.
839 @param[in] SignatureList Pointer to the Signature List in forbidden database.
840 @param[in] SignatureListSize Size of Signature List.
841 @param[out] RevocationTime Return the time that the certificate was revoked.
843 @return TRUE The certificate hash is found in the forbidden database.
844 @return FALSE The certificate hash is not found in the forbidden database.
848 IsCertHashFoundInDatabase (
849 IN UINT8
*Certificate
,
851 IN EFI_SIGNATURE_LIST
*SignatureList
,
852 IN UINTN SignatureListSize
,
853 OUT EFI_TIME
*RevocationTime
858 EFI_SIGNATURE_LIST
*DbxList
;
860 EFI_SIGNATURE_DATA
*CertHash
;
865 UINT8 CertDigest
[MAX_DIGEST_SIZE
];
867 UINTN SiglistHeaderSize
;
872 DbxList
= SignatureList
;
873 DbxSize
= SignatureListSize
;
875 HashAlg
= HASHALG_MAX
;
877 if ((RevocationTime
== NULL
) || (DbxList
== NULL
)) {
882 // Retrieve the TBSCertificate from the X.509 Certificate.
884 if (!X509GetTBSCert (Certificate
, CertSize
, &TBSCert
, &TBSCertSize
)) {
888 while ((DbxSize
> 0) && (SignatureListSize
>= DbxList
->SignatureListSize
)) {
890 // Determine Hash Algorithm of Certificate in the forbidden database.
892 if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha256Guid
)) {
893 HashAlg
= HASHALG_SHA256
;
894 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha384Guid
)) {
895 HashAlg
= HASHALG_SHA384
;
896 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha512Guid
)) {
897 HashAlg
= HASHALG_SHA512
;
899 DbxSize
-= DbxList
->SignatureListSize
;
900 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
905 // Calculate the hash value of current TBSCertificate for comparision.
907 if (mHash
[HashAlg
].GetContextSize
== NULL
) {
910 ZeroMem (CertDigest
, MAX_DIGEST_SIZE
);
911 HashCtx
= AllocatePool (mHash
[HashAlg
].GetContextSize ());
912 if (HashCtx
== NULL
) {
915 Status
= mHash
[HashAlg
].HashInit (HashCtx
);
919 Status
= mHash
[HashAlg
].HashUpdate (HashCtx
, TBSCert
, TBSCertSize
);
923 Status
= mHash
[HashAlg
].HashFinal (HashCtx
, CertDigest
);
928 SiglistHeaderSize
= sizeof (EFI_SIGNATURE_LIST
) + DbxList
->SignatureHeaderSize
;
929 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) DbxList
+ SiglistHeaderSize
);
930 CertHashCount
= (DbxList
->SignatureListSize
- SiglistHeaderSize
) / DbxList
->SignatureSize
;
931 for (Index
= 0; Index
< CertHashCount
; Index
++) {
933 // Iterate each Signature Data Node within this CertList for verify.
935 DbxCertHash
= CertHash
->SignatureData
;
936 if (CompareMem (DbxCertHash
, CertDigest
, mHash
[HashAlg
].DigestLength
) == 0) {
938 // Hash of Certificate is found in forbidden database.
943 // Return the revocation time.
945 CopyMem (RevocationTime
, (EFI_TIME
*)(DbxCertHash
+ mHash
[HashAlg
].DigestLength
), sizeof (EFI_TIME
));
948 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertHash
+ DbxList
->SignatureSize
);
951 DbxSize
-= DbxList
->SignatureListSize
;
952 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
956 if (HashCtx
!= NULL
) {
964 Check whether signature is in specified database.
966 @param[in] VariableName Name of database variable that is searched in.
967 @param[in] Signature Pointer to signature that is searched for.
968 @param[in] CertType Pointer to hash algrithom.
969 @param[in] SignatureSize Size of Signature.
971 @return TRUE Found the signature in the variable database.
972 @return FALSE Not found the signature in the variable database.
976 IsSignatureFoundInDatabase (
977 IN CHAR16
*VariableName
,
979 IN EFI_GUID
*CertType
,
980 IN UINTN SignatureSize
984 EFI_SIGNATURE_LIST
*CertList
;
985 EFI_SIGNATURE_DATA
*Cert
;
993 // Read signature database variable.
998 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
999 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1003 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1008 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
1009 if (EFI_ERROR (Status
)) {
1013 // Enumerate all signature data in SigDB to check if executable's signature exists.
1015 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1016 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1017 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1018 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1019 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
1020 for (Index
= 0; Index
< CertCount
; Index
++) {
1021 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
1023 // Find the signature in database.
1026 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1030 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1038 DataSize
-= CertList
->SignatureListSize
;
1039 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1051 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1053 @param SigningTime A pointer to the signing time.
1054 @param RevocationTime A pointer to the revocation time.
1056 @retval TRUE The SigningTime is not later than the RevocationTime.
1057 @retval FALSE The SigningTime is later than the RevocationTime.
1061 IsValidSignatureByTimestamp (
1062 IN EFI_TIME
*SigningTime
,
1063 IN EFI_TIME
*RevocationTime
1066 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1067 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1068 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1069 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1070 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1071 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1072 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1073 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1074 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1075 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1078 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1082 Check if the given time value is zero.
1084 @param[in] Time Pointer of a time value.
1086 @retval TRUE The Time is Zero.
1087 @retval FALSE The Time is not Zero.
1095 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1096 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1104 Check whether the timestamp signature is valid and the signing time is also earlier than
1105 the revocation time.
1107 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1108 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1109 @param[in] RevocationTime The time that the certificate was revoked.
1111 @retval TRUE Timestamp signature is valid and signing time is no later than the
1113 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1118 PassTimestampCheck (
1120 IN UINTN AuthDataSize
,
1121 IN EFI_TIME
*RevocationTime
1125 BOOLEAN VerifyStatus
;
1126 EFI_SIGNATURE_LIST
*CertList
;
1127 EFI_SIGNATURE_DATA
*Cert
;
1134 EFI_TIME SigningTime
;
1137 // Variable Initialization
1139 VerifyStatus
= FALSE
;
1147 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1149 if (IsTimeZero (RevocationTime
)) {
1154 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1155 // Using the dbt to get the trusted TSA certificates.
1158 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1159 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1162 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1163 if (DbtData
== NULL
) {
1166 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1167 if (EFI_ERROR (Status
)) {
1171 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1172 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1173 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1174 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1175 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1176 for (Index
= 0; Index
< CertCount
; Index
++) {
1178 // Iterate each Signature Data Node within this CertList for verify.
1180 RootCert
= Cert
->SignatureData
;
1181 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1183 // Get the signing time if the timestamp signature is valid.
1185 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1187 // The signer signature is valid only when the signing time is earlier than revocation time.
1189 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1190 VerifyStatus
= TRUE
;
1194 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1197 DbtDataSize
-= CertList
->SignatureListSize
;
1198 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1202 if (DbtData
!= NULL
) {
1206 return VerifyStatus
;
1210 Check whether the image signature is forbidden by the forbidden database (dbx).
1211 The image is forbidden to load if any certificates for signing are revoked before signing time.
1213 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1214 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1216 @retval TRUE Image is forbidden by dbx.
1217 @retval FALSE Image is not forbidden by dbx.
1223 IN UINTN AuthDataSize
1227 BOOLEAN IsForbidden
;
1230 EFI_SIGNATURE_LIST
*CertList
;
1232 EFI_SIGNATURE_DATA
*CertData
;
1240 UINTN TrustedCertLength
;
1245 EFI_TIME RevocationTime
;
1247 // Variable Initialization
1249 IsForbidden
= FALSE
;
1259 TrustedCertLength
= 0;
1262 // The image will not be forbidden if dbx can't be got.
1265 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1266 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1269 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1274 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1275 if (EFI_ERROR (Status
)) {
1280 // Verify image signature with RAW X509 certificates in DBX database.
1281 // If passed, the image will be forbidden.
1283 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1284 CertListSize
= DataSize
;
1285 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1286 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1287 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1288 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1290 for (Index
= 0; Index
< CertCount
; Index
++) {
1292 // Iterate each Signature Data Node within this CertList for verify.
1294 RootCert
= CertData
->SignatureData
;
1295 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1298 // Call AuthenticodeVerify library to Verify Authenticode struct.
1300 IsForbidden
= AuthenticodeVerify (
1309 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1310 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1314 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1318 CertListSize
-= CertList
->SignatureListSize
;
1319 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1323 // Check X.509 Certificate Hash & Possible Timestamp.
1327 // Retrieve the certificate stack from AuthData
1328 // The output CertStack format will be:
1329 // UINT8 CertNumber;
1330 // UINT32 Cert1Length;
1332 // UINT32 Cert2Length;
1335 // UINT32 CertnLength;
1338 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1339 if ((BufferLength
== 0) || (CertBuffer
== NULL
)) {
1345 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1347 CertNumber
= (UINT8
) (*CertBuffer
);
1348 CertPtr
= CertBuffer
+ 1;
1349 for (Index
= 0; Index
< CertNumber
; Index
++) {
1350 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1351 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1353 // Advance CertPtr to the next cert in image signer's cert list
1355 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1357 if (IsCertHashFoundInDatabase (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
)) {
1359 // Check the timestamp signature and signing time to determine if the image can be trusted.
1362 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1363 IsForbidden
= FALSE
;
1365 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1369 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1380 Pkcs7FreeSigners (CertBuffer
);
1381 Pkcs7FreeSigners (TrustedCert
);
1388 Check whether the image signature can be verified by the trusted certificates in DB database.
1390 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1391 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1393 @retval TRUE Image passed verification using certificate in db.
1394 @retval FALSE Image didn't pass verification using certificate in db.
1400 IN UINTN AuthDataSize
1404 BOOLEAN VerifyStatus
;
1405 EFI_SIGNATURE_LIST
*CertList
;
1406 EFI_SIGNATURE_DATA
*CertData
;
1415 EFI_TIME RevocationTime
;
1423 VerifyStatus
= FALSE
;
1426 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1427 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1428 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1430 return VerifyStatus
;
1433 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1434 if (EFI_ERROR (Status
)) {
1439 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1441 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1442 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1443 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1444 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1445 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1447 for (Index
= 0; Index
< CertCount
; Index
++) {
1449 // Iterate each Signature Data Node within this CertList for verify.
1451 RootCert
= CertData
->SignatureData
;
1452 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1455 // Call AuthenticodeVerify library to Verify Authenticode struct.
1457 VerifyStatus
= AuthenticodeVerify (
1467 // Here We still need to check if this RootCert's Hash is revoked
1469 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1470 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1473 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1474 if (DbxData
== NULL
) {
1478 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1479 if (EFI_ERROR (Status
)) {
1483 if (IsCertHashFoundInDatabase (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
)) {
1485 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1487 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1488 if (!VerifyStatus
) {
1489 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1496 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1500 DataSize
-= CertList
->SignatureListSize
;
1501 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1508 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1514 if (DbxData
!= NULL
) {
1518 return VerifyStatus
;
1522 Provide verification service for signed images, which include both signature validation
1523 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1524 MSFT Authenticode type signatures are supported.
1526 In this implementation, only verify external executables when in USER MODE.
1527 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1529 The image verification policy is:
1530 If the image is signed,
1531 At least one valid signature or at least one hash value of the image must match a record
1532 in the security database "db", and no valid signature nor any hash value of the image may
1533 be reflected in the security database "dbx".
1534 Otherwise, the image is not signed,
1535 The SHA256 hash value of the image must match a record in the security database "db", and
1536 not be reflected in the security data base "dbx".
1538 Caution: This function may receive untrusted input.
1539 PE/COFF image is external input, so this function will validate its data structure
1540 within this image buffer before use.
1542 @param[in] AuthenticationStatus
1543 This is the authentication status returned from the security
1544 measurement services for the input file.
1545 @param[in] File This is a pointer to the device path of the file that is
1546 being dispatched. This will optionally be used for logging.
1547 @param[in] FileBuffer File buffer matches the input file device path.
1548 @param[in] FileSize Size of File buffer matches the input file device path.
1549 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1551 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1552 FileBuffer did authenticate, and the platform policy dictates
1553 that the DXE Foundation may use the file.
1554 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1555 and non-NULL FileBuffer did authenticate, and the platform
1556 policy dictates that the DXE Foundation may execute the image in
1558 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1559 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1560 the platform policy dictates that File should be placed
1561 in the untrusted state. The image has been added to the file
1563 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1564 authenticate, and the platform policy dictates that the DXE
1565 Foundation many not use File.
1570 DxeImageVerificationHandler (
1571 IN UINT32 AuthenticationStatus
,
1572 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1573 IN VOID
*FileBuffer
,
1575 IN BOOLEAN BootPolicy
1580 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1581 EFI_STATUS VerifyStatus
;
1582 EFI_SIGNATURE_LIST
*SignatureList
;
1583 UINTN SignatureListSize
;
1584 EFI_SIGNATURE_DATA
*Signature
;
1585 EFI_IMAGE_EXECUTION_ACTION Action
;
1586 WIN_CERTIFICATE
*WinCertificate
;
1589 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1590 UINT32 NumberOfRvaAndSizes
;
1591 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1592 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1595 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1599 SignatureList
= NULL
;
1600 SignatureListSize
= 0;
1601 WinCertificate
= NULL
;
1603 PkcsCertData
= NULL
;
1604 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1605 Status
= EFI_ACCESS_DENIED
;
1606 VerifyStatus
= EFI_ACCESS_DENIED
;
1610 // Check the image type and get policy setting.
1612 switch (GetImageType (File
)) {
1615 Policy
= ALWAYS_EXECUTE
;
1618 case IMAGE_FROM_OPTION_ROM
:
1619 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1622 case IMAGE_FROM_REMOVABLE_MEDIA
:
1623 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1626 case IMAGE_FROM_FIXED_MEDIA
:
1627 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1631 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1635 // If policy is always/never execute, return directly.
1637 if (Policy
== ALWAYS_EXECUTE
) {
1639 } else if (Policy
== NEVER_EXECUTE
) {
1640 return EFI_ACCESS_DENIED
;
1644 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1645 // violates the UEFI spec and has been removed.
1647 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1648 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1652 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1654 // Skip verification if SecureBoot variable doesn't exist.
1656 if (SecureBoot
== NULL
) {
1661 // Skip verification if SecureBoot is disabled but not AuditMode
1663 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1664 FreePool (SecureBoot
);
1667 FreePool (SecureBoot
);
1670 // Read the Dos header.
1672 if (FileBuffer
== NULL
) {
1673 return EFI_INVALID_PARAMETER
;
1676 mImageBase
= (UINT8
*) FileBuffer
;
1677 mImageSize
= FileSize
;
1679 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1680 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1681 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1684 // Get information about the image being loaded
1686 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
1687 if (EFI_ERROR (Status
)) {
1689 // The information can't be got from the invalid PeImage
1691 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1695 Status
= EFI_ACCESS_DENIED
;
1697 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1698 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1700 // DOS image header is present,
1701 // so read the PE header after the DOS image header.
1703 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1705 mPeCoffHeaderOffset
= 0;
1708 // Check PE/COFF image.
1710 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1711 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1713 // It is not a valid Pe/Coff file.
1715 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1719 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1721 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1722 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1723 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1724 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1726 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1729 // Get the magic value from the PE/COFF Optional Header
1731 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
1734 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1738 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1739 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1740 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1744 // Use PE32+ offset.
1746 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1747 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1748 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1753 // Start Image Validation.
1755 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
1757 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1758 // and not be reflected in the security data base "dbx".
1760 if (!HashPeImage (HASHALG_SHA256
)) {
1761 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr
));
1765 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1767 // Image Hash is in forbidden database (DBX).
1769 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr
));
1773 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1775 // Image Hash is in allowed database (DB).
1781 // Image Hash is not found in both forbidden and allowed database.
1783 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr
));
1788 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1789 // "Attribute Certificate Table".
1790 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1792 for (OffSet
= SecDataDir
->VirtualAddress
;
1793 OffSet
< (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
);
1794 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
1795 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
1796 if ((SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) <= sizeof (WIN_CERTIFICATE
) ||
1797 (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) < WinCertificate
->dwLength
) {
1802 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1804 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1806 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1807 // Authenticode specification.
1809 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
1810 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
1813 AuthData
= PkcsCertData
->CertData
;
1814 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
1815 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
1817 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1819 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
1820 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
1823 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
1826 AuthData
= WinCertUefiGuid
->CertData
;
1827 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
1829 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
1835 Status
= HashPeImageByType (AuthData
, AuthDataSize
);
1836 if (EFI_ERROR (Status
)) {
1841 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1843 if (IsForbiddenByDbx (AuthData
, AuthDataSize
)) {
1844 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
1845 VerifyStatus
= EFI_ACCESS_DENIED
;
1850 // Check the digital signature against the valid certificate in allowed database (db).
1852 if (EFI_ERROR (VerifyStatus
)) {
1853 if (IsAllowedByDb (AuthData
, AuthDataSize
)) {
1854 VerifyStatus
= EFI_SUCCESS
;
1859 // Check the image's hash value.
1861 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1862 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
1863 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr
));
1864 VerifyStatus
= EFI_ACCESS_DENIED
;
1866 } else if (EFI_ERROR (VerifyStatus
)) {
1867 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1868 VerifyStatus
= EFI_SUCCESS
;
1870 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is not allowed by DB and %s hash of image is not found in DB/DBX.\n", mHashTypeStr
));
1875 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
1877 // The Size in Certificate Table or the attribute certicate table is corrupted.
1879 VerifyStatus
= EFI_ACCESS_DENIED
;
1882 if (!EFI_ERROR (VerifyStatus
)) {
1885 Status
= EFI_ACCESS_DENIED
;
1886 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
1888 // Get image hash value as executable's signature.
1890 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1891 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1892 if (SignatureList
== NULL
) {
1893 Status
= EFI_OUT_OF_RESOURCES
;
1896 SignatureList
->SignatureHeaderSize
= 0;
1897 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
1898 SignatureList
->SignatureSize
= (UINT32
) (sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
);
1899 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
1900 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
1901 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
1906 if (Status
!= EFI_SUCCESS
) {
1908 // Policy decides to defer or reject the image; add its information in image executable information table.
1910 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1911 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
1912 if (NameStr
!= NULL
) {
1913 DEBUG((EFI_D_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
1916 Status
= EFI_SECURITY_VIOLATION
;
1919 if (SignatureList
!= NULL
) {
1920 FreePool (SignatureList
);
1927 On Ready To Boot Services Event notification handler.
1929 Add the image execution information table if it is not in system configuration table.
1931 @param[in] Event Event whose notification function is being invoked
1932 @param[in] Context Pointer to the notification function's context
1942 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
1943 UINTN ImageExeInfoTableSize
;
1945 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
1946 if (ImageExeInfoTable
!= NULL
) {
1950 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
1951 ImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
);
1952 if (ImageExeInfoTable
== NULL
) {
1956 ImageExeInfoTable
->NumberOfImages
= 0;
1957 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) ImageExeInfoTable
);
1962 Register security measurement handler.
1964 @param ImageHandle ImageHandle of the loaded driver.
1965 @param SystemTable Pointer to the EFI System Table.
1967 @retval EFI_SUCCESS The handlers were registered successfully.
1971 DxeImageVerificationLibConstructor (
1972 IN EFI_HANDLE ImageHandle
,
1973 IN EFI_SYSTEM_TABLE
*SystemTable
1979 // Register the event to publish the image execution table.
1981 EfiCreateEventReadyToBootEx (
1988 return RegisterSecurity2Handler (
1989 DxeImageVerificationHandler
,
1990 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED