2 Implement image verification services for secure boot service in UEFI2.3.1.
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 - 2012, Intel Corporation. All rights reserved.<BR>
16 This program and the accompanying materials
17 are licensed and made available under the terms and conditions of the BSD License
18 which accompanies this distribution. The full text of the license may be found at
19 http://opensource.org/licenses/bsd-license.php
21 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
22 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
26 #include "DxeImageVerificationLib.h"
29 // Caution: This is used by a function which may receive untrusted input.
30 // These global variables hold PE/COFF image data, and they should be validated before use.
32 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader
;
33 UINT32 mPeCoffHeaderOffset
;
34 EFI_IMAGE_DATA_DIRECTORY
*mSecDataDir
= NULL
;
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 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, // OBJ_md5
61 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
64 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
65 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
68 HASH_TABLE mHash
[] = {
69 { L
"SHA1", 20, &mHashOidValue
[8], 5, Sha1GetContextSize
, Sha1Init
, Sha1Update
, Sha1Final
},
70 { L
"SHA224", 28, &mHashOidValue
[13], 9, NULL
, NULL
, NULL
, NULL
},
71 { L
"SHA256", 32, &mHashOidValue
[22], 9, Sha256GetContextSize
,Sha256Init
, Sha256Update
, Sha256Final
},
72 { L
"SHA384", 48, &mHashOidValue
[31], 9, NULL
, NULL
, NULL
, NULL
},
73 { L
"SHA512", 64, &mHashOidValue
[40], 9, NULL
, NULL
, NULL
, NULL
}
77 Reads contents of a PE/COFF image in memory buffer.
79 Caution: This function may receive untrusted input.
80 PE/COFF image is external input, so this function will make sure the PE/COFF image content
81 read is within the image buffer.
83 @param FileHandle Pointer to the file handle to read the PE/COFF image.
84 @param FileOffset Offset into the PE/COFF image to begin the read operation.
85 @param ReadSize On input, the size in bytes of the requested read operation.
86 On output, the number of bytes actually read.
87 @param Buffer Output buffer that contains the data read from the PE/COFF image.
89 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
93 DxeImageVerificationLibImageRead (
96 IN OUT UINTN
*ReadSize
,
102 if (FileHandle
== NULL
|| ReadSize
== NULL
|| Buffer
== NULL
) {
103 return EFI_INVALID_PARAMETER
;
106 if (MAX_ADDRESS
- FileOffset
< *ReadSize
) {
107 return EFI_INVALID_PARAMETER
;
110 EndPosition
= FileOffset
+ *ReadSize
;
111 if (EndPosition
> mImageSize
) {
112 *ReadSize
= (UINT32
)(mImageSize
- FileOffset
);
115 if (FileOffset
>= mImageSize
) {
119 CopyMem (Buffer
, (UINT8
*)((UINTN
) FileHandle
+ FileOffset
), *ReadSize
);
128 @param[in] File This is a pointer to the device path of the file that is
131 @return UINT32 Image Type
136 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
140 EFI_HANDLE DeviceHandle
;
141 EFI_DEVICE_PATH_PROTOCOL
*TempDevicePath
;
142 EFI_BLOCK_IO_PROTOCOL
*BlockIo
;
145 // First check to see if File is from a Firmware Volume
148 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
149 Status
= gBS
->LocateDevicePath (
150 &gEfiFirmwareVolume2ProtocolGuid
,
154 if (!EFI_ERROR (Status
)) {
155 Status
= gBS
->OpenProtocol (
157 &gEfiFirmwareVolume2ProtocolGuid
,
161 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
163 if (!EFI_ERROR (Status
)) {
164 return IMAGE_FROM_FV
;
169 // Next check to see if File is from a Block I/O device
172 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
173 Status
= gBS
->LocateDevicePath (
174 &gEfiBlockIoProtocolGuid
,
178 if (!EFI_ERROR (Status
)) {
180 Status
= gBS
->OpenProtocol (
182 &gEfiBlockIoProtocolGuid
,
186 EFI_OPEN_PROTOCOL_GET_PROTOCOL
188 if (!EFI_ERROR (Status
) && BlockIo
!= NULL
) {
189 if (BlockIo
->Media
!= NULL
) {
190 if (BlockIo
->Media
->RemovableMedia
) {
192 // Block I/O is present and specifies the media is removable
194 return IMAGE_FROM_REMOVABLE_MEDIA
;
197 // Block I/O is present and specifies the media is not removable
199 return IMAGE_FROM_FIXED_MEDIA
;
206 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
207 // the device path supports the Simple File System Protocol.
210 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
211 Status
= gBS
->LocateDevicePath (
212 &gEfiSimpleFileSystemProtocolGuid
,
216 if (!EFI_ERROR (Status
)) {
218 // Simple File System is present without Block I/O, so assume media is fixed.
220 return IMAGE_FROM_FIXED_MEDIA
;
224 // File is not from an FV, Block I/O or Simple File System, so the only options
225 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
227 TempDevicePath
= (EFI_DEVICE_PATH_PROTOCOL
*) File
;
228 while (!IsDevicePathEndType (TempDevicePath
)) {
229 switch (DevicePathType (TempDevicePath
)) {
231 case MEDIA_DEVICE_PATH
:
232 if (DevicePathSubType (TempDevicePath
) == MEDIA_RELATIVE_OFFSET_RANGE_DP
) {
233 return IMAGE_FROM_OPTION_ROM
;
237 case MESSAGING_DEVICE_PATH
:
238 if (DevicePathSubType(TempDevicePath
) == MSG_MAC_ADDR_DP
) {
239 return IMAGE_FROM_REMOVABLE_MEDIA
;
246 TempDevicePath
= NextDevicePathNode (TempDevicePath
);
248 return IMAGE_UNKNOWN
;
252 Caculate hash of Pe/Coff image based on the authenticode image hashing in
253 PE/COFF Specification 8.0 Appendix A
255 Caution: This function may receive untrusted input.
256 PE/COFF image is external input, so this function will validate its data structure
257 within this image buffer before use.
259 @param[in] HashAlg Hash algorithm type.
261 @retval TRUE Successfully hash image.
262 @retval FALSE Fail in hash image.
272 EFI_IMAGE_SECTION_HEADER
*Section
;
277 UINTN SumOfBytesHashed
;
278 EFI_IMAGE_SECTION_HEADER
*SectionHeader
;
282 UINT32 NumberOfRvaAndSizes
;
285 SectionHeader
= NULL
;
288 if ((HashAlg
!= HASHALG_SHA1
) && (HashAlg
!= HASHALG_SHA256
)) {
293 // Initialize context of hash.
295 ZeroMem (mImageDigest
, MAX_DIGEST_SIZE
);
297 if (HashAlg
== HASHALG_SHA1
) {
298 mImageDigestSize
= SHA1_DIGEST_SIZE
;
299 mCertType
= gEfiCertSha1Guid
;
300 } else if (HashAlg
== HASHALG_SHA256
) {
301 mImageDigestSize
= SHA256_DIGEST_SIZE
;
302 mCertType
= gEfiCertSha256Guid
;
307 CtxSize
= mHash
[HashAlg
].GetContextSize();
309 HashCtx
= AllocatePool (CtxSize
);
310 if (HashCtx
== NULL
) {
314 // 1. Load the image header into memory.
316 // 2. Initialize a SHA hash context.
317 Status
= mHash
[HashAlg
].HashInit(HashCtx
);
324 // Measuring PE/COFF Image Header;
325 // But CheckSum field and SECURITY data directory (certificate) are excluded
327 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
329 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
330 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
331 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
332 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
334 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
337 // Get the magic value from the PE/COFF Optional Header
339 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
343 // 3. Calculate the distance from the base of the image header to the image checksum address.
344 // 4. Hash the image header from its base to beginning of the image checksum.
346 HashBase
= mImageBase
;
347 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
351 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.CheckSum
) - HashBase
);
352 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
353 } else if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
) {
357 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
) - HashBase
);
358 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
361 // Invalid header magic number.
367 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
373 // 5. Skip over the image checksum (it occupies a single ULONG).
375 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
377 // 6. Since there is no Cert Directory in optional header, hash everything
378 // from the end of the checksum to the end of image header.
380 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
384 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
385 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
390 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
391 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
395 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
402 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
404 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
408 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
409 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
414 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.CheckSum
+ sizeof (UINT32
);
415 HashSize
= (UINTN
) ((UINT8
*) (&mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
]) - HashBase
);
419 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
426 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
427 // 9. Hash everything from the end of the Cert Directory to the end of image header.
429 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
433 HashBase
= (UINT8
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
434 HashSize
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
439 HashBase
= (UINT8
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
+ 1];
440 HashSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
- (UINTN
) (HashBase
- mImageBase
);
444 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
452 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
454 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
458 SumOfBytesHashed
= mNtHeader
.Pe32
->OptionalHeader
.SizeOfHeaders
;
463 SumOfBytesHashed
= mNtHeader
.Pe32Plus
->OptionalHeader
.SizeOfHeaders
;
467 Section
= (EFI_IMAGE_SECTION_HEADER
*) (
469 mPeCoffHeaderOffset
+
471 sizeof (EFI_IMAGE_FILE_HEADER
) +
472 mNtHeader
.Pe32
->FileHeader
.SizeOfOptionalHeader
476 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
477 // structures in the image. The 'NumberOfSections' field of the image
478 // header indicates how big the table should be. Do not include any
479 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
481 SectionHeader
= (EFI_IMAGE_SECTION_HEADER
*) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER
) * mNtHeader
.Pe32
->FileHeader
.NumberOfSections
);
482 if (SectionHeader
== NULL
) {
487 // 12. Using the 'PointerToRawData' in the referenced section headers as
488 // a key, arrange the elements in the table in ascending order. In other
489 // words, sort the section headers according to the disk-file offset of
492 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
494 while ((Pos
> 0) && (Section
->PointerToRawData
< SectionHeader
[Pos
- 1].PointerToRawData
)) {
495 CopyMem (&SectionHeader
[Pos
], &SectionHeader
[Pos
- 1], sizeof (EFI_IMAGE_SECTION_HEADER
));
498 CopyMem (&SectionHeader
[Pos
], Section
, sizeof (EFI_IMAGE_SECTION_HEADER
));
503 // 13. Walk through the sorted table, bring the corresponding section
504 // into memory, and hash the entire section (using the 'SizeOfRawData'
505 // field in the section header to determine the amount of data to hash).
506 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
507 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
509 for (Index
= 0; Index
< mNtHeader
.Pe32
->FileHeader
.NumberOfSections
; Index
++) {
510 Section
= &SectionHeader
[Index
];
511 if (Section
->SizeOfRawData
== 0) {
514 HashBase
= mImageBase
+ Section
->PointerToRawData
;
515 HashSize
= (UINTN
) Section
->SizeOfRawData
;
517 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
522 SumOfBytesHashed
+= HashSize
;
526 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
527 // data in the file that needs to be added to the hash. This data begins
528 // at file offset SUM_OF_BYTES_HASHED and its length is:
529 // FileSize - (CertDirectory->Size)
531 if (mImageSize
> SumOfBytesHashed
) {
532 HashBase
= mImageBase
+ SumOfBytesHashed
;
534 if (NumberOfRvaAndSizes
<= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
537 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
541 CertSize
= mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
546 CertSize
= mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
].Size
;
550 if (mImageSize
> CertSize
+ SumOfBytesHashed
) {
551 HashSize
= (UINTN
) (mImageSize
- CertSize
- SumOfBytesHashed
);
553 Status
= mHash
[HashAlg
].HashUpdate(HashCtx
, HashBase
, HashSize
);
557 } else if (mImageSize
< CertSize
+ SumOfBytesHashed
) {
563 Status
= mHash
[HashAlg
].HashFinal(HashCtx
, mImageDigest
);
566 if (HashCtx
!= NULL
) {
569 if (SectionHeader
!= NULL
) {
570 FreePool (SectionHeader
);
576 Recognize the Hash algorithm in PE/COFF Authenticode and caculate hash of
577 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
580 Caution: This function may receive untrusted input.
581 PE/COFF image is external input, so this function will validate its data structure
582 within this image buffer before use.
584 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
585 @retval EFI_SUCCESS Hash successfully.
594 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
596 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) (mImageBase
+ mSecDataDir
->VirtualAddress
);
598 if (PkcsCertData
->Hdr
.dwLength
< sizeof (WIN_CERTIFICATE_EFI_PKCS
) + 32) {
599 return EFI_UNSUPPORTED
;
602 for (Index
= 0; Index
< HASHALG_MAX
; Index
++) {
604 // Check the Hash algorithm in PE/COFF Authenticode.
605 // According to PKCS#7 Definition:
606 // SignedData ::= SEQUENCE {
608 // digestAlgorithms DigestAlgorithmIdentifiers,
609 // contentInfo ContentInfo,
611 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
612 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
613 // Fixed offset (+32) is calculated based on two bytes of length encoding.
615 if ((*(PkcsCertData
->CertData
+ 1) & TWO_BYTE_ENCODE
) != TWO_BYTE_ENCODE
) {
617 // Only support two bytes of Long Form of Length Encoding.
622 if (PkcsCertData
->Hdr
.dwLength
< sizeof (WIN_CERTIFICATE_EFI_PKCS
) + 32 + mHash
[Index
].OidLength
) {
623 return EFI_UNSUPPORTED
;
626 if (CompareMem (PkcsCertData
->CertData
+ 32, mHash
[Index
].OidValue
, mHash
[Index
].OidLength
) == 0) {
631 if (Index
== HASHALG_MAX
) {
632 return EFI_UNSUPPORTED
;
636 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
638 if (!HashPeImage(Index
)) {
639 return EFI_UNSUPPORTED
;
647 Returns the size of a given image execution info table in bytes.
649 This function returns the size, in bytes, of the image execution info table specified by
650 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
652 @param ImageExeInfoTable A pointer to a image execution info table structure.
654 @retval 0 If ImageExeInfoTable is NULL.
655 @retval Others The size of a image execution info table in bytes.
659 GetImageExeInfoTableSize (
660 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
664 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoItem
;
667 if (ImageExeInfoTable
== NULL
) {
671 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoTable
+ sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
));
672 TotalSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
673 for (Index
= 0; Index
< ImageExeInfoTable
->NumberOfImages
; Index
++) {
674 TotalSize
+= ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
);
675 ImageExeInfoItem
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) ImageExeInfoItem
+ ReadUnaligned32 ((UINT32
*) &ImageExeInfoItem
->InfoSize
));
682 Create an Image Execution Information Table entry and add it to system configuration table.
684 @param[in] Action Describes the action taken by the firmware regarding this image.
685 @param[in] Name Input a null-terminated, user-friendly name.
686 @param[in] DevicePath Input device path pointer.
687 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
688 @param[in] SignatureSize Size of signature.
693 IN EFI_IMAGE_EXECUTION_ACTION Action
,
694 IN CHAR16
*Name OPTIONAL
,
695 IN CONST EFI_DEVICE_PATH_PROTOCOL
*DevicePath
,
696 IN EFI_SIGNATURE_LIST
*Signature OPTIONAL
,
697 IN UINTN SignatureSize
700 EFI_IMAGE_EXECUTION_INFO_TABLE
*ImageExeInfoTable
;
701 EFI_IMAGE_EXECUTION_INFO_TABLE
*NewImageExeInfoTable
;
702 EFI_IMAGE_EXECUTION_INFO
*ImageExeInfoEntry
;
703 UINTN ImageExeInfoTableSize
;
704 UINTN NewImageExeInfoEntrySize
;
706 UINTN DevicePathSize
;
708 ImageExeInfoTable
= NULL
;
709 NewImageExeInfoTable
= NULL
;
710 ImageExeInfoEntry
= NULL
;
713 if (DevicePath
== NULL
) {
718 NameStringLen
= StrSize (Name
);
721 ImageExeInfoTable
= NULL
;
722 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
**) &ImageExeInfoTable
);
723 if (ImageExeInfoTable
!= NULL
) {
725 // The table has been found!
726 // We must enlarge the table to accmodate the new exe info entry.
728 ImageExeInfoTableSize
= GetImageExeInfoTableSize (ImageExeInfoTable
);
732 // We should create a new table to append to the configuration table.
734 ImageExeInfoTableSize
= sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE
);
737 DevicePathSize
= GetDevicePathSize (DevicePath
);
738 NewImageExeInfoEntrySize
= sizeof (EFI_IMAGE_EXECUTION_INFO
) + NameStringLen
+ DevicePathSize
+ SignatureSize
;
739 NewImageExeInfoTable
= (EFI_IMAGE_EXECUTION_INFO_TABLE
*) AllocateRuntimePool (ImageExeInfoTableSize
+ NewImageExeInfoEntrySize
);
740 if (NewImageExeInfoTable
== NULL
) {
744 if (ImageExeInfoTable
!= NULL
) {
745 CopyMem (NewImageExeInfoTable
, ImageExeInfoTable
, ImageExeInfoTableSize
);
747 NewImageExeInfoTable
->NumberOfImages
= 0;
749 NewImageExeInfoTable
->NumberOfImages
++;
750 ImageExeInfoEntry
= (EFI_IMAGE_EXECUTION_INFO
*) ((UINT8
*) NewImageExeInfoTable
+ ImageExeInfoTableSize
);
752 // Update new item's infomation.
754 WriteUnaligned32 ((UINT32
*) &ImageExeInfoEntry
->Action
, Action
);
755 WriteUnaligned32 ((UINT32
*) &ImageExeInfoEntry
->InfoSize
, (UINT32
) NewImageExeInfoEntrySize
);
758 CopyMem ((UINT8
*) &ImageExeInfoEntry
->InfoSize
+ sizeof (UINT32
), Name
, NameStringLen
);
761 (UINT8
*) &ImageExeInfoEntry
->InfoSize
+ sizeof (UINT32
) + NameStringLen
,
765 if (Signature
!= NULL
) {
767 (UINT8
*) &ImageExeInfoEntry
->InfoSize
+ sizeof (UINT32
) + NameStringLen
+ DevicePathSize
,
773 // Update/replace the image execution table.
775 gBS
->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid
, (VOID
*) NewImageExeInfoTable
);
778 // Free Old table data!
780 if (ImageExeInfoTable
!= NULL
) {
781 FreePool (ImageExeInfoTable
);
786 Check whether signature is in specified database.
788 @param[in] VariableName Name of database variable that is searched in.
789 @param[in] Signature Pointer to signature that is searched for.
790 @param[in] CertType Pointer to hash algrithom.
791 @param[in] SignatureSize Size of Signature.
793 @return TRUE Found the signature in the variable database.
794 @return FALSE Not found the signature in the variable database.
798 IsSignatureFoundInDatabase (
799 IN CHAR16
*VariableName
,
801 IN EFI_GUID
*CertType
,
802 IN UINTN SignatureSize
806 EFI_SIGNATURE_LIST
*CertList
;
807 EFI_SIGNATURE_DATA
*Cert
;
814 // Read signature database variable.
819 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, NULL
);
820 if (Status
!= EFI_BUFFER_TOO_SMALL
) {
824 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
829 Status
= gRT
->GetVariable (VariableName
, &gEfiImageSecurityDatabaseGuid
, NULL
, &DataSize
, Data
);
830 if (EFI_ERROR (Status
)) {
834 // Enumerate all signature data in SigDB to check if executable's signature exists.
836 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
837 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
838 CertCount
= (CertList
->SignatureListSize
- CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
839 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
840 if ((CertList
->SignatureSize
== sizeof(EFI_SIGNATURE_DATA
) - 1 + SignatureSize
) && (CompareGuid(&CertList
->SignatureType
, CertType
))) {
841 for (Index
= 0; Index
< CertCount
; Index
++) {
842 if (CompareMem (Cert
->SignatureData
, Signature
, SignatureSize
) == 0) {
844 // Find the signature in database.
850 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
858 DataSize
-= CertList
->SignatureListSize
;
859 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
871 Verify PKCS#7 SignedData using certificate found in Variable which formatted
872 as EFI_SIGNATURE_LIST. The Variable may be PK, KEK, DB or DBX.
874 @param VariableName Name of Variable to search for Certificate.
875 @param VendorGuid Variable vendor GUID.
877 @retval TRUE Image pass verification.
878 @retval FALSE Image fail verification.
882 IsPkcsSignedDataVerifiedBySignatureList (
883 IN CHAR16
*VariableName
,
884 IN EFI_GUID
*VendorGuid
888 BOOLEAN VerifyStatus
;
889 WIN_CERTIFICATE_EFI_PKCS
*PkcsCertData
;
890 EFI_SIGNATURE_LIST
*CertList
;
891 EFI_SIGNATURE_DATA
*Cert
;
904 VerifyStatus
= FALSE
;
905 PkcsCertData
= (WIN_CERTIFICATE_EFI_PKCS
*) (mImageBase
+ mSecDataDir
->VirtualAddress
);
908 Status
= gRT
->GetVariable (VariableName
, VendorGuid
, NULL
, &DataSize
, NULL
);
909 if (Status
== EFI_BUFFER_TOO_SMALL
) {
910 Data
= (UINT8
*) AllocateZeroPool (DataSize
);
915 Status
= gRT
->GetVariable (VariableName
, VendorGuid
, NULL
, &DataSize
, (VOID
*) Data
);
916 if (EFI_ERROR (Status
)) {
921 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
923 CertList
= (EFI_SIGNATURE_LIST
*) Data
;
924 while ((DataSize
> 0) && (DataSize
>= CertList
->SignatureListSize
)) {
925 if (CompareGuid (&CertList
->SignatureType
, &gEfiCertX509Guid
)) {
926 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) CertList
+ sizeof (EFI_SIGNATURE_LIST
) + CertList
->SignatureHeaderSize
);
927 CertCount
= (CertList
->SignatureListSize
- sizeof (EFI_SIGNATURE_LIST
) - CertList
->SignatureHeaderSize
) / CertList
->SignatureSize
;
928 for (Index
= 0; Index
< CertCount
; Index
++) {
930 // Iterate each Signature Data Node within this CertList for verify.
932 RootCert
= Cert
->SignatureData
;
933 RootCertSize
= CertList
->SignatureSize
- sizeof (EFI_GUID
);
936 // Call AuthenticodeVerify library to Verify Authenticode struct.
938 VerifyStatus
= AuthenticodeVerify (
939 PkcsCertData
->CertData
,
940 PkcsCertData
->Hdr
.dwLength
- sizeof(PkcsCertData
->Hdr
),
949 Cert
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) Cert
+ CertList
->SignatureSize
);
952 DataSize
-= CertList
->SignatureListSize
;
953 CertList
= (EFI_SIGNATURE_LIST
*) ((UINT8
*) CertList
+ CertList
->SignatureListSize
);
966 Verify certificate in WIN_CERT_TYPE_PKCS_SIGNED_DATA format.
968 @retval EFI_SUCCESS Image pass verification.
969 @retval EFI_SECURITY_VIOLATION Image fail verification.
973 VerifyCertPkcsSignedData (
978 // 1: Find certificate from DBX forbidden database for revoked certificate.
980 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_IMAGE_SECURITY_DATABASE1
, &gEfiImageSecurityDatabaseGuid
)) {
982 // DBX is forbidden database, if Authenticode verification pass with
983 // one of the certificate in DBX, this image should be rejected.
985 return EFI_SECURITY_VIOLATION
;
989 // 2: Find certificate from DB database and try to verify authenticode struct.
991 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_IMAGE_SECURITY_DATABASE
, &gEfiImageSecurityDatabaseGuid
)) {
994 return EFI_SECURITY_VIOLATION
;
999 Provide verification service for signed images, which include both signature validation
1000 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1001 MSFT Authenticode type signatures are supported.
1003 In this implementation, only verify external executables when in USER MODE.
1004 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1006 The image verification process is:
1007 If the image is signed,
1008 If the image's certificate verifies against a certificate (root or intermediate) in the allowed
1009 database (DB) and not in the forbidden database (DBX), the certificate verification is passed.
1010 If the image's hash digest is in DBX,
1014 If the Image's certificate verification failed.
1015 If the Image's Hash is in DB and not in DBX,
1019 Otherwise, the image is not signed,
1020 Is the Image's Hash in DBX?
1021 If yes, deny execution.
1022 If not, is the Image's Hash in DB?
1024 If not, deny execution.
1026 Caution: This function may receive untrusted input.
1027 PE/COFF image is external input, so this function will validate its data structure
1028 within this image buffer before use.
1030 @param[in] AuthenticationStatus
1031 This is the authentication status returned from the security
1032 measurement services for the input file.
1033 @param[in] File This is a pointer to the device path of the file that is
1034 being dispatched. This will optionally be used for logging.
1035 @param[in] FileBuffer File buffer matches the input file device path.
1036 @param[in] FileSize Size of File buffer matches the input file device path.
1038 @retval EFI_SUCCESS The file specified by File did authenticate, and the
1039 platform policy dictates that the DXE Core may use File.
1040 @retval EFI_INVALID_PARAMETER Input argument is incorrect.
1041 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1042 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1043 the platform policy dictates that File should be placed
1044 in the untrusted state. A file may be promoted from
1045 the untrusted to the trusted state at a future time
1046 with a call to the Trust() DXE Service.
1047 @retval EFI_ACCESS_DENIED The file specified by File did not authenticate, and
1048 the platform policy dictates that File should not be
1049 used for any purpose.
1054 DxeImageVerificationHandler (
1055 IN UINT32 AuthenticationStatus
,
1056 IN CONST EFI_DEVICE_PATH_PROTOCOL
*File
,
1057 IN VOID
*FileBuffer
,
1063 EFI_IMAGE_DOS_HEADER
*DosHdr
;
1064 EFI_STATUS VerifyStatus
;
1065 EFI_SIGNATURE_LIST
*SignatureList
;
1066 UINTN SignatureListSize
;
1067 EFI_SIGNATURE_DATA
*Signature
;
1068 EFI_IMAGE_EXECUTION_ACTION Action
;
1069 WIN_CERTIFICATE
*WinCertificate
;
1072 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext
;
1073 UINT32 NumberOfRvaAndSizes
;
1077 return EFI_INVALID_PARAMETER
;
1080 SignatureList
= NULL
;
1081 SignatureListSize
= 0;
1082 WinCertificate
= NULL
;
1083 Action
= EFI_IMAGE_EXECUTION_AUTH_UNTESTED
;
1084 Status
= EFI_ACCESS_DENIED
;
1086 // Check the image type and get policy setting.
1088 switch (GetImageType (File
)) {
1091 Policy
= ALWAYS_EXECUTE
;
1094 case IMAGE_FROM_OPTION_ROM
:
1095 Policy
= PcdGet32 (PcdOptionRomImageVerificationPolicy
);
1098 case IMAGE_FROM_REMOVABLE_MEDIA
:
1099 Policy
= PcdGet32 (PcdRemovableMediaImageVerificationPolicy
);
1102 case IMAGE_FROM_FIXED_MEDIA
:
1103 Policy
= PcdGet32 (PcdFixedMediaImageVerificationPolicy
);
1107 Policy
= DENY_EXECUTE_ON_SECURITY_VIOLATION
;
1111 // If policy is always/never execute, return directly.
1113 if (Policy
== ALWAYS_EXECUTE
) {
1115 } else if (Policy
== NEVER_EXECUTE
) {
1116 return EFI_ACCESS_DENIED
;
1119 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBoot
, NULL
);
1121 // Skip verification if SecureBoot variable doesn't exist.
1123 if (SecureBoot
== NULL
) {
1128 // Skip verification if SecureBoot is disabled.
1130 if (*SecureBoot
== SECURE_BOOT_MODE_DISABLE
) {
1131 FreePool (SecureBoot
);
1134 FreePool (SecureBoot
);
1137 // Read the Dos header.
1139 if (FileBuffer
== NULL
) {
1140 return EFI_INVALID_PARAMETER
;
1143 mImageBase
= (UINT8
*) FileBuffer
;
1144 mImageSize
= FileSize
;
1146 ZeroMem (&ImageContext
, sizeof (ImageContext
));
1147 ImageContext
.Handle
= (VOID
*) FileBuffer
;
1148 ImageContext
.ImageRead
= (PE_COFF_LOADER_READ_FILE
) DxeImageVerificationLibImageRead
;
1151 // Get information about the image being loaded
1153 Status
= PeCoffLoaderGetImageInfo (&ImageContext
);
1154 if (EFI_ERROR (Status
)) {
1156 // The information can't be got from the invalid PeImage
1161 Status
= EFI_ACCESS_DENIED
;
1163 DosHdr
= (EFI_IMAGE_DOS_HEADER
*) mImageBase
;
1164 if (DosHdr
->e_magic
== EFI_IMAGE_DOS_SIGNATURE
) {
1166 // DOS image header is present,
1167 // so read the PE header after the DOS image header.
1169 mPeCoffHeaderOffset
= DosHdr
->e_lfanew
;
1171 mPeCoffHeaderOffset
= 0;
1174 // Check PE/COFF image.
1176 mNtHeader
.Pe32
= (EFI_IMAGE_NT_HEADERS32
*) (mImageBase
+ mPeCoffHeaderOffset
);
1177 if (mNtHeader
.Pe32
->Signature
!= EFI_IMAGE_NT_SIGNATURE
) {
1179 // It is not a valid Pe/Coff file.
1184 if (mNtHeader
.Pe32
->FileHeader
.Machine
== IMAGE_FILE_MACHINE_IA64
&& mNtHeader
.Pe32
->OptionalHeader
.Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1186 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1187 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1188 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1189 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1191 Magic
= EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1194 // Get the magic value from the PE/COFF Optional Header
1196 Magic
= mNtHeader
.Pe32
->OptionalHeader
.Magic
;
1199 if (Magic
== EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
) {
1203 NumberOfRvaAndSizes
= mNtHeader
.Pe32
->OptionalHeader
.NumberOfRvaAndSizes
;
1204 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1205 mSecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1209 // Use PE32+ offset.
1211 NumberOfRvaAndSizes
= mNtHeader
.Pe32Plus
->OptionalHeader
.NumberOfRvaAndSizes
;
1212 if (NumberOfRvaAndSizes
> EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
) {
1213 mSecDataDir
= (EFI_IMAGE_DATA_DIRECTORY
*) &mNtHeader
.Pe32Plus
->OptionalHeader
.DataDirectory
[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY
];
1217 if ((mSecDataDir
== NULL
) || ((mSecDataDir
!= NULL
) && (mSecDataDir
->Size
== 0))) {
1219 // This image is not signed.
1221 if (!HashPeImage (HASHALG_SHA256
)) {
1225 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1227 // Image Hash is in forbidden database (DBX).
1232 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1234 // Image Hash is in allowed database (DB).
1240 // Image Hash is not found in both forbidden and allowed database.
1246 // Verify signature of executables.
1248 WinCertificate
= (WIN_CERTIFICATE
*) (mImageBase
+ mSecDataDir
->VirtualAddress
);
1250 CertSize
= sizeof (WIN_CERTIFICATE
);
1252 if ((mSecDataDir
->Size
<= CertSize
) || (mSecDataDir
->Size
< WinCertificate
->dwLength
)) {
1256 if (WinCertificate
->wCertificateType
== WIN_CERT_TYPE_PKCS_SIGNED_DATA
) {
1258 // Verify Pkcs signed data type.
1260 Status
= HashPeImageByType();
1261 if (EFI_ERROR (Status
)) {
1265 VerifyStatus
= VerifyCertPkcsSignedData ();
1270 if (!EFI_ERROR (VerifyStatus
)) {
1272 // Verification is passed.
1273 // Continue to check the image digest in signature database.
1275 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1277 // Executable signature verification passes, but is found in forbidden signature database.
1279 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND
;
1280 Status
= EFI_ACCESS_DENIED
;
1283 // For image verification against enrolled X.509 certificate(root or intermediate),
1284 // no need to check image's hash in the allowed database.
1290 // Verification failure.
1292 if (!IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1
, mImageDigest
, &mCertType
, mImageDigestSize
) &&
1293 IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE
, mImageDigest
, &mCertType
, mImageDigestSize
)) {
1295 // Verification fail, Image Hash is not in forbidden database (DBX),
1296 // and Image Hash is in allowed database (DB).
1298 Status
= EFI_SUCCESS
;
1300 Action
= EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED
;
1301 Status
= EFI_ACCESS_DENIED
;
1305 if (EFI_ERROR (Status
)) {
1307 // Get image hash value as executable's signature.
1309 SignatureListSize
= sizeof (EFI_SIGNATURE_LIST
) + sizeof (EFI_SIGNATURE_DATA
) - 1 + mImageDigestSize
;
1310 SignatureList
= (EFI_SIGNATURE_LIST
*) AllocateZeroPool (SignatureListSize
);
1311 if (SignatureList
== NULL
) {
1312 Status
= EFI_OUT_OF_RESOURCES
;
1315 SignatureList
->SignatureHeaderSize
= 0;
1316 SignatureList
->SignatureListSize
= (UINT32
) SignatureListSize
;
1317 SignatureList
->SignatureSize
= (UINT32
) mImageDigestSize
;
1318 CopyMem (&SignatureList
->SignatureType
, &mCertType
, sizeof (EFI_GUID
));
1319 Signature
= (EFI_SIGNATURE_DATA
*) ((UINT8
*) SignatureList
+ sizeof (EFI_SIGNATURE_LIST
));
1320 CopyMem (Signature
->SignatureData
, mImageDigest
, mImageDigestSize
);
1324 if (Status
!= EFI_SUCCESS
) {
1326 // Policy decides to defer or reject the image; add its information in image executable information table.
1328 AddImageExeInfo (Action
, NULL
, File
, SignatureList
, SignatureListSize
);
1331 if (SignatureList
!= NULL
) {
1332 FreePool (SignatureList
);
1339 When VariableWriteArchProtocol install, create "SecureBoot" variable.
1341 @param[in] Event Event whose notification function is being invoked.
1342 @param[in] Context Pointer to the notification function's context.
1347 VariableWriteCallBack (
1352 UINT8 SecureBootMode
;
1353 UINT8
*SecureBootModePtr
;
1355 VOID
*ProtocolPointer
;
1357 Status
= gBS
->LocateProtocol (&gEfiVariableWriteArchProtocolGuid
, NULL
, &ProtocolPointer
);
1358 if (EFI_ERROR (Status
)) {
1363 // Check whether "SecureBoot" variable exists.
1364 // If this library is built-in, it means firmware has capability to perform
1365 // driver signing verification.
1367 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME
, (VOID
**)&SecureBootModePtr
, NULL
);
1368 if (SecureBootModePtr
== NULL
) {
1369 SecureBootMode
= SECURE_BOOT_MODE_DISABLE
;
1371 // Authenticated variable driver will update "SecureBoot" depending on SetupMode variable.
1374 EFI_SECURE_BOOT_MODE_NAME
,
1375 &gEfiGlobalVariableGuid
,
1376 EFI_VARIABLE_BOOTSERVICE_ACCESS
| EFI_VARIABLE_RUNTIME_ACCESS
| EFI_VARIABLE_NON_VOLATILE
,
1381 FreePool (SecureBootModePtr
);
1386 Register security measurement handler.
1388 @param ImageHandle ImageHandle of the loaded driver.
1389 @param SystemTable Pointer to the EFI System Table.
1391 @retval EFI_SUCCESS The handlers were registered successfully.
1395 DxeImageVerificationLibConstructor (
1396 IN EFI_HANDLE ImageHandle
,
1397 IN EFI_SYSTEM_TABLE
*SystemTable
1403 // Register callback function upon VariableWriteArchProtocol.
1405 EfiCreateProtocolNotifyEvent (
1406 &gEfiVariableWriteArchProtocolGuid
,
1408 VariableWriteCallBack
,
1413 return RegisterSecurityHandler (
1414 DxeImageVerificationHandler
,
1415 EFI_AUTH_OPERATION_VERIFY_IMAGE
| EFI_AUTH_OPERATION_IMAGE_REQUIRED