2 Implement image verification services for secure boot service
4 Caution: This file requires additional review when modified.
5 This library will have external input - PE/COFF image.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
9 DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content
10 read is within the image buffer.
12 DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept
13 untrusted PE/COFF image and validate its data structure within this image buffer before use.
15 Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
16 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
17 SPDX-License-Identifier: BSD-2-Clause-Patent
21 #include "DxeImageVerificationLib.h"
24 // Caution: This is used by a function which may receive untrusted input.
25 // These global variables hold PE/COFF image data, and they should be validated before use.
27 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
28 UINT32 mPeCoffHeaderOffset
;
32 // Information on current PE/COFF image
35 UINT8
*mImageBase
= NULL
;
36 UINT8 mImageDigest
[MAX_DIGEST_SIZE
];
37 UINTN mImageDigestSize
;
40 // Notify string for authorization UI.
42 CHAR16 mNotifyString1
[MAX_NOTIFY_STRING_LEN
] = L
"Image verification pass but not found in authorized database!";
43 CHAR16 mNotifyString2
[MAX_NOTIFY_STRING_LEN
] = L
"Launch this image anyway? (Yes/Defer/No)";
45 // Public Exponent of RSA Key.
47 CONST UINT8 mRsaE
[] = { 0x01, 0x00, 0x01 };
51 // OID ASN.1 Value for Hash Algorithms
53 UINT8 mHashOidValue
[] = {
54 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
55 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
56 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
57 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
58 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
61 HASH_TABLE mHash
[] = {
62 #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES
63 { L
"SHA1", 20, &mHashOidValue
[0], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
65 { L
"SHA1", 20, &mHashOidValue
[0], 5, NULL
, NULL
, NULL
, NULL
},
67 { L
"SHA224", 28, &mHashOidValue
[5], 9, NULL
, NULL
, NULL
, NULL
},
68 { L
"SHA256", 32, &mHashOidValue
[14], 9, Sha256GetContextSize
, Sha256Init
, Sha256Update
, Sha256Final
},
69 { L
"SHA384", 48, &mHashOidValue
[23], 9, Sha384GetContextSize
, Sha384Init
, Sha384Update
, Sha384Final
},
70 { L
"SHA512", 64, &mHashOidValue
[32], 9, Sha512GetContextSize
, Sha512Init
, Sha512Update
, Sha512Final
}
73 EFI_STRING mHashTypeStr
;
76 SecureBoot Hook for processing image verification.
78 @param[in] VariableName Name of Variable to be found.
79 @param[in] VendorGuid Variable vendor GUID.
80 @param[in] DataSize Size of Data found. If size is less than the
81 data, this value contains the required size.
82 @param[in] Data Data pointer.
88 IN CHAR16
*VariableName
,
89 IN EFI_GUID
*VendorGuid
,
95 Reads contents of a PE/COFF image in memory buffer.
97 Caution: This function may receive untrusted input.
98 PE/COFF image is external input, so this function will make sure the PE/COFF image content
99 read is within the image buffer.
101 @param FileHandle Pointer to the file handle to read the PE/COFF image.
102 @param FileOffset Offset into the PE/COFF image to begin the read operation.
103 @param ReadSize On input, the size in bytes of the requested read operation.
104 On output, the number of bytes actually read.
105 @param Buffer Output buffer that contains the data read from the PE/COFF image.
107 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
111 DxeImageVerificationLibImageRead (
114 IN OUT UINTN
*ReadSize
,
120 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
121 return EFI_INVALID_PARAMETER
;
124 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
125 return EFI_INVALID_PARAMETER
;
128 EndPosition
= FileOffset
+ *ReadSize
;
129 if (EndPosition
> mImageSize
) {
130 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
133 if (FileOffset
>= mImageSize
) {
137 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
146 @param[in] File This is a pointer to the device path of the file that is
149 @return UINT32 Image Type
154 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
158 EFI_HANDLE DeviceHandle
;
159 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
160 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
163 return IMAGE_UNKNOWN
;
167 // First check to see if File is from a Firmware Volume
170 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
171 Status
= gBS
->LocateDevicePath (
172 &gEfiFirmwareVolume2ProtocolGuid
,
176 if (!EFI_ERROR (Status
)) {
177 Status
= gBS
->OpenProtocol (
179 &gEfiFirmwareVolume2ProtocolGuid
,
183 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
185 if (!EFI_ERROR (Status
)) {
186 return IMAGE_FROM_FV
;
191 // Next check to see if File is from a Block I/O device
194 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
195 Status
= gBS
->LocateDevicePath (
196 &gEfiBlockIoProtocolGuid
,
200 if (!EFI_ERROR (Status
)) {
202 Status
= gBS
->OpenProtocol (
204 &gEfiBlockIoProtocolGuid
,
208 EFI_OPEN_PROTOCOL_GET_PROTOCOL
210 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
211 if (BlockIo
->Media
!= NULL
) {
212 if (BlockIo
->Media
->RemovableMedia
) {
214 // Block I/O is present and specifies the media is removable
216 return IMAGE_FROM_REMOVABLE_MEDIA
;
219 // Block I/O is present and specifies the media is not removable
221 return IMAGE_FROM_FIXED_MEDIA
;
228 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
229 // the device path supports the Simple File System Protocol.
232 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
233 Status
= gBS
->LocateDevicePath (
234 &gEfiSimpleFileSystemProtocolGuid
,
238 if (!EFI_ERROR (Status
)) {
240 // Simple File System is present without Block I/O, so assume media is fixed.
242 return IMAGE_FROM_FIXED_MEDIA
;
246 // File is not from an FV, Block I/O or Simple File System, so the only options
247 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
249 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
250 while (!IsDevicePathEndType (TempDevicePath
)) {
251 switch (DevicePathType (TempDevicePath
)) {
253 case MEDIA_DEVICE_PATH
:
254 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
255 return IMAGE_FROM_OPTION_ROM
;
259 case MESSAGING_DEVICE_PATH
:
260 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
261 return IMAGE_FROM_REMOVABLE_MEDIA
;
268 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
270 return IMAGE_UNKNOWN
;
274 Calculate hash of Pe/Coff image based on the authenticode image hashing in
275 PE/COFF Specification 8.0 Appendix A
277 Caution: This function may receive untrusted input.
278 PE/COFF image is external input, so this function will validate its data structure
279 within this image buffer before use.
281 Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
282 its caller function DxeImageVerificationHandler().
284 @param[in] HashAlg Hash algorithm type.
286 @retval TRUE Successfully hash image.
287 @retval FALSE Fail in hash image.
296 EFI_IMAGE_SECTION_HEADER
*Section
;
301 UINTN SumOfBytesHashed
;
302 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
306 UINT32 NumberOfRvaAndSizes
;
309 SectionHeader
= NULL
;
312 if ((HashAlg
>= HASHALG_MAX
)) {
317 // Initialize context of hash.
319 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
322 #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES
324 mImageDigestSize
= SHA1_DIGEST_SIZE
;
325 mCertType
= gEfiCertSha1Guid
;
330 mImageDigestSize
= SHA256_DIGEST_SIZE
;
331 mCertType
= gEfiCertSha256Guid
;
335 mImageDigestSize
= SHA384_DIGEST_SIZE
;
336 mCertType
= gEfiCertSha384Guid
;
340 mImageDigestSize
= SHA512_DIGEST_SIZE
;
341 mCertType
= gEfiCertSha512Guid
;
348 mHashTypeStr
= mHash
[HashAlg
].Name
;
349 CtxSize
= mHash
[HashAlg
].GetContextSize();
351 HashCtx
= AllocatePool (CtxSize
);
352 if (HashCtx
== NULL
) {
356 // 1. Load the image header into memory.
358 // 2. Initialize a SHA hash context.
359 Status
= mHash
[HashAlg
].HashInit(HashCtx
);
366 // Measuring PE/COFF Image Header;
367 // But CheckSum field and SECURITY data directory (certificate) are excluded
371 // 3. Calculate the distance from the base of the image header to the image checksum address.
372 // 4. Hash the image header from its base to beginning of the image checksum.
374 HashBase
= mImageBase
;
375 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
379 HashSize
= (UINTN
) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - (UINTN
) HashBase
;
380 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
381 } else if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
385 HashSize
= (UINTN
) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - (UINTN
) HashBase
;
386 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
389 // Invalid header magic number.
395 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
401 // 5. Skip over the image checksum (it occupies a single ULONG).
403 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
405 // 6. Since there is no Cert Directory in optional header, hash everything
406 // from the end of the checksum to the end of image header.
408 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
412 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
413 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
418 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
419 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
423 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
430 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
432 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
436 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
437 HashSize
= (UINTN
) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - (UINTN
) HashBase
;
442 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
443 HashSize
= (UINTN
) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - (UINTN
) HashBase
;
447 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
454 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
455 // 9. Hash everything from the end of the Cert Directory to the end of image header.
457 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
461 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
462 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
467 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
468 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- ((UINTN
) HashBase
- (UINTN
) mImageBase
);
472 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
480 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
482 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
486 SumOfBytesHashed
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
;
491 SumOfBytesHashed
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
495 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
497 mPeCoffHeaderOffset
+
499 sizeof (EFI_IMAGE_FILE_HEADER
) +
500 mNtHeader
.Pe32
->FileHeader
.SizeOfOptionalHeader
504 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
505 // structures in the image. The 'NumberOfSections' field of the image
506 // header indicates how big the table should be. Do not include any
507 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
509 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * mNtHeader
.Pe32
->FileHeader
.NumberOfSections
);
510 if (SectionHeader
== NULL
) {
515 // 12. Using the 'PointerToRawData' in the referenced section headers as
516 // a key, arrange the elements in the table in ascending order. In other
517 // words, sort the section headers according to the disk-file offset of
520 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
522 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
523 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
526 CopyMem (&SectionHeader
[Pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
531 // 13. Walk through the sorted table, bring the corresponding section
532 // into memory, and hash the entire section (using the 'SizeOfRawData'
533 // field in the section header to determine the amount of data to hash).
534 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
535 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
537 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
538 Section
= &SectionHeader
[Index
];
539 if (Section
->SizeOfRawData
== 0) {
542 HashBase
= mImageBase
+ Section
->PointerToRawData
;
543 HashSize
= (UINTN
) Section
->SizeOfRawData
;
545 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
550 SumOfBytesHashed
+= HashSize
;
554 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
555 // data in the file that needs to be added to the hash. This data begins
556 // at file offset SUM_OF_BYTES_HASHED and its length is:
557 // FileSize - (CertDirectory->Size)
559 if (mImageSize
> SumOfBytesHashed
) {
560 HashBase
= mImageBase
+ SumOfBytesHashed
;
562 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
565 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
569 CertSize
= mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
574 CertSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
578 if (mImageSize
> CertSize
+ SumOfBytesHashed
) {
579 HashSize
= (UINTN
) (mImageSize
- CertSize
- SumOfBytesHashed
);
581 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
585 } else if (mImageSize
< CertSize
+ SumOfBytesHashed
) {
591 Status
= mHash
[HashAlg
].HashFinal(HashCtx
, mImageDigest
);
594 if (HashCtx
!= NULL
) {
597 if (SectionHeader
!= NULL
) {
598 FreePool (SectionHeader
);
604 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
605 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
608 Caution: This function may receive untrusted input.
609 PE/COFF image is external input, so this function will validate its data structure
610 within this image buffer before use.
612 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
613 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
615 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
616 @retval EFI_SUCCESS Hash successfully.
622 IN UINTN AuthDataSize
627 for (Index
= 0; Index
< HASHALG_MAX
; Index
++) {
629 // Check the Hash algorithm in PE/COFF Authenticode.
630 // According to PKCS#7 Definition:
631 // SignedData ::= SEQUENCE {
633 // digestAlgorithms DigestAlgorithmIdentifiers,
634 // contentInfo ContentInfo,
636 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
637 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
638 // Fixed offset (+32) is calculated based on two bytes of length encoding.
640 if ((*(AuthData
+ 1) & TWO_BYTE_ENCODE
) != TWO_BYTE_ENCODE
) {
642 // Only support two bytes of Long Form of Length Encoding.
647 if (AuthDataSize
< 32 + mHash
[Index
].OidLength
) {
648 return EFI_UNSUPPORTED
;
651 if (CompareMem (AuthData
+ 32, mHash
[Index
].OidValue
, mHash
[Index
].OidLength
) == 0) {
656 if (Index
== HASHALG_MAX
) {
657 return EFI_UNSUPPORTED
;
661 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
663 if (!HashPeImage(Index
)) {
664 return EFI_UNSUPPORTED
;
672 Returns the size of a given image execution info table in bytes.
674 This function returns the size, in bytes, of the image execution info table specified by
675 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
677 @param ImageExeInfoTable A pointer to a image execution info table structure.
679 @retval 0 If ImageExeInfoTable is NULL.
680 @retval Others The size of a image execution info table in bytes.
684 GetImageExeInfoTableSize (
685 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
689 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoItem
;
692 if (ImageExeInfoTable
== NULL
) {
696 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoTable
+ sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
));
697 TotalSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
698 for (Index
= 0; Index
< ImageExeInfoTable
->NumberOfImages
; Index
++) {
699 TotalSize
+= ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
);
700 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoItem
+ ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
));
707 Create an Image Execution Information Table entry and add it to system configuration table.
709 @param[in] Action Describes the action taken by the firmware regarding this image.
710 @param[in] Name Input a null-terminated, user-friendly name.
711 @param[in] DevicePath Input device path pointer.
712 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
713 @param[in] SignatureSize Size of signature. Must be zero if Signature is NULL.
718 IN EFI_IMAGE_EXECUTION_ACTION Action
,
719 IN CHAR16
*Name OPTIONAL
,
720 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
,
721 IN EFI_SIGNATURE_LIST
*Signature OPTIONAL
,
722 IN UINTN SignatureSize
725 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
726 EFI_IMAGE_EXECUTION_INFO_TABLE
*NewImageExeInfoTable
;
727 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoEntry
;
728 UINTN ImageExeInfoTableSize
;
729 UINTN NewImageExeInfoEntrySize
;
731 UINTN DevicePathSize
;
734 ImageExeInfoTable
= NULL
;
735 NewImageExeInfoTable
= NULL
;
736 ImageExeInfoEntry
= NULL
;
740 if (DevicePath
== NULL
) {
745 NameStringLen
= StrSize (Name
);
747 NameStringLen
= sizeof (CHAR16
);
750 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
751 if (ImageExeInfoTable
!= NULL
) {
753 // The table has been found!
754 // We must enlarge the table to accommodate the new exe info entry.
756 ImageExeInfoTableSize
= GetImageExeInfoTableSize (ImageExeInfoTable
);
760 // We should create a new table to append to the configuration table.
762 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
765 DevicePathSize
= GetDevicePathSize (DevicePath
);
768 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
770 ASSERT (Signature
!= NULL
|| SignatureSize
== 0);
771 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
773 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
774 if (NewImageExeInfoTable
== NULL
) {
778 if (ImageExeInfoTable
!= NULL
) {
779 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
781 NewImageExeInfoTable
->NumberOfImages
= 0;
783 NewImageExeInfoTable
->NumberOfImages
++;
784 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
786 // Update new item's information.
788 WriteUnaligned32 ((UINT32
*) ImageExeInfoEntry
, Action
);
789 WriteUnaligned32 ((UINT32
*) ((UINT8
*) ImageExeInfoEntry
+ sizeof (EFI_IMAGE_EXECUTION_ACTION
)), (UINT32
) NewImageExeInfoEntrySize
);
791 NameStr
= (CHAR16
*)(ImageExeInfoEntry
+ 1);
793 CopyMem ((UINT8
*) NameStr
, Name
, NameStringLen
);
795 ZeroMem ((UINT8
*) NameStr
, sizeof (CHAR16
));
799 (UINT8
*) NameStr
+ NameStringLen
,
803 if (Signature
!= NULL
) {
805 (UINT8
*) NameStr
+ NameStringLen
+ DevicePathSize
,
811 // Update/replace the image execution table.
813 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
816 // Free Old table data!
818 if (ImageExeInfoTable
!= NULL
) {
819 FreePool (ImageExeInfoTable
);
824 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
826 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
827 @param[in] CertSize Size of X.509 Certificate.
828 @param[in] SignatureList Pointer to the Signature List in forbidden database.
829 @param[in] SignatureListSize Size of Signature List.
830 @param[out] RevocationTime Return the time that the certificate was revoked.
831 @param[out] IsFound Search result. Only valid if EFI_SUCCESS returned.
833 @retval EFI_SUCCESS Finished the search without any error.
834 @retval Others Error occurred in the search of database.
838 IsCertHashFoundInDbx (
839 IN UINT8
*Certificate
,
841 IN EFI_SIGNATURE_LIST
*SignatureList
,
842 IN UINTN SignatureListSize
,
843 OUT EFI_TIME
*RevocationTime
,
848 EFI_SIGNATURE_LIST
*DbxList
;
850 EFI_SIGNATURE_DATA
*CertHash
;
855 UINT8 CertDigest
[MAX_DIGEST_SIZE
];
857 UINTN SiglistHeaderSize
;
861 Status
= EFI_ABORTED
;
863 DbxList
= SignatureList
;
864 DbxSize
= SignatureListSize
;
866 HashAlg
= HASHALG_MAX
;
868 if ((RevocationTime
== NULL
) || (DbxList
== NULL
)) {
869 return EFI_INVALID_PARAMETER
;
873 // Retrieve the TBSCertificate from the X.509 Certificate.
875 if (!X509GetTBSCert (Certificate
, CertSize
, &TBSCert
, &TBSCertSize
)) {
879 while ((DbxSize
> 0) && (SignatureListSize
>= DbxList
->SignatureListSize
)) {
881 // Determine Hash Algorithm of Certificate in the forbidden database.
883 if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha256Guid
)) {
884 HashAlg
= HASHALG_SHA256
;
885 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha384Guid
)) {
886 HashAlg
= HASHALG_SHA384
;
887 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha512Guid
)) {
888 HashAlg
= HASHALG_SHA512
;
890 DbxSize
-= DbxList
->SignatureListSize
;
891 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
896 // Calculate the hash value of current TBSCertificate for comparision.
898 if (mHash
[HashAlg
].GetContextSize
== NULL
) {
901 ZeroMem (CertDigest
, MAX_DIGEST_SIZE
);
902 HashCtx
= AllocatePool (mHash
[HashAlg
].GetContextSize ());
903 if (HashCtx
== NULL
) {
906 if (!mHash
[HashAlg
].HashInit (HashCtx
)) {
909 if (!mHash
[HashAlg
].HashUpdate (HashCtx
, TBSCert
, TBSCertSize
)) {
912 if (!mHash
[HashAlg
].HashFinal (HashCtx
, CertDigest
)) {
919 SiglistHeaderSize
= sizeof (EFI_SIGNATURE_LIST
) + DbxList
->SignatureHeaderSize
;
920 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) DbxList
+ SiglistHeaderSize
);
921 CertHashCount
= (DbxList
->SignatureListSize
- SiglistHeaderSize
) / DbxList
->SignatureSize
;
922 for (Index
= 0; Index
< CertHashCount
; Index
++) {
924 // Iterate each Signature Data Node within this CertList for verify.
926 DbxCertHash
= CertHash
->SignatureData
;
927 if (CompareMem (DbxCertHash
, CertDigest
, mHash
[HashAlg
].DigestLength
) == 0) {
929 // Hash of Certificate is found in forbidden database.
931 Status
= EFI_SUCCESS
;
935 // Return the revocation time.
937 CopyMem (RevocationTime
, (EFI_TIME
*)(DbxCertHash
+ mHash
[HashAlg
].DigestLength
), sizeof (EFI_TIME
));
940 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertHash
+ DbxList
->SignatureSize
);
943 DbxSize
-= DbxList
->SignatureListSize
;
944 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
947 Status
= EFI_SUCCESS
;
950 if (HashCtx
!= NULL
) {
958 Check whether signature is in specified database.
960 @param[in] VariableName Name of database variable that is searched in.
961 @param[in] Signature Pointer to signature that is searched for.
962 @param[in] CertType Pointer to hash algorithm.
963 @param[in] SignatureSize Size of Signature.
964 @param[out] IsFound Search result. Only valid if EFI_SUCCESS returned
966 @retval EFI_SUCCESS Finished the search without any error.
967 @retval Others Error occurred in the search of database.
971 IsSignatureFoundInDatabase (
972 IN CHAR16
*VariableName
,
974 IN EFI_GUID
*CertType
,
975 IN UINTN SignatureSize
,
980 EFI_SIGNATURE_LIST
*CertList
;
981 EFI_SIGNATURE_DATA
*Cert
;
988 // Read signature database variable.
993 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
994 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
995 if (Status
== EFI_NOT_FOUND
) {
997 // No database, no need to search.
999 Status
= EFI_SUCCESS
;
1005 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1007 return EFI_OUT_OF_RESOURCES
;
1010 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
1011 if (EFI_ERROR (Status
)) {
1015 // Enumerate all signature data in SigDB to check if signature exists for executable.
1017 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1018 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1019 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1020 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1021 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
1022 for (Index
= 0; Index
< CertCount
; Index
++) {
1023 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
1025 // Find the signature in database.
1029 // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured
1031 if (StrCmp(VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) {
1032 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1037 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1045 DataSize
-= CertList
->SignatureListSize
;
1046 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1058 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1060 @param SigningTime A pointer to the signing time.
1061 @param RevocationTime A pointer to the revocation time.
1063 @retval TRUE The SigningTime is not later than the RevocationTime.
1064 @retval FALSE The SigningTime is later than the RevocationTime.
1068 IsValidSignatureByTimestamp (
1069 IN EFI_TIME
*SigningTime
,
1070 IN EFI_TIME
*RevocationTime
1073 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1074 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1075 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1076 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1077 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1078 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1079 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1080 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1081 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1082 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1085 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1089 Check if the given time value is zero.
1091 @param[in] Time Pointer of a time value.
1093 @retval TRUE The Time is Zero.
1094 @retval FALSE The Time is not Zero.
1102 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1103 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1111 Check whether the timestamp signature is valid and the signing time is also earlier than
1112 the revocation time.
1114 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1115 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1116 @param[in] RevocationTime The time that the certificate was revoked.
1118 @retval TRUE Timestamp signature is valid and signing time is no later than the
1120 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1125 PassTimestampCheck (
1127 IN UINTN AuthDataSize
,
1128 IN EFI_TIME
*RevocationTime
1132 BOOLEAN VerifyStatus
;
1133 EFI_SIGNATURE_LIST
*CertList
;
1134 EFI_SIGNATURE_DATA
*Cert
;
1141 EFI_TIME SigningTime
;
1144 // Variable Initialization
1146 VerifyStatus
= FALSE
;
1154 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1156 if (IsTimeZero (RevocationTime
)) {
1161 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1162 // Using the dbt to get the trusted TSA certificates.
1165 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1166 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1169 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1170 if (DbtData
== NULL
) {
1173 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1174 if (EFI_ERROR (Status
)) {
1178 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1179 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1180 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1181 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1182 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1183 for (Index
= 0; Index
< CertCount
; Index
++) {
1185 // Iterate each Signature Data Node within this CertList for verify.
1187 RootCert
= Cert
->SignatureData
;
1188 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1190 // Get the signing time if the timestamp signature is valid.
1192 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1194 // The signer signature is valid only when the signing time is earlier than revocation time.
1196 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1197 VerifyStatus
= TRUE
;
1201 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1204 DbtDataSize
-= CertList
->SignatureListSize
;
1205 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1209 if (DbtData
!= NULL
) {
1213 return VerifyStatus
;
1217 Check whether the image signature is forbidden by the forbidden database (dbx).
1218 The image is forbidden to load if any certificates for signing are revoked before signing time.
1220 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1221 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1223 @retval TRUE Image is forbidden by dbx.
1224 @retval FALSE Image is not forbidden by dbx.
1230 IN UINTN AuthDataSize
1234 BOOLEAN IsForbidden
;
1238 EFI_SIGNATURE_LIST
*CertList
;
1240 EFI_SIGNATURE_DATA
*CertData
;
1248 UINTN TrustedCertLength
;
1253 EFI_TIME RevocationTime
;
1255 // Variable Initialization
1267 TrustedCertLength
= 0;
1270 // The image will not be forbidden if dbx can't be got.
1273 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1274 ASSERT (EFI_ERROR (Status
));
1275 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1276 if (Status
== EFI_NOT_FOUND
) {
1278 // Evidently not in dbx if the database doesn't exist.
1280 IsForbidden
= FALSE
;
1284 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1289 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1290 if (EFI_ERROR (Status
)) {
1295 // Verify image signature with RAW X509 certificates in DBX database.
1296 // If passed, the image will be forbidden.
1298 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1299 CertListSize
= DataSize
;
1300 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1301 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1302 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1303 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1305 for (Index
= 0; Index
< CertCount
; Index
++) {
1307 // Iterate each Signature Data Node within this CertList for verify.
1309 RootCert
= CertData
->SignatureData
;
1310 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1313 // Call AuthenticodeVerify library to Verify Authenticode struct.
1315 IsForbidden
= AuthenticodeVerify (
1324 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1328 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1332 CertListSize
-= CertList
->SignatureListSize
;
1333 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1337 // Check X.509 Certificate Hash & Possible Timestamp.
1341 // Retrieve the certificate stack from AuthData
1342 // The output CertStack format will be:
1343 // UINT8 CertNumber;
1344 // UINT32 Cert1Length;
1346 // UINT32 Cert2Length;
1349 // UINT32 CertnLength;
1352 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1353 if ((BufferLength
== 0) || (CertBuffer
== NULL
) || (*CertBuffer
) == 0) {
1359 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1361 CertNumber
= (UINT8
) (*CertBuffer
);
1362 CertPtr
= CertBuffer
+ 1;
1363 for (Index
= 0; Index
< CertNumber
; Index
++) {
1364 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1365 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1367 // Advance CertPtr to the next cert in image signer's cert list
1369 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1371 Status
= IsCertHashFoundInDbx (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
, &IsFound
);
1372 if (EFI_ERROR (Status
)) {
1374 // Error in searching dbx. Consider it as 'found'. RevocationTime might
1375 // not be valid in such situation.
1378 } else if (IsFound
) {
1380 // Found Cert in dbx successfully. Check the timestamp signature and
1381 // signing time to determine if the image can be trusted.
1383 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1384 IsForbidden
= FALSE
;
1386 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1391 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1398 IsForbidden
= FALSE
;
1405 Pkcs7FreeSigners (CertBuffer
);
1406 Pkcs7FreeSigners (TrustedCert
);
1413 Check whether the image signature can be verified by the trusted certificates in DB database.
1415 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1416 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1418 @retval TRUE Image passed verification using certificate in db.
1419 @retval FALSE Image didn't pass verification using certificate in db.
1425 IN UINTN AuthDataSize
1429 BOOLEAN VerifyStatus
;
1431 EFI_SIGNATURE_LIST
*CertList
;
1432 EFI_SIGNATURE_DATA
*CertData
;
1441 EFI_TIME RevocationTime
;
1449 VerifyStatus
= FALSE
;
1452 // Fetch 'db' content. If 'db' doesn't exist or encounters problem to get the
1453 // data, return not-allowed-by-db (FALSE).
1456 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1457 ASSERT (EFI_ERROR (Status
));
1458 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1459 return VerifyStatus
;
1462 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1464 return VerifyStatus
;
1467 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1468 if (EFI_ERROR (Status
)) {
1473 // Fetch 'dbx' content. If 'dbx' doesn't exist, continue to check 'db'.
1474 // If any other errors occurred, no need to check 'db' but just return
1475 // not-allowed-by-db (FALSE) to avoid bypass.
1478 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1479 ASSERT (EFI_ERROR (Status
));
1480 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1481 if (Status
!= EFI_NOT_FOUND
) {
1485 // 'dbx' does not exist. Continue to check 'db'.
1489 // 'dbx' exists. Get its content.
1491 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1492 if (DbxData
== NULL
) {
1496 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1497 if (EFI_ERROR (Status
)) {
1503 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1505 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1506 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1507 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1508 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1509 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1511 for (Index
= 0; Index
< CertCount
; Index
++) {
1513 // Iterate each Signature Data Node within this CertList for verify.
1515 RootCert
= CertData
->SignatureData
;
1516 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1519 // Call AuthenticodeVerify library to Verify Authenticode struct.
1521 VerifyStatus
= AuthenticodeVerify (
1531 // The image is signed and its signature is found in 'db'.
1533 if (DbxData
!= NULL
) {
1535 // Here We still need to check if this RootCert's Hash is revoked
1537 Status
= IsCertHashFoundInDbx (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
, &IsFound
);
1538 if (EFI_ERROR (Status
)) {
1540 // Error in searching dbx. Consider it as 'found'. RevocationTime might
1541 // not be valid in such situation.
1543 VerifyStatus
= FALSE
;
1544 } else if (IsFound
) {
1546 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1548 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1549 if (!VerifyStatus
) {
1550 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1556 // There's no 'dbx' to check revocation time against (must-be pass),
1557 // or, there's revocation time found in 'dbx' and checked againt 'dbt'
1558 // (maybe pass or fail, depending on timestamp compare result). Either
1559 // way the verification job has been completed at this point.
1564 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1568 DataSize
-= CertList
->SignatureListSize
;
1569 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1575 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1581 if (DbxData
!= NULL
) {
1585 return VerifyStatus
;
1589 Provide verification service for signed images, which include both signature validation
1590 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1591 MSFT Authenticode type signatures are supported.
1593 In this implementation, only verify external executables when in USER MODE.
1594 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1596 The image verification policy is:
1597 If the image is signed,
1598 At least one valid signature or at least one hash value of the image must match a record
1599 in the security database "db", and no valid signature nor any hash value of the image may
1600 be reflected in the security database "dbx".
1601 Otherwise, the image is not signed,
1602 The SHA256 hash value of the image must match a record in the security database "db", and
1603 not be reflected in the security data base "dbx".
1605 Caution: This function may receive untrusted input.
1606 PE/COFF image is external input, so this function will validate its data structure
1607 within this image buffer before use.
1609 @param[in] AuthenticationStatus
1610 This is the authentication status returned from the security
1611 measurement services for the input file.
1612 @param[in] File This is a pointer to the device path of the file that is
1613 being dispatched. This will optionally be used for logging.
1614 @param[in] FileBuffer File buffer matches the input file device path.
1615 @param[in] FileSize Size of File buffer matches the input file device path.
1616 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1618 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1619 FileBuffer did authenticate, and the platform policy dictates
1620 that the DXE Foundation may use the file.
1621 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1622 and non-NULL FileBuffer did authenticate, and the platform
1623 policy dictates that the DXE Foundation may execute the image in
1625 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1626 the platform policy dictates that File should be placed
1627 in the untrusted state. The image has been added to the file
1629 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1630 authenticate, and the platform policy dictates that the DXE
1631 Foundation may not use File. The image has
1632 been added to the file execution table.
1637 DxeImageVerificationHandler (
1638 IN UINT32 AuthenticationStatus
,
1639 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File OPTIONAL
,
1640 IN VOID
*FileBuffer
,
1642 IN BOOLEAN BootPolicy
1645 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1647 EFI_SIGNATURE_LIST
*SignatureList
;
1648 UINTN SignatureListSize
;
1649 EFI_SIGNATURE_DATA
*Signature
;
1650 EFI_IMAGE_EXECUTION_ACTION Action
;
1651 WIN_CERTIFICATE
*WinCertificate
;
1654 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1655 UINT32 NumberOfRvaAndSizes
;
1656 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1657 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1660 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1661 UINT32 SecDataDirEnd
;
1662 UINT32 SecDataDirLeft
;
1665 RETURN_STATUS PeCoffStatus
;
1666 EFI_STATUS HashStatus
;
1667 EFI_STATUS DbStatus
;
1670 SignatureList
= NULL
;
1671 SignatureListSize
= 0;
1672 WinCertificate
= NULL
;
1674 PkcsCertData
= NULL
;
1675 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1680 // Check the image type and get policy setting.
1682 switch (GetImageType (File
)) {
1685 Policy
= ALWAYS_EXECUTE
;
1688 case IMAGE_FROM_OPTION_ROM
:
1689 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1692 case IMAGE_FROM_REMOVABLE_MEDIA
:
1693 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1696 case IMAGE_FROM_FIXED_MEDIA
:
1697 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1701 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1705 // If policy is always/never execute, return directly.
1707 if (Policy
== ALWAYS_EXECUTE
) {
1710 if (Policy
== NEVER_EXECUTE
) {
1711 return EFI_ACCESS_DENIED
;
1715 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1716 // violates the UEFI spec and has been removed.
1718 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1719 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1723 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1725 // Skip verification if SecureBoot variable doesn't exist.
1727 if (SecureBoot
== NULL
) {
1732 // Skip verification if SecureBoot is disabled but not AuditMode
1734 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1735 FreePool (SecureBoot
);
1738 FreePool (SecureBoot
);
1741 // Read the Dos header.
1743 if (FileBuffer
== NULL
) {
1744 return EFI_ACCESS_DENIED
;
1747 mImageBase
= (UINT8
*) FileBuffer
;
1748 mImageSize
= FileSize
;
1750 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1751 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1752 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1755 // Get information about the image being loaded
1757 PeCoffStatus
= PeCoffLoaderGetImageInfo (&ImageContext
);
1758 if (RETURN_ERROR (PeCoffStatus
)) {
1760 // The information can't be got from the invalid PeImage
1762 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1766 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1767 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1769 // DOS image header is present,
1770 // so read the PE header after the DOS image header.
1772 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1774 mPeCoffHeaderOffset
= 0;
1777 // Check PE/COFF image.
1779 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1780 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1782 // It is not a valid Pe/Coff file.
1784 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1788 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1792 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1793 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1794 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1798 // Use PE32+ offset.
1800 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1801 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1802 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1807 // Start Image Validation.
1809 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
1811 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1812 // and not be reflected in the security data base "dbx".
1814 if (!HashPeImage (HASHALG_SHA256
)) {
1815 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr
));
1819 DbStatus
= IsSignatureFoundInDatabase (
1820 EFI_IMAGE_SECURITY_DATABASE1
,
1826 if (EFI_ERROR (DbStatus
) || IsFound
) {
1828 // Image Hash is in forbidden database (DBX).
1830 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr
));
1834 DbStatus
= IsSignatureFoundInDatabase (
1835 EFI_IMAGE_SECURITY_DATABASE
,
1841 if (!EFI_ERROR (DbStatus
) && IsFound
) {
1843 // Image Hash is in allowed database (DB).
1849 // Image Hash is not found in both forbidden and allowed database.
1851 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr
));
1856 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1857 // "Attribute Certificate Table".
1858 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1860 SecDataDirEnd
= SecDataDir
->VirtualAddress
+ SecDataDir
->Size
;
1861 for (OffSet
= SecDataDir
->VirtualAddress
;
1862 OffSet
< SecDataDirEnd
;
1863 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
1864 SecDataDirLeft
= SecDataDirEnd
- OffSet
;
1865 if (SecDataDirLeft
<= sizeof (WIN_CERTIFICATE
)) {
1868 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
1869 if (SecDataDirLeft
< WinCertificate
->dwLength
||
1870 (SecDataDirLeft
- WinCertificate
->dwLength
<
1871 ALIGN_SIZE (WinCertificate
->dwLength
))) {
1876 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1878 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1880 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1881 // Authenticode specification.
1883 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
1884 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
1887 AuthData
= PkcsCertData
->CertData
;
1888 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
1889 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
1891 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1893 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
1894 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
1897 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
1900 AuthData
= WinCertUefiGuid
->CertData
;
1901 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
1903 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
1909 HashStatus
= HashPeImageByType (AuthData
, AuthDataSize
);
1910 if (EFI_ERROR (HashStatus
)) {
1915 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1917 if (IsForbiddenByDbx (AuthData
, AuthDataSize
)) {
1918 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
1924 // Check the digital signature against the valid certificate in allowed database (db).
1927 if (IsAllowedByDb (AuthData
, AuthDataSize
)) {
1933 // Check the image's hash value.
1935 DbStatus
= IsSignatureFoundInDatabase (
1936 EFI_IMAGE_SECURITY_DATABASE1
,
1942 if (EFI_ERROR (DbStatus
) || IsFound
) {
1943 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
1944 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr
));
1950 DbStatus
= IsSignatureFoundInDatabase (
1951 EFI_IMAGE_SECURITY_DATABASE
,
1957 if (!EFI_ERROR (DbStatus
) && IsFound
) {
1960 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
));
1965 if (OffSet
!= SecDataDirEnd
) {
1967 // The Size in Certificate Table or the attribute certificate table is corrupted.
1975 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
1977 // Get image hash value as signature of executable.
1979 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1980 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1981 if (SignatureList
== NULL
) {
1982 SignatureListSize
= 0;
1985 SignatureList
->SignatureHeaderSize
= 0;
1986 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
1987 SignatureList
->SignatureSize
= (UINT32
) (sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
);
1988 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
1989 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
1990 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
1995 // Policy decides to defer or reject the image; add its information in image
1996 // executable information table in either case.
1998 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1999 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
2000 if (NameStr
!= NULL
) {
2001 DEBUG ((DEBUG_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
2005 if (SignatureList
!= NULL
) {
2006 FreePool (SignatureList
);
2009 if (Policy
== DEFER_EXECUTE_ON_SECURITY_VIOLATION
) {
2010 return EFI_SECURITY_VIOLATION
;
2012 return EFI_ACCESS_DENIED
;
2016 On Ready To Boot Services Event notification handler.
2018 Add the image execution information table if it is not in system configuration table.
2020 @param[in] Event Event whose notification function is being invoked
2021 @param[in] Context Pointer to the notification function's context
2031 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
2032 UINTN ImageExeInfoTableSize
;
2034 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
2035 if (ImageExeInfoTable
!= NULL
) {
2039 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
2040 ImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
);
2041 if (ImageExeInfoTable
== NULL
) {
2045 ImageExeInfoTable
->NumberOfImages
= 0;
2046 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) ImageExeInfoTable
);
2051 Register security measurement handler.
2053 @param ImageHandle ImageHandle of the loaded driver.
2054 @param SystemTable Pointer to the EFI System Table.
2056 @retval EFI_SUCCESS The handlers were registered successfully.
2060 DxeImageVerificationLibConstructor (
2061 IN EFI_HANDLE ImageHandle
,
2062 IN EFI_SYSTEM_TABLE
*SystemTable
2068 // Register the event to publish the image execution table.
2070 EfiCreateEventReadyToBootEx (
2077 return RegisterSecurity2Handler (
2078 DxeImageVerificationHandler
,
2079 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED