]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
2210c95f5aaec0a8cefae1f94efbf7ca941150af
[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 - 2013, 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, NULL, NULL, NULL, NULL },
71 { L"SHA512", 64, &mHashOidValue[32], 9, NULL, NULL, NULL, NULL }
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_SHA1) && (HashAlg != HASHALG_SHA256)) {
310 return FALSE;
311 }
312
313 //
314 // Initialize context of hash.
315 //
316 ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
317
318 if (HashAlg == HASHALG_SHA1) {
319 mImageDigestSize = SHA1_DIGEST_SIZE;
320 mCertType = gEfiCertSha1Guid;
321 } else if (HashAlg == HASHALG_SHA256) {
322 mImageDigestSize = SHA256_DIGEST_SIZE;
323 mCertType = gEfiCertSha256Guid;
324 } else {
325 return FALSE;
326 }
327
328 CtxSize = mHash[HashAlg].GetContextSize();
329
330 HashCtx = AllocatePool (CtxSize);
331 if (HashCtx == NULL) {
332 return FALSE;
333 }
334
335 // 1. Load the image header into memory.
336
337 // 2. Initialize a SHA hash context.
338 Status = mHash[HashAlg].HashInit(HashCtx);
339
340 if (!Status) {
341 goto Done;
342 }
343
344 //
345 // Measuring PE/COFF Image Header;
346 // But CheckSum field and SECURITY data directory (certificate) are excluded
347 //
348 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
349 //
350 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
351 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
352 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
353 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
354 //
355 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
356 } else {
357 //
358 // Get the magic value from the PE/COFF Optional Header
359 //
360 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
361 }
362
363 //
364 // 3. Calculate the distance from the base of the image header to the image checksum address.
365 // 4. Hash the image header from its base to beginning of the image checksum.
366 //
367 HashBase = mImageBase;
368 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
369 //
370 // Use PE32 offset.
371 //
372 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
373 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
374 } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
375 //
376 // Use PE32+ offset.
377 //
378 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
379 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
380 } else {
381 //
382 // Invalid header magic number.
383 //
384 Status = FALSE;
385 goto Done;
386 }
387
388 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
389 if (!Status) {
390 goto Done;
391 }
392
393 //
394 // 5. Skip over the image checksum (it occupies a single ULONG).
395 //
396 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
397 //
398 // 6. Since there is no Cert Directory in optional header, hash everything
399 // from the end of the checksum to the end of image header.
400 //
401 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
402 //
403 // Use PE32 offset.
404 //
405 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
406 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
407 } else {
408 //
409 // Use PE32+ offset.
410 //
411 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
412 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
413 }
414
415 if (HashSize != 0) {
416 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
417 if (!Status) {
418 goto Done;
419 }
420 }
421 } else {
422 //
423 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
424 //
425 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
426 //
427 // Use PE32 offset.
428 //
429 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
430 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
431 } else {
432 //
433 // Use PE32+ offset.
434 //
435 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
436 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
437 }
438
439 if (HashSize != 0) {
440 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
441 if (!Status) {
442 goto Done;
443 }
444 }
445
446 //
447 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
448 // 9. Hash everything from the end of the Cert Directory to the end of image header.
449 //
450 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
451 //
452 // Use PE32 offset
453 //
454 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
455 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
456 } else {
457 //
458 // Use PE32+ offset.
459 //
460 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
461 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
462 }
463
464 if (HashSize != 0) {
465 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
466 if (!Status) {
467 goto Done;
468 }
469 }
470 }
471
472 //
473 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
474 //
475 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
476 //
477 // Use PE32 offset.
478 //
479 SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
480 } else {
481 //
482 // Use PE32+ offset
483 //
484 SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
485 }
486
487
488 Section = (EFI_IMAGE_SECTION_HEADER *) (
489 mImageBase +
490 mPeCoffHeaderOffset +
491 sizeof (UINT32) +
492 sizeof (EFI_IMAGE_FILE_HEADER) +
493 mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
494 );
495
496 //
497 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
498 // structures in the image. The 'NumberOfSections' field of the image
499 // header indicates how big the table should be. Do not include any
500 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
501 //
502 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
503 if (SectionHeader == NULL) {
504 Status = FALSE;
505 goto Done;
506 }
507 //
508 // 12. Using the 'PointerToRawData' in the referenced section headers as
509 // a key, arrange the elements in the table in ascending order. In other
510 // words, sort the section headers according to the disk-file offset of
511 // the section.
512 //
513 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
514 Pos = Index;
515 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
516 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
517 Pos--;
518 }
519 CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
520 Section += 1;
521 }
522
523 //
524 // 13. Walk through the sorted table, bring the corresponding section
525 // into memory, and hash the entire section (using the 'SizeOfRawData'
526 // field in the section header to determine the amount of data to hash).
527 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
528 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
529 //
530 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
531 Section = &SectionHeader[Index];
532 if (Section->SizeOfRawData == 0) {
533 continue;
534 }
535 HashBase = mImageBase + Section->PointerToRawData;
536 HashSize = (UINTN) Section->SizeOfRawData;
537
538 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
539 if (!Status) {
540 goto Done;
541 }
542
543 SumOfBytesHashed += HashSize;
544 }
545
546 //
547 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
548 // data in the file that needs to be added to the hash. This data begins
549 // at file offset SUM_OF_BYTES_HASHED and its length is:
550 // FileSize - (CertDirectory->Size)
551 //
552 if (mImageSize > SumOfBytesHashed) {
553 HashBase = mImageBase + SumOfBytesHashed;
554
555 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
556 CertSize = 0;
557 } else {
558 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
559 //
560 // Use PE32 offset.
561 //
562 CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
563 } else {
564 //
565 // Use PE32+ offset.
566 //
567 CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
568 }
569 }
570
571 if (mImageSize > CertSize + SumOfBytesHashed) {
572 HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed);
573
574 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
575 if (!Status) {
576 goto Done;
577 }
578 } else if (mImageSize < CertSize + SumOfBytesHashed) {
579 Status = FALSE;
580 goto Done;
581 }
582 }
583
584 Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
585
586 Done:
587 if (HashCtx != NULL) {
588 FreePool (HashCtx);
589 }
590 if (SectionHeader != NULL) {
591 FreePool (SectionHeader);
592 }
593 return Status;
594 }
595
596 /**
597 Recognize the Hash algorithm in PE/COFF Authenticode and caculate hash of
598 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
599 8.0 Appendix A
600
601 Caution: This function may receive untrusted input.
602 PE/COFF image is external input, so this function will validate its data structure
603 within this image buffer before use.
604
605 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
606 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
607
608 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
609 @retval EFI_SUCCESS Hash successfully.
610
611 **/
612 EFI_STATUS
613 HashPeImageByType (
614 IN UINT8 *AuthData,
615 IN UINTN AuthDataSize
616 )
617 {
618 UINT8 Index;
619
620 for (Index = 0; Index < HASHALG_MAX; Index++) {
621 //
622 // Check the Hash algorithm in PE/COFF Authenticode.
623 // According to PKCS#7 Definition:
624 // SignedData ::= SEQUENCE {
625 // version Version,
626 // digestAlgorithms DigestAlgorithmIdentifiers,
627 // contentInfo ContentInfo,
628 // .... }
629 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
630 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
631 // Fixed offset (+32) is calculated based on two bytes of length encoding.
632 //
633 if ((*(AuthData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
634 //
635 // Only support two bytes of Long Form of Length Encoding.
636 //
637 continue;
638 }
639
640 if (AuthDataSize < 32 + mHash[Index].OidLength) {
641 return EFI_UNSUPPORTED;
642 }
643
644 if (CompareMem (AuthData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
645 break;
646 }
647 }
648
649 if (Index == HASHALG_MAX) {
650 return EFI_UNSUPPORTED;
651 }
652
653 //
654 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
655 //
656 if (!HashPeImage(Index)) {
657 return EFI_UNSUPPORTED;
658 }
659
660 return EFI_SUCCESS;
661 }
662
663
664 /**
665 Returns the size of a given image execution info table in bytes.
666
667 This function returns the size, in bytes, of the image execution info table specified by
668 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
669
670 @param ImageExeInfoTable A pointer to a image execution info table structure.
671
672 @retval 0 If ImageExeInfoTable is NULL.
673 @retval Others The size of a image execution info table in bytes.
674
675 **/
676 UINTN
677 GetImageExeInfoTableSize (
678 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable
679 )
680 {
681 UINTN Index;
682 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem;
683 UINTN TotalSize;
684
685 if (ImageExeInfoTable == NULL) {
686 return 0;
687 }
688
689 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE));
690 TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
691 for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) {
692 TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize);
693 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize));
694 }
695
696 return TotalSize;
697 }
698
699 /**
700 Create an Image Execution Information Table entry and add it to system configuration table.
701
702 @param[in] Action Describes the action taken by the firmware regarding this image.
703 @param[in] Name Input a null-terminated, user-friendly name.
704 @param[in] DevicePath Input device path pointer.
705 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
706 @param[in] SignatureSize Size of signature.
707
708 **/
709 VOID
710 AddImageExeInfo (
711 IN EFI_IMAGE_EXECUTION_ACTION Action,
712 IN CHAR16 *Name OPTIONAL,
713 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
714 IN EFI_SIGNATURE_LIST *Signature OPTIONAL,
715 IN UINTN SignatureSize
716 )
717 {
718 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
719 EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable;
720 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry;
721 UINTN ImageExeInfoTableSize;
722 UINTN NewImageExeInfoEntrySize;
723 UINTN NameStringLen;
724 UINTN DevicePathSize;
725
726 ImageExeInfoTable = NULL;
727 NewImageExeInfoTable = NULL;
728 ImageExeInfoEntry = NULL;
729 NameStringLen = 0;
730
731 if (DevicePath == NULL) {
732 return ;
733 }
734
735 if (Name != NULL) {
736 NameStringLen = StrSize (Name);
737 } else {
738 NameStringLen = sizeof (CHAR16);
739 }
740
741 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
742 if (ImageExeInfoTable != NULL) {
743 //
744 // The table has been found!
745 // We must enlarge the table to accomodate the new exe info entry.
746 //
747 ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable);
748 } else {
749 //
750 // Not Found!
751 // We should create a new table to append to the configuration table.
752 //
753 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
754 }
755
756 DevicePathSize = GetDevicePathSize (DevicePath);
757 NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize;
758 NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize);
759 if (NewImageExeInfoTable == NULL) {
760 return ;
761 }
762
763 if (ImageExeInfoTable != NULL) {
764 CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize);
765 } else {
766 NewImageExeInfoTable->NumberOfImages = 0;
767 }
768 NewImageExeInfoTable->NumberOfImages++;
769 ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize);
770 //
771 // Update new item's infomation.
772 //
773 WriteUnaligned32 ((UINT32 *) &ImageExeInfoEntry->Action, Action);
774 WriteUnaligned32 ((UINT32 *) &ImageExeInfoEntry->InfoSize, (UINT32) NewImageExeInfoEntrySize);
775
776 if (Name != NULL) {
777 CopyMem ((UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32), Name, NameStringLen);
778 } else {
779 ZeroMem ((UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32), sizeof (CHAR16));
780 }
781 CopyMem (
782 (UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32) + NameStringLen,
783 DevicePath,
784 DevicePathSize
785 );
786 if (Signature != NULL) {
787 CopyMem (
788 (UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32) + NameStringLen + DevicePathSize,
789 Signature,
790 SignatureSize
791 );
792 }
793 //
794 // Update/replace the image execution table.
795 //
796 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable);
797
798 //
799 // Free Old table data!
800 //
801 if (ImageExeInfoTable != NULL) {
802 FreePool (ImageExeInfoTable);
803 }
804 }
805
806 /**
807 Check whether signature is in specified database.
808
809 @param[in] VariableName Name of database variable that is searched in.
810 @param[in] Signature Pointer to signature that is searched for.
811 @param[in] CertType Pointer to hash algrithom.
812 @param[in] SignatureSize Size of Signature.
813
814 @return TRUE Found the signature in the variable database.
815 @return FALSE Not found the signature in the variable database.
816
817 **/
818 BOOLEAN
819 IsSignatureFoundInDatabase (
820 IN CHAR16 *VariableName,
821 IN UINT8 *Signature,
822 IN EFI_GUID *CertType,
823 IN UINTN SignatureSize
824 )
825 {
826 EFI_STATUS Status;
827 EFI_SIGNATURE_LIST *CertList;
828 EFI_SIGNATURE_DATA *Cert;
829 UINTN DataSize;
830 UINT8 *Data;
831 UINTN Index;
832 UINTN CertCount;
833 BOOLEAN IsFound;
834 //
835 // Read signature database variable.
836 //
837 IsFound = FALSE;
838 Data = NULL;
839 DataSize = 0;
840 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
841 if (Status != EFI_BUFFER_TOO_SMALL) {
842 return FALSE;
843 }
844
845 Data = (UINT8 *) AllocateZeroPool (DataSize);
846 if (Data == NULL) {
847 return FALSE;
848 }
849
850 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data);
851 if (EFI_ERROR (Status)) {
852 goto Done;
853 }
854 //
855 // Enumerate all signature data in SigDB to check if executable's signature exists.
856 //
857 CertList = (EFI_SIGNATURE_LIST *) Data;
858 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
859 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
860 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
861 if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) {
862 for (Index = 0; Index < CertCount; Index++) {
863 if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) {
864 //
865 // Find the signature in database.
866 //
867 IsFound = TRUE;
868 SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert);
869 break;
870 }
871
872 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
873 }
874
875 if (IsFound) {
876 break;
877 }
878 }
879
880 DataSize -= CertList->SignatureListSize;
881 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
882 }
883
884 Done:
885 if (Data != NULL) {
886 FreePool (Data);
887 }
888
889 return IsFound;
890 }
891
892 /**
893 Verify PKCS#7 SignedData using certificate found in Variable which formatted
894 as EFI_SIGNATURE_LIST. The Variable may be PK, KEK, DB or DBX.
895
896 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
897 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
898 @param[in] VariableName Name of Variable to search for Certificate.
899 @param[in] VendorGuid Variable vendor GUID.
900
901 @retval TRUE Image pass verification.
902 @retval FALSE Image fail verification.
903
904 **/
905 BOOLEAN
906 IsPkcsSignedDataVerifiedBySignatureList (
907 IN UINT8 *AuthData,
908 IN UINTN AuthDataSize,
909 IN CHAR16 *VariableName,
910 IN EFI_GUID *VendorGuid
911 )
912 {
913 EFI_STATUS Status;
914 BOOLEAN VerifyStatus;
915 EFI_SIGNATURE_LIST *CertList;
916 EFI_SIGNATURE_DATA *Cert;
917 UINTN DataSize;
918 UINT8 *Data;
919 UINT8 *RootCert;
920 UINTN RootCertSize;
921 UINTN Index;
922 UINTN CertCount;
923
924 Data = NULL;
925 CertList = NULL;
926 Cert = NULL;
927 RootCert = NULL;
928 RootCertSize = 0;
929 VerifyStatus = FALSE;
930
931 DataSize = 0;
932 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, NULL);
933 if (Status == EFI_BUFFER_TOO_SMALL) {
934 Data = (UINT8 *) AllocateZeroPool (DataSize);
935 if (Data == NULL) {
936 return VerifyStatus;
937 }
938
939 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, (VOID *) Data);
940 if (EFI_ERROR (Status)) {
941 goto Done;
942 }
943
944 //
945 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
946 //
947 CertList = (EFI_SIGNATURE_LIST *) Data;
948 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
949 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
950 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
951 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
952 for (Index = 0; Index < CertCount; Index++) {
953 //
954 // Iterate each Signature Data Node within this CertList for verify.
955 //
956 RootCert = Cert->SignatureData;
957 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
958
959 //
960 // Call AuthenticodeVerify library to Verify Authenticode struct.
961 //
962 VerifyStatus = AuthenticodeVerify (
963 AuthData,
964 AuthDataSize,
965 RootCert,
966 RootCertSize,
967 mImageDigest,
968 mImageDigestSize
969 );
970 if (VerifyStatus) {
971 SecureBootHook (VariableName, VendorGuid, CertList->SignatureSize, Cert);
972 goto Done;
973 }
974 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
975 }
976 }
977 DataSize -= CertList->SignatureListSize;
978 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
979 }
980 }
981
982 Done:
983 if (Data != NULL) {
984 FreePool (Data);
985 }
986
987 return VerifyStatus;
988 }
989
990 /**
991 Provide verification service for signed images, which include both signature validation
992 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
993 MSFT Authenticode type signatures are supported.
994
995 In this implementation, only verify external executables when in USER MODE.
996 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
997
998 The image verification policy is:
999 If the image is signed,
1000 At least one valid signature or at least one hash value of the image must match a record
1001 in the security database "db", and no valid signature nor any hash value of the image may
1002 be reflected in the security database "dbx".
1003 Otherwise, the image is not signed,
1004 The SHA256 hash value of the image must match a record in the security database "db", and
1005 not be reflected in the security data base "dbx".
1006
1007 Caution: This function may receive untrusted input.
1008 PE/COFF image is external input, so this function will validate its data structure
1009 within this image buffer before use.
1010
1011 @param[in] AuthenticationStatus
1012 This is the authentication status returned from the security
1013 measurement services for the input file.
1014 @param[in] File This is a pointer to the device path of the file that is
1015 being dispatched. This will optionally be used for logging.
1016 @param[in] FileBuffer File buffer matches the input file device path.
1017 @param[in] FileSize Size of File buffer matches the input file device path.
1018 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1019
1020 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1021 FileBuffer did authenticate, and the platform policy dictates
1022 that the DXE Foundation may use the file.
1023 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1024 and non-NULL FileBuffer did authenticate, and the platform
1025 policy dictates that the DXE Foundation may execute the image in
1026 FileBuffer.
1027 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1028 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1029 the platform policy dictates that File should be placed
1030 in the untrusted state. The image has been added to the file
1031 execution table.
1032 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1033 authenticate, and the platform policy dictates that the DXE
1034 Foundation many not use File.
1035
1036 **/
1037 EFI_STATUS
1038 EFIAPI
1039 DxeImageVerificationHandler (
1040 IN UINT32 AuthenticationStatus,
1041 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
1042 IN VOID *FileBuffer,
1043 IN UINTN FileSize,
1044 IN BOOLEAN BootPolicy
1045 )
1046 {
1047 EFI_STATUS Status;
1048 UINT16 Magic;
1049 EFI_IMAGE_DOS_HEADER *DosHdr;
1050 EFI_STATUS VerifyStatus;
1051 EFI_SIGNATURE_LIST *SignatureList;
1052 UINTN SignatureListSize;
1053 EFI_SIGNATURE_DATA *Signature;
1054 EFI_IMAGE_EXECUTION_ACTION Action;
1055 WIN_CERTIFICATE *WinCertificate;
1056 UINT32 Policy;
1057 UINT8 *SecureBoot;
1058 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1059 UINT32 NumberOfRvaAndSizes;
1060 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
1061 WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid;
1062 UINT8 *AuthData;
1063 UINTN AuthDataSize;
1064 EFI_IMAGE_DATA_DIRECTORY *SecDataDir;
1065 UINT32 OffSet;
1066
1067 SignatureList = NULL;
1068 SignatureListSize = 0;
1069 WinCertificate = NULL;
1070 SecDataDir = NULL;
1071 PkcsCertData = NULL;
1072 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1073 Status = EFI_ACCESS_DENIED;
1074 VerifyStatus = EFI_ACCESS_DENIED;
1075
1076 //
1077 // Check the image type and get policy setting.
1078 //
1079 switch (GetImageType (File)) {
1080
1081 case IMAGE_FROM_FV:
1082 Policy = ALWAYS_EXECUTE;
1083 break;
1084
1085 case IMAGE_FROM_OPTION_ROM:
1086 Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
1087 break;
1088
1089 case IMAGE_FROM_REMOVABLE_MEDIA:
1090 Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
1091 break;
1092
1093 case IMAGE_FROM_FIXED_MEDIA:
1094 Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
1095 break;
1096
1097 default:
1098 Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
1099 break;
1100 }
1101 //
1102 // If policy is always/never execute, return directly.
1103 //
1104 if (Policy == ALWAYS_EXECUTE) {
1105 return EFI_SUCCESS;
1106 } else if (Policy == NEVER_EXECUTE) {
1107 return EFI_ACCESS_DENIED;
1108 }
1109
1110 //
1111 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1112 // violates the UEFI spec and has been removed.
1113 //
1114 ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION);
1115 if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) {
1116 CpuDeadLoop ();
1117 }
1118
1119 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL);
1120 //
1121 // Skip verification if SecureBoot variable doesn't exist.
1122 //
1123 if (SecureBoot == NULL) {
1124 return EFI_SUCCESS;
1125 }
1126
1127 //
1128 // Skip verification if SecureBoot is disabled.
1129 //
1130 if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) {
1131 FreePool (SecureBoot);
1132 return EFI_SUCCESS;
1133 }
1134 FreePool (SecureBoot);
1135
1136 //
1137 // Read the Dos header.
1138 //
1139 if (FileBuffer == NULL) {
1140 return EFI_INVALID_PARAMETER;
1141 }
1142
1143 mImageBase = (UINT8 *) FileBuffer;
1144 mImageSize = FileSize;
1145
1146 ZeroMem (&ImageContext, sizeof (ImageContext));
1147 ImageContext.Handle = (VOID *) FileBuffer;
1148 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
1149
1150 //
1151 // Get information about the image being loaded
1152 //
1153 Status = PeCoffLoaderGetImageInfo (&ImageContext);
1154 if (EFI_ERROR (Status)) {
1155 //
1156 // The information can't be got from the invalid PeImage
1157 //
1158 goto Done;
1159 }
1160
1161 Status = EFI_ACCESS_DENIED;
1162
1163 DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
1164 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
1165 //
1166 // DOS image header is present,
1167 // so read the PE header after the DOS image header.
1168 //
1169 mPeCoffHeaderOffset = DosHdr->e_lfanew;
1170 } else {
1171 mPeCoffHeaderOffset = 0;
1172 }
1173 //
1174 // Check PE/COFF image.
1175 //
1176 mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
1177 if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1178 //
1179 // It is not a valid Pe/Coff file.
1180 //
1181 goto Done;
1182 }
1183
1184 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1185 //
1186 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1187 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1188 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1189 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1190 //
1191 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1192 } else {
1193 //
1194 // Get the magic value from the PE/COFF Optional Header
1195 //
1196 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
1197 }
1198
1199 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1200 //
1201 // Use PE32 offset.
1202 //
1203 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
1204 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1205 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1206 }
1207 } else {
1208 //
1209 // Use PE32+ offset.
1210 //
1211 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
1212 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1213 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1214 }
1215 }
1216
1217 //
1218 // Start Image Validation.
1219 //
1220 if (SecDataDir == NULL || SecDataDir->Size == 0) {
1221 //
1222 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1223 // and not be reflected in the security data base "dbx".
1224 //
1225 if (!HashPeImage (HASHALG_SHA256)) {
1226 goto Done;
1227 }
1228
1229 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1230 //
1231 // Image Hash is in forbidden database (DBX).
1232 //
1233 goto Done;
1234 }
1235
1236 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1237 //
1238 // Image Hash is in allowed database (DB).
1239 //
1240 return EFI_SUCCESS;
1241 }
1242
1243 //
1244 // Image Hash is not found in both forbidden and allowed database.
1245 //
1246 goto Done;
1247 }
1248
1249 //
1250 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1251 // "Attribute Certificate Table".
1252 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1253 //
1254 for (OffSet = SecDataDir->VirtualAddress;
1255 OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size);
1256 OffSet += WinCertificate->dwLength, OffSet += ALIGN_SIZE (OffSet)) {
1257 WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet);
1258 if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) ||
1259 (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) {
1260 break;
1261 }
1262
1263 //
1264 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1265 //
1266 if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1267 //
1268 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1269 // Authenticode specification.
1270 //
1271 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate;
1272 if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) {
1273 break;
1274 }
1275 AuthData = PkcsCertData->CertData;
1276 AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr);
1277 } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
1278 //
1279 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1280 //
1281 WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate;
1282 if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) {
1283 break;
1284 }
1285 if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) {
1286 continue;
1287 }
1288 AuthData = WinCertUefiGuid->CertData;
1289 AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData);
1290 } else {
1291 if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) {
1292 break;
1293 }
1294 continue;
1295 }
1296
1297 Status = HashPeImageByType (AuthData, AuthDataSize);
1298 if (EFI_ERROR (Status)) {
1299 continue;
1300 }
1301
1302 //
1303 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1304 //
1305 if (IsPkcsSignedDataVerifiedBySignatureList (AuthData, AuthDataSize, EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid)) {
1306 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
1307 VerifyStatus = EFI_ACCESS_DENIED;
1308 break;
1309 }
1310
1311 //
1312 // Check the digital signature against the valid certificate in allowed database (db).
1313 //
1314 if (EFI_ERROR (VerifyStatus)) {
1315 if (IsPkcsSignedDataVerifiedBySignatureList (AuthData, AuthDataSize, EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid)) {
1316 VerifyStatus = EFI_SUCCESS;
1317 }
1318 }
1319
1320 //
1321 // Check the image's hash value.
1322 //
1323 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1324 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
1325 VerifyStatus = EFI_ACCESS_DENIED;
1326 break;
1327 } else if (EFI_ERROR (VerifyStatus)) {
1328 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1329 VerifyStatus = EFI_SUCCESS;
1330 }
1331 }
1332 }
1333
1334 if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) {
1335 //
1336 // The Size in Certificate Table or the attribute certicate table is corrupted.
1337 //
1338 VerifyStatus = EFI_ACCESS_DENIED;
1339 }
1340
1341 if (!EFI_ERROR (VerifyStatus)) {
1342 return EFI_SUCCESS;
1343 } else {
1344 Status = EFI_ACCESS_DENIED;
1345 if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) {
1346 //
1347 // Get image hash value as executable's signature.
1348 //
1349 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
1350 SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
1351 if (SignatureList == NULL) {
1352 Status = EFI_OUT_OF_RESOURCES;
1353 goto Done;
1354 }
1355 SignatureList->SignatureHeaderSize = 0;
1356 SignatureList->SignatureListSize = (UINT32) SignatureListSize;
1357 SignatureList->SignatureSize = (UINT32) mImageDigestSize;
1358 CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
1359 Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
1360 CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
1361 }
1362 }
1363
1364 Done:
1365 if (Status != EFI_SUCCESS) {
1366 //
1367 // Policy decides to defer or reject the image; add its information in image executable information table.
1368 //
1369 AddImageExeInfo (Action, NULL, File, SignatureList, SignatureListSize);
1370 Status = EFI_SECURITY_VIOLATION;
1371 }
1372
1373 if (SignatureList != NULL) {
1374 FreePool (SignatureList);
1375 }
1376
1377 return Status;
1378 }
1379
1380 /**
1381 Register security measurement handler.
1382
1383 @param ImageHandle ImageHandle of the loaded driver.
1384 @param SystemTable Pointer to the EFI System Table.
1385
1386 @retval EFI_SUCCESS The handlers were registered successfully.
1387 **/
1388 EFI_STATUS
1389 EFIAPI
1390 DxeImageVerificationLibConstructor (
1391 IN EFI_HANDLE ImageHandle,
1392 IN EFI_SYSTEM_TABLE *SystemTable
1393 )
1394 {
1395 return RegisterSecurity2Handler (
1396 DxeImageVerificationHandler,
1397 EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
1398 );
1399 }