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