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