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 - 2018, Intel Corporation. All rights reserved.<BR>
16 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
17 SPDX-License-Identifier: BSD-2-Clause-Patent
21 #include "DxeImageVerificationLib.h"
24 // Caution: This is used by a function which may receive untrusted input.
25 // These global variables hold PE/COFF image data, and they should be validated before use.
27 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
28 UINT32 mPeCoffHeaderOffset
;
32 // Information on current PE/COFF image
35 UINT8
*mImageBase
= NULL
;
36 UINT8 mImageDigest
[MAX_DIGEST_SIZE
];
37 UINTN mImageDigestSize
;
40 // Notify string for authorization UI.
42 CHAR16 mNotifyString1
[MAX_NOTIFY_STRING_LEN
] = L
"Image verification pass but not found in authorized database!";
43 CHAR16 mNotifyString2
[MAX_NOTIFY_STRING_LEN
] = L
"Launch this image anyway? (Yes/Defer/No)";
45 // Public Exponent of RSA Key.
47 CONST UINT8 mRsaE
[] = { 0x01, 0x00, 0x01 };
51 // OID ASN.1 Value for Hash Algorithms
53 UINT8 mHashOidValue
[] = {
54 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
55 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
56 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
57 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
58 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
61 HASH_TABLE mHash
[] = {
62 { L
"SHA1", 20, &mHashOidValue
[0], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
63 { L
"SHA224", 28, &mHashOidValue
[5], 9, NULL
, NULL
, NULL
, NULL
},
64 { L
"SHA256", 32, &mHashOidValue
[14], 9, Sha256GetContextSize
, Sha256Init
, Sha256Update
, Sha256Final
},
65 { L
"SHA384", 48, &mHashOidValue
[23], 9, Sha384GetContextSize
, Sha384Init
, Sha384Update
, Sha384Final
},
66 { L
"SHA512", 64, &mHashOidValue
[32], 9, Sha512GetContextSize
, Sha512Init
, Sha512Update
, Sha512Final
}
69 EFI_STRING mHashTypeStr
;
72 SecureBoot Hook for processing image verification.
74 @param[in] VariableName Name of Variable to be found.
75 @param[in] VendorGuid Variable vendor GUID.
76 @param[in] DataSize Size of Data found. If size is less than the
77 data, this value contains the required size.
78 @param[in] Data Data pointer.
84 IN CHAR16
*VariableName
,
85 IN EFI_GUID
*VendorGuid
,
91 Reads contents of a PE/COFF image in memory buffer.
93 Caution: This function may receive untrusted input.
94 PE/COFF image is external input, so this function will make sure the PE/COFF image content
95 read is within the image buffer.
97 @param FileHandle Pointer to the file handle to read the PE/COFF image.
98 @param FileOffset Offset into the PE/COFF image to begin the read operation.
99 @param ReadSize On input, the size in bytes of the requested read operation.
100 On output, the number of bytes actually read.
101 @param Buffer Output buffer that contains the data read from the PE/COFF image.
103 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
107 DxeImageVerificationLibImageRead (
110 IN OUT UINTN
*ReadSize
,
116 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
117 return EFI_INVALID_PARAMETER
;
120 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
121 return EFI_INVALID_PARAMETER
;
124 EndPosition
= FileOffset
+ *ReadSize
;
125 if (EndPosition
> mImageSize
) {
126 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
129 if (FileOffset
>= mImageSize
) {
133 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
142 @param[in] File This is a pointer to the device path of the file that is
145 @return UINT32 Image Type
150 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
154 EFI_HANDLE DeviceHandle
;
155 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
156 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
159 return IMAGE_UNKNOWN
;
163 // First check to see if File is from a Firmware Volume
166 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
167 Status
= gBS
->LocateDevicePath (
168 &gEfiFirmwareVolume2ProtocolGuid
,
172 if (!EFI_ERROR (Status
)) {
173 Status
= gBS
->OpenProtocol (
175 &gEfiFirmwareVolume2ProtocolGuid
,
179 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
181 if (!EFI_ERROR (Status
)) {
182 return IMAGE_FROM_FV
;
187 // Next check to see if File is from a Block I/O device
190 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
191 Status
= gBS
->LocateDevicePath (
192 &gEfiBlockIoProtocolGuid
,
196 if (!EFI_ERROR (Status
)) {
198 Status
= gBS
->OpenProtocol (
200 &gEfiBlockIoProtocolGuid
,
204 EFI_OPEN_PROTOCOL_GET_PROTOCOL
206 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
207 if (BlockIo
->Media
!= NULL
) {
208 if (BlockIo
->Media
->RemovableMedia
) {
210 // Block I/O is present and specifies the media is removable
212 return IMAGE_FROM_REMOVABLE_MEDIA
;
215 // Block I/O is present and specifies the media is not removable
217 return IMAGE_FROM_FIXED_MEDIA
;
224 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
225 // the device path supports the Simple File System Protocol.
228 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
229 Status
= gBS
->LocateDevicePath (
230 &gEfiSimpleFileSystemProtocolGuid
,
234 if (!EFI_ERROR (Status
)) {
236 // Simple File System is present without Block I/O, so assume media is fixed.
238 return IMAGE_FROM_FIXED_MEDIA
;
242 // File is not from an FV, Block I/O or Simple File System, so the only options
243 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
245 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
246 while (!IsDevicePathEndType (TempDevicePath
)) {
247 switch (DevicePathType (TempDevicePath
)) {
249 case MEDIA_DEVICE_PATH
:
250 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
251 return IMAGE_FROM_OPTION_ROM
;
255 case MESSAGING_DEVICE_PATH
:
256 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
257 return IMAGE_FROM_REMOVABLE_MEDIA
;
264 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
266 return IMAGE_UNKNOWN
;
270 Calculate hash of Pe/Coff image based on the authenticode image hashing in
271 PE/COFF Specification 8.0 Appendix A
273 Caution: This function may receive untrusted input.
274 PE/COFF image is external input, so this function will validate its data structure
275 within this image buffer before use.
277 Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
278 its caller function DxeImageVerificationHandler().
280 @param[in] HashAlg Hash algorithm type.
282 @retval TRUE Successfully hash image.
283 @retval FALSE Fail in hash image.
292 EFI_IMAGE_SECTION_HEADER
*Section
;
297 UINTN SumOfBytesHashed
;
298 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
302 UINT32 NumberOfRvaAndSizes
;
305 SectionHeader
= NULL
;
308 if ((HashAlg
>= HASHALG_MAX
)) {
313 // Initialize context of hash.
315 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
319 mImageDigestSize
= SHA1_DIGEST_SIZE
;
320 mCertType
= gEfiCertSha1Guid
;
324 mImageDigestSize
= SHA256_DIGEST_SIZE
;
325 mCertType
= gEfiCertSha256Guid
;
329 mImageDigestSize
= SHA384_DIGEST_SIZE
;
330 mCertType
= gEfiCertSha384Guid
;
334 mImageDigestSize
= SHA512_DIGEST_SIZE
;
335 mCertType
= gEfiCertSha512Guid
;
342 mHashTypeStr
= mHash
[HashAlg
].Name
;
343 CtxSize
= mHash
[HashAlg
].GetContextSize();
345 HashCtx
= AllocatePool (CtxSize
);
346 if (HashCtx
== NULL
) {
350 // 1. Load the image header into memory.
352 // 2. Initialize a SHA hash context.
353 Status
= mHash
[HashAlg
].HashInit(HashCtx
);
360 // Measuring PE/COFF Image Header;
361 // But CheckSum field and SECURITY data directory (certificate) are excluded
365 // 3. Calculate the distance from the base of the image header to the image checksum address.
366 // 4. Hash the image header from its base to beginning of the image checksum.
368 HashBase
= mImageBase
;
369 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
373 HashSize
= (UINTN
) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - (UINTN
) HashBase
;
374 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
375 } else if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
379 HashSize
= (UINTN
) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - (UINTN
) HashBase
;
380 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
383 // Invalid header magic number.
389 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
395 // 5. Skip over the image checksum (it occupies a single ULONG).
397 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
399 // 6. Since there is no Cert Directory in optional header, hash everything
400 // from the end of the checksum to the end of image header.
402 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
406 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
407 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
412 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
413 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
417 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
424 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
426 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
430 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
431 HashSize
= (UINTN
) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - (UINTN
) HashBase
;
436 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
437 HashSize
= (UINTN
) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - (UINTN
) HashBase
;
441 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
448 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
449 // 9. Hash everything from the end of the Cert Directory to the end of image header.
451 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
455 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
456 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
461 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
462 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
466 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
474 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
476 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
480 SumOfBytesHashed
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
;
485 SumOfBytesHashed
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
489 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
491 mPeCoffHeaderOffset
+
493 sizeof (EFI_IMAGE_FILE_HEADER
) +
494 mNtHeader
.Pe32
->FileHeader
.SizeOfOptionalHeader
498 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
499 // structures in the image. The 'NumberOfSections' field of the image
500 // header indicates how big the table should be. Do not include any
501 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
503 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * mNtHeader
.Pe32
->FileHeader
.NumberOfSections
);
504 if (SectionHeader
== NULL
) {
509 // 12. Using the 'PointerToRawData' in the referenced section headers as
510 // a key, arrange the elements in the table in ascending order. In other
511 // words, sort the section headers according to the disk-file offset of
514 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
516 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
517 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
520 CopyMem (&SectionHeader
[Pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
525 // 13. Walk through the sorted table, bring the corresponding section
526 // into memory, and hash the entire section (using the 'SizeOfRawData'
527 // field in the section header to determine the amount of data to hash).
528 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
529 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
531 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
532 Section
= &SectionHeader
[Index
];
533 if (Section
->SizeOfRawData
== 0) {
536 HashBase
= mImageBase
+ Section
->PointerToRawData
;
537 HashSize
= (UINTN
) Section
->SizeOfRawData
;
539 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
544 SumOfBytesHashed
+= HashSize
;
548 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
549 // data in the file that needs to be added to the hash. This data begins
550 // at file offset SUM_OF_BYTES_HASHED and its length is:
551 // FileSize - (CertDirectory->Size)
553 if (mImageSize
> SumOfBytesHashed
) {
554 HashBase
= mImageBase
+ SumOfBytesHashed
;
556 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
559 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
563 CertSize
= mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
568 CertSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
572 if (mImageSize
> CertSize
+ SumOfBytesHashed
) {
573 HashSize
= (UINTN
) (mImageSize
- CertSize
- SumOfBytesHashed
);
575 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
579 } else if (mImageSize
< CertSize
+ SumOfBytesHashed
) {
585 Status
= mHash
[HashAlg
].HashFinal(HashCtx
, mImageDigest
);
588 if (HashCtx
!= NULL
) {
591 if (SectionHeader
!= NULL
) {
592 FreePool (SectionHeader
);
598 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
599 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
602 Caution: This function may receive untrusted input.
603 PE/COFF image is external input, so this function will validate its data structure
604 within this image buffer before use.
606 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
607 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
609 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
610 @retval EFI_SUCCESS Hash successfully.
616 IN UINTN AuthDataSize
621 for (Index
= 0; Index
< HASHALG_MAX
; Index
++) {
623 // Check the Hash algorithm in PE/COFF Authenticode.
624 // According to PKCS#7 Definition:
625 // SignedData ::= SEQUENCE {
627 // digestAlgorithms DigestAlgorithmIdentifiers,
628 // contentInfo ContentInfo,
630 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
631 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
632 // Fixed offset (+32) is calculated based on two bytes of length encoding.
634 if ((*(AuthData
+ 1) & TWO_BYTE_ENCODE
) != TWO_BYTE_ENCODE
) {
636 // Only support two bytes of Long Form of Length Encoding.
641 if (AuthDataSize
< 32 + mHash
[Index
].OidLength
) {
642 return EFI_UNSUPPORTED
;
645 if (CompareMem (AuthData
+ 32, mHash
[Index
].OidValue
, mHash
[Index
].OidLength
) == 0) {
650 if (Index
== HASHALG_MAX
) {
651 return EFI_UNSUPPORTED
;
655 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
657 if (!HashPeImage(Index
)) {
658 return EFI_UNSUPPORTED
;
666 Returns the size of a given image execution info table in bytes.
668 This function returns the size, in bytes, of the image execution info table specified by
669 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
671 @param ImageExeInfoTable A pointer to a image execution info table structure.
673 @retval 0 If ImageExeInfoTable is NULL.
674 @retval Others The size of a image execution info table in bytes.
678 GetImageExeInfoTableSize (
679 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
683 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoItem
;
686 if (ImageExeInfoTable
== NULL
) {
690 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoTable
+ sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
));
691 TotalSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
692 for (Index
= 0; Index
< ImageExeInfoTable
->NumberOfImages
; Index
++) {
693 TotalSize
+= ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
);
694 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoItem
+ ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
));
701 Create an Image Execution Information Table entry and add it to system configuration table.
703 @param[in] Action Describes the action taken by the firmware regarding this image.
704 @param[in] Name Input a null-terminated, user-friendly name.
705 @param[in] DevicePath Input device path pointer.
706 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
707 @param[in] SignatureSize Size of signature. Must be zero if Signature is NULL.
712 IN EFI_IMAGE_EXECUTION_ACTION Action
,
713 IN CHAR16
*Name OPTIONAL
,
714 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
,
715 IN EFI_SIGNATURE_LIST
*Signature OPTIONAL
,
716 IN UINTN SignatureSize
719 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
720 EFI_IMAGE_EXECUTION_INFO_TABLE
*NewImageExeInfoTable
;
721 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoEntry
;
722 UINTN ImageExeInfoTableSize
;
723 UINTN NewImageExeInfoEntrySize
;
725 UINTN DevicePathSize
;
728 ImageExeInfoTable
= NULL
;
729 NewImageExeInfoTable
= NULL
;
730 ImageExeInfoEntry
= NULL
;
734 if (DevicePath
== NULL
) {
739 NameStringLen
= StrSize (Name
);
741 NameStringLen
= sizeof (CHAR16
);
744 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
745 if (ImageExeInfoTable
!= NULL
) {
747 // The table has been found!
748 // We must enlarge the table to accommodate the new exe info entry.
750 ImageExeInfoTableSize
= GetImageExeInfoTableSize (ImageExeInfoTable
);
754 // We should create a new table to append to the configuration table.
756 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
759 DevicePathSize
= GetDevicePathSize (DevicePath
);
762 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
764 ASSERT (Signature
!= NULL
|| SignatureSize
== 0);
765 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
767 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
768 if (NewImageExeInfoTable
== NULL
) {
772 if (ImageExeInfoTable
!= NULL
) {
773 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
775 NewImageExeInfoTable
->NumberOfImages
= 0;
777 NewImageExeInfoTable
->NumberOfImages
++;
778 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
780 // Update new item's information.
782 WriteUnaligned32 ((UINT32
*) ImageExeInfoEntry
, Action
);
783 WriteUnaligned32 ((UINT32
*) ((UINT8
*) ImageExeInfoEntry
+ sizeof (EFI_IMAGE_EXECUTION_ACTION
)), (UINT32
) NewImageExeInfoEntrySize
);
785 NameStr
= (CHAR16
*)(ImageExeInfoEntry
+ 1);
787 CopyMem ((UINT8
*) NameStr
, Name
, NameStringLen
);
789 ZeroMem ((UINT8
*) NameStr
, sizeof (CHAR16
));
793 (UINT8
*) NameStr
+ NameStringLen
,
797 if (Signature
!= NULL
) {
799 (UINT8
*) NameStr
+ NameStringLen
+ DevicePathSize
,
805 // Update/replace the image execution table.
807 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
810 // Free Old table data!
812 if (ImageExeInfoTable
!= NULL
) {
813 FreePool (ImageExeInfoTable
);
818 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
820 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
821 @param[in] CertSize Size of X.509 Certificate.
822 @param[in] SignatureList Pointer to the Signature List in forbidden database.
823 @param[in] SignatureListSize Size of Signature List.
824 @param[out] RevocationTime Return the time that the certificate was revoked.
826 @return TRUE The certificate hash is found in the forbidden database.
827 @return FALSE The certificate hash is not found in the forbidden database.
831 IsCertHashFoundInDatabase (
832 IN UINT8
*Certificate
,
834 IN EFI_SIGNATURE_LIST
*SignatureList
,
835 IN UINTN SignatureListSize
,
836 OUT EFI_TIME
*RevocationTime
841 EFI_SIGNATURE_LIST
*DbxList
;
843 EFI_SIGNATURE_DATA
*CertHash
;
848 UINT8 CertDigest
[MAX_DIGEST_SIZE
];
850 UINTN SiglistHeaderSize
;
855 DbxList
= SignatureList
;
856 DbxSize
= SignatureListSize
;
858 HashAlg
= HASHALG_MAX
;
860 if ((RevocationTime
== NULL
) || (DbxList
== NULL
)) {
865 // Retrieve the TBSCertificate from the X.509 Certificate.
867 if (!X509GetTBSCert (Certificate
, CertSize
, &TBSCert
, &TBSCertSize
)) {
871 while ((DbxSize
> 0) && (SignatureListSize
>= DbxList
->SignatureListSize
)) {
873 // Determine Hash Algorithm of Certificate in the forbidden database.
875 if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha256Guid
)) {
876 HashAlg
= HASHALG_SHA256
;
877 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha384Guid
)) {
878 HashAlg
= HASHALG_SHA384
;
879 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha512Guid
)) {
880 HashAlg
= HASHALG_SHA512
;
882 DbxSize
-= DbxList
->SignatureListSize
;
883 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
888 // Calculate the hash value of current TBSCertificate for comparision.
890 if (mHash
[HashAlg
].GetContextSize
== NULL
) {
893 ZeroMem (CertDigest
, MAX_DIGEST_SIZE
);
894 HashCtx
= AllocatePool (mHash
[HashAlg
].GetContextSize ());
895 if (HashCtx
== NULL
) {
898 Status
= mHash
[HashAlg
].HashInit (HashCtx
);
902 Status
= mHash
[HashAlg
].HashUpdate (HashCtx
, TBSCert
, TBSCertSize
);
906 Status
= mHash
[HashAlg
].HashFinal (HashCtx
, CertDigest
);
914 SiglistHeaderSize
= sizeof (EFI_SIGNATURE_LIST
) + DbxList
->SignatureHeaderSize
;
915 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) DbxList
+ SiglistHeaderSize
);
916 CertHashCount
= (DbxList
->SignatureListSize
- SiglistHeaderSize
) / DbxList
->SignatureSize
;
917 for (Index
= 0; Index
< CertHashCount
; Index
++) {
919 // Iterate each Signature Data Node within this CertList for verify.
921 DbxCertHash
= CertHash
->SignatureData
;
922 if (CompareMem (DbxCertHash
, CertDigest
, mHash
[HashAlg
].DigestLength
) == 0) {
924 // Hash of Certificate is found in forbidden database.
929 // Return the revocation time.
931 CopyMem (RevocationTime
, (EFI_TIME
*)(DbxCertHash
+ mHash
[HashAlg
].DigestLength
), sizeof (EFI_TIME
));
934 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertHash
+ DbxList
->SignatureSize
);
937 DbxSize
-= DbxList
->SignatureListSize
;
938 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
942 if (HashCtx
!= NULL
) {
950 Check whether signature is in specified database.
952 @param[in] VariableName Name of database variable that is searched in.
953 @param[in] Signature Pointer to signature that is searched for.
954 @param[in] CertType Pointer to hash algorithm.
955 @param[in] SignatureSize Size of Signature.
957 @return TRUE Found the signature in the variable database.
958 @return FALSE Not found the signature in the variable database.
962 IsSignatureFoundInDatabase (
963 IN CHAR16
*VariableName
,
965 IN EFI_GUID
*CertType
,
966 IN UINTN SignatureSize
970 EFI_SIGNATURE_LIST
*CertList
;
971 EFI_SIGNATURE_DATA
*Cert
;
979 // Read signature database variable.
984 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
985 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
989 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
994 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
995 if (EFI_ERROR (Status
)) {
999 // Enumerate all signature data in SigDB to check if signature exists for executable.
1001 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1002 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1003 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1004 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1005 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
1006 for (Index
= 0; Index
< CertCount
; Index
++) {
1007 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
1009 // Find the signature in database.
1013 // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured
1015 if (StrCmp(VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) {
1016 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1021 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1029 DataSize
-= CertList
->SignatureListSize
;
1030 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1042 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1044 @param SigningTime A pointer to the signing time.
1045 @param RevocationTime A pointer to the revocation time.
1047 @retval TRUE The SigningTime is not later than the RevocationTime.
1048 @retval FALSE The SigningTime is later than the RevocationTime.
1052 IsValidSignatureByTimestamp (
1053 IN EFI_TIME
*SigningTime
,
1054 IN EFI_TIME
*RevocationTime
1057 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1058 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1059 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1060 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1061 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1062 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1063 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1064 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1065 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1066 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1069 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1073 Check if the given time value is zero.
1075 @param[in] Time Pointer of a time value.
1077 @retval TRUE The Time is Zero.
1078 @retval FALSE The Time is not Zero.
1086 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1087 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1095 Check whether the timestamp signature is valid and the signing time is also earlier than
1096 the revocation time.
1098 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1099 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1100 @param[in] RevocationTime The time that the certificate was revoked.
1102 @retval TRUE Timestamp signature is valid and signing time is no later than the
1104 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1109 PassTimestampCheck (
1111 IN UINTN AuthDataSize
,
1112 IN EFI_TIME
*RevocationTime
1116 BOOLEAN VerifyStatus
;
1117 EFI_SIGNATURE_LIST
*CertList
;
1118 EFI_SIGNATURE_DATA
*Cert
;
1125 EFI_TIME SigningTime
;
1128 // Variable Initialization
1130 VerifyStatus
= FALSE
;
1138 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1140 if (IsTimeZero (RevocationTime
)) {
1145 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1146 // Using the dbt to get the trusted TSA certificates.
1149 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1150 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1153 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1154 if (DbtData
== NULL
) {
1157 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1158 if (EFI_ERROR (Status
)) {
1162 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1163 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1164 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1165 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1166 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1167 for (Index
= 0; Index
< CertCount
; Index
++) {
1169 // Iterate each Signature Data Node within this CertList for verify.
1171 RootCert
= Cert
->SignatureData
;
1172 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1174 // Get the signing time if the timestamp signature is valid.
1176 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1178 // The signer signature is valid only when the signing time is earlier than revocation time.
1180 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1181 VerifyStatus
= TRUE
;
1185 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1188 DbtDataSize
-= CertList
->SignatureListSize
;
1189 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1193 if (DbtData
!= NULL
) {
1197 return VerifyStatus
;
1201 Check whether the image signature is forbidden by the forbidden database (dbx).
1202 The image is forbidden to load if any certificates for signing are revoked before signing time.
1204 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1205 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1207 @retval TRUE Image is forbidden by dbx.
1208 @retval FALSE Image is not forbidden by dbx.
1214 IN UINTN AuthDataSize
1218 BOOLEAN IsForbidden
;
1221 EFI_SIGNATURE_LIST
*CertList
;
1223 EFI_SIGNATURE_DATA
*CertData
;
1231 UINTN TrustedCertLength
;
1236 EFI_TIME RevocationTime
;
1238 // Variable Initialization
1240 IsForbidden
= FALSE
;
1250 TrustedCertLength
= 0;
1253 // The image will not be forbidden if dbx can't be got.
1256 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1257 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1260 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1265 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1266 if (EFI_ERROR (Status
)) {
1271 // Verify image signature with RAW X509 certificates in DBX database.
1272 // If passed, the image will be forbidden.
1274 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1275 CertListSize
= DataSize
;
1276 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1277 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1278 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1279 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1281 for (Index
= 0; Index
< CertCount
; Index
++) {
1283 // Iterate each Signature Data Node within this CertList for verify.
1285 RootCert
= CertData
->SignatureData
;
1286 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1289 // Call AuthenticodeVerify library to Verify Authenticode struct.
1291 IsForbidden
= AuthenticodeVerify (
1300 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1304 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1308 CertListSize
-= CertList
->SignatureListSize
;
1309 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1313 // Check X.509 Certificate Hash & Possible Timestamp.
1317 // Retrieve the certificate stack from AuthData
1318 // The output CertStack format will be:
1319 // UINT8 CertNumber;
1320 // UINT32 Cert1Length;
1322 // UINT32 Cert2Length;
1325 // UINT32 CertnLength;
1328 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1329 if ((BufferLength
== 0) || (CertBuffer
== NULL
) || (*CertBuffer
) == 0) {
1335 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1337 CertNumber
= (UINT8
) (*CertBuffer
);
1338 CertPtr
= CertBuffer
+ 1;
1339 for (Index
= 0; Index
< CertNumber
; Index
++) {
1340 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1341 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1343 // Advance CertPtr to the next cert in image signer's cert list
1345 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1347 if (IsCertHashFoundInDatabase (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
)) {
1349 // Check the timestamp signature and signing time to determine if the image can be trusted.
1352 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1353 IsForbidden
= FALSE
;
1355 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1359 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1370 Pkcs7FreeSigners (CertBuffer
);
1371 Pkcs7FreeSigners (TrustedCert
);
1378 Check whether the image signature can be verified by the trusted certificates in DB database.
1380 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1381 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1383 @retval TRUE Image passed verification using certificate in db.
1384 @retval FALSE Image didn't pass verification using certificate in db.
1390 IN UINTN AuthDataSize
1394 BOOLEAN VerifyStatus
;
1395 EFI_SIGNATURE_LIST
*CertList
;
1396 EFI_SIGNATURE_DATA
*CertData
;
1405 EFI_TIME RevocationTime
;
1413 VerifyStatus
= FALSE
;
1416 // Fetch 'db' content. If 'db' doesn't exist or encounters problem to get the
1417 // data, return not-allowed-by-db (FALSE).
1420 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1421 ASSERT (EFI_ERROR (Status
));
1422 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1423 return VerifyStatus
;
1426 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1428 return VerifyStatus
;
1431 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1432 if (EFI_ERROR (Status
)) {
1437 // Fetch 'dbx' content. If 'dbx' doesn't exist, continue to check 'db'.
1438 // If any other errors occured, no need to check 'db' but just return
1439 // not-allowed-by-db (FALSE) to avoid bypass.
1442 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1443 ASSERT (EFI_ERROR (Status
));
1444 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1445 if (Status
!= EFI_NOT_FOUND
) {
1449 // 'dbx' does not exist. Continue to check 'db'.
1453 // 'dbx' exists. Get its content.
1455 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1456 if (DbxData
== NULL
) {
1460 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1461 if (EFI_ERROR (Status
)) {
1467 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1469 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1470 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1471 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1472 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1473 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1475 for (Index
= 0; Index
< CertCount
; Index
++) {
1477 // Iterate each Signature Data Node within this CertList for verify.
1479 RootCert
= CertData
->SignatureData
;
1480 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1483 // Call AuthenticodeVerify library to Verify Authenticode struct.
1485 VerifyStatus
= AuthenticodeVerify (
1495 // The image is signed and its signature is found in 'db'.
1497 if (DbxData
!= NULL
) {
1499 // Here We still need to check if this RootCert's Hash is revoked
1501 if (IsCertHashFoundInDatabase (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
)) {
1503 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1505 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1506 if (!VerifyStatus
) {
1507 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1513 // There's no 'dbx' to check revocation time against (must-be pass),
1514 // or, there's revocation time found in 'dbx' and checked againt 'dbt'
1515 // (maybe pass or fail, depending on timestamp compare result). Either
1516 // way the verification job has been completed at this point.
1521 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1525 DataSize
-= CertList
->SignatureListSize
;
1526 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1532 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1538 if (DbxData
!= NULL
) {
1542 return VerifyStatus
;
1546 Provide verification service for signed images, which include both signature validation
1547 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1548 MSFT Authenticode type signatures are supported.
1550 In this implementation, only verify external executables when in USER MODE.
1551 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1553 The image verification policy is:
1554 If the image is signed,
1555 At least one valid signature or at least one hash value of the image must match a record
1556 in the security database "db", and no valid signature nor any hash value of the image may
1557 be reflected in the security database "dbx".
1558 Otherwise, the image is not signed,
1559 The SHA256 hash value of the image must match a record in the security database "db", and
1560 not be reflected in the security data base "dbx".
1562 Caution: This function may receive untrusted input.
1563 PE/COFF image is external input, so this function will validate its data structure
1564 within this image buffer before use.
1566 @param[in] AuthenticationStatus
1567 This is the authentication status returned from the security
1568 measurement services for the input file.
1569 @param[in] File This is a pointer to the device path of the file that is
1570 being dispatched. This will optionally be used for logging.
1571 @param[in] FileBuffer File buffer matches the input file device path.
1572 @param[in] FileSize Size of File buffer matches the input file device path.
1573 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1575 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1576 FileBuffer did authenticate, and the platform policy dictates
1577 that the DXE Foundation may use the file.
1578 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1579 and non-NULL FileBuffer did authenticate, and the platform
1580 policy dictates that the DXE Foundation may execute the image in
1582 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1583 the platform policy dictates that File should be placed
1584 in the untrusted state. The image has been added to the file
1586 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1587 authenticate, and the platform policy dictates that the DXE
1588 Foundation may not use File. The image has
1589 been added to the file execution table.
1594 DxeImageVerificationHandler (
1595 IN UINT32 AuthenticationStatus
,
1596 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1597 IN VOID
*FileBuffer
,
1599 IN BOOLEAN BootPolicy
1602 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1604 EFI_SIGNATURE_LIST
*SignatureList
;
1605 UINTN SignatureListSize
;
1606 EFI_SIGNATURE_DATA
*Signature
;
1607 EFI_IMAGE_EXECUTION_ACTION Action
;
1608 WIN_CERTIFICATE
*WinCertificate
;
1611 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1612 UINT32 NumberOfRvaAndSizes
;
1613 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1614 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1617 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1620 RETURN_STATUS PeCoffStatus
;
1621 EFI_STATUS HashStatus
;
1623 SignatureList
= NULL
;
1624 SignatureListSize
= 0;
1625 WinCertificate
= NULL
;
1627 PkcsCertData
= NULL
;
1628 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1633 // Check the image type and get policy setting.
1635 switch (GetImageType (File
)) {
1638 Policy
= ALWAYS_EXECUTE
;
1641 case IMAGE_FROM_OPTION_ROM
:
1642 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1645 case IMAGE_FROM_REMOVABLE_MEDIA
:
1646 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1649 case IMAGE_FROM_FIXED_MEDIA
:
1650 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1654 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1658 // If policy is always/never execute, return directly.
1660 if (Policy
== ALWAYS_EXECUTE
) {
1663 if (Policy
== NEVER_EXECUTE
) {
1664 return EFI_ACCESS_DENIED
;
1668 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1669 // violates the UEFI spec and has been removed.
1671 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1672 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1676 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1678 // Skip verification if SecureBoot variable doesn't exist.
1680 if (SecureBoot
== NULL
) {
1685 // Skip verification if SecureBoot is disabled but not AuditMode
1687 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1688 FreePool (SecureBoot
);
1691 FreePool (SecureBoot
);
1694 // Read the Dos header.
1696 if (FileBuffer
== NULL
) {
1697 return EFI_ACCESS_DENIED
;
1700 mImageBase
= (UINT8
*) FileBuffer
;
1701 mImageSize
= FileSize
;
1703 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1704 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1705 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1708 // Get information about the image being loaded
1710 PeCoffStatus
= PeCoffLoaderGetImageInfo (&ImageContext
);
1711 if (RETURN_ERROR (PeCoffStatus
)) {
1713 // The information can't be got from the invalid PeImage
1715 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1719 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1720 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1722 // DOS image header is present,
1723 // so read the PE header after the DOS image header.
1725 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1727 mPeCoffHeaderOffset
= 0;
1730 // Check PE/COFF image.
1732 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1733 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1735 // It is not a valid Pe/Coff file.
1737 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1741 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1745 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1746 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1747 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1751 // Use PE32+ offset.
1753 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1754 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1755 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1760 // Start Image Validation.
1762 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
1764 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1765 // and not be reflected in the security data base "dbx".
1767 if (!HashPeImage (HASHALG_SHA256
)) {
1768 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr
));
1772 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1774 // Image Hash is in forbidden database (DBX).
1776 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr
));
1780 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1782 // Image Hash is in allowed database (DB).
1788 // Image Hash is not found in both forbidden and allowed database.
1790 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr
));
1795 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1796 // "Attribute Certificate Table".
1797 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1799 for (OffSet
= SecDataDir
->VirtualAddress
;
1800 OffSet
< (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
);
1801 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
1802 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
1803 if ((SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) <= sizeof (WIN_CERTIFICATE
) ||
1804 (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) < WinCertificate
->dwLength
) {
1809 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1811 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1813 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1814 // Authenticode specification.
1816 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
1817 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
1820 AuthData
= PkcsCertData
->CertData
;
1821 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
1822 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
1824 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1826 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
1827 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
1830 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
1833 AuthData
= WinCertUefiGuid
->CertData
;
1834 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
1836 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
1842 HashStatus
= HashPeImageByType (AuthData
, AuthDataSize
);
1843 if (EFI_ERROR (HashStatus
)) {
1848 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1850 if (IsForbiddenByDbx (AuthData
, AuthDataSize
)) {
1851 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
1857 // Check the digital signature against the valid certificate in allowed database (db).
1860 if (IsAllowedByDb (AuthData
, AuthDataSize
)) {
1866 // Check the image's hash value.
1868 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1869 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
1870 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr
));
1875 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1878 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
));
1883 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
1885 // The Size in Certificate Table or the attribute certificate table is corrupted.
1893 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
1895 // Get image hash value as signature of executable.
1897 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1898 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1899 if (SignatureList
== NULL
) {
1900 SignatureListSize
= 0;
1903 SignatureList
->SignatureHeaderSize
= 0;
1904 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
1905 SignatureList
->SignatureSize
= (UINT32
) (sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
);
1906 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
1907 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
1908 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
1913 // Policy decides to defer or reject the image; add its information in image
1914 // executable information table in either case.
1916 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1917 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
1918 if (NameStr
!= NULL
) {
1919 DEBUG ((DEBUG_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
1923 if (SignatureList
!= NULL
) {
1924 FreePool (SignatureList
);
1927 if (Policy
== DEFER_EXECUTE_ON_SECURITY_VIOLATION
) {
1928 return EFI_SECURITY_VIOLATION
;
1930 return EFI_ACCESS_DENIED
;
1934 On Ready To Boot Services Event notification handler.
1936 Add the image execution information table if it is not in system configuration table.
1938 @param[in] Event Event whose notification function is being invoked
1939 @param[in] Context Pointer to the notification function's context
1949 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
1950 UINTN ImageExeInfoTableSize
;
1952 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
1953 if (ImageExeInfoTable
!= NULL
) {
1957 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
1958 ImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
);
1959 if (ImageExeInfoTable
== NULL
) {
1963 ImageExeInfoTable
->NumberOfImages
= 0;
1964 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) ImageExeInfoTable
);
1969 Register security measurement handler.
1971 @param ImageHandle ImageHandle of the loaded driver.
1972 @param SystemTable Pointer to the EFI System Table.
1974 @retval EFI_SUCCESS The handlers were registered successfully.
1978 DxeImageVerificationLibConstructor (
1979 IN EFI_HANDLE ImageHandle
,
1980 IN EFI_SYSTEM_TABLE
*SystemTable
1986 // Register the event to publish the image execution table.
1988 EfiCreateEventReadyToBootEx (
1995 return RegisterSecurity2Handler (
1996 DxeImageVerificationHandler
,
1997 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED