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