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