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 This program and the accompanying materials
18 are licensed and made available under the terms and conditions of the BSD License
19 which accompanies this distribution. The full text of the license may be found at
20 http://opensource.org/licenses/bsd-license.php
22 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
23 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
27 #include "DxeImageVerificationLib.h"
30 // Caution: This is used by a function which may receive untrusted input.
31 // These global variables hold PE/COFF image data, and they should be validated before use.
33 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
34 UINT32 mPeCoffHeaderOffset
;
38 // Information on current PE/COFF image
41 UINT8
*mImageBase
= NULL
;
42 UINT8 mImageDigest
[MAX_DIGEST_SIZE
];
43 UINTN mImageDigestSize
;
46 // Notify string for authorization UI.
48 CHAR16 mNotifyString1
[MAX_NOTIFY_STRING_LEN
] = L
"Image verification pass but not found in authorized database!";
49 CHAR16 mNotifyString2
[MAX_NOTIFY_STRING_LEN
] = L
"Launch this image anyway? (Yes/Defer/No)";
51 // Public Exponent of RSA Key.
53 CONST UINT8 mRsaE
[] = { 0x01, 0x00, 0x01 };
57 // OID ASN.1 Value for Hash Algorithms
59 UINT8 mHashOidValue
[] = {
60 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
61 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
64 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
67 HASH_TABLE mHash
[] = {
68 { L
"SHA1", 20, &mHashOidValue
[0], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
69 { L
"SHA224", 28, &mHashOidValue
[5], 9, NULL
, NULL
, NULL
, NULL
},
70 { L
"SHA256", 32, &mHashOidValue
[14], 9, Sha256GetContextSize
, Sha256Init
, Sha256Update
, Sha256Final
},
71 { L
"SHA384", 48, &mHashOidValue
[23], 9, Sha384GetContextSize
, Sha384Init
, Sha384Update
, Sha384Final
},
72 { L
"SHA512", 64, &mHashOidValue
[32], 9, Sha512GetContextSize
, Sha512Init
, Sha512Update
, Sha512Final
}
75 EFI_STRING mHashTypeStr
;
78 SecureBoot Hook for processing image verification.
80 @param[in] VariableName Name of Variable to be found.
81 @param[in] VendorGuid Variable vendor GUID.
82 @param[in] DataSize Size of Data found. If size is less than the
83 data, this value contains the required size.
84 @param[in] Data Data pointer.
90 IN CHAR16
*VariableName
,
91 IN EFI_GUID
*VendorGuid
,
97 Reads contents of a PE/COFF image in memory buffer.
99 Caution: This function may receive untrusted input.
100 PE/COFF image is external input, so this function will make sure the PE/COFF image content
101 read is within the image buffer.
103 @param FileHandle Pointer to the file handle to read the PE/COFF image.
104 @param FileOffset Offset into the PE/COFF image to begin the read operation.
105 @param ReadSize On input, the size in bytes of the requested read operation.
106 On output, the number of bytes actually read.
107 @param Buffer Output buffer that contains the data read from the PE/COFF image.
109 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
113 DxeImageVerificationLibImageRead (
116 IN OUT UINTN
*ReadSize
,
122 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
123 return EFI_INVALID_PARAMETER
;
126 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
127 return EFI_INVALID_PARAMETER
;
130 EndPosition
= FileOffset
+ *ReadSize
;
131 if (EndPosition
> mImageSize
) {
132 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
135 if (FileOffset
>= mImageSize
) {
139 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
148 @param[in] File This is a pointer to the device path of the file that is
151 @return UINT32 Image Type
156 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
160 EFI_HANDLE DeviceHandle
;
161 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
162 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
165 return IMAGE_UNKNOWN
;
169 // First check to see if File is from a Firmware Volume
172 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
173 Status
= gBS
->LocateDevicePath (
174 &gEfiFirmwareVolume2ProtocolGuid
,
178 if (!EFI_ERROR (Status
)) {
179 Status
= gBS
->OpenProtocol (
181 &gEfiFirmwareVolume2ProtocolGuid
,
185 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
187 if (!EFI_ERROR (Status
)) {
188 return IMAGE_FROM_FV
;
193 // Next check to see if File is from a Block I/O device
196 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
197 Status
= gBS
->LocateDevicePath (
198 &gEfiBlockIoProtocolGuid
,
202 if (!EFI_ERROR (Status
)) {
204 Status
= gBS
->OpenProtocol (
206 &gEfiBlockIoProtocolGuid
,
210 EFI_OPEN_PROTOCOL_GET_PROTOCOL
212 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
213 if (BlockIo
->Media
!= NULL
) {
214 if (BlockIo
->Media
->RemovableMedia
) {
216 // Block I/O is present and specifies the media is removable
218 return IMAGE_FROM_REMOVABLE_MEDIA
;
221 // Block I/O is present and specifies the media is not removable
223 return IMAGE_FROM_FIXED_MEDIA
;
230 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
231 // the device path supports the Simple File System Protocol.
234 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
235 Status
= gBS
->LocateDevicePath (
236 &gEfiSimpleFileSystemProtocolGuid
,
240 if (!EFI_ERROR (Status
)) {
242 // Simple File System is present without Block I/O, so assume media is fixed.
244 return IMAGE_FROM_FIXED_MEDIA
;
248 // File is not from an FV, Block I/O or Simple File System, so the only options
249 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
251 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
252 while (!IsDevicePathEndType (TempDevicePath
)) {
253 switch (DevicePathType (TempDevicePath
)) {
255 case MEDIA_DEVICE_PATH
:
256 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
257 return IMAGE_FROM_OPTION_ROM
;
261 case MESSAGING_DEVICE_PATH
:
262 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
263 return IMAGE_FROM_REMOVABLE_MEDIA
;
270 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
272 return IMAGE_UNKNOWN
;
276 Calculate hash of Pe/Coff image based on the authenticode image hashing in
277 PE/COFF Specification 8.0 Appendix A
279 Caution: This function may receive untrusted input.
280 PE/COFF image is external input, so this function will validate its data structure
281 within this image buffer before use.
283 Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
284 its caller function DxeImageVerificationHandler().
286 @param[in] HashAlg Hash algorithm type.
288 @retval TRUE Successfully hash image.
289 @retval FALSE Fail in hash image.
298 EFI_IMAGE_SECTION_HEADER
*Section
;
303 UINTN SumOfBytesHashed
;
304 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
308 UINT32 NumberOfRvaAndSizes
;
311 SectionHeader
= NULL
;
314 if ((HashAlg
>= HASHALG_MAX
)) {
319 // Initialize context of hash.
321 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
325 mImageDigestSize
= SHA1_DIGEST_SIZE
;
326 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.
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 accomodate 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 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
772 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
773 if (NewImageExeInfoTable
== NULL
) {
777 if (ImageExeInfoTable
!= NULL
) {
778 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
780 NewImageExeInfoTable
->NumberOfImages
= 0;
782 NewImageExeInfoTable
->NumberOfImages
++;
783 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
785 // Update new item's information.
787 WriteUnaligned32 ((UINT32
*) ImageExeInfoEntry
, Action
);
788 WriteUnaligned32 ((UINT32
*) ((UINT8
*) ImageExeInfoEntry
+ sizeof (EFI_IMAGE_EXECUTION_ACTION
)), (UINT32
) NewImageExeInfoEntrySize
);
790 NameStr
= (CHAR16
*)(ImageExeInfoEntry
+ 1);
792 CopyMem ((UINT8
*) NameStr
, Name
, NameStringLen
);
794 ZeroMem ((UINT8
*) NameStr
, sizeof (CHAR16
));
798 (UINT8
*) NameStr
+ NameStringLen
,
802 if (Signature
!= NULL
) {
804 (UINT8
*) NameStr
+ NameStringLen
+ DevicePathSize
,
810 // Update/replace the image execution table.
812 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
815 // Free Old table data!
817 if (ImageExeInfoTable
!= NULL
) {
818 FreePool (ImageExeInfoTable
);
823 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
825 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
826 @param[in] CertSize Size of X.509 Certificate.
827 @param[in] SignatureList Pointer to the Signature List in forbidden database.
828 @param[in] SignatureListSize Size of Signature List.
829 @param[out] RevocationTime Return the time that the certificate was revoked.
831 @return TRUE The certificate hash is found in the forbidden database.
832 @return FALSE The certificate hash is not found in the forbidden database.
836 IsCertHashFoundInDatabase (
837 IN UINT8
*Certificate
,
839 IN EFI_SIGNATURE_LIST
*SignatureList
,
840 IN UINTN SignatureListSize
,
841 OUT EFI_TIME
*RevocationTime
846 EFI_SIGNATURE_LIST
*DbxList
;
848 EFI_SIGNATURE_DATA
*CertHash
;
853 UINT8 CertDigest
[MAX_DIGEST_SIZE
];
855 UINTN SiglistHeaderSize
;
860 DbxList
= SignatureList
;
861 DbxSize
= SignatureListSize
;
863 HashAlg
= HASHALG_MAX
;
865 if ((RevocationTime
== NULL
) || (DbxList
== NULL
)) {
870 // Retrieve the TBSCertificate from the X.509 Certificate.
872 if (!X509GetTBSCert (Certificate
, CertSize
, &TBSCert
, &TBSCertSize
)) {
876 while ((DbxSize
> 0) && (SignatureListSize
>= DbxList
->SignatureListSize
)) {
878 // Determine Hash Algorithm of Certificate in the forbidden database.
880 if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha256Guid
)) {
881 HashAlg
= HASHALG_SHA256
;
882 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha384Guid
)) {
883 HashAlg
= HASHALG_SHA384
;
884 } else if (CompareGuid (&DbxList
->SignatureType
, &gEfiCertX509Sha512Guid
)) {
885 HashAlg
= HASHALG_SHA512
;
887 DbxSize
-= DbxList
->SignatureListSize
;
888 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
893 // Calculate the hash value of current TBSCertificate for comparision.
895 if (mHash
[HashAlg
].GetContextSize
== NULL
) {
898 ZeroMem (CertDigest
, MAX_DIGEST_SIZE
);
899 HashCtx
= AllocatePool (mHash
[HashAlg
].GetContextSize ());
900 if (HashCtx
== NULL
) {
903 Status
= mHash
[HashAlg
].HashInit (HashCtx
);
907 Status
= mHash
[HashAlg
].HashUpdate (HashCtx
, TBSCert
, TBSCertSize
);
911 Status
= mHash
[HashAlg
].HashFinal (HashCtx
, CertDigest
);
916 SiglistHeaderSize
= sizeof (EFI_SIGNATURE_LIST
) + DbxList
->SignatureHeaderSize
;
917 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) DbxList
+ SiglistHeaderSize
);
918 CertHashCount
= (DbxList
->SignatureListSize
- SiglistHeaderSize
) / DbxList
->SignatureSize
;
919 for (Index
= 0; Index
< CertHashCount
; Index
++) {
921 // Iterate each Signature Data Node within this CertList for verify.
923 DbxCertHash
= CertHash
->SignatureData
;
924 if (CompareMem (DbxCertHash
, CertDigest
, mHash
[HashAlg
].DigestLength
) == 0) {
926 // Hash of Certificate is found in forbidden database.
931 // Return the revocation time.
933 CopyMem (RevocationTime
, (EFI_TIME
*)(DbxCertHash
+ mHash
[HashAlg
].DigestLength
), sizeof (EFI_TIME
));
936 CertHash
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertHash
+ DbxList
->SignatureSize
);
939 DbxSize
-= DbxList
->SignatureListSize
;
940 DbxList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) DbxList
+ DbxList
->SignatureListSize
);
944 if (HashCtx
!= NULL
) {
952 Check whether signature is in specified database.
954 @param[in] VariableName Name of database variable that is searched in.
955 @param[in] Signature Pointer to signature that is searched for.
956 @param[in] CertType Pointer to hash algrithom.
957 @param[in] SignatureSize Size of Signature.
959 @return TRUE Found the signature in the variable database.
960 @return FALSE Not found the signature in the variable database.
964 IsSignatureFoundInDatabase (
965 IN CHAR16
*VariableName
,
967 IN EFI_GUID
*CertType
,
968 IN UINTN SignatureSize
972 EFI_SIGNATURE_LIST
*CertList
;
973 EFI_SIGNATURE_DATA
*Cert
;
981 // Read signature database variable.
986 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
987 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
991 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
996 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
997 if (EFI_ERROR (Status
)) {
1001 // Enumerate all signature data in SigDB to check if executable's signature exists.
1003 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1004 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1005 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1006 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1007 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
1008 for (Index
= 0; Index
< CertCount
; Index
++) {
1009 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
1011 // Find the signature in database.
1015 // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured
1017 if (StrCmp(VariableName
, EFI_IMAGE_SECURITY_DATABASE
) == 0) {
1018 SecureBootHook (VariableName
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, Cert
);
1023 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1031 DataSize
-= CertList
->SignatureListSize
;
1032 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1044 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1046 @param SigningTime A pointer to the signing time.
1047 @param RevocationTime A pointer to the revocation time.
1049 @retval TRUE The SigningTime is not later than the RevocationTime.
1050 @retval FALSE The SigningTime is later than the RevocationTime.
1054 IsValidSignatureByTimestamp (
1055 IN EFI_TIME
*SigningTime
,
1056 IN EFI_TIME
*RevocationTime
1059 if (SigningTime
->Year
!= RevocationTime
->Year
) {
1060 return (BOOLEAN
) (SigningTime
->Year
< RevocationTime
->Year
);
1061 } else if (SigningTime
->Month
!= RevocationTime
->Month
) {
1062 return (BOOLEAN
) (SigningTime
->Month
< RevocationTime
->Month
);
1063 } else if (SigningTime
->Day
!= RevocationTime
->Day
) {
1064 return (BOOLEAN
) (SigningTime
->Day
< RevocationTime
->Day
);
1065 } else if (SigningTime
->Hour
!= RevocationTime
->Hour
) {
1066 return (BOOLEAN
) (SigningTime
->Hour
< RevocationTime
->Hour
);
1067 } else if (SigningTime
->Minute
!= RevocationTime
->Minute
) {
1068 return (BOOLEAN
) (SigningTime
->Minute
< RevocationTime
->Minute
);
1071 return (BOOLEAN
) (SigningTime
->Second
<= RevocationTime
->Second
);
1075 Check if the given time value is zero.
1077 @param[in] Time Pointer of a time value.
1079 @retval TRUE The Time is Zero.
1080 @retval FALSE The Time is not Zero.
1088 if ((Time
->Year
== 0) && (Time
->Month
== 0) && (Time
->Day
== 0) &&
1089 (Time
->Hour
== 0) && (Time
->Minute
== 0) && (Time
->Second
== 0)) {
1097 Check whether the timestamp signature is valid and the signing time is also earlier than
1098 the revocation time.
1100 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1101 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1102 @param[in] RevocationTime The time that the certificate was revoked.
1104 @retval TRUE Timestamp signature is valid and signing time is no later than the
1106 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1111 PassTimestampCheck (
1113 IN UINTN AuthDataSize
,
1114 IN EFI_TIME
*RevocationTime
1118 BOOLEAN VerifyStatus
;
1119 EFI_SIGNATURE_LIST
*CertList
;
1120 EFI_SIGNATURE_DATA
*Cert
;
1127 EFI_TIME SigningTime
;
1130 // Variable Initialization
1132 VerifyStatus
= FALSE
;
1140 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1142 if (IsTimeZero (RevocationTime
)) {
1147 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1148 // Using the dbt to get the trusted TSA certificates.
1151 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, NULL
);
1152 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1155 DbtData
= (UINT8
*) AllocateZeroPool (DbtDataSize
);
1156 if (DbtData
== NULL
) {
1159 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE2
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbtDataSize
, (VOID
*) DbtData
);
1160 if (EFI_ERROR (Status
)) {
1164 CertList
= (EFI_SIGNATURE_LIST
*) DbtData
;
1165 while ((DbtDataSize
> 0) && (DbtDataSize
>= CertList
->SignatureListSize
)) {
1166 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1167 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1168 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1169 for (Index
= 0; Index
< CertCount
; Index
++) {
1171 // Iterate each Signature Data Node within this CertList for verify.
1173 RootCert
= Cert
->SignatureData
;
1174 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1176 // Get the signing time if the timestamp signature is valid.
1178 if (ImageTimestampVerify (AuthData
, AuthDataSize
, RootCert
, RootCertSize
, &SigningTime
)) {
1180 // The signer signature is valid only when the signing time is earlier than revocation time.
1182 if (IsValidSignatureByTimestamp (&SigningTime
, RevocationTime
)) {
1183 VerifyStatus
= TRUE
;
1187 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
1190 DbtDataSize
-= CertList
->SignatureListSize
;
1191 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1195 if (DbtData
!= NULL
) {
1199 return VerifyStatus
;
1203 Check whether the image signature is forbidden by the forbidden database (dbx).
1204 The image is forbidden to load if any certificates for signing are revoked before signing time.
1206 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1207 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1209 @retval TRUE Image is forbidden by dbx.
1210 @retval FALSE Image is not forbidden by dbx.
1216 IN UINTN AuthDataSize
1220 BOOLEAN IsForbidden
;
1223 EFI_SIGNATURE_LIST
*CertList
;
1225 EFI_SIGNATURE_DATA
*CertData
;
1233 UINTN TrustedCertLength
;
1238 EFI_TIME RevocationTime
;
1240 // Variable Initialization
1242 IsForbidden
= FALSE
;
1252 TrustedCertLength
= 0;
1255 // The image will not be forbidden if dbx can't be got.
1258 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1259 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
1262 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1267 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1268 if (EFI_ERROR (Status
)) {
1273 // Verify image signature with RAW X509 certificates in DBX database.
1274 // If passed, the image will be forbidden.
1276 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1277 CertListSize
= DataSize
;
1278 while ((CertListSize
> 0) && (CertListSize
>= CertList
->SignatureListSize
)) {
1279 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1280 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1281 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1283 for (Index
= 0; Index
< CertCount
; Index
++) {
1285 // Iterate each Signature Data Node within this CertList for verify.
1287 RootCert
= CertData
->SignatureData
;
1288 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1291 // Call AuthenticodeVerify library to Verify Authenticode struct.
1293 IsForbidden
= AuthenticodeVerify (
1302 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1306 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1310 CertListSize
-= CertList
->SignatureListSize
;
1311 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1315 // Check X.509 Certificate Hash & Possible Timestamp.
1319 // Retrieve the certificate stack from AuthData
1320 // The output CertStack format will be:
1321 // UINT8 CertNumber;
1322 // UINT32 Cert1Length;
1324 // UINT32 Cert2Length;
1327 // UINT32 CertnLength;
1330 Pkcs7GetSigners (AuthData
, AuthDataSize
, &CertBuffer
, &BufferLength
, &TrustedCert
, &TrustedCertLength
);
1331 if ((BufferLength
== 0) || (CertBuffer
== NULL
)) {
1337 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1339 CertNumber
= (UINT8
) (*CertBuffer
);
1340 CertPtr
= CertBuffer
+ 1;
1341 for (Index
= 0; Index
< CertNumber
; Index
++) {
1342 CertSize
= (UINTN
) ReadUnaligned32 ((UINT32
*)CertPtr
);
1343 Cert
= (UINT8
*)CertPtr
+ sizeof (UINT32
);
1345 // Advance CertPtr to the next cert in image signer's cert list
1347 CertPtr
= CertPtr
+ sizeof (UINT32
) + CertSize
;
1349 if (IsCertHashFoundInDatabase (Cert
, CertSize
, (EFI_SIGNATURE_LIST
*)Data
, DataSize
, &RevocationTime
)) {
1351 // Check the timestamp signature and signing time to determine if the image can be trusted.
1354 if (PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
)) {
1355 IsForbidden
= FALSE
;
1357 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1361 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1372 Pkcs7FreeSigners (CertBuffer
);
1373 Pkcs7FreeSigners (TrustedCert
);
1380 Check whether the image signature can be verified by the trusted certificates in DB database.
1382 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1383 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1385 @retval TRUE Image passed verification using certificate in db.
1386 @retval FALSE Image didn't pass verification using certificate in db.
1392 IN UINTN AuthDataSize
1396 BOOLEAN VerifyStatus
;
1397 EFI_SIGNATURE_LIST
*CertList
;
1398 EFI_SIGNATURE_DATA
*CertData
;
1407 EFI_TIME RevocationTime
;
1415 VerifyStatus
= FALSE
;
1418 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
1419 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1420 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
1422 return VerifyStatus
;
1425 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, (VOID
*) Data
);
1426 if (EFI_ERROR (Status
)) {
1431 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1433 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
1434 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
1435 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
1436 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
1437 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
1439 for (Index
= 0; Index
< CertCount
; Index
++) {
1441 // Iterate each Signature Data Node within this CertList for verify.
1443 RootCert
= CertData
->SignatureData
;
1444 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
1447 // Call AuthenticodeVerify library to Verify Authenticode struct.
1449 VerifyStatus
= AuthenticodeVerify (
1459 // Here We still need to check if this RootCert's Hash is revoked
1461 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, NULL
);
1462 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1465 DbxData
= (UINT8
*) AllocateZeroPool (DbxDataSize
);
1466 if (DbxData
== NULL
) {
1470 Status
= gRT
->GetVariable (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DbxDataSize
, (VOID
*) DbxData
);
1471 if (EFI_ERROR (Status
)) {
1475 if (IsCertHashFoundInDatabase (RootCert
, RootCertSize
, (EFI_SIGNATURE_LIST
*)DbxData
, DbxDataSize
, &RevocationTime
)) {
1477 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1479 VerifyStatus
= PassTimestampCheck (AuthData
, AuthDataSize
, &RevocationTime
);
1480 if (!VerifyStatus
) {
1481 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1488 CertData
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertData
+ CertList
->SignatureSize
);
1492 DataSize
-= CertList
->SignatureListSize
;
1493 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
1500 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
, CertList
->SignatureSize
, CertData
);
1506 if (DbxData
!= NULL
) {
1510 return VerifyStatus
;
1514 Provide verification service for signed images, which include both signature validation
1515 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1516 MSFT Authenticode type signatures are supported.
1518 In this implementation, only verify external executables when in USER MODE.
1519 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1521 The image verification policy is:
1522 If the image is signed,
1523 At least one valid signature or at least one hash value of the image must match a record
1524 in the security database "db", and no valid signature nor any hash value of the image may
1525 be reflected in the security database "dbx".
1526 Otherwise, the image is not signed,
1527 The SHA256 hash value of the image must match a record in the security database "db", and
1528 not be reflected in the security data base "dbx".
1530 Caution: This function may receive untrusted input.
1531 PE/COFF image is external input, so this function will validate its data structure
1532 within this image buffer before use.
1534 @param[in] AuthenticationStatus
1535 This is the authentication status returned from the security
1536 measurement services for the input file.
1537 @param[in] File This is a pointer to the device path of the file that is
1538 being dispatched. This will optionally be used for logging.
1539 @param[in] FileBuffer File buffer matches the input file device path.
1540 @param[in] FileSize Size of File buffer matches the input file device path.
1541 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1543 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1544 FileBuffer did authenticate, and the platform policy dictates
1545 that the DXE Foundation may use the file.
1546 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1547 and non-NULL FileBuffer did authenticate, and the platform
1548 policy dictates that the DXE Foundation may execute the image in
1550 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1551 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1552 the platform policy dictates that File should be placed
1553 in the untrusted state. The image has been added to the file
1555 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1556 authenticate, and the platform policy dictates that the DXE
1557 Foundation many not use File.
1562 DxeImageVerificationHandler (
1563 IN UINT32 AuthenticationStatus
,
1564 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1565 IN VOID
*FileBuffer
,
1567 IN BOOLEAN BootPolicy
1571 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1572 EFI_STATUS VerifyStatus
;
1573 EFI_SIGNATURE_LIST
*SignatureList
;
1574 UINTN SignatureListSize
;
1575 EFI_SIGNATURE_DATA
*Signature
;
1576 EFI_IMAGE_EXECUTION_ACTION Action
;
1577 WIN_CERTIFICATE
*WinCertificate
;
1580 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1581 UINT32 NumberOfRvaAndSizes
;
1582 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
1583 WIN_CERTIFICATE_UEFI_GUID
*WinCertUefiGuid
;
1586 EFI_IMAGE_DATA_DIRECTORY
*SecDataDir
;
1590 SignatureList
= NULL
;
1591 SignatureListSize
= 0;
1592 WinCertificate
= NULL
;
1594 PkcsCertData
= NULL
;
1595 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1596 Status
= EFI_ACCESS_DENIED
;
1597 VerifyStatus
= EFI_ACCESS_DENIED
;
1601 // Check the image type and get policy setting.
1603 switch (GetImageType (File
)) {
1606 Policy
= ALWAYS_EXECUTE
;
1609 case IMAGE_FROM_OPTION_ROM
:
1610 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1613 case IMAGE_FROM_REMOVABLE_MEDIA
:
1614 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1617 case IMAGE_FROM_FIXED_MEDIA
:
1618 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1622 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1626 // If policy is always/never execute, return directly.
1628 if (Policy
== ALWAYS_EXECUTE
) {
1630 } else if (Policy
== NEVER_EXECUTE
) {
1631 return EFI_ACCESS_DENIED
;
1635 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1636 // violates the UEFI spec and has been removed.
1638 ASSERT (Policy
!= QUERY_USER_ON_SECURITY_VIOLATION
&& Policy
!= ALLOW_EXECUTE_ON_SECURITY_VIOLATION
);
1639 if (Policy
== QUERY_USER_ON_SECURITY_VIOLATION
|| Policy
== ALLOW_EXECUTE_ON_SECURITY_VIOLATION
) {
1643 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1645 // Skip verification if SecureBoot variable doesn't exist.
1647 if (SecureBoot
== NULL
) {
1652 // Skip verification if SecureBoot is disabled but not AuditMode
1654 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1655 FreePool (SecureBoot
);
1658 FreePool (SecureBoot
);
1661 // Read the Dos header.
1663 if (FileBuffer
== NULL
) {
1664 return EFI_INVALID_PARAMETER
;
1667 mImageBase
= (UINT8
*) FileBuffer
;
1668 mImageSize
= FileSize
;
1670 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1671 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1672 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1675 // Get information about the image being loaded
1677 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
1678 if (EFI_ERROR (Status
)) {
1680 // The information can't be got from the invalid PeImage
1682 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1686 Status
= EFI_ACCESS_DENIED
;
1688 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1689 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1691 // DOS image header is present,
1692 // so read the PE header after the DOS image header.
1694 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1696 mPeCoffHeaderOffset
= 0;
1699 // Check PE/COFF image.
1701 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1702 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1704 // It is not a valid Pe/Coff file.
1706 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1710 if (mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1714 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1715 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1716 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1720 // Use PE32+ offset.
1722 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1723 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1724 SecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1729 // Start Image Validation.
1731 if (SecDataDir
== NULL
|| SecDataDir
->Size
== 0) {
1733 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1734 // and not be reflected in the security data base "dbx".
1736 if (!HashPeImage (HASHALG_SHA256
)) {
1737 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr
));
1741 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1743 // Image Hash is in forbidden database (DBX).
1745 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr
));
1749 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1751 // Image Hash is in allowed database (DB).
1757 // Image Hash is not found in both forbidden and allowed database.
1759 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr
));
1764 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1765 // "Attribute Certificate Table".
1766 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1768 for (OffSet
= SecDataDir
->VirtualAddress
;
1769 OffSet
< (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
);
1770 OffSet
+= (WinCertificate
->dwLength
+ ALIGN_SIZE (WinCertificate
->dwLength
))) {
1771 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ OffSet
);
1772 if ((SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) <= sizeof (WIN_CERTIFICATE
) ||
1773 (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
- OffSet
) < WinCertificate
->dwLength
) {
1778 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1780 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1782 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1783 // Authenticode specification.
1785 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) WinCertificate
;
1786 if (PkcsCertData
->Hdr
.dwLength
<= sizeof (PkcsCertData
->Hdr
)) {
1789 AuthData
= PkcsCertData
->CertData
;
1790 AuthDataSize
= PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
);
1791 } else if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_EFI_GUID
) {
1793 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1795 WinCertUefiGuid
= (WIN_CERTIFICATE_UEFI_GUID
*) WinCertificate
;
1796 if (WinCertUefiGuid
->Hdr
.dwLength
<= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
)) {
1799 if (!CompareGuid (&WinCertUefiGuid
->CertType
, &gEfiCertPkcs7Guid
)) {
1802 AuthData
= WinCertUefiGuid
->CertData
;
1803 AuthDataSize
= WinCertUefiGuid
->Hdr
.dwLength
- OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID
, CertData
);
1805 if (WinCertificate
->dwLength
< sizeof (WIN_CERTIFICATE
)) {
1811 Status
= HashPeImageByType (AuthData
, AuthDataSize
);
1812 if (EFI_ERROR (Status
)) {
1817 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1819 if (IsForbiddenByDbx (AuthData
, AuthDataSize
)) {
1820 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
1821 VerifyStatus
= EFI_ACCESS_DENIED
;
1826 // Check the digital signature against the valid certificate in allowed database (db).
1828 if (EFI_ERROR (VerifyStatus
)) {
1829 if (IsAllowedByDb (AuthData
, AuthDataSize
)) {
1830 VerifyStatus
= EFI_SUCCESS
;
1835 // Check the image's hash value.
1837 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1838 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
1839 DEBUG ((DEBUG_INFO
, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr
));
1840 VerifyStatus
= EFI_ACCESS_DENIED
;
1842 } else if (EFI_ERROR (VerifyStatus
)) {
1843 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1844 VerifyStatus
= EFI_SUCCESS
;
1846 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
));
1851 if (OffSet
!= (SecDataDir
->VirtualAddress
+ SecDataDir
->Size
)) {
1853 // The Size in Certificate Table or the attribute certicate table is corrupted.
1855 VerifyStatus
= EFI_ACCESS_DENIED
;
1858 if (!EFI_ERROR (VerifyStatus
)) {
1861 Status
= EFI_ACCESS_DENIED
;
1862 if (Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
|| Action
== EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
) {
1864 // Get image hash value as executable's signature.
1866 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1867 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1868 if (SignatureList
== NULL
) {
1869 Status
= EFI_OUT_OF_RESOURCES
;
1872 SignatureList
->SignatureHeaderSize
= 0;
1873 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
1874 SignatureList
->SignatureSize
= (UINT32
) (sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
);
1875 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
1876 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
1877 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
1882 if (Status
!= EFI_SUCCESS
) {
1884 // Policy decides to defer or reject the image; add its information in image executable information table.
1886 NameStr
= ConvertDevicePathToText (File
, FALSE
, TRUE
);
1887 AddImageExeInfo (Action
, NameStr
, File
, SignatureList
, SignatureListSize
);
1888 if (NameStr
!= NULL
) {
1889 DEBUG((EFI_D_INFO
, "The image doesn't pass verification: %s\n", NameStr
));
1892 Status
= EFI_SECURITY_VIOLATION
;
1895 if (SignatureList
!= NULL
) {
1896 FreePool (SignatureList
);
1903 On Ready To Boot Services Event notification handler.
1905 Add the image execution information table if it is not in system configuration table.
1907 @param[in] Event Event whose notification function is being invoked
1908 @param[in] Context Pointer to the notification function's context
1918 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
1919 UINTN ImageExeInfoTableSize
;
1921 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
1922 if (ImageExeInfoTable
!= NULL
) {
1926 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
1927 ImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
);
1928 if (ImageExeInfoTable
== NULL
) {
1932 ImageExeInfoTable
->NumberOfImages
= 0;
1933 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) ImageExeInfoTable
);
1938 Register security measurement handler.
1940 @param ImageHandle ImageHandle of the loaded driver.
1941 @param SystemTable Pointer to the EFI System Table.
1943 @retval EFI_SUCCESS The handlers were registered successfully.
1947 DxeImageVerificationLibConstructor (
1948 IN EFI_HANDLE ImageHandle
,
1949 IN EFI_SYSTEM_TABLE
*SystemTable
1955 // Register the event to publish the image execution table.
1957 EfiCreateEventReadyToBootEx (
1964 return RegisterSecurity2Handler (
1965 DxeImageVerificationHandler
,
1966 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED