]> git.proxmox.com Git - mirror_edk2.git/blob - SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
SecurityPkg/DxeImageVerificationLib: Add DEBUG messages for image verification failures
[mirror_edk2.git] / SecurityPkg / Library / DxeImageVerificationLib / DxeImageVerificationLib.c
1 /** @file
2 Implement image verification services for secure boot service
3
4 Caution: This file requires additional review when modified.
5 This library will have external input - PE/COFF image.
6 This external input must be validated carefully to avoid security issue like
7 buffer overflow, integer overflow.
8
9 DxeImageVerificationLibImageRead() function will make sure the PE/COFF image content
10 read is within the image buffer.
11
12 DxeImageVerificationHandler(), HashPeImageByType(), HashPeImage() function will accept
13 untrusted PE/COFF image and validate its data structure within this image buffer before use.
14
15 Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
16 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
17 This program and the accompanying materials
18 are licensed and made available under the terms and conditions of the BSD License
19 which accompanies this distribution. The full text of the license may be found at
20 http://opensource.org/licenses/bsd-license.php
21
22 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
23 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
24
25 **/
26
27 #include "DxeImageVerificationLib.h"
28
29 //
30 // Caution: This is used by a function which may receive untrusted input.
31 // These global variables hold PE/COFF image data, and they should be validated before use.
32 //
33 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION mNtHeader;
34 UINT32 mPeCoffHeaderOffset;
35 EFI_GUID mCertType;
36
37 //
38 // Information on current PE/COFF image
39 //
40 UINTN mImageSize;
41 UINT8 *mImageBase = NULL;
42 UINT8 mImageDigest[MAX_DIGEST_SIZE];
43 UINTN mImageDigestSize;
44
45 //
46 // Notify string for authorization UI.
47 //
48 CHAR16 mNotifyString1[MAX_NOTIFY_STRING_LEN] = L"Image verification pass but not found in authorized database!";
49 CHAR16 mNotifyString2[MAX_NOTIFY_STRING_LEN] = L"Launch this image anyway? (Yes/Defer/No)";
50 //
51 // Public Exponent of RSA Key.
52 //
53 CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 };
54
55
56 //
57 // OID ASN.1 Value for Hash Algorithms
58 //
59 UINT8 mHashOidValue[] = {
60 0x2B, 0x0E, 0x03, 0x02, 0x1A, // OBJ_sha1
61 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, // OBJ_sha224
62 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, // OBJ_sha256
63 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, // OBJ_sha384
64 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, // OBJ_sha512
65 };
66
67 HASH_TABLE mHash[] = {
68 { L"SHA1", 20, &mHashOidValue[0], 5, Sha1GetContextSize, Sha1Init, Sha1Update, Sha1Final },
69 { L"SHA224", 28, &mHashOidValue[5], 9, NULL, NULL, NULL, NULL },
70 { L"SHA256", 32, &mHashOidValue[14], 9, Sha256GetContextSize, Sha256Init, Sha256Update, Sha256Final},
71 { L"SHA384", 48, &mHashOidValue[23], 9, Sha384GetContextSize, Sha384Init, Sha384Update, Sha384Final},
72 { L"SHA512", 64, &mHashOidValue[32], 9, Sha512GetContextSize, Sha512Init, Sha512Update, Sha512Final}
73 };
74
75 EFI_STRING mHashTypeStr;
76
77 /**
78 SecureBoot Hook for processing image verification.
79
80 @param[in] VariableName Name of Variable to be found.
81 @param[in] VendorGuid Variable vendor GUID.
82 @param[in] DataSize Size of Data found. If size is less than the
83 data, this value contains the required size.
84 @param[in] Data Data pointer.
85
86 **/
87 VOID
88 EFIAPI
89 SecureBootHook (
90 IN CHAR16 *VariableName,
91 IN EFI_GUID *VendorGuid,
92 IN UINTN DataSize,
93 IN VOID *Data
94 );
95
96 /**
97 Reads contents of a PE/COFF image in memory buffer.
98
99 Caution: This function may receive untrusted input.
100 PE/COFF image is external input, so this function will make sure the PE/COFF image content
101 read is within the image buffer.
102
103 @param FileHandle Pointer to the file handle to read the PE/COFF image.
104 @param FileOffset Offset into the PE/COFF image to begin the read operation.
105 @param ReadSize On input, the size in bytes of the requested read operation.
106 On output, the number of bytes actually read.
107 @param Buffer Output buffer that contains the data read from the PE/COFF image.
108
109 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
110 **/
111 EFI_STATUS
112 EFIAPI
113 DxeImageVerificationLibImageRead (
114 IN VOID *FileHandle,
115 IN UINTN FileOffset,
116 IN OUT UINTN *ReadSize,
117 OUT VOID *Buffer
118 )
119 {
120 UINTN EndPosition;
121
122 if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {
123 return EFI_INVALID_PARAMETER;
124 }
125
126 if (MAX_ADDRESS - FileOffset < *ReadSize) {
127 return EFI_INVALID_PARAMETER;
128 }
129
130 EndPosition = FileOffset + *ReadSize;
131 if (EndPosition > mImageSize) {
132 *ReadSize = (UINT32)(mImageSize - FileOffset);
133 }
134
135 if (FileOffset >= mImageSize) {
136 *ReadSize = 0;
137 }
138
139 CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);
140
141 return EFI_SUCCESS;
142 }
143
144
145 /**
146 Get the image type.
147
148 @param[in] File This is a pointer to the device path of the file that is
149 being dispatched.
150
151 @return UINT32 Image Type
152
153 **/
154 UINT32
155 GetImageType (
156 IN CONST EFI_DEVICE_PATH_PROTOCOL *File
157 )
158 {
159 EFI_STATUS Status;
160 EFI_HANDLE DeviceHandle;
161 EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;
162 EFI_BLOCK_IO_PROTOCOL *BlockIo;
163
164 if (File == NULL) {
165 return IMAGE_UNKNOWN;
166 }
167
168 //
169 // First check to see if File is from a Firmware Volume
170 //
171 DeviceHandle = NULL;
172 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
173 Status = gBS->LocateDevicePath (
174 &gEfiFirmwareVolume2ProtocolGuid,
175 &TempDevicePath,
176 &DeviceHandle
177 );
178 if (!EFI_ERROR (Status)) {
179 Status = gBS->OpenProtocol (
180 DeviceHandle,
181 &gEfiFirmwareVolume2ProtocolGuid,
182 NULL,
183 NULL,
184 NULL,
185 EFI_OPEN_PROTOCOL_TEST_PROTOCOL
186 );
187 if (!EFI_ERROR (Status)) {
188 return IMAGE_FROM_FV;
189 }
190 }
191
192 //
193 // Next check to see if File is from a Block I/O device
194 //
195 DeviceHandle = NULL;
196 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
197 Status = gBS->LocateDevicePath (
198 &gEfiBlockIoProtocolGuid,
199 &TempDevicePath,
200 &DeviceHandle
201 );
202 if (!EFI_ERROR (Status)) {
203 BlockIo = NULL;
204 Status = gBS->OpenProtocol (
205 DeviceHandle,
206 &gEfiBlockIoProtocolGuid,
207 (VOID **) &BlockIo,
208 NULL,
209 NULL,
210 EFI_OPEN_PROTOCOL_GET_PROTOCOL
211 );
212 if (!EFI_ERROR (Status) && BlockIo != NULL) {
213 if (BlockIo->Media != NULL) {
214 if (BlockIo->Media->RemovableMedia) {
215 //
216 // Block I/O is present and specifies the media is removable
217 //
218 return IMAGE_FROM_REMOVABLE_MEDIA;
219 } else {
220 //
221 // Block I/O is present and specifies the media is not removable
222 //
223 return IMAGE_FROM_FIXED_MEDIA;
224 }
225 }
226 }
227 }
228
229 //
230 // File is not in a Firmware Volume or on a Block I/O device, so check to see if
231 // the device path supports the Simple File System Protocol.
232 //
233 DeviceHandle = NULL;
234 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
235 Status = gBS->LocateDevicePath (
236 &gEfiSimpleFileSystemProtocolGuid,
237 &TempDevicePath,
238 &DeviceHandle
239 );
240 if (!EFI_ERROR (Status)) {
241 //
242 // Simple File System is present without Block I/O, so assume media is fixed.
243 //
244 return IMAGE_FROM_FIXED_MEDIA;
245 }
246
247 //
248 // File is not from an FV, Block I/O or Simple File System, so the only options
249 // left are a PCI Option ROM and a Load File Protocol such as a PXE Boot from a NIC.
250 //
251 TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File;
252 while (!IsDevicePathEndType (TempDevicePath)) {
253 switch (DevicePathType (TempDevicePath)) {
254
255 case MEDIA_DEVICE_PATH:
256 if (DevicePathSubType (TempDevicePath) == MEDIA_RELATIVE_OFFSET_RANGE_DP) {
257 return IMAGE_FROM_OPTION_ROM;
258 }
259 break;
260
261 case MESSAGING_DEVICE_PATH:
262 if (DevicePathSubType(TempDevicePath) == MSG_MAC_ADDR_DP) {
263 return IMAGE_FROM_REMOVABLE_MEDIA;
264 }
265 break;
266
267 default:
268 break;
269 }
270 TempDevicePath = NextDevicePathNode (TempDevicePath);
271 }
272 return IMAGE_UNKNOWN;
273 }
274
275 /**
276 Calculate hash of Pe/Coff image based on the authenticode image hashing in
277 PE/COFF Specification 8.0 Appendix A
278
279 Caution: This function may receive untrusted input.
280 PE/COFF image is external input, so this function will validate its data structure
281 within this image buffer before use.
282
283 @param[in] HashAlg Hash algorithm type.
284
285 @retval TRUE Successfully hash image.
286 @retval FALSE Fail in hash image.
287
288 **/
289 BOOLEAN
290 HashPeImage (
291 IN UINT32 HashAlg
292 )
293 {
294 BOOLEAN Status;
295 UINT16 Magic;
296 EFI_IMAGE_SECTION_HEADER *Section;
297 VOID *HashCtx;
298 UINTN CtxSize;
299 UINT8 *HashBase;
300 UINTN HashSize;
301 UINTN SumOfBytesHashed;
302 EFI_IMAGE_SECTION_HEADER *SectionHeader;
303 UINTN Index;
304 UINTN Pos;
305 UINT32 CertSize;
306 UINT32 NumberOfRvaAndSizes;
307
308 HashCtx = NULL;
309 SectionHeader = NULL;
310 Status = FALSE;
311
312 if ((HashAlg >= HASHALG_MAX)) {
313 return FALSE;
314 }
315
316 //
317 // Initialize context of hash.
318 //
319 ZeroMem (mImageDigest, MAX_DIGEST_SIZE);
320
321 switch (HashAlg) {
322 case HASHALG_SHA1:
323 mImageDigestSize = SHA1_DIGEST_SIZE;
324 mCertType = gEfiCertSha1Guid;
325 break;
326
327 case HASHALG_SHA256:
328 mImageDigestSize = SHA256_DIGEST_SIZE;
329 mCertType = gEfiCertSha256Guid;
330 break;
331
332 case HASHALG_SHA384:
333 mImageDigestSize = SHA384_DIGEST_SIZE;
334 mCertType = gEfiCertSha384Guid;
335 break;
336
337 case HASHALG_SHA512:
338 mImageDigestSize = SHA512_DIGEST_SIZE;
339 mCertType = gEfiCertSha512Guid;
340 break;
341
342 default:
343 return FALSE;
344 }
345
346 mHashTypeStr = mHash[HashAlg].Name;
347 CtxSize = mHash[HashAlg].GetContextSize();
348
349 HashCtx = AllocatePool (CtxSize);
350 if (HashCtx == NULL) {
351 return FALSE;
352 }
353
354 // 1. Load the image header into memory.
355
356 // 2. Initialize a SHA hash context.
357 Status = mHash[HashAlg].HashInit(HashCtx);
358
359 if (!Status) {
360 goto Done;
361 }
362
363 //
364 // Measuring PE/COFF Image Header;
365 // But CheckSum field and SECURITY data directory (certificate) are excluded
366 //
367 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
368 //
369 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
370 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
371 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
372 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
373 //
374 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
375 } else {
376 //
377 // Get the magic value from the PE/COFF Optional Header
378 //
379 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
380 }
381
382 //
383 // 3. Calculate the distance from the base of the image header to the image checksum address.
384 // 4. Hash the image header from its base to beginning of the image checksum.
385 //
386 HashBase = mImageBase;
387 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
388 //
389 // Use PE32 offset.
390 //
391 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
392 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
393 } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
394 //
395 // Use PE32+ offset.
396 //
397 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
398 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
399 } else {
400 //
401 // Invalid header magic number.
402 //
403 Status = FALSE;
404 goto Done;
405 }
406
407 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
408 if (!Status) {
409 goto Done;
410 }
411
412 //
413 // 5. Skip over the image checksum (it occupies a single ULONG).
414 //
415 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
416 //
417 // 6. Since there is no Cert Directory in optional header, hash everything
418 // from the end of the checksum to the end of image header.
419 //
420 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
421 //
422 // Use PE32 offset.
423 //
424 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
425 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
426 } else {
427 //
428 // Use PE32+ offset.
429 //
430 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
431 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
432 }
433
434 if (HashSize != 0) {
435 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
436 if (!Status) {
437 goto Done;
438 }
439 }
440 } else {
441 //
442 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
443 //
444 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
445 //
446 // Use PE32 offset.
447 //
448 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
449 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
450 } else {
451 //
452 // Use PE32+ offset.
453 //
454 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
455 HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
456 }
457
458 if (HashSize != 0) {
459 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
460 if (!Status) {
461 goto Done;
462 }
463 }
464
465 //
466 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
467 // 9. Hash everything from the end of the Cert Directory to the end of image header.
468 //
469 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
470 //
471 // Use PE32 offset
472 //
473 HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
474 HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
475 } else {
476 //
477 // Use PE32+ offset.
478 //
479 HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
480 HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
481 }
482
483 if (HashSize != 0) {
484 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
485 if (!Status) {
486 goto Done;
487 }
488 }
489 }
490
491 //
492 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header.
493 //
494 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
495 //
496 // Use PE32 offset.
497 //
498 SumOfBytesHashed = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders;
499 } else {
500 //
501 // Use PE32+ offset
502 //
503 SumOfBytesHashed = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders;
504 }
505
506
507 Section = (EFI_IMAGE_SECTION_HEADER *) (
508 mImageBase +
509 mPeCoffHeaderOffset +
510 sizeof (UINT32) +
511 sizeof (EFI_IMAGE_FILE_HEADER) +
512 mNtHeader.Pe32->FileHeader.SizeOfOptionalHeader
513 );
514
515 //
516 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
517 // structures in the image. The 'NumberOfSections' field of the image
518 // header indicates how big the table should be. Do not include any
519 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
520 //
521 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * mNtHeader.Pe32->FileHeader.NumberOfSections);
522 if (SectionHeader == NULL) {
523 Status = FALSE;
524 goto Done;
525 }
526 //
527 // 12. Using the 'PointerToRawData' in the referenced section headers as
528 // a key, arrange the elements in the table in ascending order. In other
529 // words, sort the section headers according to the disk-file offset of
530 // the section.
531 //
532 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
533 Pos = Index;
534 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
535 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
536 Pos--;
537 }
538 CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
539 Section += 1;
540 }
541
542 //
543 // 13. Walk through the sorted table, bring the corresponding section
544 // into memory, and hash the entire section (using the 'SizeOfRawData'
545 // field in the section header to determine the amount of data to hash).
546 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
547 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
548 //
549 for (Index = 0; Index < mNtHeader.Pe32->FileHeader.NumberOfSections; Index++) {
550 Section = &SectionHeader[Index];
551 if (Section->SizeOfRawData == 0) {
552 continue;
553 }
554 HashBase = mImageBase + Section->PointerToRawData;
555 HashSize = (UINTN) Section->SizeOfRawData;
556
557 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
558 if (!Status) {
559 goto Done;
560 }
561
562 SumOfBytesHashed += HashSize;
563 }
564
565 //
566 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
567 // data in the file that needs to be added to the hash. This data begins
568 // at file offset SUM_OF_BYTES_HASHED and its length is:
569 // FileSize - (CertDirectory->Size)
570 //
571 if (mImageSize > SumOfBytesHashed) {
572 HashBase = mImageBase + SumOfBytesHashed;
573
574 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
575 CertSize = 0;
576 } else {
577 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
578 //
579 // Use PE32 offset.
580 //
581 CertSize = mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
582 } else {
583 //
584 // Use PE32+ offset.
585 //
586 CertSize = mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
587 }
588 }
589
590 if (mImageSize > CertSize + SumOfBytesHashed) {
591 HashSize = (UINTN) (mImageSize - CertSize - SumOfBytesHashed);
592
593 Status = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
594 if (!Status) {
595 goto Done;
596 }
597 } else if (mImageSize < CertSize + SumOfBytesHashed) {
598 Status = FALSE;
599 goto Done;
600 }
601 }
602
603 Status = mHash[HashAlg].HashFinal(HashCtx, mImageDigest);
604
605 Done:
606 if (HashCtx != NULL) {
607 FreePool (HashCtx);
608 }
609 if (SectionHeader != NULL) {
610 FreePool (SectionHeader);
611 }
612 return Status;
613 }
614
615 /**
616 Recognize the Hash algorithm in PE/COFF Authenticode and calculate hash of
617 Pe/Coff image based on the authenticode image hashing in PE/COFF Specification
618 8.0 Appendix A
619
620 Caution: This function may receive untrusted input.
621 PE/COFF image is external input, so this function will validate its data structure
622 within this image buffer before use.
623
624 @param[in] AuthData Pointer to the Authenticode Signature retrieved from signed image.
625 @param[in] AuthDataSize Size of the Authenticode Signature in bytes.
626
627 @retval EFI_UNSUPPORTED Hash algorithm is not supported.
628 @retval EFI_SUCCESS Hash successfully.
629
630 **/
631 EFI_STATUS
632 HashPeImageByType (
633 IN UINT8 *AuthData,
634 IN UINTN AuthDataSize
635 )
636 {
637 UINT8 Index;
638
639 for (Index = 0; Index < HASHALG_MAX; Index++) {
640 //
641 // Check the Hash algorithm in PE/COFF Authenticode.
642 // According to PKCS#7 Definition:
643 // SignedData ::= SEQUENCE {
644 // version Version,
645 // digestAlgorithms DigestAlgorithmIdentifiers,
646 // contentInfo ContentInfo,
647 // .... }
648 // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm in PE/COFF hashing
649 // This field has the fixed offset (+32) in final Authenticode ASN.1 data.
650 // Fixed offset (+32) is calculated based on two bytes of length encoding.
651 //
652 if ((*(AuthData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) {
653 //
654 // Only support two bytes of Long Form of Length Encoding.
655 //
656 continue;
657 }
658
659 if (AuthDataSize < 32 + mHash[Index].OidLength) {
660 return EFI_UNSUPPORTED;
661 }
662
663 if (CompareMem (AuthData + 32, mHash[Index].OidValue, mHash[Index].OidLength) == 0) {
664 break;
665 }
666 }
667
668 if (Index == HASHALG_MAX) {
669 return EFI_UNSUPPORTED;
670 }
671
672 //
673 // HASH PE Image based on Hash algorithm in PE/COFF Authenticode.
674 //
675 if (!HashPeImage(Index)) {
676 return EFI_UNSUPPORTED;
677 }
678
679 return EFI_SUCCESS;
680 }
681
682
683 /**
684 Returns the size of a given image execution info table in bytes.
685
686 This function returns the size, in bytes, of the image execution info table specified by
687 ImageExeInfoTable. If ImageExeInfoTable is NULL, then 0 is returned.
688
689 @param ImageExeInfoTable A pointer to a image execution info table structure.
690
691 @retval 0 If ImageExeInfoTable is NULL.
692 @retval Others The size of a image execution info table in bytes.
693
694 **/
695 UINTN
696 GetImageExeInfoTableSize (
697 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable
698 )
699 {
700 UINTN Index;
701 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoItem;
702 UINTN TotalSize;
703
704 if (ImageExeInfoTable == NULL) {
705 return 0;
706 }
707
708 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoTable + sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE));
709 TotalSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
710 for (Index = 0; Index < ImageExeInfoTable->NumberOfImages; Index++) {
711 TotalSize += ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize);
712 ImageExeInfoItem = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) ImageExeInfoItem + ReadUnaligned32 ((UINT32 *) &ImageExeInfoItem->InfoSize));
713 }
714
715 return TotalSize;
716 }
717
718 /**
719 Create an Image Execution Information Table entry and add it to system configuration table.
720
721 @param[in] Action Describes the action taken by the firmware regarding this image.
722 @param[in] Name Input a null-terminated, user-friendly name.
723 @param[in] DevicePath Input device path pointer.
724 @param[in] Signature Input signature info in EFI_SIGNATURE_LIST data structure.
725 @param[in] SignatureSize Size of signature.
726
727 **/
728 VOID
729 AddImageExeInfo (
730 IN EFI_IMAGE_EXECUTION_ACTION Action,
731 IN CHAR16 *Name OPTIONAL,
732 IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
733 IN EFI_SIGNATURE_LIST *Signature OPTIONAL,
734 IN UINTN SignatureSize
735 )
736 {
737 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
738 EFI_IMAGE_EXECUTION_INFO_TABLE *NewImageExeInfoTable;
739 EFI_IMAGE_EXECUTION_INFO *ImageExeInfoEntry;
740 UINTN ImageExeInfoTableSize;
741 UINTN NewImageExeInfoEntrySize;
742 UINTN NameStringLen;
743 UINTN DevicePathSize;
744 CHAR16 *NameStr;
745
746 ImageExeInfoTable = NULL;
747 NewImageExeInfoTable = NULL;
748 ImageExeInfoEntry = NULL;
749 NameStringLen = 0;
750 NameStr = NULL;
751
752 if (DevicePath == NULL) {
753 return ;
754 }
755
756 if (Name != NULL) {
757 NameStringLen = StrSize (Name);
758 } else {
759 NameStringLen = sizeof (CHAR16);
760 }
761
762 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
763 if (ImageExeInfoTable != NULL) {
764 //
765 // The table has been found!
766 // We must enlarge the table to accomodate the new exe info entry.
767 //
768 ImageExeInfoTableSize = GetImageExeInfoTableSize (ImageExeInfoTable);
769 } else {
770 //
771 // Not Found!
772 // We should create a new table to append to the configuration table.
773 //
774 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
775 }
776
777 DevicePathSize = GetDevicePathSize (DevicePath);
778
779 //
780 // Signature size can be odd. Pad after signature to ensure next EXECUTION_INFO entry align
781 //
782 NewImageExeInfoEntrySize = sizeof (EFI_IMAGE_EXECUTION_INFO) + NameStringLen + DevicePathSize + SignatureSize;
783
784 NewImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize + NewImageExeInfoEntrySize);
785 if (NewImageExeInfoTable == NULL) {
786 return ;
787 }
788
789 if (ImageExeInfoTable != NULL) {
790 CopyMem (NewImageExeInfoTable, ImageExeInfoTable, ImageExeInfoTableSize);
791 } else {
792 NewImageExeInfoTable->NumberOfImages = 0;
793 }
794 NewImageExeInfoTable->NumberOfImages++;
795 ImageExeInfoEntry = (EFI_IMAGE_EXECUTION_INFO *) ((UINT8 *) NewImageExeInfoTable + ImageExeInfoTableSize);
796 //
797 // Update new item's information.
798 //
799 WriteUnaligned32 ((UINT32 *) ImageExeInfoEntry, Action);
800 WriteUnaligned32 ((UINT32 *) ((UINT8 *) ImageExeInfoEntry + sizeof (EFI_IMAGE_EXECUTION_ACTION)), (UINT32) NewImageExeInfoEntrySize);
801
802 NameStr = (CHAR16 *)(ImageExeInfoEntry + 1);
803 if (Name != NULL) {
804 CopyMem ((UINT8 *) NameStr, Name, NameStringLen);
805 } else {
806 ZeroMem ((UINT8 *) NameStr, sizeof (CHAR16));
807 }
808
809 CopyMem (
810 (UINT8 *) NameStr + NameStringLen,
811 DevicePath,
812 DevicePathSize
813 );
814 if (Signature != NULL) {
815 CopyMem (
816 (UINT8 *) NameStr + NameStringLen + DevicePathSize,
817 Signature,
818 SignatureSize
819 );
820 }
821 //
822 // Update/replace the image execution table.
823 //
824 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) NewImageExeInfoTable);
825
826 //
827 // Free Old table data!
828 //
829 if (ImageExeInfoTable != NULL) {
830 FreePool (ImageExeInfoTable);
831 }
832 }
833
834 /**
835 Check whether the hash of an given X.509 certificate is in forbidden database (DBX).
836
837 @param[in] Certificate Pointer to X.509 Certificate that is searched for.
838 @param[in] CertSize Size of X.509 Certificate.
839 @param[in] SignatureList Pointer to the Signature List in forbidden database.
840 @param[in] SignatureListSize Size of Signature List.
841 @param[out] RevocationTime Return the time that the certificate was revoked.
842
843 @return TRUE The certificate hash is found in the forbidden database.
844 @return FALSE The certificate hash is not found in the forbidden database.
845
846 **/
847 BOOLEAN
848 IsCertHashFoundInDatabase (
849 IN UINT8 *Certificate,
850 IN UINTN CertSize,
851 IN EFI_SIGNATURE_LIST *SignatureList,
852 IN UINTN SignatureListSize,
853 OUT EFI_TIME *RevocationTime
854 )
855 {
856 BOOLEAN IsFound;
857 BOOLEAN Status;
858 EFI_SIGNATURE_LIST *DbxList;
859 UINTN DbxSize;
860 EFI_SIGNATURE_DATA *CertHash;
861 UINTN CertHashCount;
862 UINTN Index;
863 UINT32 HashAlg;
864 VOID *HashCtx;
865 UINT8 CertDigest[MAX_DIGEST_SIZE];
866 UINT8 *DbxCertHash;
867 UINTN SiglistHeaderSize;
868 UINT8 *TBSCert;
869 UINTN TBSCertSize;
870
871 IsFound = FALSE;
872 DbxList = SignatureList;
873 DbxSize = SignatureListSize;
874 HashCtx = NULL;
875 HashAlg = HASHALG_MAX;
876
877 if ((RevocationTime == NULL) || (DbxList == NULL)) {
878 return FALSE;
879 }
880
881 //
882 // Retrieve the TBSCertificate from the X.509 Certificate.
883 //
884 if (!X509GetTBSCert (Certificate, CertSize, &TBSCert, &TBSCertSize)) {
885 return FALSE;
886 }
887
888 while ((DbxSize > 0) && (SignatureListSize >= DbxList->SignatureListSize)) {
889 //
890 // Determine Hash Algorithm of Certificate in the forbidden database.
891 //
892 if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha256Guid)) {
893 HashAlg = HASHALG_SHA256;
894 } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha384Guid)) {
895 HashAlg = HASHALG_SHA384;
896 } else if (CompareGuid (&DbxList->SignatureType, &gEfiCertX509Sha512Guid)) {
897 HashAlg = HASHALG_SHA512;
898 } else {
899 DbxSize -= DbxList->SignatureListSize;
900 DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize);
901 continue;
902 }
903
904 //
905 // Calculate the hash value of current TBSCertificate for comparision.
906 //
907 if (mHash[HashAlg].GetContextSize == NULL) {
908 goto Done;
909 }
910 ZeroMem (CertDigest, MAX_DIGEST_SIZE);
911 HashCtx = AllocatePool (mHash[HashAlg].GetContextSize ());
912 if (HashCtx == NULL) {
913 goto Done;
914 }
915 Status = mHash[HashAlg].HashInit (HashCtx);
916 if (!Status) {
917 goto Done;
918 }
919 Status = mHash[HashAlg].HashUpdate (HashCtx, TBSCert, TBSCertSize);
920 if (!Status) {
921 goto Done;
922 }
923 Status = mHash[HashAlg].HashFinal (HashCtx, CertDigest);
924 if (!Status) {
925 goto Done;
926 }
927
928 SiglistHeaderSize = sizeof (EFI_SIGNATURE_LIST) + DbxList->SignatureHeaderSize;
929 CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) DbxList + SiglistHeaderSize);
930 CertHashCount = (DbxList->SignatureListSize - SiglistHeaderSize) / DbxList->SignatureSize;
931 for (Index = 0; Index < CertHashCount; Index++) {
932 //
933 // Iterate each Signature Data Node within this CertList for verify.
934 //
935 DbxCertHash = CertHash->SignatureData;
936 if (CompareMem (DbxCertHash, CertDigest, mHash[HashAlg].DigestLength) == 0) {
937 //
938 // Hash of Certificate is found in forbidden database.
939 //
940 IsFound = TRUE;
941
942 //
943 // Return the revocation time.
944 //
945 CopyMem (RevocationTime, (EFI_TIME *)(DbxCertHash + mHash[HashAlg].DigestLength), sizeof (EFI_TIME));
946 goto Done;
947 }
948 CertHash = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertHash + DbxList->SignatureSize);
949 }
950
951 DbxSize -= DbxList->SignatureListSize;
952 DbxList = (EFI_SIGNATURE_LIST *) ((UINT8 *) DbxList + DbxList->SignatureListSize);
953 }
954
955 Done:
956 if (HashCtx != NULL) {
957 FreePool (HashCtx);
958 }
959
960 return IsFound;
961 }
962
963 /**
964 Check whether signature is in specified database.
965
966 @param[in] VariableName Name of database variable that is searched in.
967 @param[in] Signature Pointer to signature that is searched for.
968 @param[in] CertType Pointer to hash algrithom.
969 @param[in] SignatureSize Size of Signature.
970
971 @return TRUE Found the signature in the variable database.
972 @return FALSE Not found the signature in the variable database.
973
974 **/
975 BOOLEAN
976 IsSignatureFoundInDatabase (
977 IN CHAR16 *VariableName,
978 IN UINT8 *Signature,
979 IN EFI_GUID *CertType,
980 IN UINTN SignatureSize
981 )
982 {
983 EFI_STATUS Status;
984 EFI_SIGNATURE_LIST *CertList;
985 EFI_SIGNATURE_DATA *Cert;
986 UINTN DataSize;
987 UINT8 *Data;
988 UINTN Index;
989 UINTN CertCount;
990 BOOLEAN IsFound;
991
992 //
993 // Read signature database variable.
994 //
995 IsFound = FALSE;
996 Data = NULL;
997 DataSize = 0;
998 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
999 if (Status != EFI_BUFFER_TOO_SMALL) {
1000 return FALSE;
1001 }
1002
1003 Data = (UINT8 *) AllocateZeroPool (DataSize);
1004 if (Data == NULL) {
1005 return FALSE;
1006 }
1007
1008 Status = gRT->GetVariable (VariableName, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, Data);
1009 if (EFI_ERROR (Status)) {
1010 goto Done;
1011 }
1012 //
1013 // Enumerate all signature data in SigDB to check if executable's signature exists.
1014 //
1015 CertList = (EFI_SIGNATURE_LIST *) Data;
1016 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
1017 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1018 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1019 if ((CertList->SignatureSize == sizeof(EFI_SIGNATURE_DATA) - 1 + SignatureSize) && (CompareGuid(&CertList->SignatureType, CertType))) {
1020 for (Index = 0; Index < CertCount; Index++) {
1021 if (CompareMem (Cert->SignatureData, Signature, SignatureSize) == 0) {
1022 //
1023 // Find the signature in database.
1024 //
1025 IsFound = TRUE;
1026 SecureBootHook (VariableName, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, Cert);
1027 break;
1028 }
1029
1030 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1031 }
1032
1033 if (IsFound) {
1034 break;
1035 }
1036 }
1037
1038 DataSize -= CertList->SignatureListSize;
1039 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1040 }
1041
1042 Done:
1043 if (Data != NULL) {
1044 FreePool (Data);
1045 }
1046
1047 return IsFound;
1048 }
1049
1050 /**
1051 Check whether the timestamp is valid by comparing the signing time and the revocation time.
1052
1053 @param SigningTime A pointer to the signing time.
1054 @param RevocationTime A pointer to the revocation time.
1055
1056 @retval TRUE The SigningTime is not later than the RevocationTime.
1057 @retval FALSE The SigningTime is later than the RevocationTime.
1058
1059 **/
1060 BOOLEAN
1061 IsValidSignatureByTimestamp (
1062 IN EFI_TIME *SigningTime,
1063 IN EFI_TIME *RevocationTime
1064 )
1065 {
1066 if (SigningTime->Year != RevocationTime->Year) {
1067 return (BOOLEAN) (SigningTime->Year < RevocationTime->Year);
1068 } else if (SigningTime->Month != RevocationTime->Month) {
1069 return (BOOLEAN) (SigningTime->Month < RevocationTime->Month);
1070 } else if (SigningTime->Day != RevocationTime->Day) {
1071 return (BOOLEAN) (SigningTime->Day < RevocationTime->Day);
1072 } else if (SigningTime->Hour != RevocationTime->Hour) {
1073 return (BOOLEAN) (SigningTime->Hour < RevocationTime->Hour);
1074 } else if (SigningTime->Minute != RevocationTime->Minute) {
1075 return (BOOLEAN) (SigningTime->Minute < RevocationTime->Minute);
1076 }
1077
1078 return (BOOLEAN) (SigningTime->Second <= RevocationTime->Second);
1079 }
1080
1081 /**
1082 Check if the given time value is zero.
1083
1084 @param[in] Time Pointer of a time value.
1085
1086 @retval TRUE The Time is Zero.
1087 @retval FALSE The Time is not Zero.
1088
1089 **/
1090 BOOLEAN
1091 IsTimeZero (
1092 IN EFI_TIME *Time
1093 )
1094 {
1095 if ((Time->Year == 0) && (Time->Month == 0) && (Time->Day == 0) &&
1096 (Time->Hour == 0) && (Time->Minute == 0) && (Time->Second == 0)) {
1097 return TRUE;
1098 }
1099
1100 return FALSE;
1101 }
1102
1103 /**
1104 Check whether the timestamp signature is valid and the signing time is also earlier than
1105 the revocation time.
1106
1107 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1108 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1109 @param[in] RevocationTime The time that the certificate was revoked.
1110
1111 @retval TRUE Timestamp signature is valid and signing time is no later than the
1112 revocation time.
1113 @retval FALSE Timestamp signature is not valid or the signing time is later than the
1114 revocation time.
1115
1116 **/
1117 BOOLEAN
1118 PassTimestampCheck (
1119 IN UINT8 *AuthData,
1120 IN UINTN AuthDataSize,
1121 IN EFI_TIME *RevocationTime
1122 )
1123 {
1124 EFI_STATUS Status;
1125 BOOLEAN VerifyStatus;
1126 EFI_SIGNATURE_LIST *CertList;
1127 EFI_SIGNATURE_DATA *Cert;
1128 UINT8 *DbtData;
1129 UINTN DbtDataSize;
1130 UINT8 *RootCert;
1131 UINTN RootCertSize;
1132 UINTN Index;
1133 UINTN CertCount;
1134 EFI_TIME SigningTime;
1135
1136 //
1137 // Variable Initialization
1138 //
1139 VerifyStatus = FALSE;
1140 DbtData = NULL;
1141 CertList = NULL;
1142 Cert = NULL;
1143 RootCert = NULL;
1144 RootCertSize = 0;
1145
1146 //
1147 // If RevocationTime is zero, the certificate shall be considered to always be revoked.
1148 //
1149 if (IsTimeZero (RevocationTime)) {
1150 return FALSE;
1151 }
1152
1153 //
1154 // RevocationTime is non-zero, the certificate should be considered to be revoked from that time and onwards.
1155 // Using the dbt to get the trusted TSA certificates.
1156 //
1157 DbtDataSize = 0;
1158 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, NULL);
1159 if (Status != EFI_BUFFER_TOO_SMALL) {
1160 goto Done;
1161 }
1162 DbtData = (UINT8 *) AllocateZeroPool (DbtDataSize);
1163 if (DbtData == NULL) {
1164 goto Done;
1165 }
1166 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, NULL, &DbtDataSize, (VOID *) DbtData);
1167 if (EFI_ERROR (Status)) {
1168 goto Done;
1169 }
1170
1171 CertList = (EFI_SIGNATURE_LIST *) DbtData;
1172 while ((DbtDataSize > 0) && (DbtDataSize >= CertList->SignatureListSize)) {
1173 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1174 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1175 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1176 for (Index = 0; Index < CertCount; Index++) {
1177 //
1178 // Iterate each Signature Data Node within this CertList for verify.
1179 //
1180 RootCert = Cert->SignatureData;
1181 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1182 //
1183 // Get the signing time if the timestamp signature is valid.
1184 //
1185 if (ImageTimestampVerify (AuthData, AuthDataSize, RootCert, RootCertSize, &SigningTime)) {
1186 //
1187 // The signer signature is valid only when the signing time is earlier than revocation time.
1188 //
1189 if (IsValidSignatureByTimestamp (&SigningTime, RevocationTime)) {
1190 VerifyStatus = TRUE;
1191 goto Done;
1192 }
1193 }
1194 Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
1195 }
1196 }
1197 DbtDataSize -= CertList->SignatureListSize;
1198 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1199 }
1200
1201 Done:
1202 if (DbtData != NULL) {
1203 FreePool (DbtData);
1204 }
1205
1206 return VerifyStatus;
1207 }
1208
1209 /**
1210 Check whether the image signature is forbidden by the forbidden database (dbx).
1211 The image is forbidden to load if any certificates for signing are revoked before signing time.
1212
1213 @param[in] AuthData Pointer to the Authenticode signature retrieved from the signed image.
1214 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1215
1216 @retval TRUE Image is forbidden by dbx.
1217 @retval FALSE Image is not forbidden by dbx.
1218
1219 **/
1220 BOOLEAN
1221 IsForbiddenByDbx (
1222 IN UINT8 *AuthData,
1223 IN UINTN AuthDataSize
1224 )
1225 {
1226 EFI_STATUS Status;
1227 BOOLEAN IsForbidden;
1228 UINT8 *Data;
1229 UINTN DataSize;
1230 EFI_SIGNATURE_LIST *CertList;
1231 UINTN CertListSize;
1232 EFI_SIGNATURE_DATA *CertData;
1233 UINT8 *RootCert;
1234 UINTN RootCertSize;
1235 UINTN CertCount;
1236 UINTN Index;
1237 UINT8 *CertBuffer;
1238 UINTN BufferLength;
1239 UINT8 *TrustedCert;
1240 UINTN TrustedCertLength;
1241 UINT8 CertNumber;
1242 UINT8 *CertPtr;
1243 UINT8 *Cert;
1244 UINTN CertSize;
1245 EFI_TIME RevocationTime;
1246 //
1247 // Variable Initialization
1248 //
1249 IsForbidden = FALSE;
1250 Data = NULL;
1251 CertList = NULL;
1252 CertData = NULL;
1253 RootCert = NULL;
1254 RootCertSize = 0;
1255 Cert = NULL;
1256 CertBuffer = NULL;
1257 BufferLength = 0;
1258 TrustedCert = NULL;
1259 TrustedCertLength = 0;
1260
1261 //
1262 // The image will not be forbidden if dbx can't be got.
1263 //
1264 DataSize = 0;
1265 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
1266 if (Status != EFI_BUFFER_TOO_SMALL) {
1267 return IsForbidden;
1268 }
1269 Data = (UINT8 *) AllocateZeroPool (DataSize);
1270 if (Data == NULL) {
1271 return IsForbidden;
1272 }
1273
1274 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
1275 if (EFI_ERROR (Status)) {
1276 return IsForbidden;
1277 }
1278
1279 //
1280 // Verify image signature with RAW X509 certificates in DBX database.
1281 // If passed, the image will be forbidden.
1282 //
1283 CertList = (EFI_SIGNATURE_LIST *) Data;
1284 CertListSize = DataSize;
1285 while ((CertListSize > 0) && (CertListSize >= CertList->SignatureListSize)) {
1286 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1287 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1288 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1289
1290 for (Index = 0; Index < CertCount; Index++) {
1291 //
1292 // Iterate each Signature Data Node within this CertList for verify.
1293 //
1294 RootCert = CertData->SignatureData;
1295 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1296
1297 //
1298 // Call AuthenticodeVerify library to Verify Authenticode struct.
1299 //
1300 IsForbidden = AuthenticodeVerify (
1301 AuthData,
1302 AuthDataSize,
1303 RootCert,
1304 RootCertSize,
1305 mImageDigest,
1306 mImageDigestSize
1307 );
1308 if (IsForbidden) {
1309 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData);
1310 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is forbidden by DBX.\n"));
1311 goto Done;
1312 }
1313
1314 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
1315 }
1316 }
1317
1318 CertListSize -= CertList->SignatureListSize;
1319 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1320 }
1321
1322 //
1323 // Check X.509 Certificate Hash & Possible Timestamp.
1324 //
1325
1326 //
1327 // Retrieve the certificate stack from AuthData
1328 // The output CertStack format will be:
1329 // UINT8 CertNumber;
1330 // UINT32 Cert1Length;
1331 // UINT8 Cert1[];
1332 // UINT32 Cert2Length;
1333 // UINT8 Cert2[];
1334 // ...
1335 // UINT32 CertnLength;
1336 // UINT8 Certn[];
1337 //
1338 Pkcs7GetSigners (AuthData, AuthDataSize, &CertBuffer, &BufferLength, &TrustedCert, &TrustedCertLength);
1339 if ((BufferLength == 0) || (CertBuffer == NULL)) {
1340 IsForbidden = TRUE;
1341 goto Done;
1342 }
1343
1344 //
1345 // Check if any hash of certificates embedded in AuthData is in the forbidden database.
1346 //
1347 CertNumber = (UINT8) (*CertBuffer);
1348 CertPtr = CertBuffer + 1;
1349 for (Index = 0; Index < CertNumber; Index++) {
1350 CertSize = (UINTN) ReadUnaligned32 ((UINT32 *)CertPtr);
1351 Cert = (UINT8 *)CertPtr + sizeof (UINT32);
1352 //
1353 // Advance CertPtr to the next cert in image signer's cert list
1354 //
1355 CertPtr = CertPtr + sizeof (UINT32) + CertSize;
1356
1357 if (IsCertHashFoundInDatabase (Cert, CertSize, (EFI_SIGNATURE_LIST *)Data, DataSize, &RevocationTime)) {
1358 //
1359 // Check the timestamp signature and signing time to determine if the image can be trusted.
1360 //
1361 IsForbidden = TRUE;
1362 if (PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime)) {
1363 IsForbidden = FALSE;
1364 //
1365 // Pass DBT check. Continue to check other certs in image signer's cert list against DBX, DBT
1366 //
1367 continue;
1368 }
1369 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature failed the timestamp check.\n"));
1370 goto Done;
1371 }
1372
1373 }
1374
1375 Done:
1376 if (Data != NULL) {
1377 FreePool (Data);
1378 }
1379
1380 Pkcs7FreeSigners (CertBuffer);
1381 Pkcs7FreeSigners (TrustedCert);
1382
1383 return IsForbidden;
1384 }
1385
1386
1387 /**
1388 Check whether the image signature can be verified by the trusted certificates in DB database.
1389
1390 @param[in] AuthData Pointer to the Authenticode signature retrieved from signed image.
1391 @param[in] AuthDataSize Size of the Authenticode signature in bytes.
1392
1393 @retval TRUE Image passed verification using certificate in db.
1394 @retval FALSE Image didn't pass verification using certificate in db.
1395
1396 **/
1397 BOOLEAN
1398 IsAllowedByDb (
1399 IN UINT8 *AuthData,
1400 IN UINTN AuthDataSize
1401 )
1402 {
1403 EFI_STATUS Status;
1404 BOOLEAN VerifyStatus;
1405 EFI_SIGNATURE_LIST *CertList;
1406 EFI_SIGNATURE_DATA *CertData;
1407 UINTN DataSize;
1408 UINT8 *Data;
1409 UINT8 *RootCert;
1410 UINTN RootCertSize;
1411 UINTN Index;
1412 UINTN CertCount;
1413 UINTN DbxDataSize;
1414 UINT8 *DbxData;
1415 EFI_TIME RevocationTime;
1416
1417 Data = NULL;
1418 CertList = NULL;
1419 CertData = NULL;
1420 RootCert = NULL;
1421 DbxData = NULL;
1422 RootCertSize = 0;
1423 VerifyStatus = FALSE;
1424
1425 DataSize = 0;
1426 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, NULL);
1427 if (Status == EFI_BUFFER_TOO_SMALL) {
1428 Data = (UINT8 *) AllocateZeroPool (DataSize);
1429 if (Data == NULL) {
1430 return VerifyStatus;
1431 }
1432
1433 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, NULL, &DataSize, (VOID *) Data);
1434 if (EFI_ERROR (Status)) {
1435 goto Done;
1436 }
1437
1438 //
1439 // Find X509 certificate in Signature List to verify the signature in pkcs7 signed data.
1440 //
1441 CertList = (EFI_SIGNATURE_LIST *) Data;
1442 while ((DataSize > 0) && (DataSize >= CertList->SignatureListSize)) {
1443 if (CompareGuid (&CertList->SignatureType, &gEfiCertX509Guid)) {
1444 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
1445 CertCount = (CertList->SignatureListSize - sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
1446
1447 for (Index = 0; Index < CertCount; Index++) {
1448 //
1449 // Iterate each Signature Data Node within this CertList for verify.
1450 //
1451 RootCert = CertData->SignatureData;
1452 RootCertSize = CertList->SignatureSize - sizeof (EFI_GUID);
1453
1454 //
1455 // Call AuthenticodeVerify library to Verify Authenticode struct.
1456 //
1457 VerifyStatus = AuthenticodeVerify (
1458 AuthData,
1459 AuthDataSize,
1460 RootCert,
1461 RootCertSize,
1462 mImageDigest,
1463 mImageDigestSize
1464 );
1465 if (VerifyStatus) {
1466 //
1467 // Here We still need to check if this RootCert's Hash is revoked
1468 //
1469 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, NULL);
1470 if (Status == EFI_BUFFER_TOO_SMALL) {
1471 goto Done;
1472 }
1473 DbxData = (UINT8 *) AllocateZeroPool (DbxDataSize);
1474 if (DbxData == NULL) {
1475 goto Done;
1476 }
1477
1478 Status = gRT->GetVariable (EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid, NULL, &DbxDataSize, (VOID *) DbxData);
1479 if (EFI_ERROR (Status)) {
1480 goto Done;
1481 }
1482
1483 if (IsCertHashFoundInDatabase (RootCert, RootCertSize, (EFI_SIGNATURE_LIST *)DbxData, DbxDataSize, &RevocationTime)) {
1484 //
1485 // Check the timestamp signature and signing time to determine if the RootCert can be trusted.
1486 //
1487 VerifyStatus = PassTimestampCheck (AuthData, AuthDataSize, &RevocationTime);
1488 if (!VerifyStatus) {
1489 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed and signature is accepted by DB, but its root cert failed the timestamp check.\n"));
1490 }
1491 }
1492
1493 goto Done;
1494 }
1495
1496 CertData = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertData + CertList->SignatureSize);
1497 }
1498 }
1499
1500 DataSize -= CertList->SignatureListSize;
1501 CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
1502 }
1503 }
1504
1505 Done:
1506
1507 if (VerifyStatus) {
1508 SecureBootHook (EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid, CertList->SignatureSize, CertData);
1509 }
1510
1511 if (Data != NULL) {
1512 FreePool (Data);
1513 }
1514 if (DbxData != NULL) {
1515 FreePool (DbxData);
1516 }
1517
1518 return VerifyStatus;
1519 }
1520
1521 /**
1522 Provide verification service for signed images, which include both signature validation
1523 and platform policy control. For signature types, both UEFI WIN_CERTIFICATE_UEFI_GUID and
1524 MSFT Authenticode type signatures are supported.
1525
1526 In this implementation, only verify external executables when in USER MODE.
1527 Executables from FV is bypass, so pass in AuthenticationStatus is ignored.
1528
1529 The image verification policy is:
1530 If the image is signed,
1531 At least one valid signature or at least one hash value of the image must match a record
1532 in the security database "db", and no valid signature nor any hash value of the image may
1533 be reflected in the security database "dbx".
1534 Otherwise, the image is not signed,
1535 The SHA256 hash value of the image must match a record in the security database "db", and
1536 not be reflected in the security data base "dbx".
1537
1538 Caution: This function may receive untrusted input.
1539 PE/COFF image is external input, so this function will validate its data structure
1540 within this image buffer before use.
1541
1542 @param[in] AuthenticationStatus
1543 This is the authentication status returned from the security
1544 measurement services for the input file.
1545 @param[in] File This is a pointer to the device path of the file that is
1546 being dispatched. This will optionally be used for logging.
1547 @param[in] FileBuffer File buffer matches the input file device path.
1548 @param[in] FileSize Size of File buffer matches the input file device path.
1549 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
1550
1551 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
1552 FileBuffer did authenticate, and the platform policy dictates
1553 that the DXE Foundation may use the file.
1554 @retval EFI_SUCCESS The device path specified by NULL device path DevicePath
1555 and non-NULL FileBuffer did authenticate, and the platform
1556 policy dictates that the DXE Foundation may execute the image in
1557 FileBuffer.
1558 @retval EFI_OUT_RESOURCE Fail to allocate memory.
1559 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
1560 the platform policy dictates that File should be placed
1561 in the untrusted state. The image has been added to the file
1562 execution table.
1563 @retval EFI_ACCESS_DENIED The file specified by File and FileBuffer did not
1564 authenticate, and the platform policy dictates that the DXE
1565 Foundation many not use File.
1566
1567 **/
1568 EFI_STATUS
1569 EFIAPI
1570 DxeImageVerificationHandler (
1571 IN UINT32 AuthenticationStatus,
1572 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
1573 IN VOID *FileBuffer,
1574 IN UINTN FileSize,
1575 IN BOOLEAN BootPolicy
1576 )
1577 {
1578 EFI_STATUS Status;
1579 UINT16 Magic;
1580 EFI_IMAGE_DOS_HEADER *DosHdr;
1581 EFI_STATUS VerifyStatus;
1582 EFI_SIGNATURE_LIST *SignatureList;
1583 UINTN SignatureListSize;
1584 EFI_SIGNATURE_DATA *Signature;
1585 EFI_IMAGE_EXECUTION_ACTION Action;
1586 WIN_CERTIFICATE *WinCertificate;
1587 UINT32 Policy;
1588 UINT8 *SecureBoot;
1589 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1590 UINT32 NumberOfRvaAndSizes;
1591 WIN_CERTIFICATE_EFI_PKCS *PkcsCertData;
1592 WIN_CERTIFICATE_UEFI_GUID *WinCertUefiGuid;
1593 UINT8 *AuthData;
1594 UINTN AuthDataSize;
1595 EFI_IMAGE_DATA_DIRECTORY *SecDataDir;
1596 UINT32 OffSet;
1597 CHAR16 *NameStr;
1598
1599 SignatureList = NULL;
1600 SignatureListSize = 0;
1601 WinCertificate = NULL;
1602 SecDataDir = NULL;
1603 PkcsCertData = NULL;
1604 Action = EFI_IMAGE_EXECUTION_AUTH_UNTESTED;
1605 Status = EFI_ACCESS_DENIED;
1606 VerifyStatus = EFI_ACCESS_DENIED;
1607
1608
1609 //
1610 // Check the image type and get policy setting.
1611 //
1612 switch (GetImageType (File)) {
1613
1614 case IMAGE_FROM_FV:
1615 Policy = ALWAYS_EXECUTE;
1616 break;
1617
1618 case IMAGE_FROM_OPTION_ROM:
1619 Policy = PcdGet32 (PcdOptionRomImageVerificationPolicy);
1620 break;
1621
1622 case IMAGE_FROM_REMOVABLE_MEDIA:
1623 Policy = PcdGet32 (PcdRemovableMediaImageVerificationPolicy);
1624 break;
1625
1626 case IMAGE_FROM_FIXED_MEDIA:
1627 Policy = PcdGet32 (PcdFixedMediaImageVerificationPolicy);
1628 break;
1629
1630 default:
1631 Policy = DENY_EXECUTE_ON_SECURITY_VIOLATION;
1632 break;
1633 }
1634 //
1635 // If policy is always/never execute, return directly.
1636 //
1637 if (Policy == ALWAYS_EXECUTE) {
1638 return EFI_SUCCESS;
1639 } else if (Policy == NEVER_EXECUTE) {
1640 return EFI_ACCESS_DENIED;
1641 }
1642
1643 //
1644 // The policy QUERY_USER_ON_SECURITY_VIOLATION and ALLOW_EXECUTE_ON_SECURITY_VIOLATION
1645 // violates the UEFI spec and has been removed.
1646 //
1647 ASSERT (Policy != QUERY_USER_ON_SECURITY_VIOLATION && Policy != ALLOW_EXECUTE_ON_SECURITY_VIOLATION);
1648 if (Policy == QUERY_USER_ON_SECURITY_VIOLATION || Policy == ALLOW_EXECUTE_ON_SECURITY_VIOLATION) {
1649 CpuDeadLoop ();
1650 }
1651
1652 GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID**)&SecureBoot, NULL);
1653 //
1654 // Skip verification if SecureBoot variable doesn't exist.
1655 //
1656 if (SecureBoot == NULL) {
1657 return EFI_SUCCESS;
1658 }
1659
1660 //
1661 // Skip verification if SecureBoot is disabled but not AuditMode
1662 //
1663 if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) {
1664 FreePool (SecureBoot);
1665 return EFI_SUCCESS;
1666 }
1667 FreePool (SecureBoot);
1668
1669 //
1670 // Read the Dos header.
1671 //
1672 if (FileBuffer == NULL) {
1673 return EFI_INVALID_PARAMETER;
1674 }
1675
1676 mImageBase = (UINT8 *) FileBuffer;
1677 mImageSize = FileSize;
1678
1679 ZeroMem (&ImageContext, sizeof (ImageContext));
1680 ImageContext.Handle = (VOID *) FileBuffer;
1681 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeImageVerificationLibImageRead;
1682
1683 //
1684 // Get information about the image being loaded
1685 //
1686 Status = PeCoffLoaderGetImageInfo (&ImageContext);
1687 if (EFI_ERROR (Status)) {
1688 //
1689 // The information can't be got from the invalid PeImage
1690 //
1691 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: PeImage invalid. Cannot retrieve image information.\n"));
1692 goto Done;
1693 }
1694
1695 Status = EFI_ACCESS_DENIED;
1696
1697 DosHdr = (EFI_IMAGE_DOS_HEADER *) mImageBase;
1698 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
1699 //
1700 // DOS image header is present,
1701 // so read the PE header after the DOS image header.
1702 //
1703 mPeCoffHeaderOffset = DosHdr->e_lfanew;
1704 } else {
1705 mPeCoffHeaderOffset = 0;
1706 }
1707 //
1708 // Check PE/COFF image.
1709 //
1710 mNtHeader.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) (mImageBase + mPeCoffHeaderOffset);
1711 if (mNtHeader.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
1712 //
1713 // It is not a valid Pe/Coff file.
1714 //
1715 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Not a valid PE/COFF image.\n"));
1716 goto Done;
1717 }
1718
1719 if (mNtHeader.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && mNtHeader.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1720 //
1721 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
1722 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
1723 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
1724 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
1725 //
1726 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1727 } else {
1728 //
1729 // Get the magic value from the PE/COFF Optional Header
1730 //
1731 Magic = mNtHeader.Pe32->OptionalHeader.Magic;
1732 }
1733
1734 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
1735 //
1736 // Use PE32 offset.
1737 //
1738 NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
1739 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1740 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1741 }
1742 } else {
1743 //
1744 // Use PE32+ offset.
1745 //
1746 NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
1747 if (NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
1748 SecDataDir = (EFI_IMAGE_DATA_DIRECTORY *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
1749 }
1750 }
1751
1752 //
1753 // Start Image Validation.
1754 //
1755 if (SecDataDir == NULL || SecDataDir->Size == 0) {
1756 //
1757 // This image is not signed. The SHA256 hash value of the image must match a record in the security database "db",
1758 // and not be reflected in the security data base "dbx".
1759 //
1760 if (!HashPeImage (HASHALG_SHA256)) {
1761 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Failed to hash this image using %s.\n", mHashTypeStr));
1762 goto Done;
1763 }
1764
1765 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1766 //
1767 // Image Hash is in forbidden database (DBX).
1768 //
1769 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is forbidden by DBX.\n", mHashTypeStr));
1770 goto Done;
1771 }
1772
1773 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1774 //
1775 // Image Hash is in allowed database (DB).
1776 //
1777 return EFI_SUCCESS;
1778 }
1779
1780 //
1781 // Image Hash is not found in both forbidden and allowed database.
1782 //
1783 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is not signed and %s hash of image is not found in DB/DBX.\n", mHashTypeStr));
1784 goto Done;
1785 }
1786
1787 //
1788 // Verify the signature of the image, multiple signatures are allowed as per PE/COFF Section 4.7
1789 // "Attribute Certificate Table".
1790 // The first certificate starts at offset (SecDataDir->VirtualAddress) from the start of the file.
1791 //
1792 for (OffSet = SecDataDir->VirtualAddress;
1793 OffSet < (SecDataDir->VirtualAddress + SecDataDir->Size);
1794 OffSet += (WinCertificate->dwLength + ALIGN_SIZE (WinCertificate->dwLength))) {
1795 WinCertificate = (WIN_CERTIFICATE *) (mImageBase + OffSet);
1796 if ((SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) <= sizeof (WIN_CERTIFICATE) ||
1797 (SecDataDir->VirtualAddress + SecDataDir->Size - OffSet) < WinCertificate->dwLength) {
1798 break;
1799 }
1800
1801 //
1802 // Verify the image's Authenticode signature, only DER-encoded PKCS#7 signed data is supported.
1803 //
1804 if (WinCertificate->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
1805 //
1806 // The certificate is formatted as WIN_CERTIFICATE_EFI_PKCS which is described in the
1807 // Authenticode specification.
1808 //
1809 PkcsCertData = (WIN_CERTIFICATE_EFI_PKCS *) WinCertificate;
1810 if (PkcsCertData->Hdr.dwLength <= sizeof (PkcsCertData->Hdr)) {
1811 break;
1812 }
1813 AuthData = PkcsCertData->CertData;
1814 AuthDataSize = PkcsCertData->Hdr.dwLength - sizeof(PkcsCertData->Hdr);
1815 } else if (WinCertificate->wCertificateType == WIN_CERT_TYPE_EFI_GUID) {
1816 //
1817 // The certificate is formatted as WIN_CERTIFICATE_UEFI_GUID which is described in UEFI Spec.
1818 //
1819 WinCertUefiGuid = (WIN_CERTIFICATE_UEFI_GUID *) WinCertificate;
1820 if (WinCertUefiGuid->Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) {
1821 break;
1822 }
1823 if (!CompareGuid (&WinCertUefiGuid->CertType, &gEfiCertPkcs7Guid)) {
1824 continue;
1825 }
1826 AuthData = WinCertUefiGuid->CertData;
1827 AuthDataSize = WinCertUefiGuid->Hdr.dwLength - OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData);
1828 } else {
1829 if (WinCertificate->dwLength < sizeof (WIN_CERTIFICATE)) {
1830 break;
1831 }
1832 continue;
1833 }
1834
1835 Status = HashPeImageByType (AuthData, AuthDataSize);
1836 if (EFI_ERROR (Status)) {
1837 continue;
1838 }
1839
1840 //
1841 // Check the digital signature against the revoked certificate in forbidden database (dbx).
1842 //
1843 if (IsForbiddenByDbx (AuthData, AuthDataSize)) {
1844 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED;
1845 VerifyStatus = EFI_ACCESS_DENIED;
1846 break;
1847 }
1848
1849 //
1850 // Check the digital signature against the valid certificate in allowed database (db).
1851 //
1852 if (EFI_ERROR (VerifyStatus)) {
1853 if (IsAllowedByDb (AuthData, AuthDataSize)) {
1854 VerifyStatus = EFI_SUCCESS;
1855 }
1856 }
1857
1858 //
1859 // Check the image's hash value.
1860 //
1861 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE1, mImageDigest, &mCertType, mImageDigestSize)) {
1862 Action = EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND;
1863 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but %s hash of image is found in DBX.\n", mHashTypeStr));
1864 VerifyStatus = EFI_ACCESS_DENIED;
1865 break;
1866 } else if (EFI_ERROR (VerifyStatus)) {
1867 if (IsSignatureFoundInDatabase (EFI_IMAGE_SECURITY_DATABASE, mImageDigest, &mCertType, mImageDigestSize)) {
1868 VerifyStatus = EFI_SUCCESS;
1869 } else {
1870 DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is not allowed by DB and %s hash of image is not found in DB/DBX.\n", mHashTypeStr));
1871 }
1872 }
1873 }
1874
1875 if (OffSet != (SecDataDir->VirtualAddress + SecDataDir->Size)) {
1876 //
1877 // The Size in Certificate Table or the attribute certicate table is corrupted.
1878 //
1879 VerifyStatus = EFI_ACCESS_DENIED;
1880 }
1881
1882 if (!EFI_ERROR (VerifyStatus)) {
1883 return EFI_SUCCESS;
1884 } else {
1885 Status = EFI_ACCESS_DENIED;
1886 if (Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FAILED || Action == EFI_IMAGE_EXECUTION_AUTH_SIG_FOUND) {
1887 //
1888 // Get image hash value as executable's signature.
1889 //
1890 SignatureListSize = sizeof (EFI_SIGNATURE_LIST) + sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize;
1891 SignatureList = (EFI_SIGNATURE_LIST *) AllocateZeroPool (SignatureListSize);
1892 if (SignatureList == NULL) {
1893 Status = EFI_OUT_OF_RESOURCES;
1894 goto Done;
1895 }
1896 SignatureList->SignatureHeaderSize = 0;
1897 SignatureList->SignatureListSize = (UINT32) SignatureListSize;
1898 SignatureList->SignatureSize = (UINT32) (sizeof (EFI_SIGNATURE_DATA) - 1 + mImageDigestSize);
1899 CopyMem (&SignatureList->SignatureType, &mCertType, sizeof (EFI_GUID));
1900 Signature = (EFI_SIGNATURE_DATA *) ((UINT8 *) SignatureList + sizeof (EFI_SIGNATURE_LIST));
1901 CopyMem (Signature->SignatureData, mImageDigest, mImageDigestSize);
1902 }
1903 }
1904
1905 Done:
1906 if (Status != EFI_SUCCESS) {
1907 //
1908 // Policy decides to defer or reject the image; add its information in image executable information table.
1909 //
1910 NameStr = ConvertDevicePathToText (File, FALSE, TRUE);
1911 AddImageExeInfo (Action, NameStr, File, SignatureList, SignatureListSize);
1912 if (NameStr != NULL) {
1913 DEBUG((EFI_D_INFO, "The image doesn't pass verification: %s\n", NameStr));
1914 FreePool(NameStr);
1915 }
1916 Status = EFI_SECURITY_VIOLATION;
1917 }
1918
1919 if (SignatureList != NULL) {
1920 FreePool (SignatureList);
1921 }
1922
1923 return Status;
1924 }
1925
1926 /**
1927 On Ready To Boot Services Event notification handler.
1928
1929 Add the image execution information table if it is not in system configuration table.
1930
1931 @param[in] Event Event whose notification function is being invoked
1932 @param[in] Context Pointer to the notification function's context
1933
1934 **/
1935 VOID
1936 EFIAPI
1937 OnReadyToBoot (
1938 IN EFI_EVENT Event,
1939 IN VOID *Context
1940 )
1941 {
1942 EFI_IMAGE_EXECUTION_INFO_TABLE *ImageExeInfoTable;
1943 UINTN ImageExeInfoTableSize;
1944
1945 EfiGetSystemConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID **) &ImageExeInfoTable);
1946 if (ImageExeInfoTable != NULL) {
1947 return;
1948 }
1949
1950 ImageExeInfoTableSize = sizeof (EFI_IMAGE_EXECUTION_INFO_TABLE);
1951 ImageExeInfoTable = (EFI_IMAGE_EXECUTION_INFO_TABLE *) AllocateRuntimePool (ImageExeInfoTableSize);
1952 if (ImageExeInfoTable == NULL) {
1953 return ;
1954 }
1955
1956 ImageExeInfoTable->NumberOfImages = 0;
1957 gBS->InstallConfigurationTable (&gEfiImageSecurityDatabaseGuid, (VOID *) ImageExeInfoTable);
1958
1959 }
1960
1961 /**
1962 Register security measurement handler.
1963
1964 @param ImageHandle ImageHandle of the loaded driver.
1965 @param SystemTable Pointer to the EFI System Table.
1966
1967 @retval EFI_SUCCESS The handlers were registered successfully.
1968 **/
1969 EFI_STATUS
1970 EFIAPI
1971 DxeImageVerificationLibConstructor (
1972 IN EFI_HANDLE ImageHandle,
1973 IN EFI_SYSTEM_TABLE *SystemTable
1974 )
1975 {
1976 EFI_EVENT Event;
1977
1978 //
1979 // Register the event to publish the image execution table.
1980 //
1981 EfiCreateEventReadyToBootEx (
1982 TPL_CALLBACK,
1983 OnReadyToBoot,
1984 NULL,
1985 &Event
1986 );
1987
1988 return RegisterSecurity2Handler (
1989 DxeImageVerificationHandler,
1990 EFI_AUTH_OPERATION_VERIFY_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
1991 );
1992 }