]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
0e1587bc3c3c3ca8c0b5f7860e33aaeaa73687e7
[mirror_edk2.git] / SecurityPkg / Library / DxeImageVerificationLib / DxeImageVerificationLib.c
1 /** @file
2 Implement image verification services for secure boot service
3
4 Caution: This file requires additional review when modified.
5 This library will have external input - PE/COFF image.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
8
9 DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content
10 read is within the image buffer.
11
12 DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept
13 untrusted PE/COFF image and validate its data structure within this image buffer before use.
14
15 Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
16 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
17 SPDX-License-Identifier: BSD-2-Clause-Patent
18
19 **/
20
21 #include "DxeImageVerificationLib.h"
22
23 //
24 // Caution: This is used by a function which may receive untrusted input.
25 // These global variables hold PE/COFF image data, and they should be validated before use.
26 //
27 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader;
28 UINT32 mPeCoffHeaderOffset;
29 EFI_GUID mCertType;
30
31 //
32 // Information on current PE/COFF image
33 //
34 UINTN mImageSize;
35 UINT8 *mImageBase = NULL;
36 UINT8 mImageDigest[MAX_DIGEST_SIZE];
37 UINTN mImageDigestSize;
38
39 //
40 // Notify string for authorization UI.
41 //
42 CHAR16 mNotifyString1[MAX_NOTIFY_STRING_LEN] = L"Image verification pass but not found in authorized database!";
43 CHAR16 mNotifyString2[MAX_NOTIFY_STRING_LEN] = L"Launch this image anyway? (Yes/Defer/No)";
44 //
45 // Public Exponent of RSA Key.
46 //
47 CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
48
49
50 //
51 // OID ASN.1 Value for Hash Algorithms
52 //
53 UINT8 mHashOidValue[] = {
54 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
55 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
56 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
57 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
58 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
59 };
60
61 HASH_TABLE mHash[] = {
62 { L"SHA1", 20, &mHashOidValue[0], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final },
63 { L"SHA224", 28, &mHashOidValue[5], 9, NULL, NULL, NULL, NULL },
64 { L"SHA256", 32, &mHashOidValue[14], 9, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Final},
65 { L"SHA384", 48, &mHashOidValue[23], 9, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Final},
66 { L"SHA512", 64, &mHashOidValue[32], 9, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Final}
67 };
68
69 EFI_STRING mHashTypeStr;
70
71 /**
72 SecureBoot Hook for processing image verification.
73
74 @param[in] VariableName Name of Variable to be found.
75 @param[in] VendorGuid Variable vendor GUID.
76 @param[in] DataSize Size of Data found. If size is less than the
77 data, this value contains the required size.
78 @param[in] Data Data pointer.
79
80 **/
81 VOID
82 EFIAPI
83 SecureBootHook (
84 IN CHAR16 *VariableName,
85 IN EFI_GUID *VendorGuid,
86 IN UINTN DataSize,
87 IN VOID *Data
88 );
89
90 /**
91 Reads contents of a PE/COFF image in memory buffer.
92
93 Caution: This function may receive untrusted input.
94 PE/COFF image is external input, so this function will make sure the PE/COFF image content
95 read is within the image buffer.
96
97 @param FileHandle Pointer to the file handle to read the PE/COFF image.
98 @param FileOffset Offset into the PE/COFF image to begin the read operation.
99 @param ReadSize On input, the size in bytes of the requested read operation.
100 On output, the number of bytes actually read.
101 @param Buffer Output buffer that contains the data read from the PE/COFF image.
102
103 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
104 **/
105 EFI_STATUS
106 EFIAPI
107 DxeImageVerificationLibImageRead (
108 IN VOID *FileHandle,
109 IN UINTN FileOffset,
110 IN OUT UINTN *ReadSize,
111 OUT VOID *Buffer
112 )
113 {
114 UINTN EndPosition;
115
116 if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {
117 return EFI_INVALID_PARAMETER;
118 }
119
120 if (MAX_ADDRESS - FileOffset < *ReadSize) {
121 return EFI_INVALID_PARAMETER;
122 }
123
124 EndPosition = FileOffset + *ReadSize;
125 if (EndPosition > mImageSize) {
126 *ReadSize = (UINT32)(mImageSize - FileOffset);
127 }
128
129 if (FileOffset >= mImageSize) {
130 *ReadSize = 0;
131 }
132
133 CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);
134
135 return EFI_SUCCESS;
136 }
137
138
139 /**
140 Get the image type.
141
142 @param[in] File This is a pointer to the device path of the file that is
143 being dispatched.
144
145 @return UINT32 Image Type
146
147 **/
148 UINT32
149 GetImageType (
150 IN CONST EFI_DEVICE_PATH_PROTOCOL *File
151 )
152 {
153 EFI_STATUS Status;
154 EFI_HANDLE DeviceHandle;
155 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
156 EFI_BLOCK_IO_PROTOCOL *BlockIo;
157
158 if (File == NULL) {
159 return IMAGE_UNKNOWN;
160 }
161
162 //
163 // First check to see if File is from a Firmware Volume
164 //
165 DeviceHandle = NULL;
166 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
167 Status = gBS->LocateDevicePath (
168 &gEfiFirmwareVolume2ProtocolGuid,
169 &TempDevicePath,
170 &DeviceHandle
171 );
172 if (!EFI_ERROR (Status)) {
173 Status = gBS->OpenProtocol (
174 DeviceHandle,
175 &gEfiFirmwareVolume2ProtocolGuid,
176 NULL,
177 NULL,
178 NULL,
179 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
180 );
181 if (!EFI_ERROR (Status)) {
182 return IMAGE_FROM_FV;
183 }
184 }
185
186 //
187 // Next check to see if File is from a Block I/O device
188 //
189 DeviceHandle = NULL;
190 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
191 Status = gBS->LocateDevicePath (
192 &gEfiBlockIoProtocolGuid,
193 &TempDevicePath,
194 &DeviceHandle
195 );
196 if (!EFI_ERROR (Status)) {
197 BlockIo = NULL;
198 Status = gBS->OpenProtocol (
199 DeviceHandle,
200 &gEfiBlockIoProtocolGuid,
201 (VOID **) &BlockIo,
202 NULL,
203 NULL,
204 EFI_OPEN_PROTOCOL_GET_PROTOCOL
205 );
206 if (!EFI_ERROR (Status) && BlockIo != NULL) {
207 if (BlockIo->Media != NULL) {
208 if (BlockIo->Media->RemovableMedia) {
209 //
210 // Block I/O is present and specifies the media is removable
211 //
212 return IMAGE_FROM_REMOVABLE_MEDIA;
213 } else {
214 //
215 // Block I/O is present and specifies the media is not removable
216 //
217 return IMAGE_FROM_FIXED_MEDIA;
218 }
219 }
220 }
221 }
222
223 //
224 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
225 // the device path supports the Simple File System Protocol.
226 //
227 DeviceHandle = NULL;
228 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
229 Status = gBS->LocateDevicePath (
230 &gEfiSimpleFileSystemProtocolGuid,
231 &TempDevicePath,
232 &DeviceHandle
233 );
234 if (!EFI_ERROR (Status)) {
235 //
236 // Simple File System is present without Block I/O, so assume media is fixed.
237 //
238 return IMAGE_FROM_FIXED_MEDIA;
239 }
240
241 //
242 // File is not from an FV, Block I/O or Simple File System, so the only options
243 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
244 //
245 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
246 while (!IsDevicePathEndType (TempDevicePath)) {
247 switch (DevicePathType (TempDevicePath)) {
248
249 case MEDIA_DEVICE_PATH:
250 if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) {
251 return IMAGE_FROM_OPTION_ROM;
252 }
253 break;
254
255 case MESSAGING_DEVICE_PATH:
256 if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) {
257 return IMAGE_FROM_REMOVABLE_MEDIA;
258 }
259 break;
260
261 default:
262 break;
263 }
264 TempDevicePath = NextDevicePathNode (TempDevicePath);
265 }
266 return IMAGE_UNKNOWN;
267 }
268
269 /**
270 Calculate hash of Pe/Coff image based on the authenticode image hashing in
271 PE/COFF Specification 8.0 Appendix A
272
273 Caution: This function may receive untrusted input.
274 PE/COFF image is external input, so this function will validate its data structure
275 within this image buffer before use.
276
277 Notes: PE/COFF image has been checked by BasePeCoffLib PeCoffLoaderGetImageInfo() in
278 its caller function DxeImageVerificationHandler().
279
280 @param[in] HashAlg Hash algorithm type.
281
282 @retval TRUE Successfully hash image.
283 @retval FALSE Fail in hash image.
284
285 **/
286 BOOLEAN
287 HashPeImage (
288 IN UINT32 HashAlg
289 )
290 {
291 BOOLEAN Status;
292 EFI_IMAGE_SECTION_HEADER *Section;
293 VOID *HashCtx;
294 UINTN CtxSize;
295 UINT8 *HashBase;
296 UINTN HashSize;
297 UINTN SumOfBytesHashed;
298 EFI_IMAGE_SECTION_HEADER *SectionHeader;
299 UINTN Index;
300 UINTN Pos;
301 UINT32 CertSize;
302 UINT32 NumberOfRvaAndSizes;
303
304 HashCtx = NULL;
305 SectionHeader = NULL;
306 Status = FALSE;
307
308 if ((HashAlg >= HASHALG_MAX)) {
309 return FALSE;
310 }
311
312 //
313 // Initialize context of hash.
314 //
315 ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
316
317 switch (HashAlg) {
318 case HASHALG_SHA1:
319 mImageDigestSize = SHA1_DIGEST_SIZE;
320 mCertType = gEfiCertSha1Guid;
321 break;
322
323 case HASHALG_SHA256:
324 mImageDigestSize = SHA256_DIGEST_SIZE;
325 mCertType = gEfiCertSha256Guid;
326 break;
327
328 case HASHALG_SHA384:
329 mImageDigestSize = SHA384_DIGEST_SIZE;
330 mCertType = gEfiCertSha384Guid;
331 break;
332
333 case HASHALG_SHA512:
334 mImageDigestSize = SHA512_DIGEST_SIZE;
335 mCertType = gEfiCertSha512Guid;
336 break;
337
338 default:
339 return FALSE;
340 }
341
342 mHashTypeStr = mHash[HashAlg].Name;
343 CtxSize = mHash[HashAlg].GetContextSize();
344
345 HashCtx = AllocatePool (CtxSize);
346 if (HashCtx == NULL) {
347 return FALSE;
348 }
349
350 // 1. Load the image header into memory.
351
352 // 2. Initialize a SHA hash context.
353 Status = mHash[HashAlg].HashInit(HashCtx);
354
355 if (!Status) {
356 goto Done;
357 }
358
359 //
360 // Measuring PE/COFF Image Header;
361 // But CheckSum field and SECURITY data directory (certificate) are excluded
362 //
363
364 //
365 // 3. Calculate the distance from the base of the image header to the image checksum address.
366 // 4. Hash the image header from its base to beginning of the image checksum.
367 //
368 HashBase = mImageBase;
369 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
370 //
371 // Use PE32 offset.
372 //
373 HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
374 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
375 } else if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
376 //
377 // Use PE32+ offset.
378 //
379 HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
380 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
381 } else {
382 //
383 // Invalid header magic number.
384 //
385 Status = FALSE;
386 goto Done;
387 }
388
389 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
390 if (!Status) {
391 goto Done;
392 }
393
394 //
395 // 5. Skip over the image checksum (it occupies a single ULONG).
396 //
397 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
398 //
399 // 6. Since there is no Cert Directory in optional header, hash everything
400 // from the end of the checksum to the end of image header.
401 //
402 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
403 //
404 // Use PE32 offset.
405 //
406 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
407 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
408 } else {
409 //
410 // Use PE32+ offset.
411 //
412 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
413 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
414 }
415
416 if (HashSize != 0) {
417 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
418 if (!Status) {
419 goto Done;
420 }
421 }
422 } else {
423 //
424 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
425 //
426 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
427 //
428 // Use PE32 offset.
429 //
430 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
431 HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
432 } else {
433 //
434 // Use PE32+ offset.
435 //
436 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
437 HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
438 }
439
440 if (HashSize != 0) {
441 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
442 if (!Status) {
443 goto Done;
444 }
445 }
446
447 //
448 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
449 // 9. Hash everything from the end of the Cert Directory to the end of image header.
450 //
451 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
452 //
453 // Use PE32 offset
454 //
455 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
456 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
457 } else {
458 //
459 // Use PE32+ offset.
460 //
461 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
462 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
463 }
464
465 if (HashSize != 0) {
466 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
467 if (!Status) {
468 goto Done;
469 }
470 }
471 }
472
473 //
474 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
475 //
476 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
477 //
478 // Use PE32 offset.
479 //
480 SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
481 } else {
482 //
483 // Use PE32+ offset
484 //
485 SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
486 }
487
488
489 Section = (EFI_IMAGE_SECTION_HEADER *) (
490 mImageBase +
491 mPeCoffHeaderOffset +
492 sizeof (UINT32) +
493 sizeof (EFI_IMAGE_FILE_HEADER) +
494 mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
495 );
496
497 //
498 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
499 // structures in the image. The 'NumberOfSections' field of the image
500 // header indicates how big the table should be. Do not include any
501 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
502 //
503 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
504 if (SectionHeader == NULL) {
505 Status = FALSE;
506 goto Done;
507 }
508 //
509 // 12. Using the 'PointerToRawData' in the referenced section headers as
510 // a key, arrange the elements in the table in ascending order. In other
511 // words, sort the section headers according to the disk-file offset of
512 // the section.
513 //
514 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
515 Pos = Index;
516 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
517 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
518 Pos--;
519 }
520 CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
521 Section += 1;
522 }
523
524 //
525 // 13. Walk through the sorted table, bring the corresponding section
526 // into memory, and hash the entire section (using the 'SizeOfRawData'
527 // field in the section header to determine the amount of data to hash).
528 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
529 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
530 //
531 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
532 Section = &SectionHeader[Index];
533 if (Section->SizeOfRawData == 0) {
534 continue;
535 }
536 HashBase = mImageBase + Section->PointerToRawData;
537 HashSize = (UINTN) Section->SizeOfRawData;
538
539 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
540 if (!Status) {
541 goto Done;
542 }
543
544 SumOfBytesHashed += HashSize;
545 }
546
547 //
548 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
549 // data in the file that needs to be added to the hash. This data begins
550 // at file offset SUM_OF_BYTES_HASHED and its length is:
551 // FileSize - (CertDirectory->Size)
552 //
553 if (mImageSize > SumOfBytesHashed) {
554 HashBase = mImageBase + SumOfBytesHashed;
555
556 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
557 CertSize = 0;
558 } else {
559 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
560 //
561 // Use PE32 offset.
562 //
563 CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
564 } else {
565 //
566 // Use PE32+ offset.
567 //
568 CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
569 }
570 }
571
572 if (mImageSize > CertSize + SumOfBytesHashed) {
573 HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed);
574
575 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
576 if (!Status) {
577 goto Done;
578 }
579 } else if (mImageSize < CertSize + SumOfBytesHashed) {
580 Status = FALSE;
581 goto Done;
582 }
583 }
584
585 Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
586
587 Done:
588 if (HashCtx != NULL) {
589 FreePool (HashCtx);
590 }
591 if (SectionHeader != NULL) {
592 FreePool (SectionHeader);
593 }
594 return Status;
595 }
596
597 /**
598 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
599 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
600 8.0 Appendix A
601
602 Caution: This function may receive untrusted input.
603 PE/COFF image is external input, so this function will validate its data structure
604 within this image buffer before use.
605
606 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
607 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
608
609 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
610 @retval EFI_SUCCESS Hash successfully.
611
612 **/
613 EFI_STATUS
614 HashPeImageByType (
615 IN UINT8 *AuthData,
616 IN UINTN AuthDataSize
617 )
618 {
619 UINT8 Index;
620
621 for (Index = 0; Index < HASHALG_MAX; Index++) {
622 //
623 // Check the Hash algorithm in PE/COFF Authenticode.
624 // According to PKCS#7 Definition:
625 // SignedData ::= SEQUENCE {
626 // version Version,
627 // digestAlgorithms DigestAlgorithmIdentifiers,
628 // contentInfo ContentInfo,
629 // .... }
630 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
631 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
632 // Fixed offset (+32) is calculated based on two bytes of length encoding.
633 //
634 if ((*(AuthData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
635 //
636 // Only support two bytes of Long Form of Length Encoding.
637 //
638 continue;
639 }
640
641 if (AuthDataSize < 32 + mHash[Index].OidLength) {
642 return EFI_UNSUPPORTED;
643 }
644
645 if (CompareMem (AuthData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
646 break;
647 }
648 }
649
650 if (Index == HASHALG_MAX) {
651 return EFI_UNSUPPORTED;
652 }
653
654 //
655 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
656 //
657 if (!HashPeImage(Index)) {
658 return EFI_UNSUPPORTED;
659 }
660
661 return EFI_SUCCESS;
662 }
663
664
665 /**
666 Returns the size of a given image execution info table in bytes.
667
668 This function returns the size, in bytes, of the image execution info table specified by
669 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
670
671 @param ImageExeInfoTable A pointer to a image execution info table structure.
672
673 @retval 0 If ImageExeInfoTable is NULL.
674 @retval Others The size of a image execution info table in bytes.
675
676 **/
677 UINTN
678 GetImageExeInfoTableSize (
679 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable
680 )
681 {
682 UINTN Index;
683 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem;
684 UINTN TotalSize;
685
686 if (ImageExeInfoTable == NULL) {
687 return 0;
688 }
689
690 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE));
691 TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
692 for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) {
693 TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize);
694 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize));
695 }
696
697 return TotalSize;
698 }
699
700 /**
701 Create an Image Execution Information Table entry and add it to system configuration table.
702
703 @param[in] Action Describes the action taken by the firmware regarding this image.
704 @param[in] Name Input a null-terminated, user-friendly name.
705 @param[in] DevicePath Input device path pointer.
706 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
707 @param[in] SignatureSize Size of signature. Must be zero if Signature is NULL.
708
709 **/
710 VOID
711 AddImageExeInfo (
712 IN EFI_IMAGE_EXECUTION_ACTION Action,
713 IN CHAR16 *Name OPTIONAL,
714 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
715 IN EFI_SIGNATURE_LIST *Signature OPTIONAL,
716 IN UINTN SignatureSize
717 )
718 {
719 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
720 EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable;
721 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry;
722 UINTN ImageExeInfoTableSize;
723 UINTN NewImageExeInfoEntrySize;
724 UINTN NameStringLen;
725 UINTN DevicePathSize;
726 CHAR16 *NameStr;
727
728 ImageExeInfoTable = NULL;
729 NewImageExeInfoTable = NULL;
730 ImageExeInfoEntry = NULL;
731 NameStringLen = 0;
732 NameStr = NULL;
733
734 if (DevicePath == NULL) {
735 return ;
736 }
737
738 if (Name != NULL) {
739 NameStringLen = StrSize (Name);
740 } else {
741 NameStringLen = sizeof (CHAR16);
742 }
743
744 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
745 if (ImageExeInfoTable != NULL) {
746 //
747 // The table has been found!
748 // We must enlarge the table to accommodate the new exe info entry.
749 //
750 ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable);
751 } else {
752 //
753 // Not Found!
754 // We should create a new table to append to the configuration table.
755 //
756 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
757 }
758
759 DevicePathSize = GetDevicePathSize (DevicePath);
760
761 //
762 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
763 //
764 ASSERT (Signature != NULL || SignatureSize == 0);
765 NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize;
766
767 NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize);
768 if (NewImageExeInfoTable == NULL) {
769 return ;
770 }
771
772 if (ImageExeInfoTable != NULL) {
773 CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize);
774 } else {
775 NewImageExeInfoTable->NumberOfImages = 0;
776 }
777 NewImageExeInfoTable->NumberOfImages++;
778 ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize);
779 //
780 // Update new item's information.
781 //
782 WriteUnaligned32 ((UINT32 *) ImageExeInfoEntry, Action);
783 WriteUnaligned32 ((UINT32 *) ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION)), (UINT32) NewImageExeInfoEntrySize);
784
785 NameStr = (CHAR16 *)(ImageExeInfoEntry + 1);
786 if (Name != NULL) {
787 CopyMem ((UINT8 *) NameStr, Name, NameStringLen);
788 } else {
789 ZeroMem ((UINT8 *) NameStr, sizeof (CHAR16));
790 }
791
792 CopyMem (
793 (UINT8 *) NameStr + NameStringLen,
794 DevicePath,
795 DevicePathSize
796 );
797 if (Signature != NULL) {
798 CopyMem (
799 (UINT8 *) NameStr + NameStringLen + DevicePathSize,
800 Signature,
801 SignatureSize
802 );
803 }
804 //
805 // Update/replace the image execution table.
806 //
807 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable);
808
809 //
810 // Free Old table data!
811 //
812 if (ImageExeInfoTable != NULL) {
813 FreePool (ImageExeInfoTable);
814 }
815 }
816
817 /**
818 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
819
820 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
821 @param[in] CertSize Size of X.509 Certificate.
822 @param[in] SignatureList Pointer to the Signature List in forbidden database.
823 @param[in] SignatureListSize Size of Signature List.
824 @param[out] RevocationTime Return the time that the certificate was revoked.
825 @param[out] IsFound Search result. Only valid if EFI_SUCCESS returned.
826
827 @retval EFI_SUCCESS Finished the search without any error.
828 @retval Others Error occurred in the search of database.
829
830 **/
831 EFI_STATUS
832 IsCertHashFoundInDatabase (
833 IN UINT8 *Certificate,
834 IN UINTN CertSize,
835 IN EFI_SIGNATURE_LIST *SignatureList,
836 IN UINTN SignatureListSize,
837 OUT EFI_TIME *RevocationTime,
838 OUT BOOLEAN *IsFound
839 )
840 {
841 EFI_STATUS Status;
842 EFI_SIGNATURE_LIST *DbxList;
843 UINTN DbxSize;
844 EFI_SIGNATURE_DATA *CertHash;
845 UINTN CertHashCount;
846 UINTN Index;
847 UINT32 HashAlg;
848 VOID *HashCtx;
849 UINT8 CertDigest[MAX_DIGEST_SIZE];
850 UINT8 *DbxCertHash;
851 UINTN SiglistHeaderSize;
852 UINT8 *TBSCert;
853 UINTN TBSCertSize;
854
855 Status = EFI_ABORTED;
856 *IsFound = FALSE;
857 DbxList = SignatureList;
858 DbxSize = SignatureListSize;
859 HashCtx = NULL;
860 HashAlg = HASHALG_MAX;
861
862 if ((RevocationTime == NULL) || (DbxList == NULL)) {
863 return EFI_INVALID_PARAMETER;
864 }
865
866 //
867 // Retrieve the TBSCertificate from the X.509 Certificate.
868 //
869 if (!X509GetTBSCert (Certificate, CertSize, &TBSCert, &TBSCertSize)) {
870 return Status;
871 }
872
873 while ((DbxSize > 0) && (SignatureListSize >= DbxList->SignatureListSize)) {
874 //
875 // Determine Hash Algorithm of Certificate in the forbidden database.
876 //
877 if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha256Guid)) {
878 HashAlg = HASHALG_SHA256;
879 } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha384Guid)) {
880 HashAlg = HASHALG_SHA384;
881 } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha512Guid)) {
882 HashAlg = HASHALG_SHA512;
883 } else {
884 DbxSize -= DbxList->SignatureListSize;
885 DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize);
886 continue;
887 }
888
889 //
890 // Calculate the hash value of current TBSCertificate for comparision.
891 //
892 if (mHash[HashAlg].GetContextSize == NULL) {
893 goto Done;
894 }
895 ZeroMem (CertDigest, MAX_DIGEST_SIZE);
896 HashCtx = AllocatePool (mHash[HashAlg].GetContextSize ());
897 if (HashCtx == NULL) {
898 goto Done;
899 }
900 if (!mHash[HashAlg].HashInit (HashCtx)) {
901 goto Done;
902 }
903 if (!mHash[HashAlg].HashUpdate (HashCtx, TBSCert, TBSCertSize)) {
904 goto Done;
905 }
906 if (!mHash[HashAlg].HashFinal (HashCtx, CertDigest)) {
907 goto Done;
908 }
909
910 FreePool (HashCtx);
911 HashCtx = NULL;
912
913 SiglistHeaderSize = sizeof (EFI_SIGNATURE_LIST) + DbxList->SignatureHeaderSize;
914 CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) DbxList + SiglistHeaderSize);
915 CertHashCount = (DbxList->SignatureListSize - SiglistHeaderSize) / DbxList->SignatureSize;
916 for (Index = 0; Index < CertHashCount; Index++) {
917 //
918 // Iterate each Signature Data Node within this CertList for verify.
919 //
920 DbxCertHash = CertHash->SignatureData;
921 if (CompareMem (DbxCertHash, CertDigest, mHash[HashAlg].DigestLength) == 0) {
922 //
923 // Hash of Certificate is found in forbidden database.
924 //
925 Status = EFI_SUCCESS;
926 *IsFound = TRUE;
927
928 //
929 // Return the revocation time.
930 //
931 CopyMem (RevocationTime, (EFI_TIME *)(DbxCertHash + mHash[HashAlg].DigestLength), sizeof (EFI_TIME));
932 goto Done;
933 }
934 CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertHash + DbxList->SignatureSize);
935 }
936
937 DbxSize -= DbxList->SignatureListSize;
938 DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize);
939 }
940
941 Status = EFI_SUCCESS;
942
943 Done:
944 if (HashCtx != NULL) {
945 FreePool (HashCtx);
946 }
947
948 return Status;
949 }
950
951 /**
952 Check whether signature is in specified database.
953
954 @param[in] VariableName Name of database variable that is searched in.
955 @param[in] Signature Pointer to signature that is searched for.
956 @param[in] CertType Pointer to hash algorithm.
957 @param[in] SignatureSize Size of Signature.
958 @param[out] IsFound Search result. Only valid if EFI_SUCCESS returned
959
960 @retval EFI_SUCCESS Finished the search without any error.
961 @retval Others Error occurred in the search of database.
962
963 **/
964 EFI_STATUS
965 IsSignatureFoundInDatabase (
966 IN CHAR16 *VariableName,
967 IN UINT8 *Signature,
968 IN EFI_GUID *CertType,
969 IN UINTN SignatureSize,
970 OUT BOOLEAN *IsFound
971 )
972 {
973 EFI_STATUS Status;
974 EFI_SIGNATURE_LIST *CertList;
975 EFI_SIGNATURE_DATA *Cert;
976 UINTN DataSize;
977 UINT8 *Data;
978 UINTN Index;
979 UINTN CertCount;
980
981 //
982 // Read signature database variable.
983 //
984 *IsFound = FALSE;
985 Data = NULL;
986 DataSize = 0;
987 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
988 if (Status != EFI_BUFFER_TOO_SMALL) {
989 if (Status == EFI_NOT_FOUND) {
990 //
991 // No database, no need to search.
992 //
993 Status = EFI_SUCCESS;
994 }
995
996 return Status;
997 }
998
999 Data = (UINT8 *) AllocateZeroPool (DataSize);
1000 if (Data == NULL) {
1001 return EFI_OUT_OF_RESOURCES;
1002 }
1003
1004 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data);
1005 if (EFI_ERROR (Status)) {
1006 goto Done;
1007 }
1008 //
1009 // Enumerate all signature data in SigDB to check if signature exists for executable.
1010 //
1011 CertList = (EFI_SIGNATURE_LIST *) Data;
1012 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
1013 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1014 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1015 if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) {
1016 for (Index = 0; Index < CertCount; Index++) {
1017 if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) {
1018 //
1019 // Find the signature in database.
1020 //
1021 *IsFound = TRUE;
1022 //
1023 // Entries in UEFI_IMAGE_SECURITY_DATABASE that are used to validate image should be measured
1024 //
1025 if (StrCmp(VariableName, EFI_IMAGE_SECURITY_DATABASE) == 0) {
1026 SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert);
1027 }
1028 break;
1029 }
1030
1031 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1032 }
1033
1034 if (*IsFound) {
1035 break;
1036 }
1037 }
1038
1039 DataSize -= CertList->SignatureListSize;
1040 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1041 }
1042
1043 Done:
1044 if (Data != NULL) {
1045 FreePool (Data);
1046 }
1047
1048 return Status;
1049 }
1050
1051 /**
1052 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1053
1054 @param SigningTime A pointer to the signing time.
1055 @param RevocationTime A pointer to the revocation time.
1056
1057 @retval TRUE The SigningTime is not later than the RevocationTime.
1058 @retval FALSE The SigningTime is later than the RevocationTime.
1059
1060 **/
1061 BOOLEAN
1062 IsValidSignatureByTimestamp (
1063 IN EFI_TIME *SigningTime,
1064 IN EFI_TIME *RevocationTime
1065 )
1066 {
1067 if (SigningTime->Year != RevocationTime->Year) {
1068 return (BOOLEAN) (SigningTime->Year < RevocationTime->Year);
1069 } else if (SigningTime->Month != RevocationTime->Month) {
1070 return (BOOLEAN) (SigningTime->Month < RevocationTime->Month);
1071 } else if (SigningTime->Day != RevocationTime->Day) {
1072 return (BOOLEAN) (SigningTime->Day < RevocationTime->Day);
1073 } else if (SigningTime->Hour != RevocationTime->Hour) {
1074 return (BOOLEAN) (SigningTime->Hour < RevocationTime->Hour);
1075 } else if (SigningTime->Minute != RevocationTime->Minute) {
1076 return (BOOLEAN) (SigningTime->Minute < RevocationTime->Minute);
1077 }
1078
1079 return (BOOLEAN) (SigningTime->Second <= RevocationTime->Second);
1080 }
1081
1082 /**
1083 Check if the given time value is zero.
1084
1085 @param[in] Time Pointer of a time value.
1086
1087 @retval TRUE The Time is Zero.
1088 @retval FALSE The Time is not Zero.
1089
1090 **/
1091 BOOLEAN
1092 IsTimeZero (
1093 IN EFI_TIME *Time
1094 )
1095 {
1096 if ((Time->Year == 0) && (Time->Month == 0) && (Time->Day == 0) &&
1097 (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) {
1098 return TRUE;
1099 }
1100
1101 return FALSE;
1102 }
1103
1104 /**
1105 Check whether the timestamp signature is valid and the signing time is also earlier than
1106 the revocation time.
1107
1108 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1109 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1110 @param[in] RevocationTime The time that the certificate was revoked.
1111
1112 @retval TRUE Timestamp signature is valid and signing time is no later than the
1113 revocation time.
1114 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1115 revocation time.
1116
1117 **/
1118 BOOLEAN
1119 PassTimestampCheck (
1120 IN UINT8 *AuthData,
1121 IN UINTN AuthDataSize,
1122 IN EFI_TIME *RevocationTime
1123 )
1124 {
1125 EFI_STATUS Status;
1126 BOOLEAN VerifyStatus;
1127 EFI_SIGNATURE_LIST *CertList;
1128 EFI_SIGNATURE_DATA *Cert;
1129 UINT8 *DbtData;
1130 UINTN DbtDataSize;
1131 UINT8 *RootCert;
1132 UINTN RootCertSize;
1133 UINTN Index;
1134 UINTN CertCount;
1135 EFI_TIME SigningTime;
1136
1137 //
1138 // Variable Initialization
1139 //
1140 VerifyStatus = FALSE;
1141 DbtData = NULL;
1142 CertList = NULL;
1143 Cert = NULL;
1144 RootCert = NULL;
1145 RootCertSize = 0;
1146
1147 //
1148 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1149 //
1150 if (IsTimeZero (RevocationTime)) {
1151 return FALSE;
1152 }
1153
1154 //
1155 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1156 // Using the dbt to get the trusted TSA certificates.
1157 //
1158 DbtDataSize = 0;
1159 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL);
1160 if (Status != EFI_BUFFER_TOO_SMALL) {
1161 goto Done;
1162 }
1163 DbtData = (UINT8 *) AllocateZeroPool (DbtDataSize);
1164 if (DbtData == NULL) {
1165 goto Done;
1166 }
1167 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *) DbtData);
1168 if (EFI_ERROR (Status)) {
1169 goto Done;
1170 }
1171
1172 CertList = (EFI_SIGNATURE_LIST *) DbtData;
1173 while ((DbtDataSize > 0) && (DbtDataSize >= CertList->SignatureListSize)) {
1174 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1175 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1176 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1177 for (Index = 0; Index < CertCount; Index++) {
1178 //
1179 // Iterate each Signature Data Node within this CertList for verify.
1180 //
1181 RootCert = Cert->SignatureData;
1182 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1183 //
1184 // Get the signing time if the timestamp signature is valid.
1185 //
1186 if (ImageTimestampVerify (AuthData, AuthDataSize, RootCert, RootCertSize, &SigningTime)) {
1187 //
1188 // The signer signature is valid only when the signing time is earlier than revocation time.
1189 //
1190 if (IsValidSignatureByTimestamp (&SigningTime, RevocationTime)) {
1191 VerifyStatus = TRUE;
1192 goto Done;
1193 }
1194 }
1195 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1196 }
1197 }
1198 DbtDataSize -= CertList->SignatureListSize;
1199 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1200 }
1201
1202 Done:
1203 if (DbtData != NULL) {
1204 FreePool (DbtData);
1205 }
1206
1207 return VerifyStatus;
1208 }
1209
1210 /**
1211 Check whether the image signature is forbidden by the forbidden database (dbx).
1212 The image is forbidden to load if any certificates for signing are revoked before signing time.
1213
1214 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1215 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1216
1217 @retval TRUE Image is forbidden by dbx.
1218 @retval FALSE Image is not forbidden by dbx.
1219
1220 **/
1221 BOOLEAN
1222 IsForbiddenByDbx (
1223 IN UINT8 *AuthData,
1224 IN UINTN AuthDataSize
1225 )
1226 {
1227 EFI_STATUS Status;
1228 BOOLEAN IsForbidden;
1229 BOOLEAN IsFound;
1230 UINT8 *Data;
1231 UINTN DataSize;
1232 EFI_SIGNATURE_LIST *CertList;
1233 UINTN CertListSize;
1234 EFI_SIGNATURE_DATA *CertData;
1235 UINT8 *RootCert;
1236 UINTN RootCertSize;
1237 UINTN CertCount;
1238 UINTN Index;
1239 UINT8 *CertBuffer;
1240 UINTN BufferLength;
1241 UINT8 *TrustedCert;
1242 UINTN TrustedCertLength;
1243 UINT8 CertNumber;
1244 UINT8 *CertPtr;
1245 UINT8 *Cert;
1246 UINTN CertSize;
1247 EFI_TIME RevocationTime;
1248 //
1249 // Variable Initialization
1250 //
1251 IsForbidden = TRUE;
1252 Data = NULL;
1253 CertList = NULL;
1254 CertData = NULL;
1255 RootCert = NULL;
1256 RootCertSize = 0;
1257 Cert = NULL;
1258 CertBuffer = NULL;
1259 BufferLength = 0;
1260 TrustedCert = NULL;
1261 TrustedCertLength = 0;
1262
1263 //
1264 // The image will not be forbidden if dbx can't be got.
1265 //
1266 DataSize = 0;
1267 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
1268 ASSERT (EFI_ERROR (Status));
1269 if (Status != EFI_BUFFER_TOO_SMALL) {
1270 if (Status == EFI_NOT_FOUND) {
1271 //
1272 // Evidently not in dbx if the database doesn't exist.
1273 //
1274 IsForbidden = FALSE;
1275 }
1276 return IsForbidden;
1277 }
1278 Data = (UINT8 *) AllocateZeroPool (DataSize);
1279 if (Data == NULL) {
1280 return IsForbidden;
1281 }
1282
1283 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
1284 if (EFI_ERROR (Status)) {
1285 goto Done;
1286 }
1287
1288 //
1289 // Verify image signature with RAW X509 certificates in DBX database.
1290 // If passed, the image will be forbidden.
1291 //
1292 CertList = (EFI_SIGNATURE_LIST *) Data;
1293 CertListSize = DataSize;
1294 while ((CertListSize > 0) && (CertListSize >= CertList->SignatureListSize)) {
1295 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1296 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1297 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1298
1299 for (Index = 0; Index < CertCount; Index++) {
1300 //
1301 // Iterate each Signature Data Node within this CertList for verify.
1302 //
1303 RootCert = CertData->SignatureData;
1304 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1305
1306 //
1307 // Call AuthenticodeVerify library to Verify Authenticode struct.
1308 //
1309 IsForbidden = AuthenticodeVerify (
1310 AuthData,
1311 AuthDataSize,
1312 RootCert,
1313 RootCertSize,
1314 mImageDigest,
1315 mImageDigestSize
1316 );
1317 if (IsForbidden) {
1318 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1319 goto Done;
1320 }
1321
1322 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
1323 }
1324 }
1325
1326 CertListSize -= CertList->SignatureListSize;
1327 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1328 }
1329
1330 //
1331 // Check X.509 Certificate Hash & Possible Timestamp.
1332 //
1333
1334 //
1335 // Retrieve the certificate stack from AuthData
1336 // The output CertStack format will be:
1337 // UINT8 CertNumber;
1338 // UINT32 Cert1Length;
1339 // UINT8 Cert1[];
1340 // UINT32 Cert2Length;
1341 // UINT8 Cert2[];
1342 // ...
1343 // UINT32 CertnLength;
1344 // UINT8 Certn[];
1345 //
1346 Pkcs7GetSigners (AuthData, AuthDataSize, &CertBuffer, &BufferLength, &TrustedCert, &TrustedCertLength);
1347 if ((BufferLength == 0) || (CertBuffer == NULL) || (*CertBuffer) == 0) {
1348 IsForbidden = TRUE;
1349 goto Done;
1350 }
1351
1352 //
1353 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1354 //
1355 CertNumber = (UINT8) (*CertBuffer);
1356 CertPtr = CertBuffer + 1;
1357 for (Index = 0; Index < CertNumber; Index++) {
1358 CertSize = (UINTN) ReadUnaligned32 ((UINT32 *)CertPtr);
1359 Cert = (UINT8 *)CertPtr + sizeof (UINT32);
1360 //
1361 // Advance CertPtr to the next cert in image signer's cert list
1362 //
1363 CertPtr = CertPtr + sizeof (UINT32) + CertSize;
1364
1365 Status = IsCertHashFoundInDatabase (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime, &IsFound);
1366 if (EFI_ERROR (Status)) {
1367 //
1368 // Error in searching dbx. Consider it as 'found'. RevocationTime might
1369 // not be valid in such situation.
1370 //
1371 IsForbidden = TRUE;
1372 } else if (IsFound) {
1373 //
1374 // Found Cert in dbx successfully. Check the timestamp signature and
1375 // signing time to determine if the image can be trusted.
1376 //
1377 if (PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime)) {
1378 IsForbidden = FALSE;
1379 //
1380 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1381 //
1382 continue;
1383 } else {
1384 IsForbidden = TRUE;
1385 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1386 goto Done;
1387 }
1388 }
1389
1390 }
1391
1392 IsForbidden = FALSE;
1393
1394 Done:
1395 if (Data != NULL) {
1396 FreePool (Data);
1397 }
1398
1399 Pkcs7FreeSigners (CertBuffer);
1400 Pkcs7FreeSigners (TrustedCert);
1401
1402 return IsForbidden;
1403 }
1404
1405
1406 /**
1407 Check whether the image signature can be verified by the trusted certificates in DB database.
1408
1409 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1410 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1411
1412 @retval TRUE Image passed verification using certificate in db.
1413 @retval FALSE Image didn't pass verification using certificate in db.
1414
1415 **/
1416 BOOLEAN
1417 IsAllowedByDb (
1418 IN UINT8 *AuthData,
1419 IN UINTN AuthDataSize
1420 )
1421 {
1422 EFI_STATUS Status;
1423 BOOLEAN VerifyStatus;
1424 BOOLEAN IsFound;
1425 EFI_SIGNATURE_LIST *CertList;
1426 EFI_SIGNATURE_DATA *CertData;
1427 UINTN DataSize;
1428 UINT8 *Data;
1429 UINT8 *RootCert;
1430 UINTN RootCertSize;
1431 UINTN Index;
1432 UINTN CertCount;
1433 UINTN DbxDataSize;
1434 UINT8 *DbxData;
1435 EFI_TIME RevocationTime;
1436
1437 Data = NULL;
1438 CertList = NULL;
1439 CertData = NULL;
1440 RootCert = NULL;
1441 DbxData = NULL;
1442 RootCertSize = 0;
1443 VerifyStatus = FALSE;
1444
1445 //
1446 // Fetch 'db' content. If 'db' doesn't exist or encounters problem to get the
1447 // data, return not-allowed-by-db (FALSE).
1448 //
1449 DataSize = 0;
1450 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
1451 ASSERT (EFI_ERROR (Status));
1452 if (Status != EFI_BUFFER_TOO_SMALL) {
1453 return VerifyStatus;
1454 }
1455
1456 Data = (UINT8 *) AllocateZeroPool (DataSize);
1457 if (Data == NULL) {
1458 return VerifyStatus;
1459 }
1460
1461 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
1462 if (EFI_ERROR (Status)) {
1463 goto Done;
1464 }
1465
1466 //
1467 // Fetch 'dbx' content. If 'dbx' doesn't exist, continue to check 'db'.
1468 // If any other errors occured, no need to check 'db' but just return
1469 // not-allowed-by-db (FALSE) to avoid bypass.
1470 //
1471 DbxDataSize = 0;
1472 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL);
1473 ASSERT (EFI_ERROR (Status));
1474 if (Status != EFI_BUFFER_TOO_SMALL) {
1475 if (Status != EFI_NOT_FOUND) {
1476 goto Done;
1477 }
1478 //
1479 // 'dbx' does not exist. Continue to check 'db'.
1480 //
1481 } else {
1482 //
1483 // 'dbx' exists. Get its content.
1484 //
1485 DbxData = (UINT8 *) AllocateZeroPool (DbxDataSize);
1486 if (DbxData == NULL) {
1487 goto Done;
1488 }
1489
1490 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *) DbxData);
1491 if (EFI_ERROR (Status)) {
1492 goto Done;
1493 }
1494 }
1495
1496 //
1497 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1498 //
1499 CertList = (EFI_SIGNATURE_LIST *) Data;
1500 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
1501 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1502 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1503 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1504
1505 for (Index = 0; Index < CertCount; Index++) {
1506 //
1507 // Iterate each Signature Data Node within this CertList for verify.
1508 //
1509 RootCert = CertData->SignatureData;
1510 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1511
1512 //
1513 // Call AuthenticodeVerify library to Verify Authenticode struct.
1514 //
1515 VerifyStatus = AuthenticodeVerify (
1516 AuthData,
1517 AuthDataSize,
1518 RootCert,
1519 RootCertSize,
1520 mImageDigest,
1521 mImageDigestSize
1522 );
1523 if (VerifyStatus) {
1524 //
1525 // The image is signed and its signature is found in 'db'.
1526 //
1527 if (DbxData != NULL) {
1528 //
1529 // Here We still need to check if this RootCert's Hash is revoked
1530 //
1531 Status = IsCertHashFoundInDatabase (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime, &IsFound);
1532 if (EFI_ERROR (Status)) {
1533 //
1534 // Error in searching dbx. Consider it as 'found'. RevocationTime might
1535 // not be valid in such situation.
1536 //
1537 VerifyStatus = FALSE;
1538 } else if (IsFound) {
1539 //
1540 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1541 //
1542 VerifyStatus = PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime);
1543 if (!VerifyStatus) {
1544 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1545 }
1546 }
1547 }
1548
1549 //
1550 // There's no 'dbx' to check revocation time against (must-be pass),
1551 // or, there's revocation time found in 'dbx' and checked againt 'dbt'
1552 // (maybe pass or fail, depending on timestamp compare result). Either
1553 // way the verification job has been completed at this point.
1554 //
1555 goto Done;
1556 }
1557
1558 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
1559 }
1560 }
1561
1562 DataSize -= CertList->SignatureListSize;
1563 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1564 }
1565
1566 Done:
1567
1568 if (VerifyStatus) {
1569 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData);
1570 }
1571
1572 if (Data != NULL) {
1573 FreePool (Data);
1574 }
1575 if (DbxData != NULL) {
1576 FreePool (DbxData);
1577 }
1578
1579 return VerifyStatus;
1580 }
1581
1582 /**
1583 Provide verification service for signed images, which include both signature validation
1584 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1585 MSFT Authenticode type signatures are supported.
1586
1587 In this implementation, only verify external executables when in USER MODE.
1588 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1589
1590 The image verification policy is:
1591 If the image is signed,
1592 At least one valid signature or at least one hash value of the image must match a record
1593 in the security database "db", and no valid signature nor any hash value of the image may
1594 be reflected in the security database "dbx".
1595 Otherwise, the image is not signed,
1596 The SHA256 hash value of the image must match a record in the security database "db", and
1597 not be reflected in the security data base "dbx".
1598
1599 Caution: This function may receive untrusted input.
1600 PE/COFF image is external input, so this function will validate its data structure
1601 within this image buffer before use.
1602
1603 @param[in] AuthenticationStatus
1604 This is the authentication status returned from the security
1605 measurement services for the input file.
1606 @param[in] File This is a pointer to the device path of the file that is
1607 being dispatched. This will optionally be used for logging.
1608 @param[in] FileBuffer File buffer matches the input file device path.
1609 @param[in] FileSize Size of File buffer matches the input file device path.
1610 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1611
1612 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1613 FileBuffer did authenticate, and the platform policy dictates
1614 that the DXE Foundation may use the file.
1615 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1616 and non-NULL FileBuffer did authenticate, and the platform
1617 policy dictates that the DXE Foundation may execute the image in
1618 FileBuffer.
1619 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1620 the platform policy dictates that File should be placed
1621 in the untrusted state. The image has been added to the file
1622 execution table.
1623 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1624 authenticate, and the platform policy dictates that the DXE
1625 Foundation may not use File. The image has
1626 been added to the file execution table.
1627
1628 **/
1629 EFI_STATUS
1630 EFIAPI
1631 DxeImageVerificationHandler (
1632 IN UINT32 AuthenticationStatus,
1633 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
1634 IN VOID *FileBuffer,
1635 IN UINTN FileSize,
1636 IN BOOLEAN BootPolicy
1637 )
1638 {
1639 EFI_IMAGE_DOS_HEADER *DosHdr;
1640 BOOLEAN IsVerified;
1641 EFI_SIGNATURE_LIST *SignatureList;
1642 UINTN SignatureListSize;
1643 EFI_SIGNATURE_DATA *Signature;
1644 EFI_IMAGE_EXECUTION_ACTION Action;
1645 WIN_CERTIFICATE *WinCertificate;
1646 UINT32 Policy;
1647 UINT8 *SecureBoot;
1648 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1649 UINT32 NumberOfRvaAndSizes;
1650 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
1651 WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid;
1652 UINT8 *AuthData;
1653 UINTN AuthDataSize;
1654 EFI_IMAGE_DATA_DIRECTORY *SecDataDir;
1655 UINT32 OffSet;
1656 CHAR16 *NameStr;
1657 RETURN_STATUS PeCoffStatus;
1658 EFI_STATUS HashStatus;
1659 EFI_STATUS DbStatus;
1660 BOOLEAN IsFound;
1661
1662 SignatureList = NULL;
1663 SignatureListSize = 0;
1664 WinCertificate = NULL;
1665 SecDataDir = NULL;
1666 PkcsCertData = NULL;
1667 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1668 IsVerified = FALSE;
1669 IsFound = FALSE;
1670
1671 //
1672 // Check the image type and get policy setting.
1673 //
1674 switch (GetImageType (File)) {
1675
1676 case IMAGE_FROM_FV:
1677 Policy = ALWAYS_EXECUTE;
1678 break;
1679
1680 case IMAGE_FROM_OPTION_ROM:
1681 Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
1682 break;
1683
1684 case IMAGE_FROM_REMOVABLE_MEDIA:
1685 Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
1686 break;
1687
1688 case IMAGE_FROM_FIXED_MEDIA:
1689 Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
1690 break;
1691
1692 default:
1693 Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
1694 break;
1695 }
1696 //
1697 // If policy is always/never execute, return directly.
1698 //
1699 if (Policy == ALWAYS_EXECUTE) {
1700 return EFI_SUCCESS;
1701 }
1702 if (Policy == NEVER_EXECUTE) {
1703 return EFI_ACCESS_DENIED;
1704 }
1705
1706 //
1707 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1708 // violates the UEFI spec and has been removed.
1709 //
1710 ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION);
1711 if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) {
1712 CpuDeadLoop ();
1713 }
1714
1715 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL);
1716 //
1717 // Skip verification if SecureBoot variable doesn't exist.
1718 //
1719 if (SecureBoot == NULL) {
1720 return EFI_SUCCESS;
1721 }
1722
1723 //
1724 // Skip verification if SecureBoot is disabled but not AuditMode
1725 //
1726 if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) {
1727 FreePool (SecureBoot);
1728 return EFI_SUCCESS;
1729 }
1730 FreePool (SecureBoot);
1731
1732 //
1733 // Read the Dos header.
1734 //
1735 if (FileBuffer == NULL) {
1736 return EFI_ACCESS_DENIED;
1737 }
1738
1739 mImageBase = (UINT8 *) FileBuffer;
1740 mImageSize = FileSize;
1741
1742 ZeroMem (&ImageContext, sizeof (ImageContext));
1743 ImageContext.Handle = (VOID *) FileBuffer;
1744 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
1745
1746 //
1747 // Get information about the image being loaded
1748 //
1749 PeCoffStatus = PeCoffLoaderGetImageInfo (&ImageContext);
1750 if (RETURN_ERROR (PeCoffStatus)) {
1751 //
1752 // The information can't be got from the invalid PeImage
1753 //
1754 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1755 goto Failed;
1756 }
1757
1758 DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
1759 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
1760 //
1761 // DOS image header is present,
1762 // so read the PE header after the DOS image header.
1763 //
1764 mPeCoffHeaderOffset = DosHdr->e_lfanew;
1765 } else {
1766 mPeCoffHeaderOffset = 0;
1767 }
1768 //
1769 // Check PE/COFF image.
1770 //
1771 mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
1772 if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1773 //
1774 // It is not a valid Pe/Coff file.
1775 //
1776 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1777 goto Failed;
1778 }
1779
1780 if (mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1781 //
1782 // Use PE32 offset.
1783 //
1784 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
1785 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1786 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1787 }
1788 } else {
1789 //
1790 // Use PE32+ offset.
1791 //
1792 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
1793 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1794 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1795 }
1796 }
1797
1798 //
1799 // Start Image Validation.
1800 //
1801 if (SecDataDir == NULL || SecDataDir->Size == 0) {
1802 //
1803 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1804 // and not be reflected in the security data base "dbx".
1805 //
1806 if (!HashPeImage (HASHALG_SHA256)) {
1807 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr));
1808 goto Failed;
1809 }
1810
1811 DbStatus = IsSignatureFoundInDatabase (
1812 EFI_IMAGE_SECURITY_DATABASE1,
1813 mImageDigest,
1814 &mCertType,
1815 mImageDigestSize,
1816 &IsFound
1817 );
1818 if (EFI_ERROR (DbStatus) || IsFound) {
1819 //
1820 // Image Hash is in forbidden database (DBX).
1821 //
1822 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr));
1823 goto Failed;
1824 }
1825
1826 DbStatus = IsSignatureFoundInDatabase (
1827 EFI_IMAGE_SECURITY_DATABASE,
1828 mImageDigest,
1829 &mCertType,
1830 mImageDigestSize,
1831 &IsFound
1832 );
1833 if (!EFI_ERROR (DbStatus) && IsFound) {
1834 //
1835 // Image Hash is in allowed database (DB).
1836 //
1837 return EFI_SUCCESS;
1838 }
1839
1840 //
1841 // Image Hash is not found in both forbidden and allowed database.
1842 //
1843 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr));
1844 goto Failed;
1845 }
1846
1847 //
1848 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1849 // "Attribute Certificate Table".
1850 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1851 //
1852 for (OffSet = SecDataDir->VirtualAddress;
1853 OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size);
1854 OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) {
1855 WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet);
1856 if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) ||
1857 (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) {
1858 break;
1859 }
1860
1861 //
1862 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1863 //
1864 if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1865 //
1866 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1867 // Authenticode specification.
1868 //
1869 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate;
1870 if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) {
1871 break;
1872 }
1873 AuthData = PkcsCertData->CertData;
1874 AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr);
1875 } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
1876 //
1877 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1878 //
1879 WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate;
1880 if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) {
1881 break;
1882 }
1883 if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) {
1884 continue;
1885 }
1886 AuthData = WinCertUefiGuid->CertData;
1887 AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData);
1888 } else {
1889 if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) {
1890 break;
1891 }
1892 continue;
1893 }
1894
1895 HashStatus = HashPeImageByType (AuthData, AuthDataSize);
1896 if (EFI_ERROR (HashStatus)) {
1897 continue;
1898 }
1899
1900 //
1901 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1902 //
1903 if (IsForbiddenByDbx (AuthData, AuthDataSize)) {
1904 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
1905 IsVerified = FALSE;
1906 break;
1907 }
1908
1909 //
1910 // Check the digital signature against the valid certificate in allowed database (db).
1911 //
1912 if (!IsVerified) {
1913 if (IsAllowedByDb (AuthData, AuthDataSize)) {
1914 IsVerified = TRUE;
1915 }
1916 }
1917
1918 //
1919 // Check the image's hash value.
1920 //
1921 DbStatus = IsSignatureFoundInDatabase (
1922 EFI_IMAGE_SECURITY_DATABASE1,
1923 mImageDigest,
1924 &mCertType,
1925 mImageDigestSize,
1926 &IsFound
1927 );
1928 if (EFI_ERROR (DbStatus) || IsFound) {
1929 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
1930 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr));
1931 IsVerified = FALSE;
1932 break;
1933 }
1934
1935 if (!IsVerified) {
1936 DbStatus = IsSignatureFoundInDatabase (
1937 EFI_IMAGE_SECURITY_DATABASE,
1938 mImageDigest,
1939 &mCertType,
1940 mImageDigestSize,
1941 &IsFound
1942 );
1943 if (!EFI_ERROR (DbStatus) && IsFound) {
1944 IsVerified = TRUE;
1945 } else {
1946 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));
1947 }
1948 }
1949 }
1950
1951 if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) {
1952 //
1953 // The Size in Certificate Table or the attribute certificate table is corrupted.
1954 //
1955 IsVerified = FALSE;
1956 }
1957
1958 if (IsVerified) {
1959 return EFI_SUCCESS;
1960 }
1961 if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) {
1962 //
1963 // Get image hash value as signature of executable.
1964 //
1965 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
1966 SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
1967 if (SignatureList == NULL) {
1968 SignatureListSize = 0;
1969 goto Failed;
1970 }
1971 SignatureList->SignatureHeaderSize = 0;
1972 SignatureList->SignatureListSize = (UINT32) SignatureListSize;
1973 SignatureList->SignatureSize = (UINT32) (sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize);
1974 CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
1975 Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
1976 CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
1977 }
1978
1979 Failed:
1980 //
1981 // Policy decides to defer or reject the image; add its information in image
1982 // executable information table in either case.
1983 //
1984 NameStr = ConvertDevicePathToText (File, FALSE, TRUE);
1985 AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize);
1986 if (NameStr != NULL) {
1987 DEBUG ((DEBUG_INFO, "The image doesn't pass verification: %s\n", NameStr));
1988 FreePool(NameStr);
1989 }
1990
1991 if (SignatureList != NULL) {
1992 FreePool (SignatureList);
1993 }
1994
1995 if (Policy == DEFER_EXECUTE_ON_SECURITY_VIOLATION) {
1996 return EFI_SECURITY_VIOLATION;
1997 }
1998 return EFI_ACCESS_DENIED;
1999 }
2000
2001 /**
2002 On Ready To Boot Services Event notification handler.
2003
2004 Add the image execution information table if it is not in system configuration table.
2005
2006 @param[in] Event Event whose notification function is being invoked
2007 @param[in] Context Pointer to the notification function's context
2008
2009 **/
2010 VOID
2011 EFIAPI
2012 OnReadyToBoot (
2013 IN EFI_EVENT Event,
2014 IN VOID *Context
2015 )
2016 {
2017 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
2018 UINTN ImageExeInfoTableSize;
2019
2020 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
2021 if (ImageExeInfoTable != NULL) {
2022 return;
2023 }
2024
2025 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
2026 ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize);
2027 if (ImageExeInfoTable == NULL) {
2028 return ;
2029 }
2030
2031 ImageExeInfoTable->NumberOfImages = 0;
2032 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) ImageExeInfoTable);
2033
2034 }
2035
2036 /**
2037 Register security measurement handler.
2038
2039 @param ImageHandle ImageHandle of the loaded driver.
2040 @param SystemTable Pointer to the EFI System Table.
2041
2042 @retval EFI_SUCCESS The handlers were registered successfully.
2043 **/
2044 EFI_STATUS
2045 EFIAPI
2046 DxeImageVerificationLibConstructor (
2047 IN EFI_HANDLE ImageHandle,
2048 IN EFI_SYSTEM_TABLE *SystemTable
2049 )
2050 {
2051 EFI_EVENT Event;
2052
2053 //
2054 // Register the event to publish the image execution table.
2055 //
2056 EfiCreateEventReadyToBootEx (
2057 TPL_CALLBACK,
2058 OnReadyToBoot,
2059 NULL,
2060 &Event
2061 );
2062
2063 return RegisterSecurity2Handler (
2064 DxeImageVerificationHandler,
2065 EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
2066 );
2067 }