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