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