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