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