2 Implement image verification services for secure boot service
4 Caution: This file requires additional review when modified.
5 This library will have external input - PE/COFF image.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
9 DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content
10 read is within the image buffer.
12 DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept
13 untrusted PE/COFF image and validate its data structure within this image buffer before use.
15 Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
16 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
17 This program and the accompanying materials
18 are licensed and made available under the terms and conditions of the BSD License
19 which accompanies this distribution. The full text of the license may be found at
20 http://opensource.org/licenses/bsd-license.php
22 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
23 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
27 #include "DxeImageVerificationLib.h"
30 // Caution: This is used by a function which may receive untrusted input.
31 // These global variables hold PE/COFF image data, and they should be validated before use.
33 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
34 UINT32 mPeCoffHeaderOffset
;
38 // Information on current PE/COFF image
41 UINT8
*mImageBase
= NULL
;
42 UINT8 mImageDigest
[MAX_DIGEST_SIZE
];
43 UINTN mImageDigestSize
;
46 // Notify string for authorization UI.
48 CHAR16 mNotifyString1
[MAX_NOTIFY_STRING_LEN
] = L
"Image verification pass but not found in authorized database!";
49 CHAR16 mNotifyString2
[MAX_NOTIFY_STRING_LEN
] = L
"Launch this image anyway? (Yes/Defer/No)";
51 // Public Exponent of RSA Key.
53 CONST UINT8 mRsaE
[] = { 0x01, 0x00, 0x01 };
57 // OID ASN.1 Value for Hash Algorithms
59 UINT8 mHashOidValue
[] = {
60 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
61 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
64 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
67 HASH_TABLE mHash
[] = {
68 { L
"SHA1", 20, &mHashOidValue
[0], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
69 { L
"SHA224", 28, &mHashOidValue
[5], 9, NULL
, NULL
, NULL
, NULL
},
70 { L
"SHA256", 32, &mHashOidValue
[14], 9, Sha256GetContextSize
, Sha256Init
, Sha256Update
, Sha256Final
},
71 { L
"SHA384", 48, &mHashOidValue
[23], 9, Sha384GetContextSize
, Sha384Init
, Sha384Update
, Sha384Final
},
72 { L
"SHA512", 64, &mHashOidValue
[32], 9, Sha512GetContextSize
, Sha512Init
, Sha512Update
, Sha512Final
}
75 EFI_STRING mHashTypeStr
;
78 SecureBoot Hook for processing image verification.
80 @param[in] VariableName Name of Variable to be found.
81 @param[in] VendorGuid Variable vendor GUID.
82 @param[in] DataSize Size of Data found. If size is less than the
83 data, this value contains the required size.
84 @param[in] Data Data pointer.
90 IN CHAR16
*VariableName
,
91 IN EFI_GUID
*VendorGuid
,
97 Reads contents of a PE/COFF image in memory buffer.
99 Caution: This function may receive untrusted input.
100 PE/COFF image is external input, so this function will make sure the PE/COFF image content
101 read is within the image buffer.
103 @param FileHandle Pointer to the file handle to read the PE/COFF image.
104 @param FileOffset Offset into the PE/COFF image to begin the read operation.
105 @param ReadSize On input, the size in bytes of the requested read operation.
106 On output, the number of bytes actually read.
107 @param Buffer Output buffer that contains the data read from the PE/COFF image.
109 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
113 DxeImageVerificationLibImageRead (
116 IN OUT UINTN
*ReadSize
,
122 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
123 return EFI_INVALID_PARAMETER
;
126 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
127 return EFI_INVALID_PARAMETER
;
130 EndPosition
= FileOffset
+ *ReadSize
;
131 if (EndPosition
> mImageSize
) {
132 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
135 if (FileOffset
>= mImageSize
) {
139 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
148 @param[in] File This is a pointer to the device path of the file that is
151 @return UINT32 Image Type
156 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
160 EFI_HANDLE DeviceHandle
;
161 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
162 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
165 return IMAGE_UNKNOWN
;
169 // First check to see if File is from a Firmware Volume
172 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
173 Status
= gBS
->LocateDevicePath (
174 &gEfiFirmwareVolume2ProtocolGuid
,
178 if (!EFI_ERROR (Status
)) {
179 Status
= gBS
->OpenProtocol (
181 &gEfiFirmwareVolume2ProtocolGuid
,
185 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
187 if (!EFI_ERROR (Status
)) {
188 return IMAGE_FROM_FV
;
193 // Next check to see if File is from a Block I/O device
196 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
197 Status
= gBS
->LocateDevicePath (
198 &gEfiBlockIoProtocolGuid
,
202 if (!EFI_ERROR (Status
)) {
204 Status
= gBS
->OpenProtocol (
206 &gEfiBlockIoProtocolGuid
,
210 EFI_OPEN_PROTOCOL_GET_PROTOCOL
212 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
213 if (BlockIo
->Media
!= NULL
) {
214 if (BlockIo
->Media
->RemovableMedia
) {
216 // Block I/O is present and specifies the media is removable
218 return IMAGE_FROM_REMOVABLE_MEDIA
;
221 // Block I/O is present and specifies the media is not removable
223 return IMAGE_FROM_FIXED_MEDIA
;
230 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
231 // the device path supports the Simple File System Protocol.
234 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
235 Status
= gBS
->LocateDevicePath (
236 &gEfiSimpleFileSystemProtocolGuid
,
240 if (!EFI_ERROR (Status
)) {
242 // Simple File System is present without Block I/O, so assume media is fixed.
244 return IMAGE_FROM_FIXED_MEDIA
;
248 // File is not from an FV, Block I/O or Simple File System, so the only options
249 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
251 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
252 while (!IsDevicePathEndType (TempDevicePath
)) {
253 switch (DevicePathType (TempDevicePath
)) {
255 case MEDIA_DEVICE_PATH
:
256 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
257 return IMAGE_FROM_OPTION_ROM
;
261 case MESSAGING_DEVICE_PATH
:
262 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
263 return IMAGE_FROM_REMOVABLE_MEDIA
;
270 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
272 return IMAGE_UNKNOWN
;
276 Calculate hash of Pe/Coff image based on the authenticode image hashing in
277 PE/COFF Specification 8.0 Appendix A
279 Caution: This function may receive untrusted input.
280 PE/COFF image is external input, so this function will validate its data structure
281 within this image buffer before use.
283 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
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - HashBase
);
395 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
396 } else if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
400 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - 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
- mImageBase
);
433 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
434 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- 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
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
457 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
458 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - 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
- mImageBase
);
482 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
483 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- 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.
1029 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1033 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1041 DataSize
-= CertList
->SignatureListSize
;
1042 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1054 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1056 @param SigningTime A pointer to the signing time.
1057 @param RevocationTime A pointer to the revocation time.
1059 @retval TRUE The SigningTime is not later than the RevocationTime.
1060 @retval FALSE The SigningTime is later than the RevocationTime.
1064 IsValidSignatureByTimestamp (
1065 IN EFI_TIME
*SigningTime
,
1066 IN EFI_TIME
*RevocationTime
1069 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1070 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1071 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1072 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1073 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1074 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1075 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1076 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1077 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1078 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1081 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1085 Check if the given time value is zero.
1087 @param[in] Time Pointer of a time value.
1089 @retval TRUE The Time is Zero.
1090 @retval FALSE The Time is not Zero.
1098 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1099 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1107 Check whether the timestamp signature is valid and the signing time is also earlier than
1108 the revocation time.
1110 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1111 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1112 @param[in] RevocationTime The time that the certificate was revoked.
1114 @retval TRUE Timestamp signature is valid and signing time is no later than the
1116 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1121 PassTimestampCheck (
1123 IN UINTN AuthDataSize
,
1124 IN EFI_TIME
*RevocationTime
1128 BOOLEAN VerifyStatus
;
1129 EFI_SIGNATURE_LIST
*CertList
;
1130 EFI_SIGNATURE_DATA
*Cert
;
1137 EFI_TIME SigningTime
;
1140 // Variable Initialization
1142 VerifyStatus
= FALSE
;
1150 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1152 if (IsTimeZero (RevocationTime
)) {
1157 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1158 // Using the dbt to get the trusted TSA certificates.
1161 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1162 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1165 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1166 if (DbtData
== NULL
) {
1169 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1170 if (EFI_ERROR (Status
)) {
1174 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1175 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1176 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1177 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1178 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1179 for (Index
= 0; Index
< CertCount
; Index
++) {
1181 // Iterate each Signature Data Node within this CertList for verify.
1183 RootCert
= Cert
->SignatureData
;
1184 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1186 // Get the signing time if the timestamp signature is valid.
1188 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1190 // The signer signature is valid only when the signing time is earlier than revocation time.
1192 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1193 VerifyStatus
= TRUE
;
1197 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1200 DbtDataSize
-= CertList
->SignatureListSize
;
1201 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1205 if (DbtData
!= NULL
) {
1209 return VerifyStatus
;
1213 Check whether the image signature is forbidden by the forbidden database (dbx).
1214 The image is forbidden to load if any certificates for signing are revoked before signing time.
1216 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1217 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1219 @retval TRUE Image is forbidden by dbx.
1220 @retval FALSE Image is not forbidden by dbx.
1226 IN UINTN AuthDataSize
1230 BOOLEAN IsForbidden
;
1233 EFI_SIGNATURE_LIST
*CertList
;
1235 EFI_SIGNATURE_DATA
*CertData
;
1243 UINTN TrustedCertLength
;
1248 EFI_TIME RevocationTime
;
1250 // Variable Initialization
1252 IsForbidden
= FALSE
;
1262 TrustedCertLength
= 0;
1265 // The image will not be forbidden if dbx can't be got.
1268 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1269 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1272 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1277 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1278 if (EFI_ERROR (Status
)) {
1283 // Verify image signature with RAW X509 certificates in DBX database.
1284 // If passed, the image will be forbidden.
1286 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1287 CertListSize
= DataSize
;
1288 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1289 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1290 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1291 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1293 for (Index
= 0; Index
< CertCount
; Index
++) {
1295 // Iterate each Signature Data Node within this CertList for verify.
1297 RootCert
= CertData
->SignatureData
;
1298 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1301 // Call AuthenticodeVerify library to Verify Authenticode struct.
1303 IsForbidden
= AuthenticodeVerify (
1312 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1313 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1317 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1321 CertListSize
-= CertList
->SignatureListSize
;
1322 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1326 // Check X.509 Certificate Hash & Possible Timestamp.
1330 // Retrieve the certificate stack from AuthData
1331 // The output CertStack format will be:
1332 // UINT8 CertNumber;
1333 // UINT32 Cert1Length;
1335 // UINT32 Cert2Length;
1338 // UINT32 CertnLength;
1341 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1342 if ((BufferLength
== 0) || (CertBuffer
== NULL
)) {
1348 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1350 CertNumber
= (UINT8
) (*CertBuffer
);
1351 CertPtr
= CertBuffer
+ 1;
1352 for (Index
= 0; Index
< CertNumber
; Index
++) {
1353 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1354 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1356 // Advance CertPtr to the next cert in image signer's cert list
1358 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1360 if (IsCertHashFoundInDatabase (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
)) {
1362 // Check the timestamp signature and signing time to determine if the image can be trusted.
1365 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1366 IsForbidden
= FALSE
;
1368 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1372 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1383 Pkcs7FreeSigners (CertBuffer
);
1384 Pkcs7FreeSigners (TrustedCert
);
1391 Check whether the image signature can be verified by the trusted certificates in DB database.
1393 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1394 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1396 @retval TRUE Image passed verification using certificate in db.
1397 @retval FALSE Image didn't pass verification using certificate in db.
1403 IN UINTN AuthDataSize
1407 BOOLEAN VerifyStatus
;
1408 EFI_SIGNATURE_LIST
*CertList
;
1409 EFI_SIGNATURE_DATA
*CertData
;
1418 EFI_TIME RevocationTime
;
1426 VerifyStatus
= FALSE
;
1429 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1430 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1431 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1433 return VerifyStatus
;
1436 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1437 if (EFI_ERROR (Status
)) {
1442 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1444 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1445 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1446 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1447 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1448 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1450 for (Index
= 0; Index
< CertCount
; Index
++) {
1452 // Iterate each Signature Data Node within this CertList for verify.
1454 RootCert
= CertData
->SignatureData
;
1455 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1458 // Call AuthenticodeVerify library to Verify Authenticode struct.
1460 VerifyStatus
= AuthenticodeVerify (
1470 // Here We still need to check if this RootCert's Hash is revoked
1472 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1473 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1476 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1477 if (DbxData
== NULL
) {
1481 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1482 if (EFI_ERROR (Status
)) {
1486 if (IsCertHashFoundInDatabase (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
)) {
1488 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1490 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1491 if (!VerifyStatus
) {
1492 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1499 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1503 DataSize
-= CertList
->SignatureListSize
;
1504 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1511 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1517 if (DbxData
!= NULL
) {
1521 return VerifyStatus
;
1525 Provide verification service for signed images, which include both signature validation
1526 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1527 MSFT Authenticode type signatures are supported.
1529 In this implementation, only verify external executables when in USER MODE.
1530 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1532 The image verification policy is:
1533 If the image is signed,
1534 At least one valid signature or at least one hash value of the image must match a record
1535 in the security database "db", and no valid signature nor any hash value of the image may
1536 be reflected in the security database "dbx".
1537 Otherwise, the image is not signed,
1538 The SHA256 hash value of the image must match a record in the security database "db", and
1539 not be reflected in the security data base "dbx".
1541 Caution: This function may receive untrusted input.
1542 PE/COFF image is external input, so this function will validate its data structure
1543 within this image buffer before use.
1545 @param[in] AuthenticationStatus
1546 This is the authentication status returned from the security
1547 measurement services for the input file.
1548 @param[in] File This is a pointer to the device path of the file that is
1549 being dispatched. This will optionally be used for logging.
1550 @param[in] FileBuffer File buffer matches the input file device path.
1551 @param[in] FileSize Size of File buffer matches the input file device path.
1552 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1554 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1555 FileBuffer did authenticate, and the platform policy dictates
1556 that the DXE Foundation may use the file.
1557 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1558 and non-NULL FileBuffer did authenticate, and the platform
1559 policy dictates that the DXE Foundation may execute the image in
1561 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1562 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1563 the platform policy dictates that File should be placed
1564 in the untrusted state. The image has been added to the file
1566 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1567 authenticate, and the platform policy dictates that the DXE
1568 Foundation many not use File.
1573 DxeImageVerificationHandler (
1574 IN UINT32 AuthenticationStatus
,
1575 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1576 IN VOID
*FileBuffer
,
1578 IN BOOLEAN BootPolicy
1583 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1584 EFI_STATUS VerifyStatus
;
1585 EFI_SIGNATURE_LIST
*SignatureList
;
1586 UINTN SignatureListSize
;
1587 EFI_SIGNATURE_DATA
*Signature
;
1588 EFI_IMAGE_EXECUTION_ACTION Action
;
1589 WIN_CERTIFICATE
*WinCertificate
;
1592 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1593 UINT32 NumberOfRvaAndSizes
;
1594 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1595 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1598 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1602 SignatureList
= NULL
;
1603 SignatureListSize
= 0;
1604 WinCertificate
= NULL
;
1606 PkcsCertData
= NULL
;
1607 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1608 Status
= EFI_ACCESS_DENIED
;
1609 VerifyStatus
= EFI_ACCESS_DENIED
;
1613 // Check the image type and get policy setting.
1615 switch (GetImageType (File
)) {
1618 Policy
= ALWAYS_EXECUTE
;
1621 case IMAGE_FROM_OPTION_ROM
:
1622 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1625 case IMAGE_FROM_REMOVABLE_MEDIA
:
1626 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1629 case IMAGE_FROM_FIXED_MEDIA
:
1630 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1634 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1638 // If policy is always/never execute, return directly.
1640 if (Policy
== ALWAYS_EXECUTE
) {
1642 } else if (Policy
== NEVER_EXECUTE
) {
1643 return EFI_ACCESS_DENIED
;
1647 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1648 // violates the UEFI spec and has been removed.
1650 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1651 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1655 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1657 // Skip verification if SecureBoot variable doesn't exist.
1659 if (SecureBoot
== NULL
) {
1664 // Skip verification if SecureBoot is disabled but not AuditMode
1666 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1667 FreePool (SecureBoot
);
1670 FreePool (SecureBoot
);
1673 // Read the Dos header.
1675 if (FileBuffer
== NULL
) {
1676 return EFI_INVALID_PARAMETER
;
1679 mImageBase
= (UINT8
*) FileBuffer
;
1680 mImageSize
= FileSize
;
1682 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1683 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1684 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1687 // Get information about the image being loaded
1689 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
1690 if (EFI_ERROR (Status
)) {
1692 // The information can't be got from the invalid PeImage
1694 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1698 Status
= EFI_ACCESS_DENIED
;
1700 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1701 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1703 // DOS image header is present,
1704 // so read the PE header after the DOS image header.
1706 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1708 mPeCoffHeaderOffset
= 0;
1711 // Check PE/COFF image.
1713 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1714 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1716 // It is not a valid Pe/Coff file.
1718 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1722 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1724 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1725 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1726 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1727 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1729 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1732 // Get the magic value from the PE/COFF Optional Header
1734 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
1737 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1741 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1742 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1743 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1747 // Use PE32+ offset.
1749 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1750 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1751 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1756 // Start Image Validation.
1758 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
1760 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1761 // and not be reflected in the security data base "dbx".
1763 if (!HashPeImage (HASHALG_SHA256
)) {
1764 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr
));
1768 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1770 // Image Hash is in forbidden database (DBX).
1772 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr
));
1776 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1778 // Image Hash is in allowed database (DB).
1784 // Image Hash is not found in both forbidden and allowed database.
1786 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr
));
1791 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1792 // "Attribute Certificate Table".
1793 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1795 for (OffSet
= SecDataDir
->VirtualAddress
;
1796 OffSet
< (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
);
1797 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
1798 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
1799 if ((SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) <= sizeof (WIN_CERTIFICATE
) ||
1800 (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) < WinCertificate
->dwLength
) {
1805 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1807 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1809 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1810 // Authenticode specification.
1812 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
1813 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
1816 AuthData
= PkcsCertData
->CertData
;
1817 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
1818 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
1820 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1822 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
1823 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
1826 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
1829 AuthData
= WinCertUefiGuid
->CertData
;
1830 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
1832 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
1838 Status
= HashPeImageByType (AuthData
, AuthDataSize
);
1839 if (EFI_ERROR (Status
)) {
1844 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1846 if (IsForbiddenByDbx (AuthData
, AuthDataSize
)) {
1847 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
1848 VerifyStatus
= EFI_ACCESS_DENIED
;
1853 // Check the digital signature against the valid certificate in allowed database (db).
1855 if (EFI_ERROR (VerifyStatus
)) {
1856 if (IsAllowedByDb (AuthData
, AuthDataSize
)) {
1857 VerifyStatus
= EFI_SUCCESS
;
1862 // Check the image's hash value.
1864 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1865 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
1866 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr
));
1867 VerifyStatus
= EFI_ACCESS_DENIED
;
1869 } else if (EFI_ERROR (VerifyStatus
)) {
1870 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1871 VerifyStatus
= EFI_SUCCESS
;
1873 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
));
1878 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
1880 // The Size in Certificate Table or the attribute certicate table is corrupted.
1882 VerifyStatus
= EFI_ACCESS_DENIED
;
1885 if (!EFI_ERROR (VerifyStatus
)) {
1888 Status
= EFI_ACCESS_DENIED
;
1889 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
1891 // Get image hash value as executable's signature.
1893 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1894 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1895 if (SignatureList
== NULL
) {
1896 Status
= EFI_OUT_OF_RESOURCES
;
1899 SignatureList
->SignatureHeaderSize
= 0;
1900 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
1901 SignatureList
->SignatureSize
= (UINT32
) (sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
);
1902 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
1903 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
1904 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
1909 if (Status
!= EFI_SUCCESS
) {
1911 // Policy decides to defer or reject the image; add its information in image executable information table.
1913 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1914 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
1915 if (NameStr
!= NULL
) {
1916 DEBUG((EFI_D_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
1919 Status
= EFI_SECURITY_VIOLATION
;
1922 if (SignatureList
!= NULL
) {
1923 FreePool (SignatureList
);
1930 On Ready To Boot Services Event notification handler.
1932 Add the image execution information table if it is not in system configuration table.
1934 @param[in] Event Event whose notification function is being invoked
1935 @param[in] Context Pointer to the notification function's context
1945 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
1946 UINTN ImageExeInfoTableSize
;
1948 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
1949 if (ImageExeInfoTable
!= NULL
) {
1953 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
1954 ImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
);
1955 if (ImageExeInfoTable
== NULL
) {
1959 ImageExeInfoTable
->NumberOfImages
= 0;
1960 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) ImageExeInfoTable
);
1965 Register security measurement handler.
1967 @param ImageHandle ImageHandle of the loaded driver.
1968 @param SystemTable Pointer to the EFI System Table.
1970 @retval EFI_SUCCESS The handlers were registered successfully.
1974 DxeImageVerificationLibConstructor (
1975 IN EFI_HANDLE ImageHandle
,
1976 IN EFI_SYSTEM_TABLE
*SystemTable
1982 // Register the event to publish the image execution table.
1984 EfiCreateEventReadyToBootEx (
1991 return RegisterSecurity2Handler (
1992 DxeImageVerificationHandler
,
1993 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED