X-Git-Url: https://git.proxmox.com/?a=blobdiff_plain;f=SecurityPkg%2FLibrary%2FDxeImageVerificationLib%2FDxeImageVerificationLib.c;h=66e2f5eaa3c0380c88aa397aa150c8950e99c583;hb=HEAD;hp=3331b6862e1d34173dd3e0dbf352adc102391ff1;hpb=3cd2484e3a9c8e07aa6df9c4b9fb4783d282b05d;p=mirror_edk2.git diff --git a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c index 3331b6862e..66e2f5eaa3 100644 --- a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c +++ b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c @@ -12,14 +12,9 @@ DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept untrusted PE/COFF image and validate its data structure within this image buffer before use. -Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.
-This program and the accompanying materials -are licensed and made available under the terms and conditions of the BSD License -which accompanies this distribution. The full text of the license may be found at -http://opensource.org/licenses/bsd-license.php - -THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+(C) Copyright 2016 Hewlett Packard Enterprise Development LP
+SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -29,17 +24,17 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. // Caution: This is used by a function which may receive untrusted input. // These global variables hold PE/COFF image data, and they should be validated before use. // -EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader; -UINT32 mPeCoffHeaderOffset; -EFI_GUID mCertType; +EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader; +UINT32 mPeCoffHeaderOffset; +EFI_GUID mCertType; // // Information on current PE/COFF image // -UINTN mImageSize; -UINT8 *mImageBase = NULL; -UINT8 mImageDigest[MAX_DIGEST_SIZE]; -UINTN mImageDigestSize; +UINTN mImageSize; +UINT8 *mImageBase = NULL; +UINT8 mImageDigest[MAX_DIGEST_SIZE]; +UINTN mImageDigestSize; // // Notify string for authorization UI. @@ -49,28 +44,33 @@ CHAR16 mNotifyString2[MAX_NOTIFY_STRING_LEN] = L"Launch this image anyway? (Yes // // Public Exponent of RSA Key. // -CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 }; - +CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 }; // // OID ASN.1 Value for Hash Algorithms // -UINT8 mHashOidValue[] = { - 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1 - 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224 - 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256 - 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384 - 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512 - }; - -HASH_TABLE mHash[] = { - { L"SHA1", 20, &mHashOidValue[0], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final }, - { L"SHA224", 28, &mHashOidValue[5], 9, NULL, NULL, NULL, NULL }, - { L"SHA256", 32, &mHashOidValue[14], 9, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Final}, - { L"SHA384", 48, &mHashOidValue[23], 9, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Final}, - { L"SHA512", 64, &mHashOidValue[32], 9, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Final} +UINT8 mHashOidValue[] = { + 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1 + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224 + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256 + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384 + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512 }; +HASH_TABLE mHash[] = { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES + { L"SHA1", 20, &mHashOidValue[0], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final }, + #else + { L"SHA1", 20, &mHashOidValue[0], 5, NULL, NULL, NULL, NULL }, + #endif + { L"SHA224", 28, &mHashOidValue[5], 9, NULL, NULL, NULL, NULL }, + { L"SHA256", 32, &mHashOidValue[14], 9, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Final }, + { L"SHA384", 48, &mHashOidValue[23], 9, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Final }, + { L"SHA512", 64, &mHashOidValue[32], 9, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Final } +}; + +EFI_STRING mHashTypeStr; + /** SecureBoot Hook for processing image verification. @@ -84,10 +84,10 @@ HASH_TABLE mHash[] = { VOID EFIAPI SecureBootHook ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN UINTN DataSize, - IN VOID *Data + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN UINTN DataSize, + IN VOID *Data ); /** @@ -108,15 +108,15 @@ SecureBootHook ( EFI_STATUS EFIAPI DxeImageVerificationLibImageRead ( - IN VOID *FileHandle, - IN UINTN FileOffset, - IN OUT UINTN *ReadSize, - OUT VOID *Buffer + IN VOID *FileHandle, + IN UINTN FileOffset, + IN OUT UINTN *ReadSize, + OUT VOID *Buffer ) { - UINTN EndPosition; + UINTN EndPosition; - if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) { + if ((FileHandle == NULL) || (ReadSize == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -133,12 +133,11 @@ DxeImageVerificationLibImageRead ( *ReadSize = 0; } - CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize); + CopyMem (Buffer, (UINT8 *)((UINTN)FileHandle + FileOffset), *ReadSize); return EFI_SUCCESS; } - /** Get the image type. @@ -150,13 +149,13 @@ DxeImageVerificationLibImageRead ( **/ UINT32 GetImageType ( - IN CONST EFI_DEVICE_PATH_PROTOCOL *File + IN CONST EFI_DEVICE_PATH_PROTOCOL *File ) { - EFI_STATUS Status; - EFI_HANDLE DeviceHandle; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - EFI_BLOCK_IO_PROTOCOL *BlockIo; + EFI_STATUS Status; + EFI_HANDLE DeviceHandle; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + EFI_BLOCK_IO_PROTOCOL *BlockIo; if (File == NULL) { return IMAGE_UNKNOWN; @@ -165,13 +164,13 @@ GetImageType ( // // First check to see if File is from a Firmware Volume // - DeviceHandle = NULL; - TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; - Status = gBS->LocateDevicePath ( - &gEfiFirmwareVolume2ProtocolGuid, - &TempDevicePath, - &DeviceHandle - ); + DeviceHandle = NULL; + TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)File; + Status = gBS->LocateDevicePath ( + &gEfiFirmwareVolume2ProtocolGuid, + &TempDevicePath, + &DeviceHandle + ); if (!EFI_ERROR (Status)) { Status = gBS->OpenProtocol ( DeviceHandle, @@ -190,23 +189,23 @@ GetImageType ( // Next check to see if File is from a Block I/O device // DeviceHandle = NULL; - TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; - Status = gBS->LocateDevicePath ( - &gEfiBlockIoProtocolGuid, - &TempDevicePath, - &DeviceHandle - ); + TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)File; + Status = gBS->LocateDevicePath ( + &gEfiBlockIoProtocolGuid, + &TempDevicePath, + &DeviceHandle + ); if (!EFI_ERROR (Status)) { BlockIo = NULL; - Status = gBS->OpenProtocol ( - DeviceHandle, - &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, - NULL, - NULL, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); - if (!EFI_ERROR (Status) && BlockIo != NULL) { + Status = gBS->OpenProtocol ( + DeviceHandle, + &gEfiBlockIoProtocolGuid, + (VOID **)&BlockIo, + NULL, + NULL, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); + if (!EFI_ERROR (Status) && (BlockIo != NULL)) { if (BlockIo->Media != NULL) { if (BlockIo->Media->RemovableMedia) { // @@ -228,12 +227,12 @@ GetImageType ( // the device path supports the Simple File System Protocol. // DeviceHandle = NULL; - TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; - Status = gBS->LocateDevicePath ( - &gEfiSimpleFileSystemProtocolGuid, - &TempDevicePath, - &DeviceHandle - ); + TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)File; + Status = gBS->LocateDevicePath ( + &gEfiSimpleFileSystemProtocolGuid, + &TempDevicePath, + &DeviceHandle + ); if (!EFI_ERROR (Status)) { // // Simple File System is present without Block I/O, so assume media is fixed. @@ -245,27 +244,30 @@ GetImageType ( // File is not from an FV, Block I/O or Simple File System, so the only options // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC. // - TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; + TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)File; while (!IsDevicePathEndType (TempDevicePath)) { switch (DevicePathType (TempDevicePath)) { + case MEDIA_DEVICE_PATH: + if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) { + return IMAGE_FROM_OPTION_ROM; + } - case MEDIA_DEVICE_PATH: - if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) { - return IMAGE_FROM_OPTION_ROM; - } - break; + break; - case MESSAGING_DEVICE_PATH: - if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) { - return IMAGE_FROM_REMOVABLE_MEDIA; - } - break; + case MESSAGING_DEVICE_PATH: + if (DevicePathSubType (TempDevicePath) == MSG_MAC_ADDR_DP) { + return IMAGE_FROM_REMOVABLE_MEDIA; + } - default: - break; + break; + + default: + break; } + TempDevicePath = NextDevicePathNode (TempDevicePath); } + return IMAGE_UNKNOWN; } @@ -277,6 +279,9 @@ GetImageType ( PE/COFF image is external input, so this function will validate its data structure within this image buffer before use. + Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in + its caller function DxeImageVerificationHandler(). + @param[in] HashAlg Hash algorithm type. @retval TRUE Successfully hash image. @@ -285,11 +290,10 @@ GetImageType ( **/ BOOLEAN HashPeImage ( - IN UINT32 HashAlg + IN UINT32 HashAlg ) { BOOLEAN Status; - UINT16 Magic; EFI_IMAGE_SECTION_HEADER *Section; VOID *HashCtx; UINTN CtxSize; @@ -316,31 +320,34 @@ HashPeImage ( ZeroMem (mImageDigest, MAX_DIGEST_SIZE); switch (HashAlg) { - case HASHALG_SHA1: - mImageDigestSize = SHA1_DIGEST_SIZE; - mCertType = gEfiCertSha1Guid; - break; - - case HASHALG_SHA256: - mImageDigestSize = SHA256_DIGEST_SIZE; - mCertType = gEfiCertSha256Guid; - break; - - case HASHALG_SHA384: - mImageDigestSize = SHA384_DIGEST_SIZE; - mCertType = gEfiCertSha384Guid; - break; - - case HASHALG_SHA512: - mImageDigestSize = SHA512_DIGEST_SIZE; - mCertType = gEfiCertSha512Guid; - break; - - default: - return FALSE; + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES + case HASHALG_SHA1: + mImageDigestSize = SHA1_DIGEST_SIZE; + mCertType = gEfiCertSha1Guid; + break; + #endif + + case HASHALG_SHA256: + mImageDigestSize = SHA256_DIGEST_SIZE; + mCertType = gEfiCertSha256Guid; + break; + + case HASHALG_SHA384: + mImageDigestSize = SHA384_DIGEST_SIZE; + mCertType = gEfiCertSha384Guid; + break; + + case HASHALG_SHA512: + mImageDigestSize = SHA512_DIGEST_SIZE; + mCertType = gEfiCertSha512Guid; + break; + + default: + return FALSE; } - CtxSize = mHash[HashAlg].GetContextSize(); + mHashTypeStr = mHash[HashAlg].Name; + CtxSize = mHash[HashAlg].GetContextSize (); HashCtx = AllocatePool (CtxSize); if (HashCtx == NULL) { @@ -350,7 +357,7 @@ HashPeImage ( // 1. Load the image header into memory. // 2. Initialize a SHA hash context. - Status = mHash[HashAlg].HashInit(HashCtx); + Status = mHash[HashAlg].HashInit (HashCtx); if (!Status) { goto Done; @@ -360,37 +367,23 @@ HashPeImage ( // Measuring PE/COFF Image Header; // But CheckSum field and SECURITY data directory (certificate) are excluded // - if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { - // - // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value - // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the - // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC - // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC - // - Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC; - } else { - // - // Get the magic value from the PE/COFF Optional Header - // - Magic = mNtHeader.Pe32->OptionalHeader.Magic; - } // // 3. Calculate the distance from the base of the image header to the image checksum address. // 4. Hash the image header from its base to beginning of the image checksum. // HashBase = mImageBase; - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // - HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase); + HashSize = (UINTN)(&mNtHeader.Pe32->OptionalHeader.CheckSum) - (UINTN)HashBase; NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes; - } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) { + } else if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) { // // Use PE32+ offset. // - HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase); + HashSize = (UINTN)(&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - (UINTN)HashBase; NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes; } else { // @@ -400,7 +393,7 @@ HashPeImage ( goto Done; } - Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); + Status = mHash[HashAlg].HashUpdate (HashCtx, HashBase, HashSize); if (!Status) { goto Done; } @@ -413,22 +406,22 @@ HashPeImage ( // 6. Since there is no Cert Directory in optional header, hash everything // from the end of the checksum to the end of image header. // - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // - HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32); - HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase); + HashBase = (UINT8 *)&mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32); + HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN)HashBase - (UINTN)mImageBase); } else { // // Use PE32+ offset. // - HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32); - HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase); + HashBase = (UINT8 *)&mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32); + HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN)HashBase - (UINTN)mImageBase); } if (HashSize != 0) { - Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); + Status = mHash[HashAlg].HashUpdate (HashCtx, HashBase, HashSize); if (!Status) { goto Done; } @@ -437,22 +430,22 @@ HashPeImage ( // // 7. Hash everything from the end of the checksum to the start of the Cert Directory. // - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // - HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32); - HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase); + HashBase = (UINT8 *)&mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32); + HashSize = (UINTN)(&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN)HashBase; } else { // // Use PE32+ offset. // - HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32); - HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase); + HashBase = (UINT8 *)&mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32); + HashSize = (UINTN)(&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN)HashBase; } if (HashSize != 0) { - Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); + Status = mHash[HashAlg].HashUpdate (HashCtx, HashBase, HashSize); if (!Status) { goto Done; } @@ -462,22 +455,22 @@ HashPeImage ( // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.) // 9. Hash everything from the end of the Cert Directory to the end of image header. // - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset // - HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]; - HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase); + HashBase = (UINT8 *)&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]; + HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN)HashBase - (UINTN)mImageBase); } else { // // Use PE32+ offset. // - HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]; - HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase); + HashBase = (UINT8 *)&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]; + HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN)HashBase - (UINTN)mImageBase); } if (HashSize != 0) { - Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); + Status = mHash[HashAlg].HashUpdate (HashCtx, HashBase, HashSize); if (!Status) { goto Done; } @@ -487,7 +480,7 @@ HashPeImage ( // // 10. Set the SUM_OF_BYTES_HASHED to the size of the header. // - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // @@ -499,14 +492,13 @@ HashPeImage ( SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders; } - - Section = (EFI_IMAGE_SECTION_HEADER *) ( - mImageBase + - mPeCoffHeaderOffset + - sizeof (UINT32) + - sizeof (EFI_IMAGE_FILE_HEADER) + - mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader - ); + Section = (EFI_IMAGE_SECTION_HEADER *)( + mImageBase + + mPeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader + ); // // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER @@ -514,11 +506,12 @@ HashPeImage ( // header indicates how big the table should be. Do not include any // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero. // - SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections); + SectionHeader = (EFI_IMAGE_SECTION_HEADER *)AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections); if (SectionHeader == NULL) { Status = FALSE; goto Done; } + // // 12. Using the 'PointerToRawData' in the referenced section headers as // a key, arrange the elements in the table in ascending order. In other @@ -531,6 +524,7 @@ HashPeImage ( CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER)); Pos--; } + CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER)); Section += 1; } @@ -547,10 +541,11 @@ HashPeImage ( if (Section->SizeOfRawData == 0) { continue; } - HashBase = mImageBase + Section->PointerToRawData; - HashSize = (UINTN) Section->SizeOfRawData; - Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); + HashBase = mImageBase + Section->PointerToRawData; + HashSize = (UINTN)Section->SizeOfRawData; + + Status = mHash[HashAlg].HashUpdate (HashCtx, HashBase, HashSize); if (!Status) { goto Done; } @@ -570,7 +565,7 @@ HashPeImage ( if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { CertSize = 0; } else { - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // @@ -584,9 +579,9 @@ HashPeImage ( } if (mImageSize > CertSize + SumOfBytesHashed) { - HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed); + HashSize = (UINTN)(mImageSize - CertSize - SumOfBytesHashed); - Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); + Status = mHash[HashAlg].HashUpdate (HashCtx, HashBase, HashSize); if (!Status) { goto Done; } @@ -596,15 +591,17 @@ HashPeImage ( } } - Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest); + Status = mHash[HashAlg].HashFinal (HashCtx, mImageDigest); Done: if (HashCtx != NULL) { FreePool (HashCtx); } + if (SectionHeader != NULL) { FreePool (SectionHeader); } + return Status; } @@ -626,11 +623,11 @@ Done: **/ EFI_STATUS HashPeImageByType ( - IN UINT8 *AuthData, - IN UINTN AuthDataSize + IN UINT8 *AuthData, + IN UINTN AuthDataSize ) { - UINT8 Index; + UINT8 Index; for (Index = 0; Index < HASHALG_MAX; Index++) { // @@ -668,14 +665,13 @@ HashPeImageByType ( // // HASH PE Image based on Hash algorithm in PE/COFF Authenticode. // - if (!HashPeImage(Index)) { + if (!HashPeImage (Index)) { return EFI_UNSUPPORTED; } return EFI_SUCCESS; } - /** Returns the size of a given image execution info table in bytes. @@ -690,7 +686,7 @@ HashPeImageByType ( **/ UINTN GetImageExeInfoTableSize ( - EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable + EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable ) { UINTN Index; @@ -701,11 +697,11 @@ GetImageExeInfoTableSize ( return 0; } - ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE)); - TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); + ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *)((UINT8 *)ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE)); + TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) { - TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize); - ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize)); + TotalSize += ReadUnaligned32 ((UINT32 *)&ImageExeInfoItem->InfoSize); + ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *)((UINT8 *)ImageExeInfoItem + ReadUnaligned32 ((UINT32 *)&ImageExeInfoItem->InfoSize)); } return TotalSize; @@ -718,16 +714,16 @@ GetImageExeInfoTableSize ( @param[in] Name Input a null-terminated, user-friendly name. @param[in] DevicePath Input device path pointer. @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure. - @param[in] SignatureSize Size of signature. + @param[in] SignatureSize Size of signature. Must be zero if Signature is NULL. **/ VOID AddImageExeInfo ( - IN EFI_IMAGE_EXECUTION_ACTION Action, - IN CHAR16 *Name OPTIONAL, - IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN EFI_SIGNATURE_LIST *Signature OPTIONAL, - IN UINTN SignatureSize + IN EFI_IMAGE_EXECUTION_ACTION Action, + IN CHAR16 *Name OPTIONAL, + IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN EFI_SIGNATURE_LIST *Signature OPTIONAL, + IN UINTN SignatureSize ) { EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable; @@ -737,14 +733,16 @@ AddImageExeInfo ( UINTN NewImageExeInfoEntrySize; UINTN NameStringLen; UINTN DevicePathSize; + CHAR16 *NameStr; - ImageExeInfoTable = NULL; - NewImageExeInfoTable = NULL; - ImageExeInfoEntry = NULL; - NameStringLen = 0; + ImageExeInfoTable = NULL; + NewImageExeInfoTable = NULL; + ImageExeInfoEntry = NULL; + NameStringLen = 0; + NameStr = NULL; if (DevicePath == NULL) { - return ; + return; } if (Name != NULL) { @@ -753,11 +751,11 @@ AddImageExeInfo ( NameStringLen = sizeof (CHAR16); } - EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable); + EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **)&ImageExeInfoTable); if (ImageExeInfoTable != NULL) { // // The table has been found! - // We must enlarge the table to accomodate the new exe info entry. + // We must enlarge the table to accommodate the new exe info entry. // ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable); } else { @@ -768,11 +766,17 @@ AddImageExeInfo ( ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); } - DevicePathSize = GetDevicePathSize (DevicePath); - NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize; - NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize); + DevicePathSize = GetDevicePathSize (DevicePath); + + // + // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align + // + ASSERT (Signature != NULL || SignatureSize == 0); + NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize; + + NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *)AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize); if (NewImageExeInfoTable == NULL) { - return ; + return; } if (ImageExeInfoTable != NULL) { @@ -780,35 +784,39 @@ AddImageExeInfo ( } else { NewImageExeInfoTable->NumberOfImages = 0; } + NewImageExeInfoTable->NumberOfImages++; - ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize); + ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *)((UINT8 *)NewImageExeInfoTable + ImageExeInfoTableSize); // // Update new item's information. // - WriteUnaligned32 ((UINT32 *) ImageExeInfoEntry, Action); - WriteUnaligned32 ((UINT32 *) ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION)), (UINT32) NewImageExeInfoEntrySize); + WriteUnaligned32 ((UINT32 *)ImageExeInfoEntry, Action); + WriteUnaligned32 ((UINT32 *)((UINT8 *)ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION)), (UINT32)NewImageExeInfoEntrySize); + NameStr = (CHAR16 *)(ImageExeInfoEntry + 1); if (Name != NULL) { - CopyMem ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION) + sizeof (UINT32), Name, NameStringLen); + CopyMem ((UINT8 *)NameStr, Name, NameStringLen); } else { - ZeroMem ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION) + sizeof (UINT32), sizeof (CHAR16)); + ZeroMem ((UINT8 *)NameStr, sizeof (CHAR16)); } + CopyMem ( - (UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION) + sizeof (UINT32) + NameStringLen, + (UINT8 *)NameStr + NameStringLen, DevicePath, DevicePathSize ); if (Signature != NULL) { CopyMem ( - (UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION) + sizeof (UINT32) + NameStringLen + DevicePathSize, + (UINT8 *)NameStr + NameStringLen + DevicePathSize, Signature, SignatureSize ); } + // // Update/replace the image execution table. // - gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable); + gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *)NewImageExeInfoTable); // // Free Old table data! @@ -826,22 +834,23 @@ AddImageExeInfo ( @param[in] SignatureList Pointer to the Signature List in forbidden database. @param[in] SignatureListSize Size of Signature List. @param[out] RevocationTime Return the time that the certificate was revoked. + @param[out] IsFound Search result. Only valid if EFI_SUCCESS returned. - @return TRUE The certificate hash is found in the forbidden database. - @return FALSE The certificate hash is not found in the forbidden database. + @retval EFI_SUCCESS Finished the search without any error. + @retval Others Error occurred in the search of database. **/ -BOOLEAN -IsCertHashFoundInDatabase ( +EFI_STATUS +IsCertHashFoundInDbx ( IN UINT8 *Certificate, IN UINTN CertSize, IN EFI_SIGNATURE_LIST *SignatureList, IN UINTN SignatureListSize, - OUT EFI_TIME *RevocationTime + OUT EFI_TIME *RevocationTime, + OUT BOOLEAN *IsFound ) { - BOOLEAN IsFound; - BOOLEAN Status; + EFI_STATUS Status; EFI_SIGNATURE_LIST *DbxList; UINTN DbxSize; EFI_SIGNATURE_DATA *CertHash; @@ -855,21 +864,22 @@ IsCertHashFoundInDatabase ( UINT8 *TBSCert; UINTN TBSCertSize; - IsFound = FALSE; + Status = EFI_ABORTED; + *IsFound = FALSE; DbxList = SignatureList; DbxSize = SignatureListSize; HashCtx = NULL; HashAlg = HASHALG_MAX; if ((RevocationTime == NULL) || (DbxList == NULL)) { - return FALSE; + return EFI_INVALID_PARAMETER; } // // Retrieve the TBSCertificate from the X.509 Certificate. // if (!X509GetTBSCert (Certificate, CertSize, &TBSCert, &TBSCertSize)) { - return FALSE; + return Status; } while ((DbxSize > 0) && (SignatureListSize >= DbxList->SignatureListSize)) { @@ -884,7 +894,7 @@ IsCertHashFoundInDatabase ( HashAlg = HASHALG_SHA512; } else { DbxSize -= DbxList->SignatureListSize; - DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize); + DbxList = (EFI_SIGNATURE_LIST *)((UINT8 *)DbxList + DbxList->SignatureListSize); continue; } @@ -894,26 +904,30 @@ IsCertHashFoundInDatabase ( if (mHash[HashAlg].GetContextSize == NULL) { goto Done; } + ZeroMem (CertDigest, MAX_DIGEST_SIZE); HashCtx = AllocatePool (mHash[HashAlg].GetContextSize ()); if (HashCtx == NULL) { goto Done; } - Status = mHash[HashAlg].HashInit (HashCtx); - if (!Status) { + + if (!mHash[HashAlg].HashInit (HashCtx)) { goto Done; } - Status = mHash[HashAlg].HashUpdate (HashCtx, TBSCert, TBSCertSize); - if (!Status) { + + if (!mHash[HashAlg].HashUpdate (HashCtx, TBSCert, TBSCertSize)) { goto Done; } - Status = mHash[HashAlg].HashFinal (HashCtx, CertDigest); - if (!Status) { + + if (!mHash[HashAlg].HashFinal (HashCtx, CertDigest)) { goto Done; } + FreePool (HashCtx); + HashCtx = NULL; + SiglistHeaderSize = sizeof (EFI_SIGNATURE_LIST) + DbxList->SignatureHeaderSize; - CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) DbxList + SiglistHeaderSize); + CertHash = (EFI_SIGNATURE_DATA *)((UINT8 *)DbxList + SiglistHeaderSize); CertHashCount = (DbxList->SignatureListSize - SiglistHeaderSize) / DbxList->SignatureSize; for (Index = 0; Index < CertHashCount; Index++) { // @@ -924,7 +938,8 @@ IsCertHashFoundInDatabase ( // // Hash of Certificate is found in forbidden database. // - IsFound = TRUE; + Status = EFI_SUCCESS; + *IsFound = TRUE; // // Return the revocation time. @@ -932,19 +947,22 @@ IsCertHashFoundInDatabase ( CopyMem (RevocationTime, (EFI_TIME *)(DbxCertHash + mHash[HashAlg].DigestLength), sizeof (EFI_TIME)); goto Done; } - CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertHash + DbxList->SignatureSize); + + CertHash = (EFI_SIGNATURE_DATA *)((UINT8 *)CertHash + DbxList->SignatureSize); } DbxSize -= DbxList->SignatureListSize; - DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize); + DbxList = (EFI_SIGNATURE_LIST *)((UINT8 *)DbxList + DbxList->SignatureListSize); } + Status = EFI_SUCCESS; + Done: if (HashCtx != NULL) { FreePool (HashCtx); } - return IsFound; + return Status; } /** @@ -952,19 +970,21 @@ Done: @param[in] VariableName Name of database variable that is searched in. @param[in] Signature Pointer to signature that is searched for. - @param[in] CertType Pointer to hash algrithom. + @param[in] CertType Pointer to hash algorithm. @param[in] SignatureSize Size of Signature. + @param[out] IsFound Search result. Only valid if EFI_SUCCESS returned - @return TRUE Found the signature in the variable database. - @return FALSE Not found the signature in the variable database. + @retval EFI_SUCCESS Finished the search without any error. + @retval Others Error occurred in the search of database. **/ -BOOLEAN +EFI_STATUS IsSignatureFoundInDatabase ( - IN CHAR16 *VariableName, - IN UINT8 *Signature, - IN EFI_GUID *CertType, - IN UINTN SignatureSize + IN CHAR16 *VariableName, + IN UINT8 *Signature, + IN EFI_GUID *CertType, + IN UINTN SignatureSize, + OUT BOOLEAN *IsFound ) { EFI_STATUS Status; @@ -974,56 +994,69 @@ IsSignatureFoundInDatabase ( UINT8 *Data; UINTN Index; UINTN CertCount; - BOOLEAN IsFound; // // Read signature database variable. // - IsFound = FALSE; - Data = NULL; - DataSize = 0; - Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); + *IsFound = FALSE; + Data = NULL; + DataSize = 0; + Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); if (Status != EFI_BUFFER_TOO_SMALL) { - return FALSE; + if (Status == EFI_NOT_FOUND) { + // + // No database, no need to search. + // + Status = EFI_SUCCESS; + } + + return Status; } - Data = (UINT8 *) AllocateZeroPool (DataSize); + Data = (UINT8 *)AllocateZeroPool (DataSize); if (Data == NULL) { - return FALSE; + return EFI_OUT_OF_RESOURCES; } Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data); if (EFI_ERROR (Status)) { goto Done; } + // - // Enumerate all signature data in SigDB to check if executable's signature exists. + // Enumerate all signature data in SigDB to check if signature exists for executable. // - CertList = (EFI_SIGNATURE_LIST *) Data; + CertList = (EFI_SIGNATURE_LIST *)Data; while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) { CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; - Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); - if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) { + Cert = (EFI_SIGNATURE_DATA *)((UINT8 *)CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); + if ((CertList->SignatureSize == sizeof (EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid (&CertList->SignatureType, CertType))) { for (Index = 0; Index < CertCount; Index++) { if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) { // // Find the signature in database. // - IsFound = TRUE; - SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert); + *IsFound = TRUE; + // + // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured + // + if (StrCmp (VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) { + SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert); + } + break; } - Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize); + Cert = (EFI_SIGNATURE_DATA *)((UINT8 *)Cert + CertList->SignatureSize); } - if (IsFound) { + if (*IsFound) { break; } } DataSize -= CertList->SignatureListSize; - CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); + CertList = (EFI_SIGNATURE_LIST *)((UINT8 *)CertList + CertList->SignatureListSize); } Done: @@ -1031,7 +1064,7 @@ Done: FreePool (Data); } - return IsFound; + return Status; } /** @@ -1046,23 +1079,23 @@ Done: **/ BOOLEAN IsValidSignatureByTimestamp ( - IN EFI_TIME *SigningTime, - IN EFI_TIME *RevocationTime + IN EFI_TIME *SigningTime, + IN EFI_TIME *RevocationTime ) { if (SigningTime->Year != RevocationTime->Year) { - return (BOOLEAN) (SigningTime->Year < RevocationTime->Year); + return (BOOLEAN)(SigningTime->Year < RevocationTime->Year); } else if (SigningTime->Month != RevocationTime->Month) { - return (BOOLEAN) (SigningTime->Month < RevocationTime->Month); + return (BOOLEAN)(SigningTime->Month < RevocationTime->Month); } else if (SigningTime->Day != RevocationTime->Day) { - return (BOOLEAN) (SigningTime->Day < RevocationTime->Day); + return (BOOLEAN)(SigningTime->Day < RevocationTime->Day); } else if (SigningTime->Hour != RevocationTime->Hour) { - return (BOOLEAN) (SigningTime->Hour < RevocationTime->Hour); + return (BOOLEAN)(SigningTime->Hour < RevocationTime->Hour); } else if (SigningTime->Minute != RevocationTime->Minute) { - return (BOOLEAN) (SigningTime->Minute < RevocationTime->Minute); + return (BOOLEAN)(SigningTime->Minute < RevocationTime->Minute); } - return (BOOLEAN) (SigningTime->Second <= RevocationTime->Second); + return (BOOLEAN)(SigningTime->Second <= RevocationTime->Second); } /** @@ -1076,11 +1109,12 @@ IsValidSignatureByTimestamp ( **/ BOOLEAN IsTimeZero ( - IN EFI_TIME *Time + IN EFI_TIME *Time ) { if ((Time->Year == 0) && (Time->Month == 0) && (Time->Day == 0) && - (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) { + (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) + { return TRUE; } @@ -1088,14 +1122,14 @@ IsTimeZero ( } /** - Check whether the timestamp signature is valid and the signing time is also earlier than + Check whether the timestamp signature is valid and the signing time is also earlier than the revocation time. @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image. @param[in] AuthDataSize Size of the Authenticode signature in bytes. @param[in] RevocationTime The time that the certificate was revoked. - @retval TRUE Timestamp signature is valid and signing time is no later than the + @retval TRUE Timestamp signature is valid and signing time is no later than the revocation time. @retval FALSE Timestamp signature is not valid or the signing time is later than the revocation time. @@ -1103,32 +1137,32 @@ IsTimeZero ( **/ BOOLEAN PassTimestampCheck ( - IN UINT8 *AuthData, - IN UINTN AuthDataSize, - IN EFI_TIME *RevocationTime + IN UINT8 *AuthData, + IN UINTN AuthDataSize, + IN EFI_TIME *RevocationTime ) { - EFI_STATUS Status; - BOOLEAN VerifyStatus; - EFI_SIGNATURE_LIST *CertList; - EFI_SIGNATURE_DATA *Cert; - UINT8 *DbtData; - UINTN DbtDataSize; - UINT8 *RootCert; - UINTN RootCertSize; - UINTN Index; - UINTN CertCount; - EFI_TIME SigningTime; + EFI_STATUS Status; + BOOLEAN VerifyStatus; + EFI_SIGNATURE_LIST *CertList; + EFI_SIGNATURE_DATA *Cert; + UINT8 *DbtData; + UINTN DbtDataSize; + UINT8 *RootCert; + UINTN RootCertSize; + UINTN Index; + UINTN CertCount; + EFI_TIME SigningTime; // // Variable Initialization // - VerifyStatus = FALSE; - DbtData = NULL; - CertList = NULL; - Cert = NULL; - RootCert = NULL; - RootCertSize = 0; + VerifyStatus = FALSE; + DbtData = NULL; + CertList = NULL; + Cert = NULL; + RootCert = NULL; + RootCertSize = 0; // // If RevocationTime is zero, the certificate shall be considered to always be revoked. @@ -1142,23 +1176,25 @@ PassTimestampCheck ( // Using the dbt to get the trusted TSA certificates. // DbtDataSize = 0; - Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL); + Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL); if (Status != EFI_BUFFER_TOO_SMALL) { goto Done; } - DbtData = (UINT8 *) AllocateZeroPool (DbtDataSize); + + DbtData = (UINT8 *)AllocateZeroPool (DbtDataSize); if (DbtData == NULL) { goto Done; } - Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *) DbtData); + + Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *)DbtData); if (EFI_ERROR (Status)) { goto Done; } - CertList = (EFI_SIGNATURE_LIST *) DbtData; + CertList = (EFI_SIGNATURE_LIST *)DbtData; while ((DbtDataSize > 0) && (DbtDataSize >= CertList->SignatureListSize)) { if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { - Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); + Cert = (EFI_SIGNATURE_DATA *)((UINT8 *)CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; for (Index = 0; Index < CertCount; Index++) { // @@ -1178,11 +1214,13 @@ PassTimestampCheck ( goto Done; } } - Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize); + + Cert = (EFI_SIGNATURE_DATA *)((UINT8 *)Cert + CertList->SignatureSize); } } + DbtDataSize -= CertList->SignatureListSize; - CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); + CertList = (EFI_SIGNATURE_LIST *)((UINT8 *)CertList + CertList->SignatureListSize); } Done: @@ -1206,35 +1244,36 @@ Done: **/ BOOLEAN IsForbiddenByDbx ( - IN UINT8 *AuthData, - IN UINTN AuthDataSize + IN UINT8 *AuthData, + IN UINTN AuthDataSize ) { - EFI_STATUS Status; - BOOLEAN IsForbidden; - UINT8 *Data; - UINTN DataSize; - EFI_SIGNATURE_LIST *CertList; - UINTN CertListSize; - EFI_SIGNATURE_DATA *CertData; - UINT8 *RootCert; - UINTN RootCertSize; - UINTN CertCount; - UINTN Index; - UINT8 *CertBuffer; - UINTN BufferLength; - UINT8 *TrustedCert; - UINTN TrustedCertLength; - UINT8 CertNumber; - UINT8 *CertPtr; - UINT8 *Cert; - UINTN CertSize; - EFI_TIME RevocationTime; + EFI_STATUS Status; + BOOLEAN IsForbidden; + BOOLEAN IsFound; + UINT8 *Data; + UINTN DataSize; + EFI_SIGNATURE_LIST *CertList; + UINTN CertListSize; + EFI_SIGNATURE_DATA *CertData; + UINT8 *RootCert; + UINTN RootCertSize; + UINTN CertCount; + UINTN Index; + UINT8 *CertBuffer; + UINTN BufferLength; + UINT8 *TrustedCert; + UINTN TrustedCertLength; + UINT8 CertNumber; + UINT8 *CertPtr; + UINT8 *Cert; + UINTN CertSize; + EFI_TIME RevocationTime; // // Variable Initialization // - IsForbidden = FALSE; + IsForbidden = TRUE; Data = NULL; CertList = NULL; CertData = NULL; @@ -1251,28 +1290,37 @@ IsForbiddenByDbx ( // DataSize = 0; Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); + ASSERT (EFI_ERROR (Status)); if (Status != EFI_BUFFER_TOO_SMALL) { + if (Status == EFI_NOT_FOUND) { + // + // Evidently not in dbx if the database doesn't exist. + // + IsForbidden = FALSE; + } + return IsForbidden; } - Data = (UINT8 *) AllocateZeroPool (DataSize); + + Data = (UINT8 *)AllocateZeroPool (DataSize); if (Data == NULL) { return IsForbidden; } - Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data); + Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *)Data); if (EFI_ERROR (Status)) { - return IsForbidden; + goto Done; } // // Verify image signature with RAW X509 certificates in DBX database. // If passed, the image will be forbidden. // - CertList = (EFI_SIGNATURE_LIST *) Data; + CertList = (EFI_SIGNATURE_LIST *)Data; CertListSize = DataSize; while ((CertListSize > 0) && (CertListSize >= CertList->SignatureListSize)) { if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { - CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); + CertData = (EFI_SIGNATURE_DATA *)((UINT8 *)CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; for (Index = 0; Index < CertCount; Index++) { @@ -1294,16 +1342,16 @@ IsForbiddenByDbx ( mImageDigestSize ); if (IsForbidden) { - SecureBootHook (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData); + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n")); goto Done; } - CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize); + CertData = (EFI_SIGNATURE_DATA *)((UINT8 *)CertData + CertList->SignatureSize); } } CertListSize -= CertList->SignatureListSize; - CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); + CertList = (EFI_SIGNATURE_LIST *)((UINT8 *)CertList + CertList->SignatureListSize); } // @@ -1323,7 +1371,7 @@ IsForbiddenByDbx ( // UINT8 Certn[]; // Pkcs7GetSigners (AuthData, AuthDataSize, &CertBuffer, &BufferLength, &TrustedCert, &TrustedCertLength); - if ((BufferLength == 0) || (CertBuffer == NULL)) { + if ((BufferLength == 0) || (CertBuffer == NULL) || ((*CertBuffer) == 0)) { IsForbidden = TRUE; goto Done; } @@ -1331,26 +1379,44 @@ IsForbiddenByDbx ( // // Check if any hash of certificates embedded in AuthData is in the forbidden database. // - CertNumber = (UINT8) (*CertBuffer); + CertNumber = (UINT8)(*CertBuffer); CertPtr = CertBuffer + 1; for (Index = 0; Index < CertNumber; Index++) { - CertSize = (UINTN) ReadUnaligned32 ((UINT32 *)CertPtr); + CertSize = (UINTN)ReadUnaligned32 ((UINT32 *)CertPtr); Cert = (UINT8 *)CertPtr + sizeof (UINT32); + // + // Advance CertPtr to the next cert in image signer's cert list + // + CertPtr = CertPtr + sizeof (UINT32) + CertSize; - if (IsCertHashFoundInDatabase (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime)) { + Status = IsCertHashFoundInDbx (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime, &IsFound); + if (EFI_ERROR (Status)) { // - // Check the timestamp signature and signing time to determine if the image can be trusted. + // Error in searching dbx. Consider it as 'found'. RevocationTime might + // not be valid in such situation. // IsForbidden = TRUE; + } else if (IsFound) { + // + // Found Cert in dbx successfully. Check the timestamp signature and + // signing time to determine if the image can be trusted. + // if (PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime)) { IsForbidden = FALSE; + // + // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT + // + continue; + } else { + IsForbidden = TRUE; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n")); + goto Done; } - goto Done; } - - CertPtr = CertPtr + sizeof (UINT32) + CertSize; } + IsForbidden = FALSE; + Done: if (Data != NULL) { FreePool (Data); @@ -1374,117 +1440,165 @@ Done: **/ BOOLEAN IsAllowedByDb ( - IN UINT8 *AuthData, - IN UINTN AuthDataSize + IN UINT8 *AuthData, + IN UINTN AuthDataSize ) { - EFI_STATUS Status; - BOOLEAN VerifyStatus; - EFI_SIGNATURE_LIST *CertList; - EFI_SIGNATURE_DATA *Cert; - UINTN DataSize; - UINT8 *Data; - UINT8 *RootCert; - UINTN RootCertSize; - UINTN Index; - UINTN CertCount; - UINTN DbxDataSize; - UINT8 *DbxData; - EFI_TIME RevocationTime; + EFI_STATUS Status; + BOOLEAN VerifyStatus; + BOOLEAN IsFound; + EFI_SIGNATURE_LIST *CertList; + EFI_SIGNATURE_DATA *CertData; + UINTN DataSize; + UINT8 *Data; + UINT8 *RootCert; + UINTN RootCertSize; + UINTN Index; + UINTN CertCount; + UINTN DbxDataSize; + UINT8 *DbxData; + EFI_TIME RevocationTime; Data = NULL; CertList = NULL; - Cert = NULL; + CertData = NULL; RootCert = NULL; DbxData = NULL; RootCertSize = 0; VerifyStatus = FALSE; + // + // Fetch 'db' content. If 'db' doesn't exist or encounters problem to get the + // data, return not-allowed-by-db (FALSE). + // DataSize = 0; Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL); - if (Status == EFI_BUFFER_TOO_SMALL) { - Data = (UINT8 *) AllocateZeroPool (DataSize); - if (Data == NULL) { - return VerifyStatus; - } + ASSERT (EFI_ERROR (Status)); + if (Status != EFI_BUFFER_TOO_SMALL) { + return VerifyStatus; + } - Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data); - if (EFI_ERROR (Status)) { + Data = (UINT8 *)AllocateZeroPool (DataSize); + if (Data == NULL) { + return VerifyStatus; + } + + Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *)Data); + if (EFI_ERROR (Status)) { + goto Done; + } + + // + // Fetch 'dbx' content. If 'dbx' doesn't exist, continue to check 'db'. + // If any other errors occurred, no need to check 'db' but just return + // not-allowed-by-db (FALSE) to avoid bypass. + // + DbxDataSize = 0; + Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL); + ASSERT (EFI_ERROR (Status)); + if (Status != EFI_BUFFER_TOO_SMALL) { + if (Status != EFI_NOT_FOUND) { goto Done; } // - // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data. + // 'dbx' does not exist. Continue to check 'db'. + // + } else { // - CertList = (EFI_SIGNATURE_LIST *) Data; - while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) { - if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { - Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); - CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; + // 'dbx' exists. Get its content. + // + DbxData = (UINT8 *)AllocateZeroPool (DbxDataSize); + if (DbxData == NULL) { + goto Done; + } - for (Index = 0; Index < CertCount; Index++) { - // - // Iterate each Signature Data Node within this CertList for verify. - // - RootCert = Cert->SignatureData; - RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID); + Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *)DbxData); + if (EFI_ERROR (Status)) { + goto Done; + } + } + + // + // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data. + // + CertList = (EFI_SIGNATURE_LIST *)Data; + while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) { + if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) { + CertData = (EFI_SIGNATURE_DATA *)((UINT8 *)CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize); + CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize; + for (Index = 0; Index < CertCount; Index++) { + // + // Iterate each Signature Data Node within this CertList for verify. + // + RootCert = CertData->SignatureData; + RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID); + + // + // Call AuthenticodeVerify library to Verify Authenticode struct. + // + VerifyStatus = AuthenticodeVerify ( + AuthData, + AuthDataSize, + RootCert, + RootCertSize, + mImageDigest, + mImageDigestSize + ); + if (VerifyStatus) { // - // Call AuthenticodeVerify library to Verify Authenticode struct. + // The image is signed and its signature is found in 'db'. // - VerifyStatus = AuthenticodeVerify ( - AuthData, - AuthDataSize, - RootCert, - RootCertSize, - mImageDigest, - mImageDigestSize - ); - if (VerifyStatus) { + if (DbxData != NULL) { // // Here We still need to check if this RootCert's Hash is revoked // - Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL); - if (Status == EFI_BUFFER_TOO_SMALL) { - goto Done; - } - DbxData = (UINT8 *) AllocateZeroPool (DataSize); - if (DbxData == NULL) { - goto Done; - } - - Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *) DbxData); + Status = IsCertHashFoundInDbx (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime, &IsFound); if (EFI_ERROR (Status)) { - goto Done; - } - - if (IsCertHashFoundInDatabase (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime)) { // - // Check the timestamp signature and signing time to determine if the image can be trusted. + // Error in searching dbx. Consider it as 'found'. RevocationTime might + // not be valid in such situation. + // + VerifyStatus = FALSE; + } else if (IsFound) { + // + // Check the timestamp signature and signing time to determine if the RootCert can be trusted. // VerifyStatus = PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime); + if (!VerifyStatus) { + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n")); + } } - - goto Done; } - Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize); + // + // There's no 'dbx' to check revocation time against (must-be pass), + // or, there's revocation time found in 'dbx' and checked againt 'dbt' + // (maybe pass or fail, depending on timestamp compare result). Either + // way the verification job has been completed at this point. + // + goto Done; } - } - DataSize -= CertList->SignatureListSize; - CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize); + CertData = (EFI_SIGNATURE_DATA *)((UINT8 *)CertData + CertList->SignatureSize); + } } + + DataSize -= CertList->SignatureListSize; + CertList = (EFI_SIGNATURE_LIST *)((UINT8 *)CertList + CertList->SignatureListSize); } Done: + if (VerifyStatus) { - SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert); + SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData); } if (Data != NULL) { FreePool (Data); } + if (DbxData != NULL) { FreePool (DbxData); } @@ -1529,46 +1643,50 @@ Done: and non-NULL FileBuffer did authenticate, and the platform policy dictates that the DXE Foundation may execute the image in FileBuffer. - @retval EFI_OUT_RESOURCE Fail to allocate memory. @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and the platform policy dictates that File should be placed in the untrusted state. The image has been added to the file execution table. @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not authenticate, and the platform policy dictates that the DXE - Foundation many not use File. + Foundation may not use File. The image has + been added to the file execution table. **/ EFI_STATUS EFIAPI DxeImageVerificationHandler ( - IN UINT32 AuthenticationStatus, - IN CONST EFI_DEVICE_PATH_PROTOCOL *File, - IN VOID *FileBuffer, - IN UINTN FileSize, - IN BOOLEAN BootPolicy + IN UINT32 AuthenticationStatus, + IN CONST EFI_DEVICE_PATH_PROTOCOL *File OPTIONAL, + IN VOID *FileBuffer, + IN UINTN FileSize, + IN BOOLEAN BootPolicy ) { - EFI_STATUS Status; - UINT16 Magic; - EFI_IMAGE_DOS_HEADER *DosHdr; - EFI_STATUS VerifyStatus; - EFI_SIGNATURE_LIST *SignatureList; - UINTN SignatureListSize; - EFI_SIGNATURE_DATA *Signature; - EFI_IMAGE_EXECUTION_ACTION Action; - WIN_CERTIFICATE *WinCertificate; - UINT32 Policy; - UINT8 *SecureBoot; - PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; - UINT32 NumberOfRvaAndSizes; - WIN_CERTIFICATE_EFI_PKCS *PkcsCertData; - WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid; - UINT8 *AuthData; - UINTN AuthDataSize; - EFI_IMAGE_DATA_DIRECTORY *SecDataDir; - UINT32 OffSet; - CHAR16 *NameStr; + EFI_IMAGE_DOS_HEADER *DosHdr; + BOOLEAN IsVerified; + EFI_SIGNATURE_LIST *SignatureList; + UINTN SignatureListSize; + EFI_SIGNATURE_DATA *Signature; + EFI_IMAGE_EXECUTION_ACTION Action; + WIN_CERTIFICATE *WinCertificate; + UINT32 Policy; + UINT8 *SecureBoot; + PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; + UINT32 NumberOfRvaAndSizes; + WIN_CERTIFICATE_EFI_PKCS *PkcsCertData; + WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid; + UINT8 *AuthData; + UINTN AuthDataSize; + EFI_IMAGE_DATA_DIRECTORY *SecDataDir; + UINT32 SecDataDirEnd; + UINT32 SecDataDirLeft; + UINT32 OffSet; + CHAR16 *NameStr; + RETURN_STATUS PeCoffStatus; + EFI_STATUS HashStatus; + EFI_STATUS DbStatus; + BOOLEAN IsFound; SignatureList = NULL; SignatureListSize = 0; @@ -1576,40 +1694,42 @@ DxeImageVerificationHandler ( SecDataDir = NULL; PkcsCertData = NULL; Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED; - Status = EFI_ACCESS_DENIED; - VerifyStatus = EFI_ACCESS_DENIED; + IsVerified = FALSE; + IsFound = FALSE; // // Check the image type and get policy setting. // switch (GetImageType (File)) { + case IMAGE_FROM_FV: + Policy = ALWAYS_EXECUTE; + break; - case IMAGE_FROM_FV: - Policy = ALWAYS_EXECUTE; - break; - - case IMAGE_FROM_OPTION_ROM: - Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy); - break; + case IMAGE_FROM_OPTION_ROM: + Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy); + break; - case IMAGE_FROM_REMOVABLE_MEDIA: - Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy); - break; + case IMAGE_FROM_REMOVABLE_MEDIA: + Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy); + break; - case IMAGE_FROM_FIXED_MEDIA: - Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy); - break; + case IMAGE_FROM_FIXED_MEDIA: + Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy); + break; - default: - Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION; - break; + default: + Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION; + break; } + // // If policy is always/never execute, return directly. // if (Policy == ALWAYS_EXECUTE) { return EFI_SUCCESS; - } else if (Policy == NEVER_EXECUTE) { + } + + if (Policy == NEVER_EXECUTE) { return EFI_ACCESS_DENIED; } @@ -1618,11 +1738,11 @@ DxeImageVerificationHandler ( // violates the UEFI spec and has been removed. // ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION); - if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) { + if ((Policy == QUERY_USER_ON_SECURITY_VIOLATION) || (Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION)) { CpuDeadLoop (); } - GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL); + GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID **)&SecureBoot, NULL); // // Skip verification if SecureBoot variable doesn't exist. // @@ -1631,42 +1751,42 @@ DxeImageVerificationHandler ( } // - // Skip verification if SecureBoot is disabled. + // Skip verification if SecureBoot is disabled but not AuditMode // if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) { FreePool (SecureBoot); return EFI_SUCCESS; } + FreePool (SecureBoot); // // Read the Dos header. // if (FileBuffer == NULL) { - return EFI_INVALID_PARAMETER; + return EFI_ACCESS_DENIED; } - mImageBase = (UINT8 *) FileBuffer; - mImageSize = FileSize; + mImageBase = (UINT8 *)FileBuffer; + mImageSize = FileSize; ZeroMem (&ImageContext, sizeof (ImageContext)); - ImageContext.Handle = (VOID *) FileBuffer; - ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead; + ImageContext.Handle = (VOID *)FileBuffer; + ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)DxeImageVerificationLibImageRead; // // Get information about the image being loaded // - Status = PeCoffLoaderGetImageInfo (&ImageContext); - if (EFI_ERROR (Status)) { + PeCoffStatus = PeCoffLoaderGetImageInfo (&ImageContext); + if (RETURN_ERROR (PeCoffStatus)) { // // The information can't be got from the invalid PeImage // - goto Done; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n")); + goto Failed; } - Status = EFI_ACCESS_DENIED; - - DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase; + DosHdr = (EFI_IMAGE_DOS_HEADER *)mImageBase; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { // // DOS image header is present, @@ -1676,39 +1796,26 @@ DxeImageVerificationHandler ( } else { mPeCoffHeaderOffset = 0; } + // // Check PE/COFF image. // - mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset); + mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)(mImageBase + mPeCoffHeaderOffset); if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { // // It is not a valid Pe/Coff file. // - goto Done; - } - - if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { - // - // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value - // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the - // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC - // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC - // - Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC; - } else { - // - // Get the magic value from the PE/COFF Optional Header - // - Magic = mNtHeader.Pe32->OptionalHeader.Magic; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Not a valid PE/COFF image.\n")); + goto Failed; } - if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { // // Use PE32 offset. // NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes; if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { - SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; + SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *)&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; } } else { // @@ -1716,30 +1823,46 @@ DxeImageVerificationHandler ( // NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes; if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) { - SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; + SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *)&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]; } } // // Start Image Validation. // - if (SecDataDir == NULL || SecDataDir->Size == 0) { + if ((SecDataDir == NULL) || (SecDataDir->Size == 0)) { // // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db", // and not be reflected in the security data base "dbx". // if (!HashPeImage (HASHALG_SHA256)) { - goto Done; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr)); + goto Failed; } - if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) { + DbStatus = IsSignatureFoundInDatabase ( + EFI_IMAGE_SECURITY_DATABASE1, + mImageDigest, + &mCertType, + mImageDigestSize, + &IsFound + ); + if (EFI_ERROR (DbStatus) || IsFound) { // // Image Hash is in forbidden database (DBX). // - goto Done; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr)); + goto Failed; } - if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) { + DbStatus = IsSignatureFoundInDatabase ( + EFI_IMAGE_SECURITY_DATABASE, + mImageDigest, + &mCertType, + mImageDigestSize, + &IsFound + ); + if (!EFI_ERROR (DbStatus) && IsFound) { // // Image Hash is in allowed database (DB). // @@ -1749,7 +1872,8 @@ DxeImageVerificationHandler ( // // Image Hash is not found in both forbidden and allowed database. // - goto Done; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr)); + goto Failed; } // @@ -1757,12 +1881,21 @@ DxeImageVerificationHandler ( // "Attribute Certificate Table". // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file. // + SecDataDirEnd = SecDataDir->VirtualAddress + SecDataDir->Size; for (OffSet = SecDataDir->VirtualAddress; - OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size); - OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) { - WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet); - if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) || - (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) { + OffSet < SecDataDirEnd; + OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) + { + SecDataDirLeft = SecDataDirEnd - OffSet; + if (SecDataDirLeft <= sizeof (WIN_CERTIFICATE)) { + break; + } + + WinCertificate = (WIN_CERTIFICATE *)(mImageBase + OffSet); + if ((SecDataDirLeft < WinCertificate->dwLength) || + (SecDataDirLeft - WinCertificate->dwLength < + ALIGN_SIZE (WinCertificate->dwLength))) + { break; } @@ -1774,34 +1907,38 @@ DxeImageVerificationHandler ( // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the // Authenticode specification. // - PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate; + PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *)WinCertificate; if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) { break; } - AuthData = PkcsCertData->CertData; - AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr); + + AuthData = PkcsCertData->CertData; + AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof (PkcsCertData->Hdr); } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) { // // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec. // - WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate; - if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) { + WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *)WinCertificate; + if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) { break; } + if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) { continue; } - AuthData = WinCertUefiGuid->CertData; - AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData); + + AuthData = WinCertUefiGuid->CertData; + AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData); } else { if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) { break; } + continue; } - Status = HashPeImageByType (AuthData, AuthDataSize); - if (EFI_ERROR (Status)) { + HashStatus = HashPeImageByType (AuthData, AuthDataSize); + if (EFI_ERROR (HashStatus)) { continue; } @@ -1809,83 +1946,104 @@ DxeImageVerificationHandler ( // Check the digital signature against the revoked certificate in forbidden database (dbx). // if (IsForbiddenByDbx (AuthData, AuthDataSize)) { - Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED; - VerifyStatus = EFI_ACCESS_DENIED; + Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED; + IsVerified = FALSE; break; } // // Check the digital signature against the valid certificate in allowed database (db). // - if (EFI_ERROR (VerifyStatus)) { + if (!IsVerified) { if (IsAllowedByDb (AuthData, AuthDataSize)) { - VerifyStatus = EFI_SUCCESS; + IsVerified = TRUE; } } // // Check the image's hash value. // - if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) { + DbStatus = IsSignatureFoundInDatabase ( + EFI_IMAGE_SECURITY_DATABASE1, + mImageDigest, + &mCertType, + mImageDigestSize, + &IsFound + ); + if (EFI_ERROR (DbStatus) || IsFound) { Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND; - VerifyStatus = EFI_ACCESS_DENIED; + DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr)); + IsVerified = FALSE; break; - } else if (EFI_ERROR (VerifyStatus)) { - if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) { - VerifyStatus = EFI_SUCCESS; + } + + if (!IsVerified) { + DbStatus = IsSignatureFoundInDatabase ( + EFI_IMAGE_SECURITY_DATABASE, + mImageDigest, + &mCertType, + mImageDigestSize, + &IsFound + ); + if (!EFI_ERROR (DbStatus) && IsFound) { + IsVerified = TRUE; + } else { + 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)); } } } - if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) { + if (OffSet != SecDataDirEnd) { // - // The Size in Certificate Table or the attribute certicate table is corrupted. + // The Size in Certificate Table or the attribute certificate table is corrupted. // - VerifyStatus = EFI_ACCESS_DENIED; + IsVerified = FALSE; } - if (!EFI_ERROR (VerifyStatus)) { + if (IsVerified) { return EFI_SUCCESS; - } else { - Status = EFI_ACCESS_DENIED; - if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) { - // - // Get image hash value as executable's signature. - // - SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize; - SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize); - if (SignatureList == NULL) { - Status = EFI_OUT_OF_RESOURCES; - goto Done; - } - SignatureList->SignatureHeaderSize = 0; - SignatureList->SignatureListSize = (UINT32) SignatureListSize; - SignatureList->SignatureSize = (UINT32) mImageDigestSize; - CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID)); - Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST)); - CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize); - } } -Done: - if (Status != EFI_SUCCESS) { + if ((Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED) || (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND)) { // - // Policy decides to defer or reject the image; add its information in image executable information table. + // Get image hash value as signature of executable. // - NameStr = ConvertDevicePathToText (File, FALSE, TRUE); - AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize); - if (NameStr != NULL) { - DEBUG((EFI_D_INFO, "The image doesn't pass verification: %s\n", NameStr)); - FreePool(NameStr); + SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize; + SignatureList = (EFI_SIGNATURE_LIST *)AllocateZeroPool (SignatureListSize); + if (SignatureList == NULL) { + SignatureListSize = 0; + goto Failed; } - Status = EFI_SECURITY_VIOLATION; + + SignatureList->SignatureHeaderSize = 0; + SignatureList->SignatureListSize = (UINT32)SignatureListSize; + SignatureList->SignatureSize = (UINT32)(sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize); + CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID)); + Signature = (EFI_SIGNATURE_DATA *)((UINT8 *)SignatureList + sizeof (EFI_SIGNATURE_LIST)); + CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize); + } + +Failed: + // + // Policy decides to defer or reject the image; add its information in image + // executable information table in either case. + // + NameStr = ConvertDevicePathToText (File, FALSE, TRUE); + AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize); + if (NameStr != NULL) { + DEBUG ((DEBUG_INFO, "The image doesn't pass verification: %s\n", NameStr)); + FreePool (NameStr); } if (SignatureList != NULL) { FreePool (SignatureList); } - return Status; + if (Policy == DEFER_EXECUTE_ON_SECURITY_VIOLATION) { + return EFI_SECURITY_VIOLATION; + } + + return EFI_ACCESS_DENIED; } /** @@ -1900,27 +2058,26 @@ Done: VOID EFIAPI OnReadyToBoot ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable; UINTN ImageExeInfoTableSize; - EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable); + EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **)&ImageExeInfoTable); if (ImageExeInfoTable != NULL) { return; } ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE); - ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize); + ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *)AllocateRuntimePool (ImageExeInfoTableSize); if (ImageExeInfoTable == NULL) { - return ; + return; } ImageExeInfoTable->NumberOfImages = 0; - gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) ImageExeInfoTable); - + gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *)ImageExeInfoTable); } /** @@ -1938,7 +2095,7 @@ DxeImageVerificationLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_EVENT Event; + EFI_EVENT Event; // // Register the event to publish the image execution table. @@ -1951,7 +2108,7 @@ DxeImageVerificationLibConstructor ( ); return RegisterSecurity2Handler ( - DxeImageVerificationHandler, - EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED - ); + DxeImageVerificationHandler, + EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED + ); }