]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
7b7e6af784147922b2c4de8c76ede269eda9e7bc
[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 - 2016, 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 SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert);
1030 break;
1031 }
1032
1033 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1034 }
1035
1036 if (IsFound) {
1037 break;
1038 }
1039 }
1040
1041 DataSize -= CertList->SignatureListSize;
1042 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1043 }
1044
1045 Done:
1046 if (Data != NULL) {
1047 FreePool (Data);
1048 }
1049
1050 return IsFound;
1051 }
1052
1053 /**
1054 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1055
1056 @param SigningTime A pointer to the signing time.
1057 @param RevocationTime A pointer to the revocation time.
1058
1059 @retval TRUE The SigningTime is not later than the RevocationTime.
1060 @retval FALSE The SigningTime is later than the RevocationTime.
1061
1062 **/
1063 BOOLEAN
1064 IsValidSignatureByTimestamp (
1065 IN EFI_TIME *SigningTime,
1066 IN EFI_TIME *RevocationTime
1067 )
1068 {
1069 if (SigningTime->Year != RevocationTime->Year) {
1070 return (BOOLEAN) (SigningTime->Year < RevocationTime->Year);
1071 } else if (SigningTime->Month != RevocationTime->Month) {
1072 return (BOOLEAN) (SigningTime->Month < RevocationTime->Month);
1073 } else if (SigningTime->Day != RevocationTime->Day) {
1074 return (BOOLEAN) (SigningTime->Day < RevocationTime->Day);
1075 } else if (SigningTime->Hour != RevocationTime->Hour) {
1076 return (BOOLEAN) (SigningTime->Hour < RevocationTime->Hour);
1077 } else if (SigningTime->Minute != RevocationTime->Minute) {
1078 return (BOOLEAN) (SigningTime->Minute < RevocationTime->Minute);
1079 }
1080
1081 return (BOOLEAN) (SigningTime->Second <= RevocationTime->Second);
1082 }
1083
1084 /**
1085 Check if the given time value is zero.
1086
1087 @param[in] Time Pointer of a time value.
1088
1089 @retval TRUE The Time is Zero.
1090 @retval FALSE The Time is not Zero.
1091
1092 **/
1093 BOOLEAN
1094 IsTimeZero (
1095 IN EFI_TIME *Time
1096 )
1097 {
1098 if ((Time->Year == 0) && (Time->Month == 0) && (Time->Day == 0) &&
1099 (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) {
1100 return TRUE;
1101 }
1102
1103 return FALSE;
1104 }
1105
1106 /**
1107 Check whether the timestamp signature is valid and the signing time is also earlier than
1108 the revocation time.
1109
1110 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1111 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1112 @param[in] RevocationTime The time that the certificate was revoked.
1113
1114 @retval TRUE Timestamp signature is valid and signing time is no later than the
1115 revocation time.
1116 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1117 revocation time.
1118
1119 **/
1120 BOOLEAN
1121 PassTimestampCheck (
1122 IN UINT8 *AuthData,
1123 IN UINTN AuthDataSize,
1124 IN EFI_TIME *RevocationTime
1125 )
1126 {
1127 EFI_STATUS Status;
1128 BOOLEAN VerifyStatus;
1129 EFI_SIGNATURE_LIST *CertList;
1130 EFI_SIGNATURE_DATA *Cert;
1131 UINT8 *DbtData;
1132 UINTN DbtDataSize;
1133 UINT8 *RootCert;
1134 UINTN RootCertSize;
1135 UINTN Index;
1136 UINTN CertCount;
1137 EFI_TIME SigningTime;
1138
1139 //
1140 // Variable Initialization
1141 //
1142 VerifyStatus = FALSE;
1143 DbtData = NULL;
1144 CertList = NULL;
1145 Cert = NULL;
1146 RootCert = NULL;
1147 RootCertSize = 0;
1148
1149 //
1150 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1151 //
1152 if (IsTimeZero (RevocationTime)) {
1153 return FALSE;
1154 }
1155
1156 //
1157 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1158 // Using the dbt to get the trusted TSA certificates.
1159 //
1160 DbtDataSize = 0;
1161 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL);
1162 if (Status != EFI_BUFFER_TOO_SMALL) {
1163 goto Done;
1164 }
1165 DbtData = (UINT8 *) AllocateZeroPool (DbtDataSize);
1166 if (DbtData == NULL) {
1167 goto Done;
1168 }
1169 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *) DbtData);
1170 if (EFI_ERROR (Status)) {
1171 goto Done;
1172 }
1173
1174 CertList = (EFI_SIGNATURE_LIST *) DbtData;
1175 while ((DbtDataSize > 0) && (DbtDataSize >= CertList->SignatureListSize)) {
1176 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1177 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1178 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1179 for (Index = 0; Index < CertCount; Index++) {
1180 //
1181 // Iterate each Signature Data Node within this CertList for verify.
1182 //
1183 RootCert = Cert->SignatureData;
1184 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1185 //
1186 // Get the signing time if the timestamp signature is valid.
1187 //
1188 if (ImageTimestampVerify (AuthData, AuthDataSize, RootCert, RootCertSize, &SigningTime)) {
1189 //
1190 // The signer signature is valid only when the signing time is earlier than revocation time.
1191 //
1192 if (IsValidSignatureByTimestamp (&SigningTime, RevocationTime)) {
1193 VerifyStatus = TRUE;
1194 goto Done;
1195 }
1196 }
1197 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1198 }
1199 }
1200 DbtDataSize -= CertList->SignatureListSize;
1201 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1202 }
1203
1204 Done:
1205 if (DbtData != NULL) {
1206 FreePool (DbtData);
1207 }
1208
1209 return VerifyStatus;
1210 }
1211
1212 /**
1213 Check whether the image signature is forbidden by the forbidden database (dbx).
1214 The image is forbidden to load if any certificates for signing are revoked before signing time.
1215
1216 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1217 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1218
1219 @retval TRUE Image is forbidden by dbx.
1220 @retval FALSE Image is not forbidden by dbx.
1221
1222 **/
1223 BOOLEAN
1224 IsForbiddenByDbx (
1225 IN UINT8 *AuthData,
1226 IN UINTN AuthDataSize
1227 )
1228 {
1229 EFI_STATUS Status;
1230 BOOLEAN IsForbidden;
1231 UINT8 *Data;
1232 UINTN DataSize;
1233 EFI_SIGNATURE_LIST *CertList;
1234 UINTN CertListSize;
1235 EFI_SIGNATURE_DATA *CertData;
1236 UINT8 *RootCert;
1237 UINTN RootCertSize;
1238 UINTN CertCount;
1239 UINTN Index;
1240 UINT8 *CertBuffer;
1241 UINTN BufferLength;
1242 UINT8 *TrustedCert;
1243 UINTN TrustedCertLength;
1244 UINT8 CertNumber;
1245 UINT8 *CertPtr;
1246 UINT8 *Cert;
1247 UINTN CertSize;
1248 EFI_TIME RevocationTime;
1249 //
1250 // Variable Initialization
1251 //
1252 IsForbidden = FALSE;
1253 Data = NULL;
1254 CertList = NULL;
1255 CertData = NULL;
1256 RootCert = NULL;
1257 RootCertSize = 0;
1258 Cert = NULL;
1259 CertBuffer = NULL;
1260 BufferLength = 0;
1261 TrustedCert = NULL;
1262 TrustedCertLength = 0;
1263
1264 //
1265 // The image will not be forbidden if dbx can't be got.
1266 //
1267 DataSize = 0;
1268 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
1269 if (Status != EFI_BUFFER_TOO_SMALL) {
1270 return IsForbidden;
1271 }
1272 Data = (UINT8 *) AllocateZeroPool (DataSize);
1273 if (Data == NULL) {
1274 return IsForbidden;
1275 }
1276
1277 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
1278 if (EFI_ERROR (Status)) {
1279 return IsForbidden;
1280 }
1281
1282 //
1283 // Verify image signature with RAW X509 certificates in DBX database.
1284 // If passed, the image will be forbidden.
1285 //
1286 CertList = (EFI_SIGNATURE_LIST *) Data;
1287 CertListSize = DataSize;
1288 while ((CertListSize > 0) && (CertListSize >= CertList->SignatureListSize)) {
1289 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1290 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1291 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1292
1293 for (Index = 0; Index < CertCount; Index++) {
1294 //
1295 // Iterate each Signature Data Node within this CertList for verify.
1296 //
1297 RootCert = CertData->SignatureData;
1298 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1299
1300 //
1301 // Call AuthenticodeVerify library to Verify Authenticode struct.
1302 //
1303 IsForbidden = AuthenticodeVerify (
1304 AuthData,
1305 AuthDataSize,
1306 RootCert,
1307 RootCertSize,
1308 mImageDigest,
1309 mImageDigestSize
1310 );
1311 if (IsForbidden) {
1312 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData);
1313 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1314 goto Done;
1315 }
1316
1317 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
1318 }
1319 }
1320
1321 CertListSize -= CertList->SignatureListSize;
1322 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1323 }
1324
1325 //
1326 // Check X.509 Certificate Hash & Possible Timestamp.
1327 //
1328
1329 //
1330 // Retrieve the certificate stack from AuthData
1331 // The output CertStack format will be:
1332 // UINT8 CertNumber;
1333 // UINT32 Cert1Length;
1334 // UINT8 Cert1[];
1335 // UINT32 Cert2Length;
1336 // UINT8 Cert2[];
1337 // ...
1338 // UINT32 CertnLength;
1339 // UINT8 Certn[];
1340 //
1341 Pkcs7GetSigners (AuthData, AuthDataSize, &CertBuffer, &BufferLength, &TrustedCert, &TrustedCertLength);
1342 if ((BufferLength == 0) || (CertBuffer == NULL)) {
1343 IsForbidden = TRUE;
1344 goto Done;
1345 }
1346
1347 //
1348 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1349 //
1350 CertNumber = (UINT8) (*CertBuffer);
1351 CertPtr = CertBuffer + 1;
1352 for (Index = 0; Index < CertNumber; Index++) {
1353 CertSize = (UINTN) ReadUnaligned32 ((UINT32 *)CertPtr);
1354 Cert = (UINT8 *)CertPtr + sizeof (UINT32);
1355 //
1356 // Advance CertPtr to the next cert in image signer's cert list
1357 //
1358 CertPtr = CertPtr + sizeof (UINT32) + CertSize;
1359
1360 if (IsCertHashFoundInDatabase (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime)) {
1361 //
1362 // Check the timestamp signature and signing time to determine if the image can be trusted.
1363 //
1364 IsForbidden = TRUE;
1365 if (PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime)) {
1366 IsForbidden = FALSE;
1367 //
1368 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1369 //
1370 continue;
1371 }
1372 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1373 goto Done;
1374 }
1375
1376 }
1377
1378 Done:
1379 if (Data != NULL) {
1380 FreePool (Data);
1381 }
1382
1383 Pkcs7FreeSigners (CertBuffer);
1384 Pkcs7FreeSigners (TrustedCert);
1385
1386 return IsForbidden;
1387 }
1388
1389
1390 /**
1391 Check whether the image signature can be verified by the trusted certificates in DB database.
1392
1393 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1394 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1395
1396 @retval TRUE Image passed verification using certificate in db.
1397 @retval FALSE Image didn't pass verification using certificate in db.
1398
1399 **/
1400 BOOLEAN
1401 IsAllowedByDb (
1402 IN UINT8 *AuthData,
1403 IN UINTN AuthDataSize
1404 )
1405 {
1406 EFI_STATUS Status;
1407 BOOLEAN VerifyStatus;
1408 EFI_SIGNATURE_LIST *CertList;
1409 EFI_SIGNATURE_DATA *CertData;
1410 UINTN DataSize;
1411 UINT8 *Data;
1412 UINT8 *RootCert;
1413 UINTN RootCertSize;
1414 UINTN Index;
1415 UINTN CertCount;
1416 UINTN DbxDataSize;
1417 UINT8 *DbxData;
1418 EFI_TIME RevocationTime;
1419
1420 Data = NULL;
1421 CertList = NULL;
1422 CertData = NULL;
1423 RootCert = NULL;
1424 DbxData = NULL;
1425 RootCertSize = 0;
1426 VerifyStatus = FALSE;
1427
1428 DataSize = 0;
1429 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
1430 if (Status == EFI_BUFFER_TOO_SMALL) {
1431 Data = (UINT8 *) AllocateZeroPool (DataSize);
1432 if (Data == NULL) {
1433 return VerifyStatus;
1434 }
1435
1436 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
1437 if (EFI_ERROR (Status)) {
1438 goto Done;
1439 }
1440
1441 //
1442 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1443 //
1444 CertList = (EFI_SIGNATURE_LIST *) Data;
1445 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
1446 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1447 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1448 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1449
1450 for (Index = 0; Index < CertCount; Index++) {
1451 //
1452 // Iterate each Signature Data Node within this CertList for verify.
1453 //
1454 RootCert = CertData->SignatureData;
1455 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1456
1457 //
1458 // Call AuthenticodeVerify library to Verify Authenticode struct.
1459 //
1460 VerifyStatus = AuthenticodeVerify (
1461 AuthData,
1462 AuthDataSize,
1463 RootCert,
1464 RootCertSize,
1465 mImageDigest,
1466 mImageDigestSize
1467 );
1468 if (VerifyStatus) {
1469 //
1470 // Here We still need to check if this RootCert's Hash is revoked
1471 //
1472 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL);
1473 if (Status == EFI_BUFFER_TOO_SMALL) {
1474 goto Done;
1475 }
1476 DbxData = (UINT8 *) AllocateZeroPool (DbxDataSize);
1477 if (DbxData == NULL) {
1478 goto Done;
1479 }
1480
1481 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *) DbxData);
1482 if (EFI_ERROR (Status)) {
1483 goto Done;
1484 }
1485
1486 if (IsCertHashFoundInDatabase (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime)) {
1487 //
1488 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1489 //
1490 VerifyStatus = PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime);
1491 if (!VerifyStatus) {
1492 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1493 }
1494 }
1495
1496 goto Done;
1497 }
1498
1499 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
1500 }
1501 }
1502
1503 DataSize -= CertList->SignatureListSize;
1504 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1505 }
1506 }
1507
1508 Done:
1509
1510 if (VerifyStatus) {
1511 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData);
1512 }
1513
1514 if (Data != NULL) {
1515 FreePool (Data);
1516 }
1517 if (DbxData != NULL) {
1518 FreePool (DbxData);
1519 }
1520
1521 return VerifyStatus;
1522 }
1523
1524 /**
1525 Provide verification service for signed images, which include both signature validation
1526 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1527 MSFT Authenticode type signatures are supported.
1528
1529 In this implementation, only verify external executables when in USER MODE.
1530 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1531
1532 The image verification policy is:
1533 If the image is signed,
1534 At least one valid signature or at least one hash value of the image must match a record
1535 in the security database "db", and no valid signature nor any hash value of the image may
1536 be reflected in the security database "dbx".
1537 Otherwise, the image is not signed,
1538 The SHA256 hash value of the image must match a record in the security database "db", and
1539 not be reflected in the security data base "dbx".
1540
1541 Caution: This function may receive untrusted input.
1542 PE/COFF image is external input, so this function will validate its data structure
1543 within this image buffer before use.
1544
1545 @param[in] AuthenticationStatus
1546 This is the authentication status returned from the security
1547 measurement services for the input file.
1548 @param[in] File This is a pointer to the device path of the file that is
1549 being dispatched. This will optionally be used for logging.
1550 @param[in] FileBuffer File buffer matches the input file device path.
1551 @param[in] FileSize Size of File buffer matches the input file device path.
1552 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1553
1554 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1555 FileBuffer did authenticate, and the platform policy dictates
1556 that the DXE Foundation may use the file.
1557 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1558 and non-NULL FileBuffer did authenticate, and the platform
1559 policy dictates that the DXE Foundation may execute the image in
1560 FileBuffer.
1561 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1562 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1563 the platform policy dictates that File should be placed
1564 in the untrusted state. The image has been added to the file
1565 execution table.
1566 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1567 authenticate, and the platform policy dictates that the DXE
1568 Foundation many not use File.
1569
1570 **/
1571 EFI_STATUS
1572 EFIAPI
1573 DxeImageVerificationHandler (
1574 IN UINT32 AuthenticationStatus,
1575 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
1576 IN VOID *FileBuffer,
1577 IN UINTN FileSize,
1578 IN BOOLEAN BootPolicy
1579 )
1580 {
1581 EFI_STATUS Status;
1582 UINT16 Magic;
1583 EFI_IMAGE_DOS_HEADER *DosHdr;
1584 EFI_STATUS VerifyStatus;
1585 EFI_SIGNATURE_LIST *SignatureList;
1586 UINTN SignatureListSize;
1587 EFI_SIGNATURE_DATA *Signature;
1588 EFI_IMAGE_EXECUTION_ACTION Action;
1589 WIN_CERTIFICATE *WinCertificate;
1590 UINT32 Policy;
1591 UINT8 *SecureBoot;
1592 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1593 UINT32 NumberOfRvaAndSizes;
1594 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
1595 WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid;
1596 UINT8 *AuthData;
1597 UINTN AuthDataSize;
1598 EFI_IMAGE_DATA_DIRECTORY *SecDataDir;
1599 UINT32 OffSet;
1600 CHAR16 *NameStr;
1601
1602 SignatureList = NULL;
1603 SignatureListSize = 0;
1604 WinCertificate = NULL;
1605 SecDataDir = NULL;
1606 PkcsCertData = NULL;
1607 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1608 Status = EFI_ACCESS_DENIED;
1609 VerifyStatus = EFI_ACCESS_DENIED;
1610
1611
1612 //
1613 // Check the image type and get policy setting.
1614 //
1615 switch (GetImageType (File)) {
1616
1617 case IMAGE_FROM_FV:
1618 Policy = ALWAYS_EXECUTE;
1619 break;
1620
1621 case IMAGE_FROM_OPTION_ROM:
1622 Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
1623 break;
1624
1625 case IMAGE_FROM_REMOVABLE_MEDIA:
1626 Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
1627 break;
1628
1629 case IMAGE_FROM_FIXED_MEDIA:
1630 Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
1631 break;
1632
1633 default:
1634 Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
1635 break;
1636 }
1637 //
1638 // If policy is always/never execute, return directly.
1639 //
1640 if (Policy == ALWAYS_EXECUTE) {
1641 return EFI_SUCCESS;
1642 } else if (Policy == NEVER_EXECUTE) {
1643 return EFI_ACCESS_DENIED;
1644 }
1645
1646 //
1647 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1648 // violates the UEFI spec and has been removed.
1649 //
1650 ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION);
1651 if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) {
1652 CpuDeadLoop ();
1653 }
1654
1655 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL);
1656 //
1657 // Skip verification if SecureBoot variable doesn't exist.
1658 //
1659 if (SecureBoot == NULL) {
1660 return EFI_SUCCESS;
1661 }
1662
1663 //
1664 // Skip verification if SecureBoot is disabled but not AuditMode
1665 //
1666 if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) {
1667 FreePool (SecureBoot);
1668 return EFI_SUCCESS;
1669 }
1670 FreePool (SecureBoot);
1671
1672 //
1673 // Read the Dos header.
1674 //
1675 if (FileBuffer == NULL) {
1676 return EFI_INVALID_PARAMETER;
1677 }
1678
1679 mImageBase = (UINT8 *) FileBuffer;
1680 mImageSize = FileSize;
1681
1682 ZeroMem (&ImageContext, sizeof (ImageContext));
1683 ImageContext.Handle = (VOID *) FileBuffer;
1684 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
1685
1686 //
1687 // Get information about the image being loaded
1688 //
1689 Status = PeCoffLoaderGetImageInfo (&ImageContext);
1690 if (EFI_ERROR (Status)) {
1691 //
1692 // The information can't be got from the invalid PeImage
1693 //
1694 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1695 goto Done;
1696 }
1697
1698 Status = EFI_ACCESS_DENIED;
1699
1700 DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
1701 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
1702 //
1703 // DOS image header is present,
1704 // so read the PE header after the DOS image header.
1705 //
1706 mPeCoffHeaderOffset = DosHdr->e_lfanew;
1707 } else {
1708 mPeCoffHeaderOffset = 0;
1709 }
1710 //
1711 // Check PE/COFF image.
1712 //
1713 mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
1714 if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1715 //
1716 // It is not a valid Pe/Coff file.
1717 //
1718 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1719 goto Done;
1720 }
1721
1722 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1723 //
1724 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1725 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1726 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1727 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1728 //
1729 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1730 } else {
1731 //
1732 // Get the magic value from the PE/COFF Optional Header
1733 //
1734 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
1735 }
1736
1737 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1738 //
1739 // Use PE32 offset.
1740 //
1741 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
1742 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1743 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1744 }
1745 } else {
1746 //
1747 // Use PE32+ offset.
1748 //
1749 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
1750 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1751 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1752 }
1753 }
1754
1755 //
1756 // Start Image Validation.
1757 //
1758 if (SecDataDir == NULL || SecDataDir->Size == 0) {
1759 //
1760 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1761 // and not be reflected in the security data base "dbx".
1762 //
1763 if (!HashPeImage (HASHALG_SHA256)) {
1764 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr));
1765 goto Done;
1766 }
1767
1768 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1769 //
1770 // Image Hash is in forbidden database (DBX).
1771 //
1772 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr));
1773 goto Done;
1774 }
1775
1776 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1777 //
1778 // Image Hash is in allowed database (DB).
1779 //
1780 return EFI_SUCCESS;
1781 }
1782
1783 //
1784 // Image Hash is not found in both forbidden and allowed database.
1785 //
1786 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr));
1787 goto Done;
1788 }
1789
1790 //
1791 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1792 // "Attribute Certificate Table".
1793 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1794 //
1795 for (OffSet = SecDataDir->VirtualAddress;
1796 OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size);
1797 OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) {
1798 WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet);
1799 if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) ||
1800 (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) {
1801 break;
1802 }
1803
1804 //
1805 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1806 //
1807 if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1808 //
1809 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1810 // Authenticode specification.
1811 //
1812 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate;
1813 if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) {
1814 break;
1815 }
1816 AuthData = PkcsCertData->CertData;
1817 AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr);
1818 } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
1819 //
1820 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1821 //
1822 WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate;
1823 if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) {
1824 break;
1825 }
1826 if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) {
1827 continue;
1828 }
1829 AuthData = WinCertUefiGuid->CertData;
1830 AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData);
1831 } else {
1832 if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) {
1833 break;
1834 }
1835 continue;
1836 }
1837
1838 Status = HashPeImageByType (AuthData, AuthDataSize);
1839 if (EFI_ERROR (Status)) {
1840 continue;
1841 }
1842
1843 //
1844 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1845 //
1846 if (IsForbiddenByDbx (AuthData, AuthDataSize)) {
1847 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
1848 VerifyStatus = EFI_ACCESS_DENIED;
1849 break;
1850 }
1851
1852 //
1853 // Check the digital signature against the valid certificate in allowed database (db).
1854 //
1855 if (EFI_ERROR (VerifyStatus)) {
1856 if (IsAllowedByDb (AuthData, AuthDataSize)) {
1857 VerifyStatus = EFI_SUCCESS;
1858 }
1859 }
1860
1861 //
1862 // Check the image's hash value.
1863 //
1864 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1865 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
1866 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr));
1867 VerifyStatus = EFI_ACCESS_DENIED;
1868 break;
1869 } else if (EFI_ERROR (VerifyStatus)) {
1870 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1871 VerifyStatus = EFI_SUCCESS;
1872 } else {
1873 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));
1874 }
1875 }
1876 }
1877
1878 if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) {
1879 //
1880 // The Size in Certificate Table or the attribute certicate table is corrupted.
1881 //
1882 VerifyStatus = EFI_ACCESS_DENIED;
1883 }
1884
1885 if (!EFI_ERROR (VerifyStatus)) {
1886 return EFI_SUCCESS;
1887 } else {
1888 Status = EFI_ACCESS_DENIED;
1889 if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) {
1890 //
1891 // Get image hash value as executable's signature.
1892 //
1893 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
1894 SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
1895 if (SignatureList == NULL) {
1896 Status = EFI_OUT_OF_RESOURCES;
1897 goto Done;
1898 }
1899 SignatureList->SignatureHeaderSize = 0;
1900 SignatureList->SignatureListSize = (UINT32) SignatureListSize;
1901 SignatureList->SignatureSize = (UINT32) (sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize);
1902 CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
1903 Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
1904 CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
1905 }
1906 }
1907
1908 Done:
1909 if (Status != EFI_SUCCESS) {
1910 //
1911 // Policy decides to defer or reject the image; add its information in image executable information table.
1912 //
1913 NameStr = ConvertDevicePathToText (File, FALSE, TRUE);
1914 AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize);
1915 if (NameStr != NULL) {
1916 DEBUG((EFI_D_INFO, "The image doesn't pass verification: %s\n", NameStr));
1917 FreePool(NameStr);
1918 }
1919 Status = EFI_SECURITY_VIOLATION;
1920 }
1921
1922 if (SignatureList != NULL) {
1923 FreePool (SignatureList);
1924 }
1925
1926 return Status;
1927 }
1928
1929 /**
1930 On Ready To Boot Services Event notification handler.
1931
1932 Add the image execution information table if it is not in system configuration table.
1933
1934 @param[in] Event Event whose notification function is being invoked
1935 @param[in] Context Pointer to the notification function's context
1936
1937 **/
1938 VOID
1939 EFIAPI
1940 OnReadyToBoot (
1941 IN EFI_EVENT Event,
1942 IN VOID *Context
1943 )
1944 {
1945 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
1946 UINTN ImageExeInfoTableSize;
1947
1948 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
1949 if (ImageExeInfoTable != NULL) {
1950 return;
1951 }
1952
1953 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
1954 ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize);
1955 if (ImageExeInfoTable == NULL) {
1956 return ;
1957 }
1958
1959 ImageExeInfoTable->NumberOfImages = 0;
1960 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) ImageExeInfoTable);
1961
1962 }
1963
1964 /**
1965 Register security measurement handler.
1966
1967 @param ImageHandle ImageHandle of the loaded driver.
1968 @param SystemTable Pointer to the EFI System Table.
1969
1970 @retval EFI_SUCCESS The handlers were registered successfully.
1971 **/
1972 EFI_STATUS
1973 EFIAPI
1974 DxeImageVerificationLibConstructor (
1975 IN EFI_HANDLE ImageHandle,
1976 IN EFI_SYSTEM_TABLE *SystemTable
1977 )
1978 {
1979 EFI_EVENT Event;
1980
1981 //
1982 // Register the event to publish the image execution table.
1983 //
1984 EfiCreateEventReadyToBootEx (
1985 TPL_CALLBACK,
1986 OnReadyToBoot,
1987 NULL,
1988 &Event
1989 );
1990
1991 return RegisterSecurity2Handler (
1992 DxeImageVerificationHandler,
1993 EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
1994 );
1995 }