]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
Enhances PE image hash algorithm in DxeImageVerificationLib and DxeTpmMeasureBootLib.
[mirror_edk2.git] / SecurityPkg / Library / DxeImageVerificationLib / DxeImageVerificationLib.c
1 /** @file
2 Implement image verification services for secure boot service in UEFI2.3.1.
3
4 Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "DxeImageVerificationLib.h"
16
17 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader;
18 UINTN mImageSize;
19 UINT32 mPeCoffHeaderOffset;
20 UINT8 mImageDigest[MAX_DIGEST_SIZE];
21 UINTN mImageDigestSize;
22 EFI_IMAGE_DATA_DIRECTORY *mSecDataDir = NULL;
23 UINT8 *mImageBase = NULL;
24 EFI_GUID mCertType;
25
26 //
27 // Notify string for authorization UI.
28 //
29 CHAR16 mNotifyString1[MAX_NOTIFY_STRING_LEN] = L"Image verification pass but not found in authorized database!";
30 CHAR16 mNotifyString2[MAX_NOTIFY_STRING_LEN] = L"Launch this image anyway? (Yes/Defer/No)";
31 //
32 // Public Exponent of RSA Key.
33 //
34 CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
35
36
37 //
38 // OID ASN.1 Value for Hash Algorithms
39 //
40 UINT8 mHashOidValue[] = {
41 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, // OBJ_md5
42 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
43 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
44 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
45 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
46 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
47 };
48
49 HASH_TABLE mHash[] = {
50 { L"SHA1", 20, &mHashOidValue[8], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final },
51 { L"SHA224", 28, &mHashOidValue[13], 9, NULL, NULL, NULL, NULL },
52 { L"SHA256", 32, &mHashOidValue[22], 9, Sha256GetContextSize,Sha256Init, Sha256Update, Sha256Final},
53 { L"SHA384", 48, &mHashOidValue[31], 9, NULL, NULL, NULL, NULL },
54 { L"SHA512", 64, &mHashOidValue[40], 9, NULL, NULL, NULL, NULL }
55 };
56
57 /**
58 Reads contents of a PE/COFF image in memory buffer.
59
60 @param FileHandle Pointer to the file handle to read the PE/COFF image.
61 @param FileOffset Offset into the PE/COFF image to begin the read operation.
62 @param ReadSize On input, the size in bytes of the requested read operation.
63 On output, the number of bytes actually read.
64 @param Buffer Output buffer that contains the data read from the PE/COFF image.
65
66 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
67 **/
68 EFI_STATUS
69 EFIAPI
70 DxeImageVerificationLibImageRead (
71 IN VOID *FileHandle,
72 IN UINTN FileOffset,
73 IN OUT UINTN *ReadSize,
74 OUT VOID *Buffer
75 )
76 {
77 UINTN EndPosition;
78
79 if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {
80 return EFI_INVALID_PARAMETER;
81 }
82
83 if (MAX_ADDRESS - FileOffset < *ReadSize) {
84 return EFI_INVALID_PARAMETER;
85 }
86
87 EndPosition = FileOffset + *ReadSize;
88 if (EndPosition > mImageSize) {
89 *ReadSize = (UINT32)(mImageSize - FileOffset);
90 }
91
92 if (FileOffset >= mImageSize) {
93 *ReadSize = 0;
94 }
95
96 CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);
97
98 return EFI_SUCCESS;
99 }
100
101
102 /**
103 Get the image type.
104
105 @param[in] File This is a pointer to the device path of the file that is
106 being dispatched.
107
108 @return UINT32 Image Type
109
110 **/
111 UINT32
112 GetImageType (
113 IN CONST EFI_DEVICE_PATH_PROTOCOL *File
114 )
115 {
116 EFI_STATUS Status;
117 EFI_HANDLE DeviceHandle;
118 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
119 EFI_BLOCK_IO_PROTOCOL *BlockIo;
120
121 //
122 // First check to see if File is from a Firmware Volume
123 //
124 DeviceHandle = NULL;
125 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
126 Status = gBS->LocateDevicePath (
127 &gEfiFirmwareVolume2ProtocolGuid,
128 &TempDevicePath,
129 &DeviceHandle
130 );
131 if (!EFI_ERROR (Status)) {
132 Status = gBS->OpenProtocol (
133 DeviceHandle,
134 &gEfiFirmwareVolume2ProtocolGuid,
135 NULL,
136 NULL,
137 NULL,
138 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
139 );
140 if (!EFI_ERROR (Status)) {
141 return IMAGE_FROM_FV;
142 }
143 }
144
145 //
146 // Next check to see if File is from a Block I/O device
147 //
148 DeviceHandle = NULL;
149 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
150 Status = gBS->LocateDevicePath (
151 &gEfiBlockIoProtocolGuid,
152 &TempDevicePath,
153 &DeviceHandle
154 );
155 if (!EFI_ERROR (Status)) {
156 BlockIo = NULL;
157 Status = gBS->OpenProtocol (
158 DeviceHandle,
159 &gEfiBlockIoProtocolGuid,
160 (VOID **) &BlockIo,
161 NULL,
162 NULL,
163 EFI_OPEN_PROTOCOL_GET_PROTOCOL
164 );
165 if (!EFI_ERROR (Status) && BlockIo != NULL) {
166 if (BlockIo->Media != NULL) {
167 if (BlockIo->Media->RemovableMedia) {
168 //
169 // Block I/O is present and specifies the media is removable
170 //
171 return IMAGE_FROM_REMOVABLE_MEDIA;
172 } else {
173 //
174 // Block I/O is present and specifies the media is not removable
175 //
176 return IMAGE_FROM_FIXED_MEDIA;
177 }
178 }
179 }
180 }
181
182 //
183 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
184 // the device path supports the Simple File System Protocol.
185 //
186 DeviceHandle = NULL;
187 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
188 Status = gBS->LocateDevicePath (
189 &gEfiSimpleFileSystemProtocolGuid,
190 &TempDevicePath,
191 &DeviceHandle
192 );
193 if (!EFI_ERROR (Status)) {
194 //
195 // Simple File System is present without Block I/O, so assume media is fixed.
196 //
197 return IMAGE_FROM_FIXED_MEDIA;
198 }
199
200 //
201 // File is not from an FV, Block I/O or Simple File System, so the only options
202 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
203 //
204 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
205 while (!IsDevicePathEndType (TempDevicePath)) {
206 switch (DevicePathType (TempDevicePath)) {
207
208 case MEDIA_DEVICE_PATH:
209 if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) {
210 return IMAGE_FROM_OPTION_ROM;
211 }
212 break;
213
214 case MESSAGING_DEVICE_PATH:
215 if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) {
216 return IMAGE_FROM_REMOVABLE_MEDIA;
217 }
218 break;
219
220 default:
221 break;
222 }
223 TempDevicePath = NextDevicePathNode (TempDevicePath);
224 }
225 return IMAGE_UNKNOWN;
226 }
227
228 /**
229 Caculate hash of Pe/Coff image based on the authenticode image hashing in
230 PE/COFF Specification 8.0 Appendix A
231
232 @param[in] HashAlg Hash algorithm type.
233
234 @retval TRUE Successfully hash image.
235 @retval FALSE Fail in hash image.
236
237 **/
238 BOOLEAN
239 HashPeImage (
240 IN UINT32 HashAlg
241 )
242 {
243 BOOLEAN Status;
244 UINT16 Magic;
245 EFI_IMAGE_SECTION_HEADER *Section;
246 VOID *HashCtx;
247 UINTN CtxSize;
248 UINT8 *HashBase;
249 UINTN HashSize;
250 UINTN SumOfBytesHashed;
251 EFI_IMAGE_SECTION_HEADER *SectionHeader;
252 UINTN Index;
253 UINTN Pos;
254 UINTN SumOfSectionBytes;
255 EFI_IMAGE_SECTION_HEADER *SectionCache;
256 UINT32 CertSize;
257 UINT32 NumberOfRvaAndSizes;
258
259 HashCtx = NULL;
260 SectionHeader = NULL;
261 Status = FALSE;
262
263 if ((HashAlg != HASHALG_SHA1) && (HashAlg != HASHALG_SHA256)) {
264 return FALSE;
265 }
266
267 //
268 // Initialize context of hash.
269 //
270 ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
271
272 if (HashAlg == HASHALG_SHA1) {
273 mImageDigestSize = SHA1_DIGEST_SIZE;
274 mCertType = gEfiCertSha1Guid;
275 } else if (HashAlg == HASHALG_SHA256) {
276 mImageDigestSize = SHA256_DIGEST_SIZE;
277 mCertType = gEfiCertSha256Guid;
278 } else {
279 return FALSE;
280 }
281
282 CtxSize = mHash[HashAlg].GetContextSize();
283
284 HashCtx = AllocatePool (CtxSize);
285 if (HashCtx == NULL) {
286 return FALSE;
287 }
288
289 // 1. Load the image header into memory.
290
291 // 2. Initialize a SHA hash context.
292 Status = mHash[HashAlg].HashInit(HashCtx);
293
294 if (!Status) {
295 goto Done;
296 }
297
298 //
299 // Measuring PE/COFF Image Header;
300 // But CheckSum field and SECURITY data directory (certificate) are excluded
301 //
302 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
303 //
304 // 3. Calculate the distance from the base of the image header to the image checksum address.
305 // 4. Hash the image header from its base to beginning of the image checksum.
306 //
307 HashBase = mImageBase;
308 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
309 //
310 // Use PE32 offset.
311 //
312 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
313 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
314 } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
315 //
316 // Use PE32+ offset.
317 //
318 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
319 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
320 } else {
321 //
322 // Invalid header magic number.
323 //
324 Status = FALSE;
325 goto Done;
326 }
327
328 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
329 if (!Status) {
330 goto Done;
331 }
332
333 //
334 // 5. Skip over the image checksum (it occupies a single ULONG).
335 //
336 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
337 //
338 // 6. Since there is no Cert Directory in optional header, hash everything
339 // from the end of the checksum to the end of image header.
340 //
341 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
342 //
343 // Use PE32 offset.
344 //
345 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
346 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
347 } else {
348 //
349 // Use PE32+ offset.
350 //
351 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
352 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
353 }
354
355 if (HashSize != 0) {
356 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
357 if (!Status) {
358 goto Done;
359 }
360 }
361 } else {
362 //
363 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
364 //
365 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
366 //
367 // Use PE32 offset.
368 //
369 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
370 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
371 } else {
372 //
373 // Use PE32+ offset.
374 //
375 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
376 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
377 }
378
379 if (HashSize != 0) {
380 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
381 if (!Status) {
382 goto Done;
383 }
384 }
385
386 //
387 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
388 // 9. Hash everything from the end of the Cert Directory to the end of image header.
389 //
390 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
391 //
392 // Use PE32 offset
393 //
394 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
395 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
396 } else {
397 //
398 // Use PE32+ offset.
399 //
400 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
401 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
402 }
403
404 if (HashSize != 0) {
405 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
406 if (!Status) {
407 goto Done;
408 }
409 }
410 }
411
412 //
413 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
414 //
415 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
416 //
417 // Use PE32 offset.
418 //
419 SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
420 } else {
421 //
422 // Use PE32+ offset
423 //
424 SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
425 }
426
427
428 Section = (EFI_IMAGE_SECTION_HEADER *) (
429 mImageBase +
430 mPeCoffHeaderOffset +
431 sizeof (UINT32) +
432 sizeof (EFI_IMAGE_FILE_HEADER) +
433 mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
434 );
435
436 SectionCache = Section;
437 for (Index = 0, SumOfSectionBytes = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++, SectionCache++) {
438 SumOfSectionBytes += SectionCache->SizeOfRawData;
439 }
440
441 //
442 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
443 // structures in the image. The 'NumberOfSections' field of the image
444 // header indicates how big the table should be. Do not include any
445 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
446 //
447 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
448 if (SectionHeader == NULL) {
449 Status = FALSE;
450 goto Done;
451 }
452 //
453 // 12. Using the 'PointerToRawData' in the referenced section headers as
454 // a key, arrange the elements in the table in ascending order. In other
455 // words, sort the section headers according to the disk-file offset of
456 // the section.
457 //
458 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
459 Pos = Index;
460 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
461 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
462 Pos--;
463 }
464 CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
465 Section += 1;
466 }
467
468 //
469 // 13. Walk through the sorted table, bring the corresponding section
470 // into memory, and hash the entire section (using the 'SizeOfRawData'
471 // field in the section header to determine the amount of data to hash).
472 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
473 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
474 //
475 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
476 Section = &SectionHeader[Index];
477 if (Section->SizeOfRawData == 0) {
478 continue;
479 }
480 HashBase = mImageBase + Section->PointerToRawData;
481 HashSize = (UINTN) Section->SizeOfRawData;
482
483 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
484 if (!Status) {
485 goto Done;
486 }
487
488 SumOfBytesHashed += HashSize;
489 }
490
491 //
492 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
493 // data in the file that needs to be added to the hash. This data begins
494 // at file offset SUM_OF_BYTES_HASHED and its length is:
495 // FileSize - (CertDirectory->Size)
496 //
497 if (mImageSize > SumOfBytesHashed) {
498 HashBase = mImageBase + SumOfBytesHashed;
499
500 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
501 CertSize = 0;
502 } else {
503 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
504 //
505 // Use PE32 offset.
506 //
507 CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
508 } else {
509 //
510 // Use PE32+ offset.
511 //
512 CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
513 }
514 }
515
516 if (mImageSize > CertSize + SumOfBytesHashed) {
517 HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed);
518
519 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
520 if (!Status) {
521 goto Done;
522 }
523 } else if (mImageSize < CertSize + SumOfBytesHashed) {
524 Status = FALSE;
525 goto Done;
526 }
527 }
528
529 Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
530
531 Done:
532 if (HashCtx != NULL) {
533 FreePool (HashCtx);
534 }
535 if (SectionHeader != NULL) {
536 FreePool (SectionHeader);
537 }
538 return Status;
539 }
540
541 /**
542 Recognize the Hash algorithm in PE/COFF Authenticode and caculate hash of
543 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
544 8.0 Appendix A
545
546 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
547 @retval EFI_SUCCESS Hash successfully.
548
549 **/
550 EFI_STATUS
551 HashPeImageByType (
552 VOID
553 )
554 {
555 UINT8 Index;
556 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
557
558 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) (mImageBase + mSecDataDir->VirtualAddress);
559
560 for (Index = 0; Index < HASHALG_MAX; Index++) {
561 //
562 // Check the Hash algorithm in PE/COFF Authenticode.
563 // According to PKCS#7 Definition:
564 // SignedData ::= SEQUENCE {
565 // version Version,
566 // digestAlgorithms DigestAlgorithmIdentifiers,
567 // contentInfo ContentInfo,
568 // .... }
569 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
570 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
571 // Fixed offset (+32) is calculated based on two bytes of length encoding.
572 //
573 if ((*(PkcsCertData->CertData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
574 //
575 // Only support two bytes of Long Form of Length Encoding.
576 //
577 continue;
578 }
579
580 if (CompareMem (PkcsCertData->CertData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
581 break;
582 }
583 }
584
585 if (Index == HASHALG_MAX) {
586 return EFI_UNSUPPORTED;
587 }
588
589 //
590 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
591 //
592 if (!HashPeImage(Index)) {
593 return EFI_UNSUPPORTED;
594 }
595
596 return EFI_SUCCESS;
597 }
598
599
600 /**
601 Returns the size of a given image execution info table in bytes.
602
603 This function returns the size, in bytes, of the image execution info table specified by
604 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
605
606 @param ImageExeInfoTable A pointer to a image execution info table structure.
607
608 @retval 0 If ImageExeInfoTable is NULL.
609 @retval Others The size of a image execution info table in bytes.
610
611 **/
612 UINTN
613 GetImageExeInfoTableSize (
614 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable
615 )
616 {
617 UINTN Index;
618 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem;
619 UINTN TotalSize;
620
621 if (ImageExeInfoTable == NULL) {
622 return 0;
623 }
624
625 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE));
626 TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
627 for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) {
628 TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize);
629 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize));
630 }
631
632 return TotalSize;
633 }
634
635 /**
636 Create an Image Execution Information Table entry and add it to system configuration table.
637
638 @param[in] Action Describes the action taken by the firmware regarding this image.
639 @param[in] Name Input a null-terminated, user-friendly name.
640 @param[in] DevicePath Input device path pointer.
641 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
642 @param[in] SignatureSize Size of signature.
643
644 **/
645 VOID
646 AddImageExeInfo (
647 IN EFI_IMAGE_EXECUTION_ACTION Action,
648 IN CHAR16 *Name OPTIONAL,
649 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
650 IN EFI_SIGNATURE_LIST *Signature OPTIONAL,
651 IN UINTN SignatureSize
652 )
653 {
654 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
655 EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable;
656 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry;
657 UINTN ImageExeInfoTableSize;
658 UINTN NewImageExeInfoEntrySize;
659 UINTN NameStringLen;
660 UINTN DevicePathSize;
661
662 ImageExeInfoTable = NULL;
663 NewImageExeInfoTable = NULL;
664 ImageExeInfoEntry = NULL;
665 NameStringLen = 0;
666
667 if (DevicePath == NULL) {
668 return ;
669 }
670
671 if (Name != NULL) {
672 NameStringLen = StrSize (Name);
673 }
674
675 ImageExeInfoTable = NULL;
676 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
677 if (ImageExeInfoTable != NULL) {
678 //
679 // The table has been found!
680 // We must enlarge the table to accmodate the new exe info entry.
681 //
682 ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable);
683 } else {
684 //
685 // Not Found!
686 // We should create a new table to append to the configuration table.
687 //
688 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
689 }
690
691 DevicePathSize = GetDevicePathSize (DevicePath);
692 NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize;
693 NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize);
694 if (NewImageExeInfoTable == NULL) {
695 return ;
696 }
697
698 if (ImageExeInfoTable != NULL) {
699 CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize);
700 } else {
701 NewImageExeInfoTable->NumberOfImages = 0;
702 }
703 NewImageExeInfoTable->NumberOfImages++;
704 ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize);
705 //
706 // Update new item's infomation.
707 //
708 WriteUnaligned32 ((UINT32 *) &ImageExeInfoEntry->Action, Action);
709 WriteUnaligned32 ((UINT32 *) &ImageExeInfoEntry->InfoSize, (UINT32) NewImageExeInfoEntrySize);
710
711 if (Name != NULL) {
712 CopyMem ((UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32), Name, NameStringLen);
713 }
714 CopyMem (
715 (UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32) + NameStringLen,
716 DevicePath,
717 DevicePathSize
718 );
719 if (Signature != NULL) {
720 CopyMem (
721 (UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32) + NameStringLen + DevicePathSize,
722 Signature,
723 SignatureSize
724 );
725 }
726 //
727 // Update/replace the image execution table.
728 //
729 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable);
730
731 //
732 // Free Old table data!
733 //
734 if (ImageExeInfoTable != NULL) {
735 FreePool (ImageExeInfoTable);
736 }
737 }
738
739 /**
740 Discover if the UEFI image is authorized by user's policy setting.
741
742 @param[in] Policy Specify platform's policy setting.
743
744 @retval EFI_ACCESS_DENIED Image is not allowed to run.
745 @retval EFI_SECURITY_VIOLATION Image is deferred.
746 @retval EFI_SUCCESS Image is authorized to run.
747
748 **/
749 EFI_STATUS
750 ImageAuthorization (
751 IN UINT32 Policy
752 )
753 {
754 EFI_STATUS Status;
755 EFI_INPUT_KEY Key;
756
757 Status = EFI_ACCESS_DENIED;
758
759 switch (Policy) {
760
761 case QUERY_USER_ON_SECURITY_VIOLATION:
762 do {
763 CreatePopUp (EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE, &Key, mNotifyString1, mNotifyString2, NULL);
764 if (Key.UnicodeChar == L'Y' || Key.UnicodeChar == L'y') {
765 Status = EFI_SUCCESS;
766 break;
767 } else if (Key.UnicodeChar == L'N' || Key.UnicodeChar == L'n') {
768 Status = EFI_ACCESS_DENIED;
769 break;
770 } else if (Key.UnicodeChar == L'D' || Key.UnicodeChar == L'd') {
771 Status = EFI_SECURITY_VIOLATION;
772 break;
773 }
774 } while (TRUE);
775 break;
776
777 case ALLOW_EXECUTE_ON_SECURITY_VIOLATION:
778 Status = EFI_SUCCESS;
779 break;
780
781 case DEFER_EXECUTE_ON_SECURITY_VIOLATION:
782 Status = EFI_SECURITY_VIOLATION;
783 break;
784
785 case DENY_EXECUTE_ON_SECURITY_VIOLATION:
786 Status = EFI_ACCESS_DENIED;
787 break;
788 }
789
790 return Status;
791 }
792
793 /**
794 Check whether signature is in specified database.
795
796 @param[in] VariableName Name of database variable that is searched in.
797 @param[in] Signature Pointer to signature that is searched for.
798 @param[in] CertType Pointer to hash algrithom.
799 @param[in] SignatureSize Size of Signature.
800
801 @return TRUE Found the signature in the variable database.
802 @return FALSE Not found the signature in the variable database.
803
804 **/
805 BOOLEAN
806 IsSignatureFoundInDatabase (
807 IN CHAR16 *VariableName,
808 IN UINT8 *Signature,
809 IN EFI_GUID *CertType,
810 IN UINTN SignatureSize
811 )
812 {
813 EFI_STATUS Status;
814 EFI_SIGNATURE_LIST *CertList;
815 EFI_SIGNATURE_DATA *Cert;
816 UINTN DataSize;
817 UINT8 *Data;
818 UINTN Index;
819 UINTN CertCount;
820 BOOLEAN IsFound;
821 //
822 // Read signature database variable.
823 //
824 IsFound = FALSE;
825 Data = NULL;
826 DataSize = 0;
827 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
828 if (Status != EFI_BUFFER_TOO_SMALL) {
829 return FALSE;
830 }
831
832 Data = (UINT8 *) AllocateZeroPool (DataSize);
833 if (Data == NULL) {
834 return FALSE;
835 }
836
837 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data);
838 if (EFI_ERROR (Status)) {
839 goto Done;
840 }
841 //
842 // Enumerate all signature data in SigDB to check if executable's signature exists.
843 //
844 CertList = (EFI_SIGNATURE_LIST *) Data;
845 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
846 CertCount = (CertList->SignatureListSize - CertList->SignatureHeaderSize) / CertList->SignatureSize;
847 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
848 if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) {
849 for (Index = 0; Index < CertCount; Index++) {
850 if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) {
851 //
852 // Find the signature in database.
853 //
854 IsFound = TRUE;
855 break;
856 }
857
858 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
859 }
860
861 if (IsFound) {
862 break;
863 }
864 }
865
866 DataSize -= CertList->SignatureListSize;
867 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
868 }
869
870 Done:
871 if (Data != NULL) {
872 FreePool (Data);
873 }
874
875 return IsFound;
876 }
877
878 /**
879 Verify PKCS#7 SignedData using certificate found in Variable which formatted
880 as EFI_SIGNATURE_LIST. The Variable may be PK, KEK, DB or DBX.
881
882 @param VariableName Name of Variable to search for Certificate.
883 @param VendorGuid Variable vendor GUID.
884
885 @retval TRUE Image pass verification.
886 @retval FALSE Image fail verification.
887
888 **/
889 BOOLEAN
890 IsPkcsSignedDataVerifiedBySignatureList (
891 IN CHAR16 *VariableName,
892 IN EFI_GUID *VendorGuid
893 )
894 {
895 EFI_STATUS Status;
896 BOOLEAN VerifyStatus;
897 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
898 EFI_SIGNATURE_LIST *CertList;
899 EFI_SIGNATURE_DATA *Cert;
900 UINTN DataSize;
901 UINT8 *Data;
902 UINT8 *RootCert;
903 UINTN RootCertSize;
904 UINTN Index;
905 UINTN CertCount;
906
907 Data = NULL;
908 CertList = NULL;
909 Cert = NULL;
910 RootCert = NULL;
911 RootCertSize = 0;
912 VerifyStatus = FALSE;
913 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) (mImageBase + mSecDataDir->VirtualAddress);
914
915 DataSize = 0;
916 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, NULL);
917 if (Status == EFI_BUFFER_TOO_SMALL) {
918 Data = (UINT8 *) AllocateZeroPool (DataSize);
919 if (Data == NULL) {
920 return VerifyStatus;
921 }
922
923 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, (VOID *) Data);
924 if (EFI_ERROR (Status)) {
925 goto Done;
926 }
927
928 //
929 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
930 //
931 CertList = (EFI_SIGNATURE_LIST *) Data;
932 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
933 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
934 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
935 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
936 for (Index = 0; Index < CertCount; Index++) {
937 //
938 // Iterate each Signature Data Node within this CertList for verify.
939 //
940 RootCert = Cert->SignatureData;
941 RootCertSize = CertList->SignatureSize;
942
943 //
944 // Call AuthenticodeVerify library to Verify Authenticode struct.
945 //
946 VerifyStatus = AuthenticodeVerify (
947 PkcsCertData->CertData,
948 mSecDataDir->Size - sizeof(PkcsCertData->Hdr),
949 RootCert,
950 RootCertSize,
951 mImageDigest,
952 mImageDigestSize
953 );
954 if (VerifyStatus) {
955 goto Done;
956 }
957 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
958 }
959 }
960 DataSize -= CertList->SignatureListSize;
961 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
962 }
963 }
964
965 Done:
966 if (Data != NULL) {
967 FreePool (Data);
968 }
969
970 return VerifyStatus;
971 }
972
973 /**
974 Verify certificate in WIN_CERT_TYPE_PKCS_SIGNED_DATA format.
975
976 @retval EFI_SUCCESS Image pass verification.
977 @retval EFI_SECURITY_VIOLATION Image fail verification.
978
979 **/
980 EFI_STATUS
981 VerifyCertPkcsSignedData (
982 VOID
983 )
984 {
985 //
986 // 1: Find certificate from DBX forbidden database for revoked certificate.
987 //
988 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid)) {
989 //
990 // DBX is forbidden database, if Authenticode verification pass with
991 // one of the certificate in DBX, this image should be rejected.
992 //
993 return EFI_SECURITY_VIOLATION;
994 }
995
996 //
997 // 2: Find certificate from KEK database and try to verify authenticode struct.
998 //
999 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_KEY_EXCHANGE_KEY_NAME, &gEfiGlobalVariableGuid)) {
1000 return EFI_SUCCESS;
1001 }
1002
1003 //
1004 // 3: Find certificate from DB database and try to verify authenticode struct.
1005 //
1006 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid)) {
1007 return EFI_SUCCESS;
1008 } else {
1009 return EFI_SECURITY_VIOLATION;
1010 }
1011 }
1012
1013 /**
1014 Verify certificate in WIN_CERTIFICATE_UEFI_GUID format.
1015
1016 @retval EFI_SUCCESS Image pass verification.
1017 @retval EFI_SECURITY_VIOLATION Image fail verification.
1018 @retval other error value
1019
1020 **/
1021 EFI_STATUS
1022 VerifyCertUefiGuid (
1023 VOID
1024 )
1025 {
1026 BOOLEAN Status;
1027 WIN_CERTIFICATE_UEFI_GUID *EfiCert;
1028 EFI_SIGNATURE_LIST *KekList;
1029 EFI_SIGNATURE_DATA *KekItem;
1030 EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlock;
1031 VOID *Rsa;
1032 UINTN KekCount;
1033 UINTN Index;
1034 UINTN KekDataSize;
1035 BOOLEAN IsFound;
1036 EFI_STATUS Result;
1037
1038 EfiCert = NULL;
1039 KekList = NULL;
1040 KekItem = NULL;
1041 CertBlock = NULL;
1042 Rsa = NULL;
1043 Status = FALSE;
1044 IsFound = FALSE;
1045 KekDataSize = 0;
1046
1047 EfiCert = (WIN_CERTIFICATE_UEFI_GUID *) (mImageBase + mSecDataDir->VirtualAddress);
1048 CertBlock = (EFI_CERT_BLOCK_RSA_2048_SHA256 *) EfiCert->CertData;
1049 if (!CompareGuid (&EfiCert->CertType, &gEfiCertTypeRsa2048Sha256Guid)) {
1050 //
1051 // Invalid Certificate Data Type.
1052 //
1053 return EFI_SECURITY_VIOLATION;
1054 }
1055
1056 //
1057 // Get KEK database variable data size
1058 //
1059 Result = gRT->GetVariable (EFI_KEY_EXCHANGE_KEY_NAME, &gEfiGlobalVariableGuid, NULL, &KekDataSize, NULL);
1060 if (Result != EFI_BUFFER_TOO_SMALL) {
1061 return EFI_SECURITY_VIOLATION;
1062 }
1063
1064 //
1065 // Get KEK database variable.
1066 //
1067 KekList = GetEfiGlobalVariable (EFI_KEY_EXCHANGE_KEY_NAME);
1068 if (KekList == NULL) {
1069 return EFI_SECURITY_VIOLATION;
1070 }
1071
1072 //
1073 // Enumerate all Kek items in this list to verify the variable certificate data.
1074 // If anyone is authenticated successfully, it means the variable is correct!
1075 //
1076 while ((KekDataSize > 0) && (KekDataSize >= KekList->SignatureListSize)) {
1077 if (CompareGuid (&KekList->SignatureType, &gEfiCertRsa2048Guid)) {
1078 KekItem = (EFI_SIGNATURE_DATA *) ((UINT8 *) KekList + sizeof (EFI_SIGNATURE_LIST) + KekList->SignatureHeaderSize);
1079 KekCount = (KekList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - KekList->SignatureHeaderSize) / KekList->SignatureSize;
1080 for (Index = 0; Index < KekCount; Index++) {
1081 if (CompareMem (KekItem->SignatureData, CertBlock->PublicKey, EFI_CERT_TYPE_RSA2048_SIZE) == 0) {
1082 IsFound = TRUE;
1083 break;
1084 }
1085 KekItem = (EFI_SIGNATURE_DATA *) ((UINT8 *) KekItem + KekList->SignatureSize);
1086 }
1087 }
1088 KekDataSize -= KekList->SignatureListSize;
1089 KekList = (EFI_SIGNATURE_LIST *) ((UINT8 *) KekList + KekList->SignatureListSize);
1090 }
1091
1092 if (!IsFound) {
1093 //
1094 // Signed key is not a trust one.
1095 //
1096 goto Done;
1097 }
1098
1099 //
1100 // Now, we found the corresponding security policy.
1101 // Verify the data payload.
1102 //
1103 Rsa = RsaNew ();
1104 if (Rsa == NULL) {
1105 Status = FALSE;
1106 goto Done;
1107 }
1108
1109 //
1110 // Set RSA Key Components.
1111 // NOTE: Only N and E are needed to be set as RSA public key for signature verification.
1112 //
1113 Status = RsaSetKey (Rsa, RsaKeyN, CertBlock->PublicKey, EFI_CERT_TYPE_RSA2048_SIZE);
1114 if (!Status) {
1115 goto Done;
1116 }
1117 Status = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE));
1118 if (!Status) {
1119 goto Done;
1120 }
1121 //
1122 // Verify the signature.
1123 //
1124 Status = RsaPkcs1Verify (
1125 Rsa,
1126 mImageDigest,
1127 mImageDigestSize,
1128 CertBlock->Signature,
1129 EFI_CERT_TYPE_RSA2048_SHA256_SIZE
1130 );
1131
1132 Done:
1133 if (KekList != NULL) {
1134 FreePool (KekList);
1135 }
1136 if (Rsa != NULL ) {
1137 RsaFree (Rsa);
1138 }
1139 if (Status) {
1140 return EFI_SUCCESS;
1141 } else {
1142 return EFI_SECURITY_VIOLATION;
1143 }
1144 }
1145
1146 /**
1147 Provide verification service for signed images, which include both signature validation
1148 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1149 MSFT Authenticode type signatures are supported.
1150
1151 In this implementation, only verify external executables when in USER MODE.
1152 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1153
1154 The image verification process is:
1155 Is the Image signed?
1156 If yes,
1157 Does the image verify against a certificate (root or intermediate) in the allowed db?
1158 Run it
1159 Image verification fail
1160 Is the Image's Hash not in forbidden database and the Image's Hash in allowed db?
1161 Run it
1162 If no,
1163 Is the Image's Hash in the forbidden database (DBX)?
1164 if yes,
1165 Error out
1166 Is the Image's Hash in the allowed database (DB)?
1167 If yes,
1168 Run it
1169 If no,
1170 Error out
1171
1172 @param[in] AuthenticationStatus
1173 This is the authentication status returned from the security
1174 measurement services for the input file.
1175 @param[in] File This is a pointer to the device path of the file that is
1176 being dispatched. This will optionally be used for logging.
1177 @param[in] FileBuffer File buffer matches the input file device path.
1178 @param[in] FileSize Size of File buffer matches the input file device path.
1179
1180 @retval EFI_SUCCESS The file specified by File did authenticate, and the
1181 platform policy dictates that the DXE Core may use File.
1182 @retval EFI_INVALID_PARAMETER Input argument is incorrect.
1183 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1184 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1185 the platform policy dictates that File should be placed
1186 in the untrusted state. A file may be promoted from
1187 the untrusted to the trusted state at a future time
1188 with a call to the Trust() DXE Service.
1189 @retval EFI_ACCESS_DENIED The file specified by File did not authenticate, and
1190 the platform policy dictates that File should not be
1191 used for any purpose.
1192
1193 **/
1194 EFI_STATUS
1195 EFIAPI
1196 DxeImageVerificationHandler (
1197 IN UINT32 AuthenticationStatus,
1198 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
1199 IN VOID *FileBuffer,
1200 IN UINTN FileSize
1201 )
1202 {
1203 EFI_STATUS Status;
1204 UINT16 Magic;
1205 EFI_IMAGE_DOS_HEADER *DosHdr;
1206 EFI_STATUS VerifyStatus;
1207 UINT8 *SetupMode;
1208 EFI_SIGNATURE_LIST *SignatureList;
1209 UINTN SignatureListSize;
1210 EFI_SIGNATURE_DATA *Signature;
1211 EFI_IMAGE_EXECUTION_ACTION Action;
1212 WIN_CERTIFICATE *WinCertificate;
1213 UINT32 Policy;
1214 UINT8 *SecureBootEnable;
1215 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1216 UINT32 NumberOfRvaAndSizes;
1217
1218 if (File == NULL) {
1219 return EFI_INVALID_PARAMETER;
1220 }
1221
1222 SignatureList = NULL;
1223 SignatureListSize = 0;
1224 WinCertificate = NULL;
1225 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1226 Status = EFI_ACCESS_DENIED;
1227 //
1228 // Check the image type and get policy setting.
1229 //
1230 switch (GetImageType (File)) {
1231
1232 case IMAGE_FROM_FV:
1233 Policy = ALWAYS_EXECUTE;
1234 break;
1235
1236 case IMAGE_FROM_OPTION_ROM:
1237 Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
1238 break;
1239
1240 case IMAGE_FROM_REMOVABLE_MEDIA:
1241 Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
1242 break;
1243
1244 case IMAGE_FROM_FIXED_MEDIA:
1245 Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
1246 break;
1247
1248 default:
1249 Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
1250 break;
1251 }
1252 //
1253 // If policy is always/never execute, return directly.
1254 //
1255 if (Policy == ALWAYS_EXECUTE) {
1256 return EFI_SUCCESS;
1257 } else if (Policy == NEVER_EXECUTE) {
1258 return EFI_ACCESS_DENIED;
1259 }
1260
1261 SecureBootEnable = GetVariable (EFI_SECURE_BOOT_ENABLE_NAME, &gEfiSecureBootEnableDisableGuid);
1262 //
1263 // Skip verification if SecureBootEnable variable doesn't exist.
1264 //
1265 if (SecureBootEnable == NULL) {
1266 return EFI_SUCCESS;
1267 }
1268
1269 //
1270 // Skip verification if SecureBootEnable is disabled.
1271 //
1272 if (*SecureBootEnable == SECURE_BOOT_DISABLE) {
1273 FreePool (SecureBootEnable);
1274 return EFI_SUCCESS;
1275 }
1276
1277 FreePool (SecureBootEnable);
1278
1279 SetupMode = GetEfiGlobalVariable (EFI_SETUP_MODE_NAME);
1280
1281 //
1282 // SetupMode doesn't exist means no AuthVar driver is dispatched,
1283 // skip verification.
1284 //
1285 if (SetupMode == NULL) {
1286 return EFI_SUCCESS;
1287 }
1288
1289 //
1290 // If platform is in SETUP MODE, skip verification.
1291 //
1292 if (*SetupMode == SETUP_MODE) {
1293 FreePool (SetupMode);
1294 return EFI_SUCCESS;
1295 }
1296
1297 FreePool (SetupMode);
1298
1299 //
1300 // Read the Dos header.
1301 //
1302 if (FileBuffer == NULL) {
1303 return EFI_INVALID_PARAMETER;
1304 }
1305
1306 mImageBase = (UINT8 *) FileBuffer;
1307 mImageSize = FileSize;
1308
1309 ZeroMem (&ImageContext, sizeof (ImageContext));
1310 ImageContext.Handle = (VOID *) FileBuffer;
1311 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
1312
1313 //
1314 // Get information about the image being loaded
1315 //
1316 Status = PeCoffLoaderGetImageInfo (&ImageContext);
1317 if (EFI_ERROR (Status)) {
1318 //
1319 // The information can't be got from the invalid PeImage
1320 //
1321 goto Done;
1322 }
1323
1324 DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
1325 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
1326 //
1327 // DOS image header is present,
1328 // so read the PE header after the DOS image header.
1329 //
1330 mPeCoffHeaderOffset = DosHdr->e_lfanew;
1331 } else {
1332 mPeCoffHeaderOffset = 0;
1333 }
1334 //
1335 // Check PE/COFF image.
1336 //
1337 mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
1338 if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1339 //
1340 // It is not a valid Pe/Coff file.
1341 //
1342 Status = EFI_ACCESS_DENIED;
1343 goto Done;
1344 }
1345
1346 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
1347 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1348 //
1349 // Use PE32 offset.
1350 //
1351 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
1352 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1353 mSecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1354 }
1355 } else {
1356 //
1357 // Use PE32+ offset.
1358 //
1359 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
1360 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1361 mSecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1362 }
1363 }
1364
1365 if ((mSecDataDir == NULL) || ((mSecDataDir != NULL) && (mSecDataDir->Size == 0))) {
1366 //
1367 // This image is not signed.
1368 //
1369 if (!HashPeImage (HASHALG_SHA256)) {
1370 goto Done;
1371 }
1372
1373 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1374 //
1375 // Image Hash is in forbidden database (DBX).
1376 //
1377 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1378 Status = EFI_ACCESS_DENIED;
1379 goto Done;
1380 }
1381
1382 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1383 //
1384 // Image Hash is in allowed database (DB).
1385 //
1386 return EFI_SUCCESS;
1387 }
1388
1389 //
1390 // Image Hash is not found in both forbidden and allowed database.
1391 //
1392 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1393 Status = EFI_ACCESS_DENIED;
1394 goto Done;
1395 }
1396
1397 //
1398 // Verify signature of executables.
1399 //
1400 WinCertificate = (WIN_CERTIFICATE *) (mImageBase + mSecDataDir->VirtualAddress);
1401
1402 switch (WinCertificate->wCertificateType) {
1403
1404 case WIN_CERT_TYPE_EFI_GUID:
1405 //
1406 // Verify UEFI GUID type.
1407 //
1408 if (!HashPeImage (HASHALG_SHA256)) {
1409 goto Done;
1410 }
1411
1412 VerifyStatus = VerifyCertUefiGuid ();
1413 break;
1414
1415 case WIN_CERT_TYPE_PKCS_SIGNED_DATA:
1416 //
1417 // Verify Pkcs signed data type.
1418 //
1419 Status = HashPeImageByType();
1420 if (EFI_ERROR (Status)) {
1421 goto Done;
1422 }
1423
1424 VerifyStatus = VerifyCertPkcsSignedData ();
1425
1426 //
1427 // For image verification against enrolled certificate(root or intermediate),
1428 // no need to check image's hash in the allowed database.
1429 //
1430 if (!EFI_ERROR (VerifyStatus)) {
1431 if (!IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1432 return EFI_SUCCESS;
1433 }
1434 }
1435 break;
1436
1437 default:
1438 Status = EFI_ACCESS_DENIED;
1439 goto Done;
1440 }
1441 //
1442 // Get image hash value as executable's signature.
1443 //
1444 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
1445 SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
1446 if (SignatureList == NULL) {
1447 Status = EFI_OUT_OF_RESOURCES;
1448 goto Done;
1449 }
1450 SignatureList->SignatureHeaderSize = 0;
1451 SignatureList->SignatureListSize = (UINT32) SignatureListSize;
1452 SignatureList->SignatureSize = (UINT32) mImageDigestSize;
1453 CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
1454 Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
1455 CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
1456 //
1457 // Signature database check after verification.
1458 //
1459 if (EFI_ERROR (VerifyStatus)) {
1460 //
1461 // Verification failure.
1462 //
1463 if (!IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize) &&
1464 IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1465 //
1466 // Verification fail, Image Hash is not in forbidden database (DBX),
1467 // and Image Hash is in allowed database (DB).
1468 //
1469 Status = EFI_SUCCESS;
1470 } else {
1471 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
1472 Status = EFI_ACCESS_DENIED;
1473 }
1474 } else if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, Signature->SignatureData, &mCertType, mImageDigestSize)) {
1475 //
1476 // Executable signature verification passes, but is found in forbidden signature database.
1477 //
1478 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
1479 Status = EFI_ACCESS_DENIED;
1480 } else if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, Signature->SignatureData, &mCertType, mImageDigestSize)) {
1481 //
1482 // Executable signature is found in authorized signature database.
1483 //
1484 Status = EFI_SUCCESS;
1485 } else {
1486 //
1487 // Executable signature verification passes, but cannot be found in authorized signature database.
1488 // Get platform policy to determine the action.
1489 //
1490 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_PASSED;
1491 Status = ImageAuthorization (Policy);
1492 }
1493
1494 Done:
1495 if (Status != EFI_SUCCESS) {
1496 //
1497 // Policy decides to defer or reject the image; add its information in image executable information table.
1498 //
1499 AddImageExeInfo (Action, NULL, File, SignatureList, SignatureListSize);
1500 }
1501
1502 if (SignatureList != NULL) {
1503 FreePool (SignatureList);
1504 }
1505
1506 return Status;
1507 }
1508
1509 /**
1510 When VariableWriteArchProtocol install, create "SecureBoot" variable.
1511
1512 @param[in] Event Event whose notification function is being invoked.
1513 @param[in] Context Pointer to the notification function's context.
1514
1515 **/
1516 VOID
1517 EFIAPI
1518 VariableWriteCallBack (
1519 IN EFI_EVENT Event,
1520 IN VOID *Context
1521 )
1522 {
1523 UINT8 SecureBootMode;
1524 UINT8 *SecureBootModePtr;
1525 EFI_STATUS Status;
1526 VOID *ProtocolPointer;
1527
1528 Status = gBS->LocateProtocol (&gEfiVariableWriteArchProtocolGuid, NULL, &ProtocolPointer);
1529 if (EFI_ERROR (Status)) {
1530 return;
1531 }
1532
1533 //
1534 // Check whether "SecureBoot" variable exists.
1535 // If this library is built-in, it means firmware has capability to perform
1536 // driver signing verification.
1537 //
1538 SecureBootModePtr = GetEfiGlobalVariable (EFI_SECURE_BOOT_MODE_NAME);
1539 if (SecureBootModePtr == NULL) {
1540 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
1541 //
1542 // Authenticated variable driver will update "SecureBoot" depending on SetupMode variable.
1543 //
1544 gRT->SetVariable (
1545 EFI_SECURE_BOOT_MODE_NAME,
1546 &gEfiGlobalVariableGuid,
1547 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1548 sizeof (UINT8),
1549 &SecureBootMode
1550 );
1551 } else {
1552 FreePool (SecureBootModePtr);
1553 }
1554 }
1555
1556 /**
1557 Register security measurement handler.
1558
1559 @param ImageHandle ImageHandle of the loaded driver.
1560 @param SystemTable Pointer to the EFI System Table.
1561
1562 @retval EFI_SUCCESS The handlers were registered successfully.
1563 **/
1564 EFI_STATUS
1565 EFIAPI
1566 DxeImageVerificationLibConstructor (
1567 IN EFI_HANDLE ImageHandle,
1568 IN EFI_SYSTEM_TABLE *SystemTable
1569 )
1570 {
1571 VOID *Registration;
1572
1573 //
1574 // Register callback function upon VariableWriteArchProtocol.
1575 //
1576 EfiCreateProtocolNotifyEvent (
1577 &gEfiVariableWriteArchProtocolGuid,
1578 TPL_CALLBACK,
1579 VariableWriteCallBack,
1580 NULL,
1581 &Registration
1582 );
1583
1584 return RegisterSecurityHandler (
1585 DxeImageVerificationHandler,
1586 EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
1587 );
1588 }