Add PI1.2.1 SAP2 support and UEFI231B mantis 896
[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 - 2012, 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_IMAGE_DATA_DIRECTORY *mSecDataDir = NULL;
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 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, // OBJ_md5
61 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
64 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
65 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
66 };
67
68 HASH_TABLE mHash[] = {
69 { L"SHA1", 20, &mHashOidValue[8], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final },
70 { L"SHA224", 28, &mHashOidValue[13], 9, NULL, NULL, NULL, NULL },
71 { L"SHA256", 32, &mHashOidValue[22], 9, Sha256GetContextSize,Sha256Init, Sha256Update, Sha256Final},
72 { L"SHA384", 48, &mHashOidValue[31], 9, NULL, NULL, NULL, NULL },
73 { L"SHA512", 64, &mHashOidValue[40], 9, NULL, NULL, NULL, NULL }
74 };
75
76 /**
77 Reads contents of a PE/COFF image in memory buffer.
78
79 Caution: This function may receive untrusted input.
80 PE/COFF image is external input, so this function will make sure the PE/COFF image content
81 read is within the image buffer.
82
83 @param FileHandle Pointer to the file handle to read the PE/COFF image.
84 @param FileOffset Offset into the PE/COFF image to begin the read operation.
85 @param ReadSize On input, the size in bytes of the requested read operation.
86 On output, the number of bytes actually read.
87 @param Buffer Output buffer that contains the data read from the PE/COFF image.
88
89 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
90 **/
91 EFI_STATUS
92 EFIAPI
93 DxeImageVerificationLibImageRead (
94 IN VOID *FileHandle,
95 IN UINTN FileOffset,
96 IN OUT UINTN *ReadSize,
97 OUT VOID *Buffer
98 )
99 {
100 UINTN EndPosition;
101
102 if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {
103 return EFI_INVALID_PARAMETER;
104 }
105
106 if (MAX_ADDRESS - FileOffset < *ReadSize) {
107 return EFI_INVALID_PARAMETER;
108 }
109
110 EndPosition = FileOffset + *ReadSize;
111 if (EndPosition > mImageSize) {
112 *ReadSize = (UINT32)(mImageSize - FileOffset);
113 }
114
115 if (FileOffset >= mImageSize) {
116 *ReadSize = 0;
117 }
118
119 CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);
120
121 return EFI_SUCCESS;
122 }
123
124
125 /**
126 Get the image type.
127
128 @param[in] File This is a pointer to the device path of the file that is
129 being dispatched.
130
131 @return UINT32 Image Type
132
133 **/
134 UINT32
135 GetImageType (
136 IN CONST EFI_DEVICE_PATH_PROTOCOL *File
137 )
138 {
139 EFI_STATUS Status;
140 EFI_HANDLE DeviceHandle;
141 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
142 EFI_BLOCK_IO_PROTOCOL *BlockIo;
143
144 if (File == NULL) {
145 return IMAGE_UNKNOWN;
146 }
147
148 //
149 // First check to see if File is from a Firmware Volume
150 //
151 DeviceHandle = NULL;
152 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
153 Status = gBS->LocateDevicePath (
154 &gEfiFirmwareVolume2ProtocolGuid,
155 &TempDevicePath,
156 &DeviceHandle
157 );
158 if (!EFI_ERROR (Status)) {
159 Status = gBS->OpenProtocol (
160 DeviceHandle,
161 &gEfiFirmwareVolume2ProtocolGuid,
162 NULL,
163 NULL,
164 NULL,
165 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
166 );
167 if (!EFI_ERROR (Status)) {
168 return IMAGE_FROM_FV;
169 }
170 }
171
172 //
173 // Next check to see if File is from a Block I/O device
174 //
175 DeviceHandle = NULL;
176 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
177 Status = gBS->LocateDevicePath (
178 &gEfiBlockIoProtocolGuid,
179 &TempDevicePath,
180 &DeviceHandle
181 );
182 if (!EFI_ERROR (Status)) {
183 BlockIo = NULL;
184 Status = gBS->OpenProtocol (
185 DeviceHandle,
186 &gEfiBlockIoProtocolGuid,
187 (VOID **) &BlockIo,
188 NULL,
189 NULL,
190 EFI_OPEN_PROTOCOL_GET_PROTOCOL
191 );
192 if (!EFI_ERROR (Status) && BlockIo != NULL) {
193 if (BlockIo->Media != NULL) {
194 if (BlockIo->Media->RemovableMedia) {
195 //
196 // Block I/O is present and specifies the media is removable
197 //
198 return IMAGE_FROM_REMOVABLE_MEDIA;
199 } else {
200 //
201 // Block I/O is present and specifies the media is not removable
202 //
203 return IMAGE_FROM_FIXED_MEDIA;
204 }
205 }
206 }
207 }
208
209 //
210 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
211 // the device path supports the Simple File System Protocol.
212 //
213 DeviceHandle = NULL;
214 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
215 Status = gBS->LocateDevicePath (
216 &gEfiSimpleFileSystemProtocolGuid,
217 &TempDevicePath,
218 &DeviceHandle
219 );
220 if (!EFI_ERROR (Status)) {
221 //
222 // Simple File System is present without Block I/O, so assume media is fixed.
223 //
224 return IMAGE_FROM_FIXED_MEDIA;
225 }
226
227 //
228 // File is not from an FV, Block I/O or Simple File System, so the only options
229 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
230 //
231 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
232 while (!IsDevicePathEndType (TempDevicePath)) {
233 switch (DevicePathType (TempDevicePath)) {
234
235 case MEDIA_DEVICE_PATH:
236 if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) {
237 return IMAGE_FROM_OPTION_ROM;
238 }
239 break;
240
241 case MESSAGING_DEVICE_PATH:
242 if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) {
243 return IMAGE_FROM_REMOVABLE_MEDIA;
244 }
245 break;
246
247 default:
248 break;
249 }
250 TempDevicePath = NextDevicePathNode (TempDevicePath);
251 }
252 return IMAGE_UNKNOWN;
253 }
254
255 /**
256 Caculate hash of Pe/Coff image based on the authenticode image hashing in
257 PE/COFF Specification 8.0 Appendix A
258
259 Caution: This function may receive untrusted input.
260 PE/COFF image is external input, so this function will validate its data structure
261 within this image buffer before use.
262
263 @param[in] HashAlg Hash algorithm type.
264
265 @retval TRUE Successfully hash image.
266 @retval FALSE Fail in hash image.
267
268 **/
269 BOOLEAN
270 HashPeImage (
271 IN UINT32 HashAlg
272 )
273 {
274 BOOLEAN Status;
275 UINT16 Magic;
276 EFI_IMAGE_SECTION_HEADER *Section;
277 VOID *HashCtx;
278 UINTN CtxSize;
279 UINT8 *HashBase;
280 UINTN HashSize;
281 UINTN SumOfBytesHashed;
282 EFI_IMAGE_SECTION_HEADER *SectionHeader;
283 UINTN Index;
284 UINTN Pos;
285 UINT32 CertSize;
286 UINT32 NumberOfRvaAndSizes;
287
288 HashCtx = NULL;
289 SectionHeader = NULL;
290 Status = FALSE;
291
292 if ((HashAlg != HASHALG_SHA1) && (HashAlg != HASHALG_SHA256)) {
293 return FALSE;
294 }
295
296 //
297 // Initialize context of hash.
298 //
299 ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
300
301 if (HashAlg == HASHALG_SHA1) {
302 mImageDigestSize = SHA1_DIGEST_SIZE;
303 mCertType = gEfiCertSha1Guid;
304 } else if (HashAlg == HASHALG_SHA256) {
305 mImageDigestSize = SHA256_DIGEST_SIZE;
306 mCertType = gEfiCertSha256Guid;
307 } else {
308 return FALSE;
309 }
310
311 CtxSize = mHash[HashAlg].GetContextSize();
312
313 HashCtx = AllocatePool (CtxSize);
314 if (HashCtx == NULL) {
315 return FALSE;
316 }
317
318 // 1. Load the image header into memory.
319
320 // 2. Initialize a SHA hash context.
321 Status = mHash[HashAlg].HashInit(HashCtx);
322
323 if (!Status) {
324 goto Done;
325 }
326
327 //
328 // Measuring PE/COFF Image Header;
329 // But CheckSum field and SECURITY data directory (certificate) are excluded
330 //
331 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
332 //
333 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
334 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
335 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
336 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
337 //
338 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
339 } else {
340 //
341 // Get the magic value from the PE/COFF Optional Header
342 //
343 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
344 }
345
346 //
347 // 3. Calculate the distance from the base of the image header to the image checksum address.
348 // 4. Hash the image header from its base to beginning of the image checksum.
349 //
350 HashBase = mImageBase;
351 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
352 //
353 // Use PE32 offset.
354 //
355 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
356 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
357 } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
358 //
359 // Use PE32+ offset.
360 //
361 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
362 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
363 } else {
364 //
365 // Invalid header magic number.
366 //
367 Status = FALSE;
368 goto Done;
369 }
370
371 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
372 if (!Status) {
373 goto Done;
374 }
375
376 //
377 // 5. Skip over the image checksum (it occupies a single ULONG).
378 //
379 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
380 //
381 // 6. Since there is no Cert Directory in optional header, hash everything
382 // from the end of the checksum to the end of image header.
383 //
384 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
385 //
386 // Use PE32 offset.
387 //
388 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
389 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
390 } else {
391 //
392 // Use PE32+ offset.
393 //
394 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
395 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
396 }
397
398 if (HashSize != 0) {
399 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
400 if (!Status) {
401 goto Done;
402 }
403 }
404 } else {
405 //
406 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
407 //
408 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
409 //
410 // Use PE32 offset.
411 //
412 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
413 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
414 } else {
415 //
416 // Use PE32+ offset.
417 //
418 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
419 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
420 }
421
422 if (HashSize != 0) {
423 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
424 if (!Status) {
425 goto Done;
426 }
427 }
428
429 //
430 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
431 // 9. Hash everything from the end of the Cert Directory to the end of image header.
432 //
433 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
434 //
435 // Use PE32 offset
436 //
437 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
438 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
439 } else {
440 //
441 // Use PE32+ offset.
442 //
443 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
444 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
445 }
446
447 if (HashSize != 0) {
448 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
449 if (!Status) {
450 goto Done;
451 }
452 }
453 }
454
455 //
456 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
457 //
458 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
459 //
460 // Use PE32 offset.
461 //
462 SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
463 } else {
464 //
465 // Use PE32+ offset
466 //
467 SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
468 }
469
470
471 Section = (EFI_IMAGE_SECTION_HEADER *) (
472 mImageBase +
473 mPeCoffHeaderOffset +
474 sizeof (UINT32) +
475 sizeof (EFI_IMAGE_FILE_HEADER) +
476 mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
477 );
478
479 //
480 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
481 // structures in the image. The 'NumberOfSections' field of the image
482 // header indicates how big the table should be. Do not include any
483 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
484 //
485 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
486 if (SectionHeader == NULL) {
487 Status = FALSE;
488 goto Done;
489 }
490 //
491 // 12. Using the 'PointerToRawData' in the referenced section headers as
492 // a key, arrange the elements in the table in ascending order. In other
493 // words, sort the section headers according to the disk-file offset of
494 // the section.
495 //
496 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
497 Pos = Index;
498 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
499 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
500 Pos--;
501 }
502 CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
503 Section += 1;
504 }
505
506 //
507 // 13. Walk through the sorted table, bring the corresponding section
508 // into memory, and hash the entire section (using the 'SizeOfRawData'
509 // field in the section header to determine the amount of data to hash).
510 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
511 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
512 //
513 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
514 Section = &SectionHeader[Index];
515 if (Section->SizeOfRawData == 0) {
516 continue;
517 }
518 HashBase = mImageBase + Section->PointerToRawData;
519 HashSize = (UINTN) Section->SizeOfRawData;
520
521 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
522 if (!Status) {
523 goto Done;
524 }
525
526 SumOfBytesHashed += HashSize;
527 }
528
529 //
530 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
531 // data in the file that needs to be added to the hash. This data begins
532 // at file offset SUM_OF_BYTES_HASHED and its length is:
533 // FileSize - (CertDirectory->Size)
534 //
535 if (mImageSize > SumOfBytesHashed) {
536 HashBase = mImageBase + SumOfBytesHashed;
537
538 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
539 CertSize = 0;
540 } else {
541 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
542 //
543 // Use PE32 offset.
544 //
545 CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
546 } else {
547 //
548 // Use PE32+ offset.
549 //
550 CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
551 }
552 }
553
554 if (mImageSize > CertSize + SumOfBytesHashed) {
555 HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed);
556
557 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
558 if (!Status) {
559 goto Done;
560 }
561 } else if (mImageSize < CertSize + SumOfBytesHashed) {
562 Status = FALSE;
563 goto Done;
564 }
565 }
566
567 Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
568
569 Done:
570 if (HashCtx != NULL) {
571 FreePool (HashCtx);
572 }
573 if (SectionHeader != NULL) {
574 FreePool (SectionHeader);
575 }
576 return Status;
577 }
578
579 /**
580 Recognize the Hash algorithm in PE/COFF Authenticode and caculate hash of
581 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
582 8.0 Appendix A
583
584 Caution: This function may receive untrusted input.
585 PE/COFF image is external input, so this function will validate its data structure
586 within this image buffer before use.
587
588 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
589 @retval EFI_SUCCESS Hash successfully.
590
591 **/
592 EFI_STATUS
593 HashPeImageByType (
594 VOID
595 )
596 {
597 UINT8 Index;
598 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
599
600 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) (mImageBase + mSecDataDir->VirtualAddress);
601
602 if (PkcsCertData->Hdr.dwLength < sizeof (WIN_CERTIFICATE_EFI_PKCS) + 32) {
603 return EFI_UNSUPPORTED;
604 }
605
606 for (Index = 0; Index < HASHALG_MAX; Index++) {
607 //
608 // Check the Hash algorithm in PE/COFF Authenticode.
609 // According to PKCS#7 Definition:
610 // SignedData ::= SEQUENCE {
611 // version Version,
612 // digestAlgorithms DigestAlgorithmIdentifiers,
613 // contentInfo ContentInfo,
614 // .... }
615 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
616 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
617 // Fixed offset (+32) is calculated based on two bytes of length encoding.
618 //
619 if ((*(PkcsCertData->CertData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
620 //
621 // Only support two bytes of Long Form of Length Encoding.
622 //
623 continue;
624 }
625
626 if (PkcsCertData->Hdr.dwLength < sizeof (WIN_CERTIFICATE_EFI_PKCS) + 32 + mHash[Index].OidLength) {
627 return EFI_UNSUPPORTED;
628 }
629
630 if (CompareMem (PkcsCertData->CertData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
631 break;
632 }
633 }
634
635 if (Index == HASHALG_MAX) {
636 return EFI_UNSUPPORTED;
637 }
638
639 //
640 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
641 //
642 if (!HashPeImage(Index)) {
643 return EFI_UNSUPPORTED;
644 }
645
646 return EFI_SUCCESS;
647 }
648
649
650 /**
651 Returns the size of a given image execution info table in bytes.
652
653 This function returns the size, in bytes, of the image execution info table specified by
654 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
655
656 @param ImageExeInfoTable A pointer to a image execution info table structure.
657
658 @retval 0 If ImageExeInfoTable is NULL.
659 @retval Others The size of a image execution info table in bytes.
660
661 **/
662 UINTN
663 GetImageExeInfoTableSize (
664 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable
665 )
666 {
667 UINTN Index;
668 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem;
669 UINTN TotalSize;
670
671 if (ImageExeInfoTable == NULL) {
672 return 0;
673 }
674
675 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE));
676 TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
677 for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) {
678 TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize);
679 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize));
680 }
681
682 return TotalSize;
683 }
684
685 /**
686 Create an Image Execution Information Table entry and add it to system configuration table.
687
688 @param[in] Action Describes the action taken by the firmware regarding this image.
689 @param[in] Name Input a null-terminated, user-friendly name.
690 @param[in] DevicePath Input device path pointer.
691 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
692 @param[in] SignatureSize Size of signature.
693
694 **/
695 VOID
696 AddImageExeInfo (
697 IN EFI_IMAGE_EXECUTION_ACTION Action,
698 IN CHAR16 *Name OPTIONAL,
699 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
700 IN EFI_SIGNATURE_LIST *Signature OPTIONAL,
701 IN UINTN SignatureSize
702 )
703 {
704 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
705 EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable;
706 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry;
707 UINTN ImageExeInfoTableSize;
708 UINTN NewImageExeInfoEntrySize;
709 UINTN NameStringLen;
710 UINTN DevicePathSize;
711
712 ImageExeInfoTable = NULL;
713 NewImageExeInfoTable = NULL;
714 ImageExeInfoEntry = NULL;
715 NameStringLen = 0;
716
717 if (DevicePath == NULL) {
718 return ;
719 }
720
721 if (Name != NULL) {
722 NameStringLen = StrSize (Name);
723 }
724
725 ImageExeInfoTable = NULL;
726 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
727 if (ImageExeInfoTable != NULL) {
728 //
729 // The table has been found!
730 // We must enlarge the table to accmodate the new exe info entry.
731 //
732 ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable);
733 } else {
734 //
735 // Not Found!
736 // We should create a new table to append to the configuration table.
737 //
738 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
739 }
740
741 DevicePathSize = GetDevicePathSize (DevicePath);
742 NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize;
743 NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize);
744 if (NewImageExeInfoTable == NULL) {
745 return ;
746 }
747
748 if (ImageExeInfoTable != NULL) {
749 CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize);
750 } else {
751 NewImageExeInfoTable->NumberOfImages = 0;
752 }
753 NewImageExeInfoTable->NumberOfImages++;
754 ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize);
755 //
756 // Update new item's infomation.
757 //
758 WriteUnaligned32 ((UINT32 *) &ImageExeInfoEntry->Action, Action);
759 WriteUnaligned32 ((UINT32 *) &ImageExeInfoEntry->InfoSize, (UINT32) NewImageExeInfoEntrySize);
760
761 if (Name != NULL) {
762 CopyMem ((UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32), Name, NameStringLen);
763 }
764 CopyMem (
765 (UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32) + NameStringLen,
766 DevicePath,
767 DevicePathSize
768 );
769 if (Signature != NULL) {
770 CopyMem (
771 (UINT8 *) &ImageExeInfoEntry->InfoSize + sizeof (UINT32) + NameStringLen + DevicePathSize,
772 Signature,
773 SignatureSize
774 );
775 }
776 //
777 // Update/replace the image execution table.
778 //
779 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable);
780
781 //
782 // Free Old table data!
783 //
784 if (ImageExeInfoTable != NULL) {
785 FreePool (ImageExeInfoTable);
786 }
787 }
788
789 /**
790 Check whether signature is in specified database.
791
792 @param[in] VariableName Name of database variable that is searched in.
793 @param[in] Signature Pointer to signature that is searched for.
794 @param[in] CertType Pointer to hash algrithom.
795 @param[in] SignatureSize Size of Signature.
796
797 @return TRUE Found the signature in the variable database.
798 @return FALSE Not found the signature in the variable database.
799
800 **/
801 BOOLEAN
802 IsSignatureFoundInDatabase (
803 IN CHAR16 *VariableName,
804 IN UINT8 *Signature,
805 IN EFI_GUID *CertType,
806 IN UINTN SignatureSize
807 )
808 {
809 EFI_STATUS Status;
810 EFI_SIGNATURE_LIST *CertList;
811 EFI_SIGNATURE_DATA *Cert;
812 UINTN DataSize;
813 UINT8 *Data;
814 UINTN Index;
815 UINTN CertCount;
816 BOOLEAN IsFound;
817 //
818 // Read signature database variable.
819 //
820 IsFound = FALSE;
821 Data = NULL;
822 DataSize = 0;
823 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
824 if (Status != EFI_BUFFER_TOO_SMALL) {
825 return FALSE;
826 }
827
828 Data = (UINT8 *) AllocateZeroPool (DataSize);
829 if (Data == NULL) {
830 return FALSE;
831 }
832
833 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data);
834 if (EFI_ERROR (Status)) {
835 goto Done;
836 }
837 //
838 // Enumerate all signature data in SigDB to check if executable's signature exists.
839 //
840 CertList = (EFI_SIGNATURE_LIST *) Data;
841 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
842 CertCount = (CertList->SignatureListSize - CertList->SignatureHeaderSize) / CertList->SignatureSize;
843 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
844 if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) {
845 for (Index = 0; Index < CertCount; Index++) {
846 if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) {
847 //
848 // Find the signature in database.
849 //
850 IsFound = TRUE;
851 break;
852 }
853
854 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
855 }
856
857 if (IsFound) {
858 break;
859 }
860 }
861
862 DataSize -= CertList->SignatureListSize;
863 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
864 }
865
866 Done:
867 if (Data != NULL) {
868 FreePool (Data);
869 }
870
871 return IsFound;
872 }
873
874 /**
875 Verify PKCS#7 SignedData using certificate found in Variable which formatted
876 as EFI_SIGNATURE_LIST. The Variable may be PK, KEK, DB or DBX.
877
878 @param VariableName Name of Variable to search for Certificate.
879 @param VendorGuid Variable vendor GUID.
880
881 @retval TRUE Image pass verification.
882 @retval FALSE Image fail verification.
883
884 **/
885 BOOLEAN
886 IsPkcsSignedDataVerifiedBySignatureList (
887 IN CHAR16 *VariableName,
888 IN EFI_GUID *VendorGuid
889 )
890 {
891 EFI_STATUS Status;
892 BOOLEAN VerifyStatus;
893 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
894 EFI_SIGNATURE_LIST *CertList;
895 EFI_SIGNATURE_DATA *Cert;
896 UINTN DataSize;
897 UINT8 *Data;
898 UINT8 *RootCert;
899 UINTN RootCertSize;
900 UINTN Index;
901 UINTN CertCount;
902
903 Data = NULL;
904 CertList = NULL;
905 Cert = NULL;
906 RootCert = NULL;
907 RootCertSize = 0;
908 VerifyStatus = FALSE;
909 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) (mImageBase + mSecDataDir->VirtualAddress);
910
911 DataSize = 0;
912 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, NULL);
913 if (Status == EFI_BUFFER_TOO_SMALL) {
914 Data = (UINT8 *) AllocateZeroPool (DataSize);
915 if (Data == NULL) {
916 return VerifyStatus;
917 }
918
919 Status = gRT->GetVariable (VariableName, VendorGuid, NULL, &DataSize, (VOID *) Data);
920 if (EFI_ERROR (Status)) {
921 goto Done;
922 }
923
924 //
925 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
926 //
927 CertList = (EFI_SIGNATURE_LIST *) Data;
928 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
929 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
930 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
931 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
932 for (Index = 0; Index < CertCount; Index++) {
933 //
934 // Iterate each Signature Data Node within this CertList for verify.
935 //
936 RootCert = Cert->SignatureData;
937 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
938
939 //
940 // Call AuthenticodeVerify library to Verify Authenticode struct.
941 //
942 VerifyStatus = AuthenticodeVerify (
943 PkcsCertData->CertData,
944 PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr),
945 RootCert,
946 RootCertSize,
947 mImageDigest,
948 mImageDigestSize
949 );
950 if (VerifyStatus) {
951 goto Done;
952 }
953 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
954 }
955 }
956 DataSize -= CertList->SignatureListSize;
957 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
958 }
959 }
960
961 Done:
962 if (Data != NULL) {
963 FreePool (Data);
964 }
965
966 return VerifyStatus;
967 }
968
969 /**
970 Verify certificate in WIN_CERT_TYPE_PKCS_SIGNED_DATA format.
971
972 @retval EFI_SUCCESS Image pass verification.
973 @retval EFI_SECURITY_VIOLATION Image fail verification.
974
975 **/
976 EFI_STATUS
977 VerifyCertPkcsSignedData (
978 VOID
979 )
980 {
981 //
982 // 1: Find certificate from DBX forbidden database for revoked certificate.
983 //
984 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid)) {
985 //
986 // DBX is forbidden database, if Authenticode verification pass with
987 // one of the certificate in DBX, this image should be rejected.
988 //
989 return EFI_SECURITY_VIOLATION;
990 }
991
992 //
993 // 2: Find certificate from DB database and try to verify authenticode struct.
994 //
995 if (IsPkcsSignedDataVerifiedBySignatureList (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid)) {
996 return EFI_SUCCESS;
997 } else {
998 return EFI_SECURITY_VIOLATION;
999 }
1000 }
1001
1002 /**
1003 Provide verification service for signed images, which include both signature validation
1004 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1005 MSFT Authenticode type signatures are supported.
1006
1007 In this implementation, only verify external executables when in USER MODE.
1008 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1009
1010 The image verification process is:
1011 If the image is signed,
1012 If the image's certificate verifies against a certificate (root or intermediate) in the allowed
1013 database (DB) and not in the forbidden database (DBX), the certificate verification is passed.
1014 If the image's hash digest is in DBX,
1015 deny execution.
1016 If not,
1017 run it.
1018 If the Image's certificate verification failed.
1019 If the Image's Hash is in DB and not in DBX,
1020 run it.
1021 Otherwise,
1022 deny execution.
1023 Otherwise, the image is not signed,
1024 Is the Image's Hash in DBX?
1025 If yes, deny execution.
1026 If not, is the Image's Hash in DB?
1027 If yes, run it.
1028 If not, deny execution.
1029
1030 Caution: This function may receive untrusted input.
1031 PE/COFF image is external input, so this function will validate its data structure
1032 within this image buffer before use.
1033
1034 @param[in] AuthenticationStatus
1035 This is the authentication status returned from the security
1036 measurement services for the input file.
1037 @param[in] File This is a pointer to the device path of the file that is
1038 being dispatched. This will optionally be used for logging.
1039 @param[in] FileBuffer File buffer matches the input file device path.
1040 @param[in] FileSize Size of File buffer matches the input file device path.
1041 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1042
1043 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1044 FileBuffer did authenticate, and the platform policy dictates
1045 that the DXE Foundation may use the file.
1046 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1047 and non-NULL FileBuffer did authenticate, and the platform
1048 policy dictates that the DXE Foundation may execute the image in
1049 FileBuffer.
1050 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1051 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1052 the platform policy dictates that File should be placed
1053 in the untrusted state. The image has been added to the file
1054 execution table.
1055 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1056 authenticate, and the platform policy dictates that the DXE
1057 Foundation many not use File.
1058
1059 **/
1060 EFI_STATUS
1061 EFIAPI
1062 DxeImageVerificationHandler (
1063 IN UINT32 AuthenticationStatus,
1064 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
1065 IN VOID *FileBuffer,
1066 IN UINTN FileSize,
1067 IN BOOLEAN BootPolicy
1068 )
1069 {
1070 EFI_STATUS Status;
1071 UINT16 Magic;
1072 EFI_IMAGE_DOS_HEADER *DosHdr;
1073 EFI_STATUS VerifyStatus;
1074 EFI_SIGNATURE_LIST *SignatureList;
1075 UINTN SignatureListSize;
1076 EFI_SIGNATURE_DATA *Signature;
1077 EFI_IMAGE_EXECUTION_ACTION Action;
1078 WIN_CERTIFICATE *WinCertificate;
1079 UINT32 Policy;
1080 UINT8 *SecureBoot;
1081 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1082 UINT32 NumberOfRvaAndSizes;
1083 UINT32 CertSize;
1084
1085 SignatureList = NULL;
1086 SignatureListSize = 0;
1087 WinCertificate = NULL;
1088 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1089 Status = EFI_ACCESS_DENIED;
1090 //
1091 // Check the image type and get policy setting.
1092 //
1093 switch (GetImageType (File)) {
1094
1095 case IMAGE_FROM_FV:
1096 Policy = ALWAYS_EXECUTE;
1097 break;
1098
1099 case IMAGE_FROM_OPTION_ROM:
1100 Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
1101 break;
1102
1103 case IMAGE_FROM_REMOVABLE_MEDIA:
1104 Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
1105 break;
1106
1107 case IMAGE_FROM_FIXED_MEDIA:
1108 Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
1109 break;
1110
1111 default:
1112 Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
1113 break;
1114 }
1115 //
1116 // If policy is always/never execute, return directly.
1117 //
1118 if (Policy == ALWAYS_EXECUTE) {
1119 return EFI_SUCCESS;
1120 } else if (Policy == NEVER_EXECUTE) {
1121 return EFI_ACCESS_DENIED;
1122 }
1123
1124 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL);
1125 //
1126 // Skip verification if SecureBoot variable doesn't exist.
1127 //
1128 if (SecureBoot == NULL) {
1129 return EFI_SUCCESS;
1130 }
1131
1132 //
1133 // Skip verification if SecureBoot is disabled.
1134 //
1135 if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) {
1136 FreePool (SecureBoot);
1137 return EFI_SUCCESS;
1138 }
1139 FreePool (SecureBoot);
1140
1141 //
1142 // Read the Dos header.
1143 //
1144 if (FileBuffer == NULL) {
1145 return EFI_INVALID_PARAMETER;
1146 }
1147
1148 mImageBase = (UINT8 *) FileBuffer;
1149 mImageSize = FileSize;
1150
1151 ZeroMem (&ImageContext, sizeof (ImageContext));
1152 ImageContext.Handle = (VOID *) FileBuffer;
1153 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
1154
1155 //
1156 // Get information about the image being loaded
1157 //
1158 Status = PeCoffLoaderGetImageInfo (&ImageContext);
1159 if (EFI_ERROR (Status)) {
1160 //
1161 // The information can't be got from the invalid PeImage
1162 //
1163 goto Done;
1164 }
1165
1166 Status = EFI_ACCESS_DENIED;
1167
1168 DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
1169 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
1170 //
1171 // DOS image header is present,
1172 // so read the PE header after the DOS image header.
1173 //
1174 mPeCoffHeaderOffset = DosHdr->e_lfanew;
1175 } else {
1176 mPeCoffHeaderOffset = 0;
1177 }
1178 //
1179 // Check PE/COFF image.
1180 //
1181 mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
1182 if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1183 //
1184 // It is not a valid Pe/Coff file.
1185 //
1186 goto Done;
1187 }
1188
1189 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1190 //
1191 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1192 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1193 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1194 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1195 //
1196 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1197 } else {
1198 //
1199 // Get the magic value from the PE/COFF Optional Header
1200 //
1201 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
1202 }
1203
1204 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1205 //
1206 // Use PE32 offset.
1207 //
1208 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
1209 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1210 mSecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1211 }
1212 } else {
1213 //
1214 // Use PE32+ offset.
1215 //
1216 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
1217 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1218 mSecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1219 }
1220 }
1221
1222 if ((mSecDataDir == NULL) || ((mSecDataDir != NULL) && (mSecDataDir->Size == 0))) {
1223 //
1224 // This image is not signed.
1225 //
1226 if (!HashPeImage (HASHALG_SHA256)) {
1227 goto Done;
1228 }
1229
1230 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1231 //
1232 // Image Hash is in forbidden database (DBX).
1233 //
1234 goto Done;
1235 }
1236
1237 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1238 //
1239 // Image Hash is in allowed database (DB).
1240 //
1241 return EFI_SUCCESS;
1242 }
1243
1244 //
1245 // Image Hash is not found in both forbidden and allowed database.
1246 //
1247 goto Done;
1248 }
1249
1250 //
1251 // Verify signature of executables.
1252 //
1253 WinCertificate = (WIN_CERTIFICATE *) (mImageBase + mSecDataDir->VirtualAddress);
1254
1255 CertSize = sizeof (WIN_CERTIFICATE);
1256
1257 if ((mSecDataDir->Size <= CertSize) || (mSecDataDir->Size < WinCertificate->dwLength)) {
1258 goto Done;
1259 }
1260
1261 if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1262 //
1263 // Verify Pkcs signed data type.
1264 //
1265 Status = HashPeImageByType();
1266 if (EFI_ERROR (Status)) {
1267 goto Done;
1268 }
1269
1270 VerifyStatus = VerifyCertPkcsSignedData ();
1271 } else {
1272 goto Done;
1273 }
1274
1275 if (!EFI_ERROR (VerifyStatus)) {
1276 //
1277 // Verification is passed.
1278 // Continue to check the image digest in signature database.
1279 //
1280 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1281 //
1282 // Executable signature verification passes, but is found in forbidden signature database.
1283 //
1284 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
1285 Status = EFI_ACCESS_DENIED;
1286 } else {
1287 //
1288 // For image verification against enrolled X.509 certificate(root or intermediate),
1289 // no need to check image's hash in the allowed database.
1290 //
1291 return EFI_SUCCESS;
1292 }
1293 } else {
1294 //
1295 // Verification failure.
1296 //
1297 if (!IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize) &&
1298 IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1299 //
1300 // Verification fail, Image Hash is not in forbidden database (DBX),
1301 // and Image Hash is in allowed database (DB).
1302 //
1303 Status = EFI_SUCCESS;
1304 } else {
1305 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
1306 Status = EFI_ACCESS_DENIED;
1307 }
1308 }
1309
1310 if (EFI_ERROR (Status)) {
1311 //
1312 // Get image hash value as executable's signature.
1313 //
1314 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
1315 SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
1316 if (SignatureList == NULL) {
1317 Status = EFI_OUT_OF_RESOURCES;
1318 goto Done;
1319 }
1320 SignatureList->SignatureHeaderSize = 0;
1321 SignatureList->SignatureListSize = (UINT32) SignatureListSize;
1322 SignatureList->SignatureSize = (UINT32) mImageDigestSize;
1323 CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
1324 Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
1325 CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
1326 }
1327
1328 Done:
1329 if (Status != EFI_SUCCESS) {
1330 //
1331 // Policy decides to defer or reject the image; add its information in image executable information table.
1332 //
1333 AddImageExeInfo (Action, NULL, File, SignatureList, SignatureListSize);
1334 Status = EFI_SECURITY_VIOLATION;
1335 }
1336
1337 if (SignatureList != NULL) {
1338 FreePool (SignatureList);
1339 }
1340
1341 return Status;
1342 }
1343
1344 /**
1345 When VariableWriteArchProtocol install, create "SecureBoot" variable.
1346
1347 @param[in] Event Event whose notification function is being invoked.
1348 @param[in] Context Pointer to the notification function's context.
1349
1350 **/
1351 VOID
1352 EFIAPI
1353 VariableWriteCallBack (
1354 IN EFI_EVENT Event,
1355 IN VOID *Context
1356 )
1357 {
1358 UINT8 SecureBootMode;
1359 UINT8 *SecureBootModePtr;
1360 EFI_STATUS Status;
1361 VOID *ProtocolPointer;
1362
1363 Status = gBS->LocateProtocol (&gEfiVariableWriteArchProtocolGuid, NULL, &ProtocolPointer);
1364 if (EFI_ERROR (Status)) {
1365 return;
1366 }
1367
1368 //
1369 // Check whether "SecureBoot" variable exists.
1370 // If this library is built-in, it means firmware has capability to perform
1371 // driver signing verification.
1372 //
1373 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBootModePtr, NULL);
1374 if (SecureBootModePtr == NULL) {
1375 SecureBootMode = SECURE_BOOT_MODE_DISABLE;
1376 //
1377 // Authenticated variable driver will update "SecureBoot" depending on SetupMode variable.
1378 //
1379 gRT->SetVariable (
1380 EFI_SECURE_BOOT_MODE_NAME,
1381 &gEfiGlobalVariableGuid,
1382 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
1383 sizeof (UINT8),
1384 &SecureBootMode
1385 );
1386 } else {
1387 FreePool (SecureBootModePtr);
1388 }
1389 }
1390
1391 /**
1392 Register security measurement handler.
1393
1394 @param ImageHandle ImageHandle of the loaded driver.
1395 @param SystemTable Pointer to the EFI System Table.
1396
1397 @retval EFI_SUCCESS The handlers were registered successfully.
1398 **/
1399 EFI_STATUS
1400 EFIAPI
1401 DxeImageVerificationLibConstructor (
1402 IN EFI_HANDLE ImageHandle,
1403 IN EFI_SYSTEM_TABLE *SystemTable
1404 )
1405 {
1406 VOID *Registration;
1407
1408 //
1409 // Register callback function upon VariableWriteArchProtocol.
1410 //
1411 EfiCreateProtocolNotifyEvent (
1412 &gEfiVariableWriteArchProtocolGuid,
1413 TPL_CALLBACK,
1414 VariableWriteCallBack,
1415 NULL,
1416 &Registration
1417 );
1418
1419 return RegisterSecurity2Handler (
1420 DxeImageVerificationHandler,
1421 EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
1422 );
1423 }