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 This program and the accompanying materials
17 are licensed and made available under the terms and conditions of the BSD License
18 which accompanies this distribution. The full text of the license may be found at
19 http://opensource.org/licenses/bsd-license.php
21 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
22 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
26 #include "DxeImageVerificationLib.h"
29 // Caution: This is used by a function which may receive untrusted input.
30 // These global variables hold PE/COFF image data, and they should be validated before use.
32 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
33 UINT32 mPeCoffHeaderOffset
;
37 // Information on current PE/COFF image
40 UINT8
*mImageBase
= NULL
;
41 UINT8 mImageDigest
[MAX_DIGEST_SIZE
];
42 UINTN mImageDigestSize
;
45 // Notify string for authorization UI.
47 CHAR16 mNotifyString1
[MAX_NOTIFY_STRING_LEN
] = L
"Image verification pass but not found in authorized database!";
48 CHAR16 mNotifyString2
[MAX_NOTIFY_STRING_LEN
] = L
"Launch this image anyway? (Yes/Defer/No)";
50 // Public Exponent of RSA Key.
52 CONST UINT8 mRsaE
[] = { 0x01, 0x00, 0x01 };
56 // OID ASN.1 Value for Hash Algorithms
58 UINT8 mHashOidValue
[] = {
59 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
60 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
61 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
66 HASH_TABLE mHash
[] = {
67 { L
"SHA1", 20, &mHashOidValue
[0], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
68 { L
"SHA224", 28, &mHashOidValue
[5], 9, NULL
, NULL
, NULL
, NULL
},
69 { L
"SHA256", 32, &mHashOidValue
[14], 9, Sha256GetContextSize
, Sha256Init
, Sha256Update
, Sha256Final
},
70 { L
"SHA384", 48, &mHashOidValue
[23], 9, Sha384GetContextSize
, Sha384Init
, Sha384Update
, Sha384Final
},
71 { L
"SHA512", 64, &mHashOidValue
[32], 9, Sha512GetContextSize
, Sha512Init
, Sha512Update
, Sha512Final
}
75 SecureBoot Hook for processing image verification.
77 @param[in] VariableName Name of Variable to be found.
78 @param[in] VendorGuid Variable vendor GUID.
79 @param[in] DataSize Size of Data found. If size is less than the
80 data, this value contains the required size.
81 @param[in] Data Data pointer.
87 IN CHAR16
*VariableName
,
88 IN EFI_GUID
*VendorGuid
,
94 Reads contents of a PE/COFF image in memory buffer.
96 Caution: This function may receive untrusted input.
97 PE/COFF image is external input, so this function will make sure the PE/COFF image content
98 read is within the image buffer.
100 @param FileHandle Pointer to the file handle to read the PE/COFF image.
101 @param FileOffset Offset into the PE/COFF image to begin the read operation.
102 @param ReadSize On input, the size in bytes of the requested read operation.
103 On output, the number of bytes actually read.
104 @param Buffer Output buffer that contains the data read from the PE/COFF image.
106 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
110 DxeImageVerificationLibImageRead (
113 IN OUT UINTN
*ReadSize
,
119 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
120 return EFI_INVALID_PARAMETER
;
123 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
124 return EFI_INVALID_PARAMETER
;
127 EndPosition
= FileOffset
+ *ReadSize
;
128 if (EndPosition
> mImageSize
) {
129 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
132 if (FileOffset
>= mImageSize
) {
136 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
145 @param[in] File This is a pointer to the device path of the file that is
148 @return UINT32 Image Type
153 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
157 EFI_HANDLE DeviceHandle
;
158 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
159 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
162 return IMAGE_UNKNOWN
;
166 // First check to see if File is from a Firmware Volume
169 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
170 Status
= gBS
->LocateDevicePath (
171 &gEfiFirmwareVolume2ProtocolGuid
,
175 if (!EFI_ERROR (Status
)) {
176 Status
= gBS
->OpenProtocol (
178 &gEfiFirmwareVolume2ProtocolGuid
,
182 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
184 if (!EFI_ERROR (Status
)) {
185 return IMAGE_FROM_FV
;
190 // Next check to see if File is from a Block I/O device
193 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
194 Status
= gBS
->LocateDevicePath (
195 &gEfiBlockIoProtocolGuid
,
199 if (!EFI_ERROR (Status
)) {
201 Status
= gBS
->OpenProtocol (
203 &gEfiBlockIoProtocolGuid
,
207 EFI_OPEN_PROTOCOL_GET_PROTOCOL
209 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
210 if (BlockIo
->Media
!= NULL
) {
211 if (BlockIo
->Media
->RemovableMedia
) {
213 // Block I/O is present and specifies the media is removable
215 return IMAGE_FROM_REMOVABLE_MEDIA
;
218 // Block I/O is present and specifies the media is not removable
220 return IMAGE_FROM_FIXED_MEDIA
;
227 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
228 // the device path supports the Simple File System Protocol.
231 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
232 Status
= gBS
->LocateDevicePath (
233 &gEfiSimpleFileSystemProtocolGuid
,
237 if (!EFI_ERROR (Status
)) {
239 // Simple File System is present without Block I/O, so assume media is fixed.
241 return IMAGE_FROM_FIXED_MEDIA
;
245 // File is not from an FV, Block I/O or Simple File System, so the only options
246 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
248 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
249 while (!IsDevicePathEndType (TempDevicePath
)) {
250 switch (DevicePathType (TempDevicePath
)) {
252 case MEDIA_DEVICE_PATH
:
253 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
254 return IMAGE_FROM_OPTION_ROM
;
258 case MESSAGING_DEVICE_PATH
:
259 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
260 return IMAGE_FROM_REMOVABLE_MEDIA
;
267 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
269 return IMAGE_UNKNOWN
;
273 Calculate hash of Pe/Coff image based on the authenticode image hashing in
274 PE/COFF Specification 8.0 Appendix A
276 Caution: This function may receive untrusted input.
277 PE/COFF image is external input, so this function will validate its data structure
278 within this image buffer before use.
280 @param[in] HashAlg Hash algorithm type.
282 @retval TRUE Successfully hash image.
283 @retval FALSE Fail in hash image.
293 EFI_IMAGE_SECTION_HEADER
*Section
;
298 UINTN SumOfBytesHashed
;
299 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
303 UINT32 NumberOfRvaAndSizes
;
306 SectionHeader
= NULL
;
309 if ((HashAlg
>= HASHALG_MAX
)) {
314 // Initialize context of hash.
316 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
320 mImageDigestSize
= SHA1_DIGEST_SIZE
;
321 mCertType
= gEfiCertSha1Guid
;
325 mImageDigestSize
= SHA256_DIGEST_SIZE
;
326 mCertType
= gEfiCertSha256Guid
;
330 mImageDigestSize
= SHA384_DIGEST_SIZE
;
331 mCertType
= gEfiCertSha384Guid
;
335 mImageDigestSize
= SHA512_DIGEST_SIZE
;
336 mCertType
= gEfiCertSha512Guid
;
343 CtxSize
= mHash
[HashAlg
].GetContextSize();
345 HashCtx
= AllocatePool (CtxSize
);
346 if (HashCtx
== NULL
) {
350 // 1. Load the image header into memory.
352 // 2. Initialize a SHA hash context.
353 Status
= mHash
[HashAlg
].HashInit(HashCtx
);
360 // Measuring PE/COFF Image Header;
361 // But CheckSum field and SECURITY data directory (certificate) are excluded
363 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
365 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
366 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
367 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
368 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
370 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
373 // Get the magic value from the PE/COFF Optional Header
375 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
379 // 3. Calculate the distance from the base of the image header to the image checksum address.
380 // 4. Hash the image header from its base to beginning of the image checksum.
382 HashBase
= mImageBase
;
383 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
387 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - HashBase
);
388 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
389 } else if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
393 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - HashBase
);
394 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
397 // Invalid header magic number.
403 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
409 // 5. Skip over the image checksum (it occupies a single ULONG).
411 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
413 // 6. Since there is no Cert Directory in optional header, hash everything
414 // from the end of the checksum to the end of image header.
416 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
420 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
421 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
426 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
427 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
431 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
438 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
440 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
444 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
445 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
450 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
451 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
455 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
462 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
463 // 9. Hash everything from the end of the Cert Directory to the end of image header.
465 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
469 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
470 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
475 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
476 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
480 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
488 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
490 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
494 SumOfBytesHashed
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
;
499 SumOfBytesHashed
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
503 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
505 mPeCoffHeaderOffset
+
507 sizeof (EFI_IMAGE_FILE_HEADER
) +
508 mNtHeader
.Pe32
->FileHeader
.SizeOfOptionalHeader
512 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
513 // structures in the image. The 'NumberOfSections' field of the image
514 // header indicates how big the table should be. Do not include any
515 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
517 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * mNtHeader
.Pe32
->FileHeader
.NumberOfSections
);
518 if (SectionHeader
== NULL
) {
523 // 12. Using the 'PointerToRawData' in the referenced section headers as
524 // a key, arrange the elements in the table in ascending order. In other
525 // words, sort the section headers according to the disk-file offset of
528 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
530 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
531 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
534 CopyMem (&SectionHeader
[Pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
539 // 13. Walk through the sorted table, bring the corresponding section
540 // into memory, and hash the entire section (using the 'SizeOfRawData'
541 // field in the section header to determine the amount of data to hash).
542 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
543 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
545 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
546 Section
= &SectionHeader
[Index
];
547 if (Section
->SizeOfRawData
== 0) {
550 HashBase
= mImageBase
+ Section
->PointerToRawData
;
551 HashSize
= (UINTN
) Section
->SizeOfRawData
;
553 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
558 SumOfBytesHashed
+= HashSize
;
562 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
563 // data in the file that needs to be added to the hash. This data begins
564 // at file offset SUM_OF_BYTES_HASHED and its length is:
565 // FileSize - (CertDirectory->Size)
567 if (mImageSize
> SumOfBytesHashed
) {
568 HashBase
= mImageBase
+ SumOfBytesHashed
;
570 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
573 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
577 CertSize
= mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
582 CertSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
586 if (mImageSize
> CertSize
+ SumOfBytesHashed
) {
587 HashSize
= (UINTN
) (mImageSize
- CertSize
- SumOfBytesHashed
);
589 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
593 } else if (mImageSize
< CertSize
+ SumOfBytesHashed
) {
599 Status
= mHash
[HashAlg
].HashFinal(HashCtx
, mImageDigest
);
602 if (HashCtx
!= NULL
) {
605 if (SectionHeader
!= NULL
) {
606 FreePool (SectionHeader
);
612 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
613 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
616 Caution: This function may receive untrusted input.
617 PE/COFF image is external input, so this function will validate its data structure
618 within this image buffer before use.
620 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
621 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
623 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
624 @retval EFI_SUCCESS Hash successfully.
630 IN UINTN AuthDataSize
635 for (Index
= 0; Index
< HASHALG_MAX
; Index
++) {
637 // Check the Hash algorithm in PE/COFF Authenticode.
638 // According to PKCS#7 Definition:
639 // SignedData ::= SEQUENCE {
641 // digestAlgorithms DigestAlgorithmIdentifiers,
642 // contentInfo ContentInfo,
644 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
645 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
646 // Fixed offset (+32) is calculated based on two bytes of length encoding.
648 if ((*(AuthData
+ 1) & TWO_BYTE_ENCODE
) != TWO_BYTE_ENCODE
) {
650 // Only support two bytes of Long Form of Length Encoding.
655 if (AuthDataSize
< 32 + mHash
[Index
].OidLength
) {
656 return EFI_UNSUPPORTED
;
659 if (CompareMem (AuthData
+ 32, mHash
[Index
].OidValue
, mHash
[Index
].OidLength
) == 0) {
664 if (Index
== HASHALG_MAX
) {
665 return EFI_UNSUPPORTED
;
669 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
671 if (!HashPeImage(Index
)) {
672 return EFI_UNSUPPORTED
;
680 Returns the size of a given image execution info table in bytes.
682 This function returns the size, in bytes, of the image execution info table specified by
683 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
685 @param ImageExeInfoTable A pointer to a image execution info table structure.
687 @retval 0 If ImageExeInfoTable is NULL.
688 @retval Others The size of a image execution info table in bytes.
692 GetImageExeInfoTableSize (
693 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
697 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoItem
;
700 if (ImageExeInfoTable
== NULL
) {
704 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoTable
+ sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
));
705 TotalSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
706 for (Index
= 0; Index
< ImageExeInfoTable
->NumberOfImages
; Index
++) {
707 TotalSize
+= ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
);
708 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoItem
+ ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
));
715 Create signature list based on input signature data and certificate type GUID. Caller is reposible
716 to free new created SignatureList.
718 @param[in] SignatureData Signature data in SignatureList.
719 @param[in] SignatureDataSize Signature data size.
720 @param[in] CertType Certificate Type.
721 @param[out] SignatureList Created SignatureList.
722 @param[out] SignatureListSize Created SignatureListSize.
724 @return EFI_OUT_OF_RESOURCES The operation is failed due to lack of resources.
725 @retval EFI_SUCCESS Successfully create signature list.
730 IN UINT8
*SignatureData
,
731 IN UINTN SignatureDataSize
,
732 IN EFI_GUID
*CertType
,
733 OUT EFI_SIGNATURE_LIST
**SignatureList
,
734 OUT UINTN
*SignatureListSize
737 EFI_SIGNATURE_LIST
*SignList
;
739 EFI_SIGNATURE_DATA
*Signature
;
742 *SignatureList
= NULL
;
744 SignListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + SignatureDataSize
;
745 SignList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignListSize
);
746 if (SignList
== NULL
) {
747 return EFI_OUT_OF_RESOURCES
;
750 SignList
->SignatureHeaderSize
= 0;
751 SignList
->SignatureListSize
= (UINT32
) SignListSize
;
752 SignList
->SignatureSize
= (UINT32
) SignatureDataSize
+ sizeof (EFI_SIGNATURE_DATA
) - 1;
753 CopyMem (&SignList
->SignatureType
, CertType
, sizeof (EFI_GUID
));
755 DEBUG((EFI_D_INFO
, "SignatureDataSize %x\n", SignatureDataSize
));
756 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignList
+ sizeof (EFI_SIGNATURE_LIST
));
757 CopyMem (Signature
->SignatureData
, SignatureData
, SignatureDataSize
);
759 *SignatureList
= SignList
;
760 *SignatureListSize
= SignListSize
;
767 Create an Image Execution Information Table entry and add it to system configuration table.
769 @param[in] Action Describes the action taken by the firmware regarding this image.
770 @param[in] Name Input a null-terminated, user-friendly name.
771 @param[in] DevicePath Input device path pointer.
772 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
773 @param[in] SignatureSize Size of signature.
778 IN EFI_IMAGE_EXECUTION_ACTION Action
,
779 IN CHAR16
*Name OPTIONAL
,
780 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
,
781 IN EFI_SIGNATURE_LIST
*Signature OPTIONAL
,
782 IN UINTN SignatureSize
785 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
786 EFI_IMAGE_EXECUTION_INFO_TABLE
*NewImageExeInfoTable
;
787 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoEntry
;
788 UINTN ImageExeInfoTableSize
;
789 UINTN NewImageExeInfoEntrySize
;
791 UINTN DevicePathSize
;
794 ImageExeInfoTable
= NULL
;
795 NewImageExeInfoTable
= NULL
;
796 ImageExeInfoEntry
= NULL
;
800 if (DevicePath
== NULL
) {
805 NameStringLen
= StrSize (Name
);
807 NameStringLen
= sizeof (CHAR16
);
810 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
811 if (ImageExeInfoTable
!= NULL
) {
813 // The table has been found!
814 // We must enlarge the table to accomodate the new exe info entry.
816 ImageExeInfoTableSize
= GetImageExeInfoTableSize (ImageExeInfoTable
);
820 // We should create a new table to append to the configuration table.
822 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
825 DevicePathSize
= GetDevicePathSize (DevicePath
);
828 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
830 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
832 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
833 if (NewImageExeInfoTable
== NULL
) {
837 if (ImageExeInfoTable
!= NULL
) {
838 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
840 NewImageExeInfoTable
->NumberOfImages
= 0;
842 NewImageExeInfoTable
->NumberOfImages
++;
843 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
845 // Update new item's information.
847 WriteUnaligned32 ((UINT32
*) ImageExeInfoEntry
, Action
);
848 WriteUnaligned32 ((UINT32
*) ((UINT8
*) ImageExeInfoEntry
+ sizeof (EFI_IMAGE_EXECUTION_ACTION
)), (UINT32
) NewImageExeInfoEntrySize
);
850 NameStr
= (CHAR16
*)(ImageExeInfoEntry
+ 1);
852 CopyMem ((UINT8
*) NameStr
, Name
, NameStringLen
);
854 ZeroMem ((UINT8
*) NameStr
, sizeof (CHAR16
));
858 (UINT8
*) NameStr
+ NameStringLen
,
862 if (Signature
!= NULL
) {
864 (UINT8
*) NameStr
+ NameStringLen
+ DevicePathSize
,
870 // Update/replace the image execution table.
872 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
875 // Free Old table data!
877 if (ImageExeInfoTable
!= NULL
) {
878 FreePool (ImageExeInfoTable
);
883 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
885 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
886 @param[in] CertSize Size of X.509 Certificate.
887 @param[in] SignatureList Pointer to the Signature List in forbidden database.
888 @param[in] SignatureListSize Size of Signature List.
889 @param[out] RevocationTime Return the time that the certificate was revoked.
891 @return TRUE The certificate hash is found in the forbidden database.
892 @return FALSE The certificate hash is not found in the forbidden database.
896 IsCertHashFoundInDatabase (
897 IN UINT8
*Certificate
,
899 IN EFI_SIGNATURE_LIST
*SignatureList
,
900 IN UINTN SignatureListSize
,
901 OUT EFI_TIME
*RevocationTime
906 EFI_SIGNATURE_LIST
*DbxList
;
908 EFI_SIGNATURE_DATA
*CertHash
;
913 UINT8 CertDigest
[MAX_DIGEST_SIZE
];
915 UINTN SiglistHeaderSize
;
920 DbxList
= SignatureList
;
921 DbxSize
= SignatureListSize
;
923 HashAlg
= HASHALG_MAX
;
925 if ((RevocationTime
== NULL
) || (DbxList
== NULL
)) {
930 // Retrieve the TBSCertificate from the X.509 Certificate.
932 if (!X509GetTBSCert (Certificate
, CertSize
, &TBSCert
, &TBSCertSize
)) {
936 while ((DbxSize
> 0) && (SignatureListSize
>= DbxList
->SignatureListSize
)) {
938 // Determine Hash Algorithm of Certificate in the forbidden database.
940 if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha256Guid
)) {
941 HashAlg
= HASHALG_SHA256
;
942 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha384Guid
)) {
943 HashAlg
= HASHALG_SHA384
;
944 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha512Guid
)) {
945 HashAlg
= HASHALG_SHA512
;
947 DbxSize
-= DbxList
->SignatureListSize
;
948 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
953 // Calculate the hash value of current TBSCertificate for comparision.
955 if (mHash
[HashAlg
].GetContextSize
== NULL
) {
958 ZeroMem (CertDigest
, MAX_DIGEST_SIZE
);
959 HashCtx
= AllocatePool (mHash
[HashAlg
].GetContextSize ());
960 if (HashCtx
== NULL
) {
963 Status
= mHash
[HashAlg
].HashInit (HashCtx
);
967 Status
= mHash
[HashAlg
].HashUpdate (HashCtx
, TBSCert
, TBSCertSize
);
971 Status
= mHash
[HashAlg
].HashFinal (HashCtx
, CertDigest
);
976 SiglistHeaderSize
= sizeof (EFI_SIGNATURE_LIST
) + DbxList
->SignatureHeaderSize
;
977 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) DbxList
+ SiglistHeaderSize
);
978 CertHashCount
= (DbxList
->SignatureListSize
- SiglistHeaderSize
) / DbxList
->SignatureSize
;
979 for (Index
= 0; Index
< CertHashCount
; Index
++) {
981 // Iterate each Signature Data Node within this CertList for verify.
983 DbxCertHash
= CertHash
->SignatureData
;
984 if (CompareMem (DbxCertHash
, CertDigest
, mHash
[HashAlg
].DigestLength
) == 0) {
986 // Hash of Certificate is found in forbidden database.
991 // Return the revocation time.
993 CopyMem (RevocationTime
, (EFI_TIME
*)(DbxCertHash
+ mHash
[HashAlg
].DigestLength
), sizeof (EFI_TIME
));
996 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertHash
+ DbxList
->SignatureSize
);
999 DbxSize
-= DbxList
->SignatureListSize
;
1000 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
1004 if (HashCtx
!= NULL
) {
1012 Check whether signature is in specified database.
1014 @param[in] VariableName Name of database variable that is searched in.
1015 @param[in] Signature Pointer to signature that is searched for.
1016 @param[in] CertType Pointer to hash algrithom.
1017 @param[in] SignatureSize Size of Signature.
1019 @return TRUE Found the signature in the variable database.
1020 @return FALSE Not found the signature in the variable database.
1024 IsSignatureFoundInDatabase (
1025 IN CHAR16
*VariableName
,
1026 IN UINT8
*Signature
,
1027 IN EFI_GUID
*CertType
,
1028 IN UINTN SignatureSize
1032 EFI_SIGNATURE_LIST
*CertList
;
1033 EFI_SIGNATURE_DATA
*Cert
;
1041 // Read signature database variable.
1046 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1047 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1051 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1056 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
1057 if (EFI_ERROR (Status
)) {
1061 // Enumerate all signature data in SigDB to check if executable's signature exists.
1063 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1064 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1065 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1066 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1067 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
1068 for (Index
= 0; Index
< CertCount
; Index
++) {
1069 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
1071 // Find the signature in database.
1074 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1078 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1086 DataSize
-= CertList
->SignatureListSize
;
1087 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1099 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1101 @param SigningTime A pointer to the signing time.
1102 @param RevocationTime A pointer to the revocation time.
1104 @retval TRUE The SigningTime is not later than the RevocationTime.
1105 @retval FALSE The SigningTime is later than the RevocationTime.
1109 IsValidSignatureByTimestamp (
1110 IN EFI_TIME
*SigningTime
,
1111 IN EFI_TIME
*RevocationTime
1114 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1115 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1116 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1117 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1118 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1119 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1120 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1121 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1122 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1123 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1126 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1130 Check if the given time value is zero.
1132 @param[in] Time Pointer of a time value.
1134 @retval TRUE The Time is Zero.
1135 @retval FALSE The Time is not Zero.
1143 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1144 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1152 Record multiple certificate list & verification state of a verified image to
1153 IMAGE_EXECUTION_TABLE.
1155 @param[in] CertBuf Certificate list buffer.
1156 @param[in] CertBufLength Certificate list buffer.
1157 @param[in] Action Certificate list action to be record.
1158 @param[in] ImageName Image name.
1159 @param[in] ImageDevicePath Image device path.
1163 RecordCertListToImageExeuctionTable(
1165 IN UINTN CertBufLength
,
1166 IN EFI_IMAGE_EXECUTION_ACTION Action
,
1167 IN CHAR16
*ImageName OPTIONAL
,
1168 IN CONST EFI_DEVICE_PATH_PROTOCOL
*ImageDevicePath OPTIONAL
1177 EFI_SIGNATURE_LIST
*SignatureList
;
1178 UINTN SignatureListSize
;
1180 CertNumber
= (UINT8
) (*CertBuf
);
1181 CertPtr
= CertBuf
+ 1;
1182 for (Index
= 0; Index
< CertNumber
; Index
++) {
1183 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1184 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1187 // Record all cert in cert chain to be passed
1189 Status
= CreateSignatureList(Cert
, CertSize
, &gEfiCertX509Guid
, &SignatureList
, &SignatureListSize
);
1190 if (!EFI_ERROR(Status
)) {
1191 AddImageExeInfo (Action
, ImageName
, ImageDevicePath
, SignatureList
, SignatureListSize
);
1192 FreePool (SignatureList
);
1199 Check whether the timestamp signature is valid and the signing time is also earlier than
1200 the revocation time.
1202 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1203 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1204 @param[in] RevocationTime The time that the certificate was revoked.
1206 @retval TRUE Timestamp signature is valid and signing time is no later than the
1208 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1213 PassTimestampCheck (
1215 IN UINTN AuthDataSize
,
1216 IN EFI_TIME
*RevocationTime
1220 BOOLEAN VerifyStatus
;
1221 EFI_SIGNATURE_LIST
*CertList
;
1222 EFI_SIGNATURE_DATA
*Cert
;
1229 EFI_TIME SigningTime
;
1232 // Variable Initialization
1234 VerifyStatus
= FALSE
;
1242 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1244 if (IsTimeZero (RevocationTime
)) {
1249 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1250 // Using the dbt to get the trusted TSA certificates.
1253 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1254 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1257 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1258 if (DbtData
== NULL
) {
1261 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1262 if (EFI_ERROR (Status
)) {
1266 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1267 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1268 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1269 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1270 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1271 for (Index
= 0; Index
< CertCount
; Index
++) {
1273 // Iterate each Signature Data Node within this CertList for verify.
1275 RootCert
= Cert
->SignatureData
;
1276 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1278 // Get the signing time if the timestamp signature is valid.
1280 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1282 // The signer signature is valid only when the signing time is earlier than revocation time.
1284 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1285 VerifyStatus
= TRUE
;
1289 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1292 DbtDataSize
-= CertList
->SignatureListSize
;
1293 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1297 if (DbtData
!= NULL
) {
1301 return VerifyStatus
;
1305 Check whether the image signature is forbidden by the forbidden database (dbx).
1306 The image is forbidden to load if any certificates for signing are revoked before signing time.
1308 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1309 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1310 @param[in] IsAuditMode Whether system Secure Boot Mode is in AuditMode.
1311 @param[in] ImageName Name of the image to verify.
1312 @param[in] ImageDevicePath DevicePath of the image to verify.
1314 @retval TRUE Image is forbidden by dbx.
1315 @retval FALSE Image is not forbidden by dbx.
1321 IN UINTN AuthDataSize
,
1322 IN BOOLEAN IsAuditMode
,
1323 IN CHAR16
*ImageName OPTIONAL
,
1324 IN CONST EFI_DEVICE_PATH_PROTOCOL
*ImageDevicePath OPTIONAL
1328 BOOLEAN IsForbidden
;
1331 EFI_SIGNATURE_LIST
*CertList
;
1333 EFI_SIGNATURE_DATA
*CertData
;
1341 UINTN TrustedCertLength
;
1346 EFI_TIME RevocationTime
;
1348 UINTN SignerCertLength
;
1350 UINTN UnchainCertLength
;
1352 // Variable Initialization
1354 IsForbidden
= FALSE
;
1364 TrustedCertLength
= 0;
1366 SignerCertLength
= 0;
1368 UnchainCertLength
= 0;
1371 // The image will not be forbidden if dbx can't be got.
1374 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1375 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1378 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1383 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1384 if (EFI_ERROR (Status
)) {
1389 // Verify image signature with RAW X509 certificates in DBX database.
1390 // If passed, the image will be forbidden.
1392 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1393 CertListSize
= DataSize
;
1394 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1395 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1396 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1397 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1399 for (Index
= 0; Index
< CertCount
; Index
++) {
1401 // Iterate each Signature Data Node within this CertList for verify.
1403 RootCert
= CertData
->SignatureData
;
1404 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1407 // Call AuthenticodeVerify library to Verify Authenticode struct.
1409 IsForbidden
= AuthenticodeVerify (
1418 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1422 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1426 CertListSize
-= CertList
->SignatureListSize
;
1427 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1431 // Check X.509 Certificate Hash & Possible Timestamp.
1435 // Retrieve the certificate stack from AuthData
1436 // The output CertStack format will be:
1437 // UINT8 CertNumber;
1438 // UINT32 Cert1Length;
1440 // UINT32 Cert2Length;
1443 // UINT32 CertnLength;
1446 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1447 if ((BufferLength
== 0) || (CertBuffer
== NULL
)) {
1453 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1455 CertNumber
= (UINT8
) (*CertBuffer
);
1456 CertPtr
= CertBuffer
+ 1;
1457 for (Index
= 0; Index
< CertNumber
; Index
++) {
1458 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1459 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1461 // Advance CertPtr to the next cert in image signer's cert list
1463 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1465 if (IsCertHashFoundInDatabase (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
)) {
1467 // Check the timestamp signature and signing time to determine if the image can be trusted.
1470 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1471 IsForbidden
= FALSE
;
1473 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1483 if (IsForbidden
&& IsAuditMode
) {
1484 Pkcs7GetCertificatesList(AuthData
, AuthDataSize
, &SignerCert
, &SignerCertLength
, &UnchainCert
, &UnchainCertLength
);
1487 // Record all certs in image to be failed
1489 if ((SignerCertLength
!= 0) && (SignerCert
!= NULL
)) {
1490 RecordCertListToImageExeuctionTable(
1493 EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
,
1499 if ((UnchainCertLength
!= 0) && (UnchainCert
!= NULL
)) {
1500 RecordCertListToImageExeuctionTable(
1503 EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
,
1514 Pkcs7FreeSigners (CertBuffer
);
1515 Pkcs7FreeSigners (TrustedCert
);
1516 Pkcs7FreeSigners (SignerCert
);
1517 Pkcs7FreeSigners (UnchainCert
);
1524 Check whether the image signature can be verified by the trusted certificates in DB database.
1526 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1527 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1528 @param[in] IsAuditMode Whether system Secure Boot Mode is in AuditMode.
1529 @param[in] ImageName Name of the image to verify.
1530 @param[in] ImageDevicePath DevicePath of the image to verify.
1532 @retval TRUE Image passed verification using certificate in db.
1533 @retval FALSE Image didn't pass verification using certificate in db.
1539 IN UINTN AuthDataSize
,
1540 IN BOOLEAN IsAuditMode
,
1541 IN CHAR16
*ImageName OPTIONAL
,
1542 IN CONST EFI_DEVICE_PATH_PROTOCOL
*ImageDevicePath OPTIONAL
1546 BOOLEAN VerifyStatus
;
1547 EFI_SIGNATURE_LIST
*CertList
;
1548 EFI_SIGNATURE_DATA
*CertData
;
1557 EFI_TIME RevocationTime
;
1559 UINTN SignerCertLength
;
1561 UINTN UnchainCertLength
;
1569 VerifyStatus
= FALSE
;
1571 SignerCertLength
= 0;
1573 UnchainCertLength
= 0;
1576 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1577 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1578 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1580 return VerifyStatus
;
1583 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1584 if (EFI_ERROR (Status
)) {
1589 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1591 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1592 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1593 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1594 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1595 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1597 for (Index
= 0; Index
< CertCount
; Index
++) {
1599 // Iterate each Signature Data Node within this CertList for verify.
1601 RootCert
= CertData
->SignatureData
;
1602 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1605 // Call AuthenticodeVerify library to Verify Authenticode struct.
1607 VerifyStatus
= AuthenticodeVerify (
1617 // Here We still need to check if this RootCert's Hash is revoked
1619 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1620 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1623 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1624 if (DbxData
== NULL
) {
1628 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1629 if (EFI_ERROR (Status
)) {
1633 if (IsCertHashFoundInDatabase (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
)) {
1635 // Check the timestamp signature and signing time to determine if the image can be trusted.
1637 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1643 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1647 DataSize
-= CertList
->SignatureListSize
;
1648 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1655 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1660 Pkcs7GetCertificatesList(AuthData
, AuthDataSize
, &SignerCert
, &SignerCertLength
, &UnchainCert
, &UnchainCertLength
);
1662 if ((SignerCertLength
!= 0) && (SignerCert
!= NULL
)) {
1664 // Record all cert in signer's cert chain to be passed
1666 RecordCertListToImageExeuctionTable(
1669 EFI_IMAGE_EXECUTION_AUTH_SIG_PASSED
| EFI_IMAGE_EXECUTION_INITIALIZED
,
1675 if ((UnchainCertLength
!= 0) && (UnchainCert
!= NULL
)) {
1677 // Record all certs in unchained certificates lists to be failed
1679 RecordCertListToImageExeuctionTable(
1682 EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
,
1689 // Record all certs in image to be failed
1691 if ((SignerCertLength
!= 0) && (SignerCert
!= NULL
)) {
1692 RecordCertListToImageExeuctionTable(
1695 EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
,
1701 if ((UnchainCertLength
!= 0) && (UnchainCert
!= NULL
)) {
1702 RecordCertListToImageExeuctionTable(
1705 EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
,
1717 if (DbxData
!= NULL
) {
1721 Pkcs7FreeSigners (SignerCert
);
1722 Pkcs7FreeSigners (UnchainCert
);
1724 return VerifyStatus
;
1728 Provide verification service for signed images in AuditMode, which include both signature validation
1729 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1730 MSFT Authenticode type signatures are supported.
1732 In this implementation, only verify external executables when in AuditMode.
1733 Executables from FV is bypass, so pass in AuthenticationStatus is ignored. Other authentication status
1734 are record into IMAGE_EXECUTION_TABLE.
1736 The image verification policy is:
1737 If the image is signed,
1738 At least one valid signature or at least one hash value of the image must match a record
1739 in the security database "db", and no valid signature nor any hash value of the image may
1740 be reflected in the security database "dbx".
1741 Otherwise, the image is not signed,
1742 The SHA256 hash value of the image must match a record in the security database "db", and
1743 not be reflected in the security data base "dbx".
1745 Caution: This function may receive untrusted input.
1746 PE/COFF image is external input, so this function will validate its data structure
1747 within this image buffer before use.
1749 @param[in] AuthenticationStatus
1750 This is the authentication status returned from the security
1751 measurement services for the input file.
1752 @param[in] File This is a pointer to the device path of the file that is
1753 being dispatched. This will optionally be used for logging.
1754 @param[in] FileBuffer File buffer matches the input file device path.
1755 @param[in] FileSize Size of File buffer matches the input file device path.
1756 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1758 @retval EFI_SUCCESS The authenticate info is sucessfully stored for the file
1759 specified by DevicePath and non-NULL FileBuffer
1760 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1761 authenticate, and the platform policy dictates that the DXE
1762 Foundation many not use File.
1767 ImageVerificationInAuditMode (
1768 IN UINT32 AuthenticationStatus
,
1769 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1770 IN VOID
*FileBuffer
,
1772 IN BOOLEAN BootPolicy
1777 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1778 EFI_SIGNATURE_LIST
*SignatureList
;
1779 EFI_IMAGE_EXECUTION_ACTION Action
;
1780 WIN_CERTIFICATE
*WinCertificate
;
1782 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1783 UINT32 NumberOfRvaAndSizes
;
1784 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1785 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1788 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1790 CHAR16
*FilePathStr
;
1791 UINTN SignatureListSize
;
1793 SignatureList
= NULL
;
1794 WinCertificate
= NULL
;
1796 PkcsCertData
= NULL
;
1798 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
;
1799 Status
= EFI_ACCESS_DENIED
;
1803 // Check the image type and get policy setting.
1805 switch (GetImageType (File
)) {
1808 Policy
= ALWAYS_EXECUTE
;
1811 case IMAGE_FROM_OPTION_ROM
:
1812 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1815 case IMAGE_FROM_REMOVABLE_MEDIA
:
1816 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1819 case IMAGE_FROM_FIXED_MEDIA
:
1820 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1824 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1829 // If policy is always/never execute, return directly.
1831 if (Policy
== ALWAYS_EXECUTE
) {
1836 // Get Image Device Path Str
1838 FilePathStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1841 // Authentication failed because of (unspecified) firmware security policy
1843 if (Policy
== NEVER_EXECUTE
) {
1845 // No signature, record FilePath/FilePathStr only
1847 AddImageExeInfo (EFI_IMAGE_EXECUTION_POLICY_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
, FilePathStr
, File
, NULL
, 0);
1852 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1853 // violates the UEFI spec and has been removed.
1855 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1856 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1861 // Read the Dos header.
1863 if (FileBuffer
== NULL
) {
1864 Status
= EFI_INVALID_PARAMETER
;
1868 mImageBase
= (UINT8
*) FileBuffer
;
1869 mImageSize
= FileSize
;
1871 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1872 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1873 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1876 // Get information about the image being loaded
1878 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
1879 if (EFI_ERROR (Status
)) {
1881 // The information can't be got from the invalid PeImage
1887 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1888 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1890 // DOS image header is present,
1891 // so read the PE header after the DOS image header.
1893 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1895 mPeCoffHeaderOffset
= 0;
1899 // Check PE/COFF image.
1901 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1902 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1904 // It is not a valid Pe/Coff file.
1906 Status
= EFI_ACCESS_DENIED
;
1910 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1912 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1913 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1914 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1915 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1917 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1920 // Get the magic value from the PE/COFF Optional Header
1922 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
1925 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1929 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1930 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1931 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1935 // Use PE32+ offset.
1937 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1938 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1939 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1944 // Start Image Validation.
1946 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
1948 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1949 // and not be reflected in the security data base "dbx".
1951 if (!HashPeImage (HASHALG_SHA256
)) {
1952 Status
= EFI_ACCESS_DENIED
;
1957 // Image Hash is in forbidden database (DBX).
1959 if (!IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1961 // Image Hash is in allowed database (DB).
1963 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1964 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_PASSED
| EFI_IMAGE_EXECUTION_INITIALIZED
;
1969 // Add HASH digest for image without signature
1971 Status
= CreateSignatureList(mImageDigest
, mImageDigestSize
, &mCertType
, &SignatureList
, &SignatureListSize
);
1972 if (!EFI_ERROR(Status
)) {
1973 AddImageExeInfo (Action
, FilePathStr
, File
, SignatureList
, SignatureListSize
);
1974 FreePool (SignatureList
);
1980 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1981 // "Attribute Certificate Table".
1982 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1984 for (OffSet
= SecDataDir
->VirtualAddress
;
1985 OffSet
< (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
);
1986 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
1987 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
1988 if ((SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) <= sizeof (WIN_CERTIFICATE
) ||
1989 (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) < WinCertificate
->dwLength
) {
1994 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1996 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1998 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1999 // Authenticode specification.
2001 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
2002 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
2005 AuthData
= PkcsCertData
->CertData
;
2006 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
2007 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
2009 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
2011 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
2012 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
2015 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
2018 AuthData
= WinCertUefiGuid
->CertData
;
2019 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
2021 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
2027 Status
= HashPeImageByType (AuthData
, AuthDataSize
);
2028 if (EFI_ERROR (Status
)) {
2032 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
| EFI_IMAGE_EXECUTION_INITIALIZED
;
2035 // Check the digital signature against the revoked certificate in forbidden database (dbx).
2036 // Check the digital signature against the valid certificate in allowed database (db).
2038 if (!IsForbiddenByDbx (AuthData
, AuthDataSize
, TRUE
, FilePathStr
, File
)) {
2039 IsAllowedByDb (AuthData
, AuthDataSize
, TRUE
, FilePathStr
, File
);
2043 // Check the image's hash value.
2045 if (!IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
2046 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
2047 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_PASSED
| EFI_IMAGE_EXECUTION_INITIALIZED
;
2052 // Add HASH digest for image with signature
2054 Status
= CreateSignatureList(mImageDigest
, mImageDigestSize
, &mCertType
, &SignatureList
, &SignatureListSize
);
2056 if (!EFI_ERROR(Status
)) {
2057 AddImageExeInfo (Action
, FilePathStr
, File
, SignatureList
, SignatureListSize
);
2058 FreePool (SignatureList
);
2065 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
2067 // The Size in Certificate Table or the attribute certicate table is corrupted.
2069 Status
= EFI_ACCESS_DENIED
;
2071 Status
= EFI_SUCCESS
;
2076 if (FilePathStr
!= NULL
) {
2077 FreePool(FilePathStr
);
2085 Provide verification service for signed images, which include both signature validation
2086 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
2087 MSFT Authenticode type signatures are supported.
2089 In this implementation, only verify external executables when in USER MODE.
2090 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
2092 The image verification policy is:
2093 If the image is signed,
2094 At least one valid signature or at least one hash value of the image must match a record
2095 in the security database "db", and no valid signature nor any hash value of the image may
2096 be reflected in the security database "dbx".
2097 Otherwise, the image is not signed,
2098 The SHA256 hash value of the image must match a record in the security database "db", and
2099 not be reflected in the security data base "dbx".
2101 Caution: This function may receive untrusted input.
2102 PE/COFF image is external input, so this function will validate its data structure
2103 within this image buffer before use.
2105 @param[in] AuthenticationStatus
2106 This is the authentication status returned from the security
2107 measurement services for the input file.
2108 @param[in] File This is a pointer to the device path of the file that is
2109 being dispatched. This will optionally be used for logging.
2110 @param[in] FileBuffer File buffer matches the input file device path.
2111 @param[in] FileSize Size of File buffer matches the input file device path.
2112 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
2114 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
2115 FileBuffer did authenticate, and the platform policy dictates
2116 that the DXE Foundation may use the file.
2117 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
2118 and non-NULL FileBuffer did authenticate, and the platform
2119 policy dictates that the DXE Foundation may execute the image in
2121 @retval EFI_OUT_RESOURCE Fail to allocate memory.
2122 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
2123 the platform policy dictates that File should be placed
2124 in the untrusted state. The image has been added to the file
2126 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
2127 authenticate, and the platform policy dictates that the DXE
2128 Foundation many not use File.
2133 DxeImageVerificationHandler (
2134 IN UINT32 AuthenticationStatus
,
2135 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
2136 IN VOID
*FileBuffer
,
2138 IN BOOLEAN BootPolicy
2143 EFI_IMAGE_DOS_HEADER
*DosHdr
;
2144 EFI_STATUS VerifyStatus
;
2145 EFI_SIGNATURE_LIST
*SignatureList
;
2146 UINTN SignatureListSize
;
2147 EFI_SIGNATURE_DATA
*Signature
;
2148 EFI_IMAGE_EXECUTION_ACTION Action
;
2149 WIN_CERTIFICATE
*WinCertificate
;
2154 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
2155 UINT32 NumberOfRvaAndSizes
;
2156 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
2157 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
2160 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
2164 SignatureList
= NULL
;
2165 SignatureListSize
= 0;
2166 WinCertificate
= NULL
;
2168 PkcsCertData
= NULL
;
2169 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
2170 Status
= EFI_ACCESS_DENIED
;
2171 VerifyStatus
= EFI_ACCESS_DENIED
;
2173 GetEfiGlobalVariable2 (EFI_AUDIT_MODE_NAME
, (VOID
**)&VarData
, NULL
);
2175 // Skip verification if AuditMode variable doesn't exist. AuditMode should always exist
2177 if (VarData
== NULL
) {
2180 AuditMode
= *VarData
;
2183 if (AuditMode
== AUDIT_MODE_ENABLE
) {
2184 return ImageVerificationInAuditMode(AuthenticationStatus
, File
, FileBuffer
, FileSize
, BootPolicy
);
2188 // Check the image type and get policy setting.
2190 switch (GetImageType (File
)) {
2193 Policy
= ALWAYS_EXECUTE
;
2196 case IMAGE_FROM_OPTION_ROM
:
2197 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
2200 case IMAGE_FROM_REMOVABLE_MEDIA
:
2201 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
2204 case IMAGE_FROM_FIXED_MEDIA
:
2205 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
2209 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
2213 // If policy is always/never execute, return directly.
2215 if (Policy
== ALWAYS_EXECUTE
) {
2217 } else if (Policy
== NEVER_EXECUTE
) {
2218 return EFI_ACCESS_DENIED
;
2222 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
2223 // violates the UEFI spec and has been removed.
2225 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
2226 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
2230 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&VarData
, NULL
);
2232 // Skip verification if SecureBoot variable doesn't exist.
2234 if (VarData
== NULL
) {
2237 SecureBoot
= *VarData
;
2241 // Skip verification if SecureBoot is disabled but not AuditMode
2243 if (SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
2248 // Read the Dos header.
2250 if (FileBuffer
== NULL
) {
2251 return EFI_INVALID_PARAMETER
;
2254 mImageBase
= (UINT8
*) FileBuffer
;
2255 mImageSize
= FileSize
;
2257 ZeroMem (&ImageContext
, sizeof (ImageContext
));
2258 ImageContext
.Handle
= (VOID
*) FileBuffer
;
2259 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
2262 // Get information about the image being loaded
2264 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
2265 if (EFI_ERROR (Status
)) {
2267 // The information can't be got from the invalid PeImage
2272 Status
= EFI_ACCESS_DENIED
;
2274 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
2275 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
2277 // DOS image header is present,
2278 // so read the PE header after the DOS image header.
2280 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
2282 mPeCoffHeaderOffset
= 0;
2285 // Check PE/COFF image.
2287 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
2288 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
2290 // It is not a valid Pe/Coff file.
2295 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
2297 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
2298 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
2299 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
2300 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
2302 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
2305 // Get the magic value from the PE/COFF Optional Header
2307 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
2310 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
2314 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
2315 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
2316 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
2320 // Use PE32+ offset.
2322 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
2323 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
2324 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
2329 // Start Image Validation.
2331 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
2333 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
2334 // and not be reflected in the security data base "dbx".
2336 if (!HashPeImage (HASHALG_SHA256
)) {
2340 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
2342 // Image Hash is in forbidden database (DBX).
2347 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
2349 // Image Hash is in allowed database (DB).
2355 // Image Hash is not found in both forbidden and allowed database.
2361 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
2362 // "Attribute Certificate Table".
2363 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
2365 for (OffSet
= SecDataDir
->VirtualAddress
;
2366 OffSet
< (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
);
2367 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
2368 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
2369 if ((SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) <= sizeof (WIN_CERTIFICATE
) ||
2370 (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) < WinCertificate
->dwLength
) {
2375 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
2377 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
2379 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
2380 // Authenticode specification.
2382 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
2383 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
2386 AuthData
= PkcsCertData
->CertData
;
2387 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
2388 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
2390 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
2392 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
2393 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
2396 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
2399 AuthData
= WinCertUefiGuid
->CertData
;
2400 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
2402 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
2408 Status
= HashPeImageByType (AuthData
, AuthDataSize
);
2409 if (EFI_ERROR (Status
)) {
2414 // Check the digital signature against the revoked certificate in forbidden database (dbx).
2416 if (IsForbiddenByDbx (AuthData
, AuthDataSize
, FALSE
, NULL
, NULL
)) {
2417 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
2418 VerifyStatus
= EFI_ACCESS_DENIED
;
2423 // Check the digital signature against the valid certificate in allowed database (db).
2425 if (EFI_ERROR (VerifyStatus
)) {
2426 if (IsAllowedByDb (AuthData
, AuthDataSize
, FALSE
, NULL
, NULL
)) {
2427 VerifyStatus
= EFI_SUCCESS
;
2432 // Check the image's hash value.
2434 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
2435 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
2436 VerifyStatus
= EFI_ACCESS_DENIED
;
2438 } else if (EFI_ERROR (VerifyStatus
)) {
2439 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
2440 VerifyStatus
= EFI_SUCCESS
;
2445 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
2447 // The Size in Certificate Table or the attribute certicate table is corrupted.
2449 VerifyStatus
= EFI_ACCESS_DENIED
;
2452 if (!EFI_ERROR (VerifyStatus
)) {
2455 Status
= EFI_ACCESS_DENIED
;
2456 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
2458 // Get image hash value as executable's signature.
2460 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
2461 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
2462 if (SignatureList
== NULL
) {
2463 Status
= EFI_OUT_OF_RESOURCES
;
2466 SignatureList
->SignatureHeaderSize
= 0;
2467 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
2468 SignatureList
->SignatureSize
= (UINT32
) (sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
);
2469 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
2470 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
2471 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
2476 if (Status
!= EFI_SUCCESS
) {
2478 // Policy decides to defer or reject the image; add its information in image executable information table.
2480 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
2481 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
2482 if (NameStr
!= NULL
) {
2483 DEBUG((EFI_D_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
2486 Status
= EFI_SECURITY_VIOLATION
;
2489 if (SignatureList
!= NULL
) {
2490 FreePool (SignatureList
);
2497 On Ready To Boot Services Event notification handler.
2499 Add the image execution information table if it is not in system configuration table.
2501 @param[in] Event Event whose notification function is being invoked
2502 @param[in] Context Pointer to the notification function's context
2512 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
2513 UINTN ImageExeInfoTableSize
;
2515 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
2516 if (ImageExeInfoTable
!= NULL
) {
2520 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
2521 ImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
);
2522 if (ImageExeInfoTable
== NULL
) {
2526 ImageExeInfoTable
->NumberOfImages
= 0;
2527 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) ImageExeInfoTable
);
2532 Register security measurement handler.
2534 @param ImageHandle ImageHandle of the loaded driver.
2535 @param SystemTable Pointer to the EFI System Table.
2537 @retval EFI_SUCCESS The handlers were registered successfully.
2541 DxeImageVerificationLibConstructor (
2542 IN EFI_HANDLE ImageHandle
,
2543 IN EFI_SYSTEM_TABLE
*SystemTable
2549 // Register the event to publish the image execution table.
2551 EfiCreateEventReadyToBootEx (
2558 return RegisterSecurity2Handler (
2559 DxeImageVerificationHandler
,
2560 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED