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