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