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 - 2017, 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 Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
284 its caller function DxeImageVerificationHandler().
286 @param[in] HashAlg Hash algorithm type.
288 @retval TRUE Successfully hash image.
289 @retval FALSE Fail in hash image.
299 EFI_IMAGE_SECTION_HEADER
*Section
;
304 UINTN SumOfBytesHashed
;
305 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
309 UINT32 NumberOfRvaAndSizes
;
312 SectionHeader
= NULL
;
315 if ((HashAlg
>= HASHALG_MAX
)) {
320 // Initialize context of hash.
322 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
326 mImageDigestSize
= SHA1_DIGEST_SIZE
;
327 mCertType
= gEfiCertSha1Guid
;
331 mImageDigestSize
= SHA256_DIGEST_SIZE
;
332 mCertType
= gEfiCertSha256Guid
;
336 mImageDigestSize
= SHA384_DIGEST_SIZE
;
337 mCertType
= gEfiCertSha384Guid
;
341 mImageDigestSize
= SHA512_DIGEST_SIZE
;
342 mCertType
= gEfiCertSha512Guid
;
349 mHashTypeStr
= mHash
[HashAlg
].Name
;
350 CtxSize
= mHash
[HashAlg
].GetContextSize();
352 HashCtx
= AllocatePool (CtxSize
);
353 if (HashCtx
== NULL
) {
357 // 1. Load the image header into memory.
359 // 2. Initialize a SHA hash context.
360 Status
= mHash
[HashAlg
].HashInit(HashCtx
);
367 // Measuring PE/COFF Image Header;
368 // But CheckSum field and SECURITY data directory (certificate) are excluded
370 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
372 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
373 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
374 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
375 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
377 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
380 // Get the magic value from the PE/COFF Optional Header
382 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
386 // 3. Calculate the distance from the base of the image header to the image checksum address.
387 // 4. Hash the image header from its base to beginning of the image checksum.
389 HashBase
= mImageBase
;
390 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
394 HashSize
= (UINTN
) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - (UINTN
) HashBase
;
395 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
396 } else if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
400 HashSize
= (UINTN
) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - (UINTN
) HashBase
;
401 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
404 // Invalid header magic number.
410 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
416 // 5. Skip over the image checksum (it occupies a single ULONG).
418 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
420 // 6. Since there is no Cert Directory in optional header, hash everything
421 // from the end of the checksum to the end of image header.
423 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
427 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
428 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
433 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
434 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
438 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
445 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
447 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
451 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
452 HashSize
= (UINTN
) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - (UINTN
) HashBase
;
457 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
458 HashSize
= (UINTN
) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - (UINTN
) HashBase
;
462 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
469 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
470 // 9. Hash everything from the end of the Cert Directory to the end of image header.
472 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
476 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
477 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
482 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
483 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
487 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
495 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
497 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
501 SumOfBytesHashed
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
;
506 SumOfBytesHashed
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
510 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
512 mPeCoffHeaderOffset
+
514 sizeof (EFI_IMAGE_FILE_HEADER
) +
515 mNtHeader
.Pe32
->FileHeader
.SizeOfOptionalHeader
519 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
520 // structures in the image. The 'NumberOfSections' field of the image
521 // header indicates how big the table should be. Do not include any
522 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
524 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * mNtHeader
.Pe32
->FileHeader
.NumberOfSections
);
525 if (SectionHeader
== NULL
) {
530 // 12. Using the 'PointerToRawData' in the referenced section headers as
531 // a key, arrange the elements in the table in ascending order. In other
532 // words, sort the section headers according to the disk-file offset of
535 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
537 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
538 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
541 CopyMem (&SectionHeader
[Pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
546 // 13. Walk through the sorted table, bring the corresponding section
547 // into memory, and hash the entire section (using the 'SizeOfRawData'
548 // field in the section header to determine the amount of data to hash).
549 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
550 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
552 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
553 Section
= &SectionHeader
[Index
];
554 if (Section
->SizeOfRawData
== 0) {
557 HashBase
= mImageBase
+ Section
->PointerToRawData
;
558 HashSize
= (UINTN
) Section
->SizeOfRawData
;
560 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
565 SumOfBytesHashed
+= HashSize
;
569 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
570 // data in the file that needs to be added to the hash. This data begins
571 // at file offset SUM_OF_BYTES_HASHED and its length is:
572 // FileSize - (CertDirectory->Size)
574 if (mImageSize
> SumOfBytesHashed
) {
575 HashBase
= mImageBase
+ SumOfBytesHashed
;
577 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
580 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
584 CertSize
= mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
589 CertSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
593 if (mImageSize
> CertSize
+ SumOfBytesHashed
) {
594 HashSize
= (UINTN
) (mImageSize
- CertSize
- SumOfBytesHashed
);
596 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
600 } else if (mImageSize
< CertSize
+ SumOfBytesHashed
) {
606 Status
= mHash
[HashAlg
].HashFinal(HashCtx
, mImageDigest
);
609 if (HashCtx
!= NULL
) {
612 if (SectionHeader
!= NULL
) {
613 FreePool (SectionHeader
);
619 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
620 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
623 Caution: This function may receive untrusted input.
624 PE/COFF image is external input, so this function will validate its data structure
625 within this image buffer before use.
627 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
628 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
630 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
631 @retval EFI_SUCCESS Hash successfully.
637 IN UINTN AuthDataSize
642 for (Index
= 0; Index
< HASHALG_MAX
; Index
++) {
644 // Check the Hash algorithm in PE/COFF Authenticode.
645 // According to PKCS#7 Definition:
646 // SignedData ::= SEQUENCE {
648 // digestAlgorithms DigestAlgorithmIdentifiers,
649 // contentInfo ContentInfo,
651 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
652 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
653 // Fixed offset (+32) is calculated based on two bytes of length encoding.
655 if ((*(AuthData
+ 1) & TWO_BYTE_ENCODE
) != TWO_BYTE_ENCODE
) {
657 // Only support two bytes of Long Form of Length Encoding.
662 if (AuthDataSize
< 32 + mHash
[Index
].OidLength
) {
663 return EFI_UNSUPPORTED
;
666 if (CompareMem (AuthData
+ 32, mHash
[Index
].OidValue
, mHash
[Index
].OidLength
) == 0) {
671 if (Index
== HASHALG_MAX
) {
672 return EFI_UNSUPPORTED
;
676 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
678 if (!HashPeImage(Index
)) {
679 return EFI_UNSUPPORTED
;
687 Returns the size of a given image execution info table in bytes.
689 This function returns the size, in bytes, of the image execution info table specified by
690 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
692 @param ImageExeInfoTable A pointer to a image execution info table structure.
694 @retval 0 If ImageExeInfoTable is NULL.
695 @retval Others The size of a image execution info table in bytes.
699 GetImageExeInfoTableSize (
700 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
704 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoItem
;
707 if (ImageExeInfoTable
== NULL
) {
711 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoTable
+ sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
));
712 TotalSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
713 for (Index
= 0; Index
< ImageExeInfoTable
->NumberOfImages
; Index
++) {
714 TotalSize
+= ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
);
715 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoItem
+ ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
));
722 Create an Image Execution Information Table entry and add it to system configuration table.
724 @param[in] Action Describes the action taken by the firmware regarding this image.
725 @param[in] Name Input a null-terminated, user-friendly name.
726 @param[in] DevicePath Input device path pointer.
727 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
728 @param[in] SignatureSize Size of signature.
733 IN EFI_IMAGE_EXECUTION_ACTION Action
,
734 IN CHAR16
*Name OPTIONAL
,
735 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
,
736 IN EFI_SIGNATURE_LIST
*Signature OPTIONAL
,
737 IN UINTN SignatureSize
740 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
741 EFI_IMAGE_EXECUTION_INFO_TABLE
*NewImageExeInfoTable
;
742 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoEntry
;
743 UINTN ImageExeInfoTableSize
;
744 UINTN NewImageExeInfoEntrySize
;
746 UINTN DevicePathSize
;
749 ImageExeInfoTable
= NULL
;
750 NewImageExeInfoTable
= NULL
;
751 ImageExeInfoEntry
= NULL
;
755 if (DevicePath
== NULL
) {
760 NameStringLen
= StrSize (Name
);
762 NameStringLen
= sizeof (CHAR16
);
765 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
766 if (ImageExeInfoTable
!= NULL
) {
768 // The table has been found!
769 // We must enlarge the table to accomodate the new exe info entry.
771 ImageExeInfoTableSize
= GetImageExeInfoTableSize (ImageExeInfoTable
);
775 // We should create a new table to append to the configuration table.
777 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
780 DevicePathSize
= GetDevicePathSize (DevicePath
);
783 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
785 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
787 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
788 if (NewImageExeInfoTable
== NULL
) {
792 if (ImageExeInfoTable
!= NULL
) {
793 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
795 NewImageExeInfoTable
->NumberOfImages
= 0;
797 NewImageExeInfoTable
->NumberOfImages
++;
798 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
800 // Update new item's information.
802 WriteUnaligned32 ((UINT32
*) ImageExeInfoEntry
, Action
);
803 WriteUnaligned32 ((UINT32
*) ((UINT8
*) ImageExeInfoEntry
+ sizeof (EFI_IMAGE_EXECUTION_ACTION
)), (UINT32
) NewImageExeInfoEntrySize
);
805 NameStr
= (CHAR16
*)(ImageExeInfoEntry
+ 1);
807 CopyMem ((UINT8
*) NameStr
, Name
, NameStringLen
);
809 ZeroMem ((UINT8
*) NameStr
, sizeof (CHAR16
));
813 (UINT8
*) NameStr
+ NameStringLen
,
817 if (Signature
!= NULL
) {
819 (UINT8
*) NameStr
+ NameStringLen
+ DevicePathSize
,
825 // Update/replace the image execution table.
827 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
830 // Free Old table data!
832 if (ImageExeInfoTable
!= NULL
) {
833 FreePool (ImageExeInfoTable
);
838 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
840 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
841 @param[in] CertSize Size of X.509 Certificate.
842 @param[in] SignatureList Pointer to the Signature List in forbidden database.
843 @param[in] SignatureListSize Size of Signature List.
844 @param[out] RevocationTime Return the time that the certificate was revoked.
846 @return TRUE The certificate hash is found in the forbidden database.
847 @return FALSE The certificate hash is not found in the forbidden database.
851 IsCertHashFoundInDatabase (
852 IN UINT8
*Certificate
,
854 IN EFI_SIGNATURE_LIST
*SignatureList
,
855 IN UINTN SignatureListSize
,
856 OUT EFI_TIME
*RevocationTime
861 EFI_SIGNATURE_LIST
*DbxList
;
863 EFI_SIGNATURE_DATA
*CertHash
;
868 UINT8 CertDigest
[MAX_DIGEST_SIZE
];
870 UINTN SiglistHeaderSize
;
875 DbxList
= SignatureList
;
876 DbxSize
= SignatureListSize
;
878 HashAlg
= HASHALG_MAX
;
880 if ((RevocationTime
== NULL
) || (DbxList
== NULL
)) {
885 // Retrieve the TBSCertificate from the X.509 Certificate.
887 if (!X509GetTBSCert (Certificate
, CertSize
, &TBSCert
, &TBSCertSize
)) {
891 while ((DbxSize
> 0) && (SignatureListSize
>= DbxList
->SignatureListSize
)) {
893 // Determine Hash Algorithm of Certificate in the forbidden database.
895 if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha256Guid
)) {
896 HashAlg
= HASHALG_SHA256
;
897 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha384Guid
)) {
898 HashAlg
= HASHALG_SHA384
;
899 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha512Guid
)) {
900 HashAlg
= HASHALG_SHA512
;
902 DbxSize
-= DbxList
->SignatureListSize
;
903 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
908 // Calculate the hash value of current TBSCertificate for comparision.
910 if (mHash
[HashAlg
].GetContextSize
== NULL
) {
913 ZeroMem (CertDigest
, MAX_DIGEST_SIZE
);
914 HashCtx
= AllocatePool (mHash
[HashAlg
].GetContextSize ());
915 if (HashCtx
== NULL
) {
918 Status
= mHash
[HashAlg
].HashInit (HashCtx
);
922 Status
= mHash
[HashAlg
].HashUpdate (HashCtx
, TBSCert
, TBSCertSize
);
926 Status
= mHash
[HashAlg
].HashFinal (HashCtx
, CertDigest
);
931 SiglistHeaderSize
= sizeof (EFI_SIGNATURE_LIST
) + DbxList
->SignatureHeaderSize
;
932 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) DbxList
+ SiglistHeaderSize
);
933 CertHashCount
= (DbxList
->SignatureListSize
- SiglistHeaderSize
) / DbxList
->SignatureSize
;
934 for (Index
= 0; Index
< CertHashCount
; Index
++) {
936 // Iterate each Signature Data Node within this CertList for verify.
938 DbxCertHash
= CertHash
->SignatureData
;
939 if (CompareMem (DbxCertHash
, CertDigest
, mHash
[HashAlg
].DigestLength
) == 0) {
941 // Hash of Certificate is found in forbidden database.
946 // Return the revocation time.
948 CopyMem (RevocationTime
, (EFI_TIME
*)(DbxCertHash
+ mHash
[HashAlg
].DigestLength
), sizeof (EFI_TIME
));
951 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertHash
+ DbxList
->SignatureSize
);
954 DbxSize
-= DbxList
->SignatureListSize
;
955 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
959 if (HashCtx
!= NULL
) {
967 Check whether signature is in specified database.
969 @param[in] VariableName Name of database variable that is searched in.
970 @param[in] Signature Pointer to signature that is searched for.
971 @param[in] CertType Pointer to hash algrithom.
972 @param[in] SignatureSize Size of Signature.
974 @return TRUE Found the signature in the variable database.
975 @return FALSE Not found the signature in the variable database.
979 IsSignatureFoundInDatabase (
980 IN CHAR16
*VariableName
,
982 IN EFI_GUID
*CertType
,
983 IN UINTN SignatureSize
987 EFI_SIGNATURE_LIST
*CertList
;
988 EFI_SIGNATURE_DATA
*Cert
;
996 // Read signature database variable.
1001 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1002 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1006 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1011 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
1012 if (EFI_ERROR (Status
)) {
1016 // Enumerate all signature data in SigDB to check if executable's signature exists.
1018 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1019 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1020 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1021 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1022 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
1023 for (Index
= 0; Index
< CertCount
; Index
++) {
1024 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
1026 // Find the signature in database.
1030 // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured
1032 if (StrCmp(VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) {
1033 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1038 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1046 DataSize
-= CertList
->SignatureListSize
;
1047 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1059 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1061 @param SigningTime A pointer to the signing time.
1062 @param RevocationTime A pointer to the revocation time.
1064 @retval TRUE The SigningTime is not later than the RevocationTime.
1065 @retval FALSE The SigningTime is later than the RevocationTime.
1069 IsValidSignatureByTimestamp (
1070 IN EFI_TIME
*SigningTime
,
1071 IN EFI_TIME
*RevocationTime
1074 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1075 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1076 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1077 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1078 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1079 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1080 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1081 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1082 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1083 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1086 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1090 Check if the given time value is zero.
1092 @param[in] Time Pointer of a time value.
1094 @retval TRUE The Time is Zero.
1095 @retval FALSE The Time is not Zero.
1103 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1104 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1112 Check whether the timestamp signature is valid and the signing time is also earlier than
1113 the revocation time.
1115 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1116 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1117 @param[in] RevocationTime The time that the certificate was revoked.
1119 @retval TRUE Timestamp signature is valid and signing time is no later than the
1121 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1126 PassTimestampCheck (
1128 IN UINTN AuthDataSize
,
1129 IN EFI_TIME
*RevocationTime
1133 BOOLEAN VerifyStatus
;
1134 EFI_SIGNATURE_LIST
*CertList
;
1135 EFI_SIGNATURE_DATA
*Cert
;
1142 EFI_TIME SigningTime
;
1145 // Variable Initialization
1147 VerifyStatus
= FALSE
;
1155 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1157 if (IsTimeZero (RevocationTime
)) {
1162 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1163 // Using the dbt to get the trusted TSA certificates.
1166 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1167 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1170 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1171 if (DbtData
== NULL
) {
1174 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1175 if (EFI_ERROR (Status
)) {
1179 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1180 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1181 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1182 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1183 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1184 for (Index
= 0; Index
< CertCount
; Index
++) {
1186 // Iterate each Signature Data Node within this CertList for verify.
1188 RootCert
= Cert
->SignatureData
;
1189 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1191 // Get the signing time if the timestamp signature is valid.
1193 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1195 // The signer signature is valid only when the signing time is earlier than revocation time.
1197 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1198 VerifyStatus
= TRUE
;
1202 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1205 DbtDataSize
-= CertList
->SignatureListSize
;
1206 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1210 if (DbtData
!= NULL
) {
1214 return VerifyStatus
;
1218 Check whether the image signature is forbidden by the forbidden database (dbx).
1219 The image is forbidden to load if any certificates for signing are revoked before signing time.
1221 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1222 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1224 @retval TRUE Image is forbidden by dbx.
1225 @retval FALSE Image is not forbidden by dbx.
1231 IN UINTN AuthDataSize
1235 BOOLEAN IsForbidden
;
1238 EFI_SIGNATURE_LIST
*CertList
;
1240 EFI_SIGNATURE_DATA
*CertData
;
1248 UINTN TrustedCertLength
;
1253 EFI_TIME RevocationTime
;
1255 // Variable Initialization
1257 IsForbidden
= FALSE
;
1267 TrustedCertLength
= 0;
1270 // The image will not be forbidden if dbx can't be got.
1273 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1274 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1277 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1282 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1283 if (EFI_ERROR (Status
)) {
1288 // Verify image signature with RAW X509 certificates in DBX database.
1289 // If passed, the image will be forbidden.
1291 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1292 CertListSize
= DataSize
;
1293 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1294 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1295 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1296 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1298 for (Index
= 0; Index
< CertCount
; Index
++) {
1300 // Iterate each Signature Data Node within this CertList for verify.
1302 RootCert
= CertData
->SignatureData
;
1303 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1306 // Call AuthenticodeVerify library to Verify Authenticode struct.
1308 IsForbidden
= AuthenticodeVerify (
1317 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1321 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1325 CertListSize
-= CertList
->SignatureListSize
;
1326 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1330 // Check X.509 Certificate Hash & Possible Timestamp.
1334 // Retrieve the certificate stack from AuthData
1335 // The output CertStack format will be:
1336 // UINT8 CertNumber;
1337 // UINT32 Cert1Length;
1339 // UINT32 Cert2Length;
1342 // UINT32 CertnLength;
1345 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1346 if ((BufferLength
== 0) || (CertBuffer
== NULL
)) {
1352 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1354 CertNumber
= (UINT8
) (*CertBuffer
);
1355 CertPtr
= CertBuffer
+ 1;
1356 for (Index
= 0; Index
< CertNumber
; Index
++) {
1357 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1358 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1360 // Advance CertPtr to the next cert in image signer's cert list
1362 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1364 if (IsCertHashFoundInDatabase (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
)) {
1366 // Check the timestamp signature and signing time to determine if the image can be trusted.
1369 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1370 IsForbidden
= FALSE
;
1372 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1376 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1387 Pkcs7FreeSigners (CertBuffer
);
1388 Pkcs7FreeSigners (TrustedCert
);
1395 Check whether the image signature can be verified by the trusted certificates in DB database.
1397 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1398 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1400 @retval TRUE Image passed verification using certificate in db.
1401 @retval FALSE Image didn't pass verification using certificate in db.
1407 IN UINTN AuthDataSize
1411 BOOLEAN VerifyStatus
;
1412 EFI_SIGNATURE_LIST
*CertList
;
1413 EFI_SIGNATURE_DATA
*CertData
;
1422 EFI_TIME RevocationTime
;
1430 VerifyStatus
= FALSE
;
1433 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1434 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1435 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1437 return VerifyStatus
;
1440 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1441 if (EFI_ERROR (Status
)) {
1446 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1448 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1449 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1450 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1451 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1452 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1454 for (Index
= 0; Index
< CertCount
; Index
++) {
1456 // Iterate each Signature Data Node within this CertList for verify.
1458 RootCert
= CertData
->SignatureData
;
1459 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1462 // Call AuthenticodeVerify library to Verify Authenticode struct.
1464 VerifyStatus
= AuthenticodeVerify (
1474 // Here We still need to check if this RootCert's Hash is revoked
1476 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1477 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1480 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1481 if (DbxData
== NULL
) {
1485 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1486 if (EFI_ERROR (Status
)) {
1490 if (IsCertHashFoundInDatabase (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
)) {
1492 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1494 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1495 if (!VerifyStatus
) {
1496 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1503 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1507 DataSize
-= CertList
->SignatureListSize
;
1508 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1515 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1521 if (DbxData
!= NULL
) {
1525 return VerifyStatus
;
1529 Provide verification service for signed images, which include both signature validation
1530 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1531 MSFT Authenticode type signatures are supported.
1533 In this implementation, only verify external executables when in USER MODE.
1534 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1536 The image verification policy is:
1537 If the image is signed,
1538 At least one valid signature or at least one hash value of the image must match a record
1539 in the security database "db", and no valid signature nor any hash value of the image may
1540 be reflected in the security database "dbx".
1541 Otherwise, the image is not signed,
1542 The SHA256 hash value of the image must match a record in the security database "db", and
1543 not be reflected in the security data base "dbx".
1545 Caution: This function may receive untrusted input.
1546 PE/COFF image is external input, so this function will validate its data structure
1547 within this image buffer before use.
1549 @param[in] AuthenticationStatus
1550 This is the authentication status returned from the security
1551 measurement services for the input file.
1552 @param[in] File This is a pointer to the device path of the file that is
1553 being dispatched. This will optionally be used for logging.
1554 @param[in] FileBuffer File buffer matches the input file device path.
1555 @param[in] FileSize Size of File buffer matches the input file device path.
1556 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1558 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1559 FileBuffer did authenticate, and the platform policy dictates
1560 that the DXE Foundation may use the file.
1561 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1562 and non-NULL FileBuffer did authenticate, and the platform
1563 policy dictates that the DXE Foundation may execute the image in
1565 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1566 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1567 the platform policy dictates that File should be placed
1568 in the untrusted state. The image has been added to the file
1570 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1571 authenticate, and the platform policy dictates that the DXE
1572 Foundation many not use File.
1577 DxeImageVerificationHandler (
1578 IN UINT32 AuthenticationStatus
,
1579 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1580 IN VOID
*FileBuffer
,
1582 IN BOOLEAN BootPolicy
1587 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1588 EFI_STATUS VerifyStatus
;
1589 EFI_SIGNATURE_LIST
*SignatureList
;
1590 UINTN SignatureListSize
;
1591 EFI_SIGNATURE_DATA
*Signature
;
1592 EFI_IMAGE_EXECUTION_ACTION Action
;
1593 WIN_CERTIFICATE
*WinCertificate
;
1596 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1597 UINT32 NumberOfRvaAndSizes
;
1598 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1599 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1602 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1606 SignatureList
= NULL
;
1607 SignatureListSize
= 0;
1608 WinCertificate
= NULL
;
1610 PkcsCertData
= NULL
;
1611 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1612 Status
= EFI_ACCESS_DENIED
;
1613 VerifyStatus
= EFI_ACCESS_DENIED
;
1617 // Check the image type and get policy setting.
1619 switch (GetImageType (File
)) {
1622 Policy
= ALWAYS_EXECUTE
;
1625 case IMAGE_FROM_OPTION_ROM
:
1626 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1629 case IMAGE_FROM_REMOVABLE_MEDIA
:
1630 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1633 case IMAGE_FROM_FIXED_MEDIA
:
1634 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1638 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1642 // If policy is always/never execute, return directly.
1644 if (Policy
== ALWAYS_EXECUTE
) {
1646 } else if (Policy
== NEVER_EXECUTE
) {
1647 return EFI_ACCESS_DENIED
;
1651 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1652 // violates the UEFI spec and has been removed.
1654 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1655 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1659 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1661 // Skip verification if SecureBoot variable doesn't exist.
1663 if (SecureBoot
== NULL
) {
1668 // Skip verification if SecureBoot is disabled but not AuditMode
1670 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1671 FreePool (SecureBoot
);
1674 FreePool (SecureBoot
);
1677 // Read the Dos header.
1679 if (FileBuffer
== NULL
) {
1680 return EFI_INVALID_PARAMETER
;
1683 mImageBase
= (UINT8
*) FileBuffer
;
1684 mImageSize
= FileSize
;
1686 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1687 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1688 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1691 // Get information about the image being loaded
1693 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
1694 if (EFI_ERROR (Status
)) {
1696 // The information can't be got from the invalid PeImage
1698 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1702 Status
= EFI_ACCESS_DENIED
;
1704 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1705 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1707 // DOS image header is present,
1708 // so read the PE header after the DOS image header.
1710 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1712 mPeCoffHeaderOffset
= 0;
1715 // Check PE/COFF image.
1717 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1718 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1720 // It is not a valid Pe/Coff file.
1722 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1726 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1728 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1729 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1730 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1731 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1733 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1736 // Get the magic value from the PE/COFF Optional Header
1738 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
1741 if (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 Status
= HashPeImageByType (AuthData
, AuthDataSize
);
1843 if (EFI_ERROR (Status
)) {
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
;
1852 VerifyStatus
= EFI_ACCESS_DENIED
;
1857 // Check the digital signature against the valid certificate in allowed database (db).
1859 if (EFI_ERROR (VerifyStatus
)) {
1860 if (IsAllowedByDb (AuthData
, AuthDataSize
)) {
1861 VerifyStatus
= EFI_SUCCESS
;
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
));
1871 VerifyStatus
= EFI_ACCESS_DENIED
;
1873 } else if (EFI_ERROR (VerifyStatus
)) {
1874 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1875 VerifyStatus
= EFI_SUCCESS
;
1877 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
));
1882 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
1884 // The Size in Certificate Table or the attribute certicate table is corrupted.
1886 VerifyStatus
= EFI_ACCESS_DENIED
;
1889 if (!EFI_ERROR (VerifyStatus
)) {
1892 Status
= EFI_ACCESS_DENIED
;
1893 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
1895 // Get image hash value as executable's signature.
1897 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1898 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1899 if (SignatureList
== NULL
) {
1900 Status
= EFI_OUT_OF_RESOURCES
;
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 if (Status
!= EFI_SUCCESS
) {
1915 // Policy decides to defer or reject the image; add its information in image executable information table.
1917 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1918 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
1919 if (NameStr
!= NULL
) {
1920 DEBUG((EFI_D_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
1923 Status
= EFI_SECURITY_VIOLATION
;
1926 if (SignatureList
!= NULL
) {
1927 FreePool (SignatureList
);
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