Rename Trusted Hob to Measured FV hob and add Guided Hob layout structure
[mirror_edk2.git] / SecurityPkg / Library / DxeTpmMeasureBootLib / DxeTpmMeasureBootLib.c
CommitLineData
0c18794e 1/** @file\r
2 The library instance provides security service of TPM measure boot. \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 and GPT partition.\r
6 This external input must be validated carefully to avoid security issue like\r
7 buffer overflow, integer overflow.\r
8\r
9 DxeTpmMeasureBootLibImageRead() function will make sure the PE/COFF image content\r
10 read is within the image buffer.\r
11\r
12 TcgMeasurePeImage() function will accept untrusted PE/COFF image and validate its\r
13 data structure within this image buffer before use.\r
14\r
15 TcgMeasureGptTable() function will receive untrusted GPT partition table, and parse\r
16 partition data carefully.\r
17\r
65cc57fc 18Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>\r
0c18794e 19This program and the accompanying materials \r
20are licensed and made available under the terms and conditions of the BSD License \r
21which accompanies this distribution. The full text of the license may be found at \r
22http://opensource.org/licenses/bsd-license.php\r
23\r
24THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, \r
25WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
26\r
27**/\r
28\r
29#include <PiDxe.h>\r
30\r
31#include <Protocol/TcgService.h>\r
0c18794e 32#include <Protocol/BlockIo.h>\r
33#include <Protocol/DiskIo.h>\r
34#include <Protocol/DevicePathToText.h>\r
2aadc920 35#include <Protocol/FirmwareVolumeBlock.h>\r
36\r
0758c830 37#include <Guid/MeasuredFvHob.h>\r
0c18794e 38\r
39#include <Library/BaseLib.h>\r
40#include <Library/DebugLib.h>\r
41#include <Library/BaseMemoryLib.h>\r
42#include <Library/MemoryAllocationLib.h>\r
43#include <Library/DevicePathLib.h>\r
44#include <Library/UefiBootServicesTableLib.h>\r
45#include <Library/BaseCryptLib.h>\r
46#include <Library/PeCoffLib.h>\r
47#include <Library/SecurityManagementLib.h>\r
2aadc920 48#include <Library/HobLib.h>\r
0c18794e 49\r
50//\r
51// Flag to check GPT partition. It only need be measured once.\r
52//\r
53BOOLEAN mMeasureGptTableFlag = FALSE;\r
54EFI_GUID mZeroGuid = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};\r
55UINTN mMeasureGptCount = 0;\r
28186d45
ED
56VOID *mFileBuffer;\r
57UINTN mImageSize;\r
2aadc920 58//\r
59// Measured FV handle cache\r
60//\r
61EFI_HANDLE mCacheMeasuredHandle = NULL;\r
0758c830 62MEASURED_HOB_DATA *mMeasuredHobData = NULL;\r
0c18794e 63\r
64/**\r
65 Reads contents of a PE/COFF image in memory buffer.\r
66\r
dc204d5a
JY
67 Caution: This function may receive untrusted input.\r
68 PE/COFF image is external input, so this function will make sure the PE/COFF image content\r
69 read is within the image buffer.\r
70\r
0c18794e 71 @param FileHandle Pointer to the file handle to read the PE/COFF image.\r
72 @param FileOffset Offset into the PE/COFF image to begin the read operation.\r
73 @param ReadSize On input, the size in bytes of the requested read operation. \r
74 On output, the number of bytes actually read.\r
75 @param Buffer Output buffer that contains the data read from the PE/COFF image.\r
76 \r
77 @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size \r
78**/\r
79EFI_STATUS\r
80EFIAPI\r
e0192326 81DxeTpmMeasureBootLibImageRead (\r
0c18794e 82 IN VOID *FileHandle,\r
83 IN UINTN FileOffset,\r
84 IN OUT UINTN *ReadSize,\r
85 OUT VOID *Buffer\r
86 )\r
87{\r
28186d45
ED
88 UINTN EndPosition;\r
89\r
90 if (FileHandle == NULL || ReadSize == NULL || Buffer == NULL) {\r
91 return EFI_INVALID_PARAMETER;\r
92 }\r
93\r
94 if (MAX_ADDRESS - FileOffset < *ReadSize) {\r
95 return EFI_INVALID_PARAMETER;\r
96 }\r
97\r
98 EndPosition = FileOffset + *ReadSize;\r
99 if (EndPosition > mImageSize) {\r
100 *ReadSize = (UINT32)(mImageSize - FileOffset);\r
101 }\r
102\r
103 if (FileOffset >= mImageSize) {\r
104 *ReadSize = 0;\r
105 }\r
106\r
0c18794e 107 CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);\r
28186d45 108\r
0c18794e 109 return EFI_SUCCESS;\r
110}\r
111\r
112/**\r
113 Measure GPT table data into TPM log.\r
114\r
dc204d5a
JY
115 Caution: This function may receive untrusted input.\r
116 The GPT partition table is external input, so this function should parse partition data carefully.\r
117\r
0c18794e 118 @param TcgProtocol Pointer to the located TCG protocol instance.\r
119 @param GptHandle Handle that GPT partition was installed.\r
120\r
121 @retval EFI_SUCCESS Successfully measure GPT table.\r
122 @retval EFI_UNSUPPORTED Not support GPT table on the given handle.\r
123 @retval EFI_DEVICE_ERROR Can't get GPT table because device error.\r
124 @retval EFI_OUT_OF_RESOURCES No enough resource to measure GPT table.\r
125 @retval other error value\r
126**/\r
127EFI_STATUS\r
128EFIAPI\r
129TcgMeasureGptTable (\r
130 IN EFI_TCG_PROTOCOL *TcgProtocol,\r
131 IN EFI_HANDLE GptHandle\r
132 )\r
133{\r
134 EFI_STATUS Status;\r
135 EFI_BLOCK_IO_PROTOCOL *BlockIo;\r
136 EFI_DISK_IO_PROTOCOL *DiskIo;\r
137 EFI_PARTITION_TABLE_HEADER *PrimaryHeader;\r
138 EFI_PARTITION_ENTRY *PartitionEntry;\r
139 UINT8 *EntryPtr;\r
140 UINTN NumberOfPartition;\r
141 UINT32 Index;\r
142 TCG_PCR_EVENT *TcgEvent;\r
143 EFI_GPT_DATA *GptData;\r
144 UINT32 EventSize;\r
145 UINT32 EventNumber;\r
146 EFI_PHYSICAL_ADDRESS EventLogLastEntry;\r
147\r
148 if (mMeasureGptCount > 0) {\r
149 return EFI_SUCCESS;\r
150 }\r
151\r
152 Status = gBS->HandleProtocol (GptHandle, &gEfiBlockIoProtocolGuid, (VOID**)&BlockIo);\r
153 if (EFI_ERROR (Status)) {\r
154 return EFI_UNSUPPORTED;\r
155 }\r
156 Status = gBS->HandleProtocol (GptHandle, &gEfiDiskIoProtocolGuid, (VOID**)&DiskIo);\r
157 if (EFI_ERROR (Status)) {\r
158 return EFI_UNSUPPORTED;\r
159 }\r
160 //\r
161 // Read the EFI Partition Table Header\r
162 // \r
163 PrimaryHeader = (EFI_PARTITION_TABLE_HEADER *) AllocatePool (BlockIo->Media->BlockSize);\r
164 if (PrimaryHeader == NULL) {\r
165 return EFI_OUT_OF_RESOURCES;\r
166 } \r
167 Status = DiskIo->ReadDisk (\r
168 DiskIo,\r
169 BlockIo->Media->MediaId,\r
170 1 * BlockIo->Media->BlockSize,\r
171 BlockIo->Media->BlockSize,\r
172 (UINT8 *)PrimaryHeader\r
173 );\r
174 if (EFI_ERROR (Status)) {\r
175 DEBUG ((EFI_D_ERROR, "Failed to Read Partition Table Header!\n"));\r
176 FreePool (PrimaryHeader);\r
177 return EFI_DEVICE_ERROR;\r
178 } \r
179 //\r
180 // Read the partition entry.\r
181 //\r
182 EntryPtr = (UINT8 *)AllocatePool (PrimaryHeader->NumberOfPartitionEntries * PrimaryHeader->SizeOfPartitionEntry);\r
183 if (EntryPtr == NULL) {\r
184 FreePool (PrimaryHeader);\r
185 return EFI_OUT_OF_RESOURCES;\r
186 }\r
187 Status = DiskIo->ReadDisk (\r
188 DiskIo,\r
189 BlockIo->Media->MediaId,\r
190 MultU64x32(PrimaryHeader->PartitionEntryLBA, BlockIo->Media->BlockSize),\r
191 PrimaryHeader->NumberOfPartitionEntries * PrimaryHeader->SizeOfPartitionEntry,\r
192 EntryPtr\r
193 );\r
194 if (EFI_ERROR (Status)) {\r
195 FreePool (PrimaryHeader);\r
196 FreePool (EntryPtr);\r
197 return EFI_DEVICE_ERROR;\r
198 }\r
199 \r
200 //\r
201 // Count the valid partition\r
202 //\r
203 PartitionEntry = (EFI_PARTITION_ENTRY *)EntryPtr;\r
204 NumberOfPartition = 0;\r
205 for (Index = 0; Index < PrimaryHeader->NumberOfPartitionEntries; Index++) {\r
206 if (!CompareGuid (&PartitionEntry->PartitionTypeGUID, &mZeroGuid)) {\r
207 NumberOfPartition++; \r
208 }\r
2ea3b920 209 PartitionEntry = (EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);\r
0c18794e 210 }\r
211\r
212 //\r
2ea3b920 213 // Prepare Data for Measurement\r
0c18794e 214 // \r
215 EventSize = (UINT32)(sizeof (EFI_GPT_DATA) - sizeof (GptData->Partitions) \r
216 + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry);\r
2ea3b920 217 TcgEvent = (TCG_PCR_EVENT *) AllocateZeroPool (EventSize + sizeof (TCG_PCR_EVENT_HDR));\r
0c18794e 218 if (TcgEvent == NULL) {\r
219 FreePool (PrimaryHeader);\r
220 FreePool (EntryPtr);\r
221 return EFI_OUT_OF_RESOURCES;\r
222 }\r
223\r
224 TcgEvent->PCRIndex = 5;\r
225 TcgEvent->EventType = EV_EFI_GPT_EVENT;\r
226 TcgEvent->EventSize = EventSize;\r
227 GptData = (EFI_GPT_DATA *) TcgEvent->Event; \r
228\r
229 //\r
230 // Copy the EFI_PARTITION_TABLE_HEADER and NumberOfPartition\r
231 // \r
232 CopyMem ((UINT8 *)GptData, (UINT8*)PrimaryHeader, sizeof (EFI_PARTITION_TABLE_HEADER));\r
233 GptData->NumberOfPartitions = NumberOfPartition;\r
234 //\r
235 // Copy the valid partition entry\r
236 //\r
237 PartitionEntry = (EFI_PARTITION_ENTRY*)EntryPtr;\r
238 NumberOfPartition = 0;\r
239 for (Index = 0; Index < PrimaryHeader->NumberOfPartitionEntries; Index++) {\r
240 if (!CompareGuid (&PartitionEntry->PartitionTypeGUID, &mZeroGuid)) {\r
241 CopyMem (\r
2ea3b920 242 (UINT8 *)&GptData->Partitions + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry,\r
0c18794e 243 (UINT8 *)PartitionEntry,\r
2ea3b920 244 PrimaryHeader->SizeOfPartitionEntry\r
0c18794e 245 );\r
246 NumberOfPartition++;\r
247 }\r
2ea3b920 248 PartitionEntry =(EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);\r
0c18794e 249 }\r
250\r
251 //\r
252 // Measure the GPT data\r
253 //\r
254 EventNumber = 1;\r
255 Status = TcgProtocol->HashLogExtendEvent (\r
256 TcgProtocol,\r
257 (EFI_PHYSICAL_ADDRESS) (UINTN) (VOID *) GptData,\r
258 (UINT64) TcgEvent->EventSize,\r
259 TPM_ALG_SHA,\r
260 TcgEvent,\r
261 &EventNumber,\r
262 &EventLogLastEntry\r
263 );\r
264 if (!EFI_ERROR (Status)) {\r
265 mMeasureGptCount++;\r
266 }\r
267\r
268 FreePool (PrimaryHeader);\r
269 FreePool (EntryPtr);\r
270 FreePool (TcgEvent);\r
271\r
272 return Status;\r
273}\r
274\r
275/**\r
276 Measure PE image into TPM log based on the authenticode image hashing in\r
277 PE/COFF Specification 8.0 Appendix A.\r
278\r
dc204d5a
JY
279 Caution: This function may receive untrusted input.\r
280 PE/COFF image is external input, so this function will validate its data structure\r
281 within this image buffer before use.\r
282\r
0c18794e 283 @param[in] TcgProtocol Pointer to the located TCG protocol instance.\r
284 @param[in] ImageAddress Start address of image buffer.\r
285 @param[in] ImageSize Image size\r
286 @param[in] LinkTimeBase Address that the image is loaded into memory.\r
287 @param[in] ImageType Image subsystem type.\r
288 @param[in] FilePath File path is corresponding to the input image.\r
289\r
290 @retval EFI_SUCCESS Successfully measure image.\r
291 @retval EFI_OUT_OF_RESOURCES No enough resource to measure image.\r
551d8081 292 @retval EFI_UNSUPPORTED ImageType is unsupported or PE image is mal-format. \r
0c18794e 293 @retval other error value\r
551d8081 294\r
0c18794e 295**/\r
296EFI_STATUS\r
297EFIAPI\r
298TcgMeasurePeImage (\r
299 IN EFI_TCG_PROTOCOL *TcgProtocol,\r
300 IN EFI_PHYSICAL_ADDRESS ImageAddress,\r
301 IN UINTN ImageSize,\r
302 IN UINTN LinkTimeBase,\r
303 IN UINT16 ImageType,\r
304 IN EFI_DEVICE_PATH_PROTOCOL *FilePath\r
305 )\r
306{\r
551d8081 307 EFI_STATUS Status;\r
308 TCG_PCR_EVENT *TcgEvent;\r
309 EFI_IMAGE_LOAD_EVENT *ImageLoad;\r
310 UINT32 FilePathSize;\r
311 VOID *Sha1Ctx;\r
312 UINTN CtxSize;\r
313 EFI_IMAGE_DOS_HEADER *DosHdr;\r
314 UINT32 PeCoffHeaderOffset;\r
315 EFI_IMAGE_SECTION_HEADER *Section;\r
316 UINT8 *HashBase;\r
317 UINTN HashSize;\r
318 UINTN SumOfBytesHashed;\r
319 EFI_IMAGE_SECTION_HEADER *SectionHeader;\r
320 UINTN Index;\r
321 UINTN Pos;\r
322 UINT16 Magic;\r
323 UINT32 EventSize;\r
324 UINT32 EventNumber;\r
325 EFI_PHYSICAL_ADDRESS EventLogLastEntry;\r
0c18794e 326 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;\r
551d8081 327 UINT32 NumberOfRvaAndSizes;\r
328 BOOLEAN HashStatus;\r
329 UINT32 CertSize;\r
0c18794e 330\r
551d8081 331 Status = EFI_UNSUPPORTED;\r
0c18794e 332 ImageLoad = NULL;\r
333 SectionHeader = NULL;\r
334 Sha1Ctx = NULL;\r
335 FilePathSize = (UINT32) GetDevicePathSize (FilePath);\r
336\r
337 //\r
338 // Determine destination PCR by BootPolicy\r
339 //\r
340 EventSize = sizeof (*ImageLoad) - sizeof (ImageLoad->DevicePath) + FilePathSize;\r
341 TcgEvent = AllocateZeroPool (EventSize + sizeof (TCG_PCR_EVENT));\r
342 if (TcgEvent == NULL) {\r
343 return EFI_OUT_OF_RESOURCES;\r
344 }\r
345\r
346 TcgEvent->EventSize = EventSize;\r
347 ImageLoad = (EFI_IMAGE_LOAD_EVENT *) TcgEvent->Event;\r
348\r
349 switch (ImageType) {\r
350 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:\r
351 TcgEvent->EventType = EV_EFI_BOOT_SERVICES_APPLICATION;\r
352 TcgEvent->PCRIndex = 4;\r
353 break;\r
354 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:\r
355 TcgEvent->EventType = EV_EFI_BOOT_SERVICES_DRIVER;\r
356 TcgEvent->PCRIndex = 2;\r
357 break;\r
358 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:\r
359 TcgEvent->EventType = EV_EFI_RUNTIME_SERVICES_DRIVER;\r
360 TcgEvent->PCRIndex = 2;\r
361 break;\r
362 default:\r
363 DEBUG ((\r
364 EFI_D_ERROR,\r
365 "TcgMeasurePeImage: Unknown subsystem type %d",\r
366 ImageType\r
367 ));\r
0c18794e 368 goto Finish;\r
369 }\r
370\r
371 ImageLoad->ImageLocationInMemory = ImageAddress;\r
372 ImageLoad->ImageLengthInMemory = ImageSize;\r
373 ImageLoad->ImageLinkTimeAddress = LinkTimeBase;\r
374 ImageLoad->LengthOfDevicePath = FilePathSize;\r
375 CopyMem (ImageLoad->DevicePath, FilePath, FilePathSize);\r
376\r
377 //\r
378 // Check PE/COFF image\r
379 //\r
380 DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress;\r
381 PeCoffHeaderOffset = 0;\r
382 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {\r
383 PeCoffHeaderOffset = DosHdr->e_lfanew;\r
384 }\r
551d8081 385\r
386 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset);\r
387 if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {\r
0c18794e 388 goto Finish;\r
389 }\r
390\r
391 //\r
392 // PE/COFF Image Measurement\r
393 //\r
394 // NOTE: The following codes/steps are based upon the authenticode image hashing in\r
395 // PE/COFF Specification 8.0 Appendix A.\r
396 //\r
397 //\r
398\r
399 // 1. Load the image header into memory.\r
400\r
401 // 2. Initialize a SHA hash context.\r
402 CtxSize = Sha1GetContextSize ();\r
403 Sha1Ctx = AllocatePool (CtxSize);\r
404 if (Sha1Ctx == NULL) {\r
405 Status = EFI_OUT_OF_RESOURCES;\r
406 goto Finish;\r
407 }\r
408\r
551d8081 409 HashStatus = Sha1Init (Sha1Ctx);\r
410 if (!HashStatus) {\r
411 goto Finish;\r
412 }\r
0c18794e 413\r
414 //\r
415 // Measuring PE/COFF Image Header;\r
416 // But CheckSum field and SECURITY data directory (certificate) are excluded\r
417 //\r
de2447dd 418 if (Hdr.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
419 //\r
420 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value \r
421 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the \r
422 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC\r
423 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC\r
424 //\r
425 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;\r
426 } else {\r
427 //\r
428 // Get the magic value from the PE/COFF Optional Header\r
429 //\r
430 Magic = Hdr.Pe32->OptionalHeader.Magic;\r
431 }\r
0c18794e 432 \r
433 //\r
434 // 3. Calculate the distance from the base of the image header to the image checksum address.\r
435 // 4. Hash the image header from its base to beginning of the image checksum.\r
436 //\r
437 HashBase = (UINT8 *) (UINTN) ImageAddress;\r
438 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
439 //\r
440 // Use PE32 offset\r
441 //\r
551d8081 442 NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;\r
0c18794e 443 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);\r
444 } else {\r
445 //\r
446 // Use PE32+ offset\r
447 //\r
551d8081 448 NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;\r
0c18794e 449 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);\r
450 }\r
451\r
551d8081 452 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
453 if (!HashStatus) {\r
454 goto Finish;\r
455 } \r
0c18794e 456\r
457 //\r
458 // 5. Skip over the image checksum (it occupies a single ULONG).\r
0c18794e 459 //\r
551d8081 460 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {\r
0c18794e 461 //\r
551d8081 462 // 6. Since there is no Cert Directory in optional header, hash everything\r
463 // from the end of the checksum to the end of image header.\r
0c18794e 464 //\r
551d8081 465 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
466 //\r
467 // Use PE32 offset.\r
468 //\r
469 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);\r
470 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
471 } else {\r
472 //\r
473 // Use PE32+ offset.\r
474 //\r
475 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);\r
476 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
477 }\r
478\r
479 if (HashSize != 0) {\r
480 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
481 if (!HashStatus) {\r
482 goto Finish;\r
483 }\r
484 } \r
0c18794e 485 } else {\r
486 //\r
551d8081 487 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.\r
488 //\r
489 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
490 //\r
491 // Use PE32 offset\r
492 //\r
493 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);\r
494 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);\r
495 } else {\r
496 //\r
497 // Use PE32+ offset\r
498 // \r
499 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);\r
500 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);\r
501 }\r
0c18794e 502\r
551d8081 503 if (HashSize != 0) {\r
504 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
505 if (!HashStatus) {\r
506 goto Finish;\r
507 }\r
508 }\r
0c18794e 509\r
0c18794e 510 //\r
551d8081 511 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)\r
512 // 9. Hash everything from the end of the Cert Directory to the end of image header.\r
0c18794e 513 //\r
551d8081 514 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
515 //\r
516 // Use PE32 offset\r
517 //\r
518 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];\r
519 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
520 } else {\r
521 //\r
522 // Use PE32+ offset\r
523 //\r
524 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];\r
525 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
526 }\r
527 \r
528 if (HashSize != 0) {\r
529 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
530 if (!HashStatus) {\r
531 goto Finish;\r
532 }\r
533 }\r
0c18794e 534 }\r
0c18794e 535\r
536 //\r
537 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header\r
538 //\r
539 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
540 //\r
541 // Use PE32 offset\r
542 //\r
543 SumOfBytesHashed = Hdr.Pe32->OptionalHeader.SizeOfHeaders;\r
544 } else {\r
545 //\r
546 // Use PE32+ offset\r
547 //\r
548 SumOfBytesHashed = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;\r
549 }\r
550\r
551 //\r
552 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER\r
553 // structures in the image. The 'NumberOfSections' field of the image\r
554 // header indicates how big the table should be. Do not include any\r
555 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.\r
556 //\r
551d8081 557 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * Hdr.Pe32->FileHeader.NumberOfSections);\r
0c18794e 558 if (SectionHeader == NULL) {\r
559 Status = EFI_OUT_OF_RESOURCES;\r
560 goto Finish;\r
561 }\r
562\r
563 //\r
564 // 12. Using the 'PointerToRawData' in the referenced section headers as\r
565 // a key, arrange the elements in the table in ascending order. In other\r
566 // words, sort the section headers according to the disk-file offset of\r
567 // the section.\r
568 //\r
569 Section = (EFI_IMAGE_SECTION_HEADER *) (\r
570 (UINT8 *) (UINTN) ImageAddress +\r
571 PeCoffHeaderOffset +\r
572 sizeof(UINT32) +\r
573 sizeof(EFI_IMAGE_FILE_HEADER) +\r
574 Hdr.Pe32->FileHeader.SizeOfOptionalHeader\r
575 );\r
576 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {\r
577 Pos = Index;\r
578 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {\r
579 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof(EFI_IMAGE_SECTION_HEADER));\r
580 Pos--;\r
581 }\r
582 CopyMem (&SectionHeader[Pos], Section, sizeof(EFI_IMAGE_SECTION_HEADER));\r
583 Section += 1;\r
584 }\r
585\r
586 //\r
587 // 13. Walk through the sorted table, bring the corresponding section\r
588 // into memory, and hash the entire section (using the 'SizeOfRawData'\r
589 // field in the section header to determine the amount of data to hash).\r
590 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .\r
591 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.\r
592 //\r
593 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {\r
594 Section = (EFI_IMAGE_SECTION_HEADER *) &SectionHeader[Index];\r
595 if (Section->SizeOfRawData == 0) {\r
596 continue;\r
597 }\r
598 HashBase = (UINT8 *) (UINTN) ImageAddress + Section->PointerToRawData;\r
599 HashSize = (UINTN) Section->SizeOfRawData;\r
600\r
551d8081 601 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
602 if (!HashStatus) {\r
603 goto Finish;\r
604 }\r
0c18794e 605\r
606 SumOfBytesHashed += HashSize;\r
607 }\r
608\r
609 //\r
610 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra\r
611 // data in the file that needs to be added to the hash. This data begins\r
612 // at file offset SUM_OF_BYTES_HASHED and its length is:\r
613 // FileSize - (CertDirectory->Size)\r
614 //\r
615 if (ImageSize > SumOfBytesHashed) {\r
616 HashBase = (UINT8 *) (UINTN) ImageAddress + SumOfBytesHashed;\r
551d8081 617\r
618 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {\r
619 CertSize = 0;\r
0c18794e 620 } else {\r
551d8081 621 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
622 //\r
623 // Use PE32 offset.\r
624 //\r
625 CertSize = Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;\r
626 } else {\r
627 //\r
628 // Use PE32+ offset.\r
629 //\r
630 CertSize = Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;\r
28186d45 631 }\r
0c18794e 632 }\r
633\r
551d8081 634 if (ImageSize > CertSize + SumOfBytesHashed) {\r
635 HashSize = (UINTN) (ImageSize - CertSize - SumOfBytesHashed);\r
636\r
637 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
638 if (!HashStatus) {\r
639 goto Finish;\r
640 }\r
641 } else if (ImageSize < CertSize + SumOfBytesHashed) {\r
642 goto Finish;\r
643 }\r
0c18794e 644 }\r
645\r
646 //\r
647 // 17. Finalize the SHA hash.\r
648 //\r
551d8081 649 HashStatus = Sha1Final (Sha1Ctx, (UINT8 *) &TcgEvent->Digest);\r
650 if (!HashStatus) {\r
651 goto Finish;\r
652 }\r
0c18794e 653\r
654 //\r
655 // Log the PE data\r
656 //\r
657 EventNumber = 1;\r
658 Status = TcgProtocol->HashLogExtendEvent (\r
659 TcgProtocol,\r
660 (EFI_PHYSICAL_ADDRESS) (UINTN) (VOID *) NULL,\r
661 0,\r
662 TPM_ALG_SHA,\r
663 TcgEvent,\r
664 &EventNumber,\r
665 &EventLogLastEntry\r
666 );\r
667\r
668Finish:\r
669 FreePool (TcgEvent);\r
670\r
671 if (SectionHeader != NULL) {\r
672 FreePool (SectionHeader);\r
673 }\r
674\r
675 if (Sha1Ctx != NULL ) {\r
676 FreePool (Sha1Ctx);\r
677 }\r
678 return Status;\r
679}\r
680\r
681/**\r
682 The security handler is used to abstract platform-specific policy \r
683 from the DXE core response to an attempt to use a file that returns a \r
684 given status for the authentication check from the section extraction protocol. \r
685\r
686 The possible responses in a given SAP implementation may include locking \r
687 flash upon failure to authenticate, attestation logging for all signed drivers, \r
688 and other exception operations. The File parameter allows for possible logging \r
689 within the SAP of the driver.\r
690\r
691 If File is NULL, then EFI_INVALID_PARAMETER is returned.\r
692\r
693 If the file specified by File with an authentication status specified by \r
694 AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.\r
695\r
696 If the file specified by File with an authentication status specified by \r
697 AuthenticationStatus is not safe for the DXE Core to use under any circumstances, \r
698 then EFI_ACCESS_DENIED is returned.\r
699\r
700 If the file specified by File with an authentication status specified by \r
701 AuthenticationStatus is not safe for the DXE Core to use right now, but it \r
702 might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is \r
703 returned.\r
704\r
5db28a67 705 @param[in] AuthenticationStatus This is the authentication status returned\r
0c18794e 706 from the securitymeasurement services for the\r
707 input file.\r
708 @param[in] File This is a pointer to the device path of the file that is\r
709 being dispatched. This will optionally be used for logging.\r
710 @param[in] FileBuffer File buffer matches the input file device path.\r
711 @param[in] FileSize Size of File buffer matches the input file device path.\r
5db28a67 712 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.\r
0c18794e 713\r
5db28a67
LG
714 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL\r
715 FileBuffer did authenticate, and the platform policy dictates\r
716 that the DXE Foundation may use the file.\r
717 @retval other error value\r
0c18794e 718**/\r
719EFI_STATUS\r
720EFIAPI\r
721DxeTpmMeasureBootHandler (\r
5db28a67 722 IN UINT32 AuthenticationStatus,\r
0c18794e 723 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,\r
5db28a67
LG
724 IN VOID *FileBuffer,\r
725 IN UINTN FileSize,\r
726 IN BOOLEAN BootPolicy\r
0c18794e 727 )\r
728{\r
2aadc920 729 EFI_TCG_PROTOCOL *TcgProtocol;\r
730 EFI_STATUS Status;\r
731 TCG_EFI_BOOT_SERVICE_CAPABILITY ProtocolCapability;\r
732 UINT32 TCGFeatureFlags;\r
733 EFI_PHYSICAL_ADDRESS EventLogLocation;\r
734 EFI_PHYSICAL_ADDRESS EventLogLastEntry;\r
735 EFI_DEVICE_PATH_PROTOCOL *DevicePathNode;\r
736 EFI_DEVICE_PATH_PROTOCOL *OrigDevicePathNode;\r
737 EFI_HANDLE Handle;\r
738 EFI_HANDLE TempHandle;\r
739 BOOLEAN ApplicationRequired;\r
740 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;\r
741 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;\r
742 EFI_PHYSICAL_ADDRESS FvAddress;\r
2aadc920 743 UINT32 Index;\r
0c18794e 744\r
0c18794e 745 Status = gBS->LocateProtocol (&gEfiTcgProtocolGuid, NULL, (VOID **) &TcgProtocol);\r
746 if (EFI_ERROR (Status)) {\r
747 //\r
748 // TCG protocol is not installed. So, TPM is not present.\r
749 // Don't do any measurement, and directly return EFI_SUCCESS.\r
750 //\r
751 return EFI_SUCCESS;\r
752 }\r
753\r
754 ProtocolCapability.Size = (UINT8) sizeof (ProtocolCapability);\r
755 Status = TcgProtocol->StatusCheck (\r
756 TcgProtocol, \r
757 &ProtocolCapability,\r
758 &TCGFeatureFlags,\r
759 &EventLogLocation,\r
760 &EventLogLastEntry\r
761 );\r
762 if (EFI_ERROR (Status) || ProtocolCapability.TPMDeactivatedFlag) {\r
763 //\r
764 // TPM device doesn't work or activate.\r
765 //\r
766 return EFI_SUCCESS;\r
767 }\r
768\r
769 //\r
770 // Copy File Device Path\r
771 //\r
772 OrigDevicePathNode = DuplicateDevicePath (File);\r
0c18794e 773 \r
774 //\r
775 // 1. Check whether this device path support BlockIo protocol.\r
776 // Is so, this device path may be a GPT device path.\r
777 //\r
778 DevicePathNode = OrigDevicePathNode;\r
779 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &DevicePathNode, &Handle);\r
780 if (!EFI_ERROR (Status) && !mMeasureGptTableFlag) {\r
781 //\r
782 // Find the gpt partion on the given devicepath\r
783 //\r
784 DevicePathNode = OrigDevicePathNode;\r
4dbb98ab 785 ASSERT (DevicePathNode != NULL);\r
0c18794e 786 while (!IsDevicePathEnd (DevicePathNode)) {\r
787 //\r
788 // Find the Gpt partition\r
789 //\r
790 if (DevicePathType (DevicePathNode) == MEDIA_DEVICE_PATH &&\r
791 DevicePathSubType (DevicePathNode) == MEDIA_HARDDRIVE_DP) {\r
792 //\r
793 // Check whether it is a gpt partition or not\r
794 // \r
795 if (((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER && \r
796 ((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->SignatureType == SIGNATURE_TYPE_GUID) {\r
797\r
798 //\r
799 // Change the partition device path to its parent device path (disk) and get the handle.\r
800 //\r
801 DevicePathNode->Type = END_DEVICE_PATH_TYPE;\r
802 DevicePathNode->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;\r
803 DevicePathNode = OrigDevicePathNode;\r
804 Status = gBS->LocateDevicePath (\r
805 &gEfiDiskIoProtocolGuid,\r
806 &DevicePathNode,\r
807 &Handle\r
808 );\r
809 if (!EFI_ERROR (Status)) {\r
810 //\r
811 // Measure GPT disk.\r
812 //\r
813 Status = TcgMeasureGptTable (TcgProtocol, Handle);\r
814 if (!EFI_ERROR (Status)) {\r
815 //\r
816 // GPT disk check done.\r
817 //\r
818 mMeasureGptTableFlag = TRUE;\r
819 }\r
820 }\r
821 FreePool (OrigDevicePathNode);\r
822 OrigDevicePathNode = DuplicateDevicePath (File);\r
823 ASSERT (OrigDevicePathNode != NULL);\r
824 break;\r
825 }\r
826 }\r
827 DevicePathNode = NextDevicePathNode (DevicePathNode);\r
828 }\r
829 }\r
830 \r
831 //\r
832 // 2. Measure PE image.\r
833 //\r
834 ApplicationRequired = FALSE;\r
835\r
836 //\r
2aadc920 837 // Check whether this device path support FVB protocol.\r
0c18794e 838 //\r
839 DevicePathNode = OrigDevicePathNode;\r
2aadc920 840 Status = gBS->LocateDevicePath (&gEfiFirmwareVolumeBlockProtocolGuid, &DevicePathNode, &Handle);\r
0c18794e 841 if (!EFI_ERROR (Status)) {\r
842 //\r
843 // Don't check FV image, and directly return EFI_SUCCESS.\r
844 // It can be extended to the specific FV authentication according to the different requirement.\r
845 //\r
846 if (IsDevicePathEnd (DevicePathNode)) {\r
847 return EFI_SUCCESS;\r
848 }\r
849 //\r
0758c830 850 // The PE image from unmeasured Firmware volume need be measured\r
851 // The PE image from measured Firmware volume will be mearsured according to policy below.\r
852 // If it is driver, do not measure\r
2aadc920 853 // If it is application, still measure.\r
0c18794e 854 //\r
855 ApplicationRequired = TRUE;\r
2aadc920 856\r
0758c830 857 if (mCacheMeasuredHandle != Handle && mMeasuredHobData != NULL) {\r
2aadc920 858 //\r
859 // Search for Root FV of this PE image\r
860 //\r
861 TempHandle = Handle;\r
862 do {\r
863 Status = gBS->HandleProtocol(\r
864 TempHandle, \r
865 &gEfiFirmwareVolumeBlockProtocolGuid,\r
6dbdb191 866 (VOID**)&FvbProtocol\r
2aadc920 867 );\r
868 TempHandle = FvbProtocol->ParentHandle;\r
869 } while (!EFI_ERROR(Status) && FvbProtocol->ParentHandle != NULL);\r
870\r
871 //\r
872 // Search in measured FV Hob\r
873 //\r
874 Status = FvbProtocol->GetPhysicalAddress(FvbProtocol, &FvAddress);\r
875 if (EFI_ERROR(Status)){\r
876 return Status;\r
877 }\r
878\r
2aadc920 879 ApplicationRequired = FALSE;\r
880\r
0758c830 881 for (Index = 0; Index < mMeasuredHobData->Num; Index++) {\r
882 if(mMeasuredHobData->MeasuredFvBuf[Index].BlobBase == FvAddress) {\r
2aadc920 883 //\r
884 // Cache measured FV for next measurement\r
885 //\r
886 mCacheMeasuredHandle = Handle;\r
887 ApplicationRequired = TRUE;\r
888 break;\r
889 }\r
890 }\r
891 }\r
0c18794e 892 }\r
2aadc920 893\r
0c18794e 894 //\r
895 // File is not found.\r
896 //\r
897 if (FileBuffer == NULL) {\r
898 Status = EFI_SECURITY_VIOLATION;\r
899 goto Finish;\r
900 }\r
901\r
28186d45
ED
902 mImageSize = FileSize;\r
903 mFileBuffer = FileBuffer;\r
904\r
0c18794e 905 //\r
906 // Measure PE Image\r
907 //\r
908 DevicePathNode = OrigDevicePathNode;\r
909 ZeroMem (&ImageContext, sizeof (ImageContext));\r
910 ImageContext.Handle = (VOID *) FileBuffer;\r
e0192326 911 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeTpmMeasureBootLibImageRead;\r
0c18794e 912\r
913 //\r
914 // Get information about the image being loaded\r
915 //\r
916 Status = PeCoffLoaderGetImageInfo (&ImageContext);\r
917 if (EFI_ERROR (Status)) {\r
918 //\r
919 // The information can't be got from the invalid PeImage\r
920 //\r
921 goto Finish;\r
922 }\r
923 \r
924 //\r
925 // Measure only application if Application flag is set\r
926 // Measure drivers and applications if Application flag is not set\r
927 //\r
928 if ((!ApplicationRequired) || \r
929 (ApplicationRequired && ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) { \r
930 //\r
931 // Print the image path to be measured.\r
932 // \r
933 DEBUG_CODE_BEGIN ();\r
934 CHAR16 *ToText;\r
935 EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText;\r
936 Status = gBS->LocateProtocol (\r
937 &gEfiDevicePathToTextProtocolGuid,\r
938 NULL,\r
939 (VOID **) &DevPathToText\r
940 );\r
941 if (!EFI_ERROR (Status)) {\r
942 ToText = DevPathToText->ConvertDevicePathToText (\r
943 DevicePathNode,\r
944 FALSE,\r
945 TRUE\r
946 );\r
947 if (ToText != NULL) {\r
948 DEBUG ((DEBUG_INFO, "The measured image path is %s.\n", ToText));\r
949 }\r
950 }\r
951 DEBUG_CODE_END ();\r
952\r
953 //\r
954 // Measure PE image into TPM log.\r
955 //\r
956 Status = TcgMeasurePeImage (\r
957 TcgProtocol,\r
958 (EFI_PHYSICAL_ADDRESS) (UINTN) FileBuffer, \r
959 FileSize, \r
960 (UINTN) ImageContext.ImageAddress, \r
961 ImageContext.ImageType, \r
962 DevicePathNode\r
963 );\r
964 }\r
965\r
966 //\r
967 // Done, free the allocated resource.\r
968 //\r
969Finish:\r
5db28a67
LG
970 if (OrigDevicePathNode != NULL) {\r
971 FreePool (OrigDevicePathNode);\r
972 }\r
0c18794e 973\r
974 return Status;\r
975}\r
976\r
977/**\r
978 Register the security handler to provide TPM measure boot service.\r
979\r
980 @param ImageHandle ImageHandle of the loaded driver.\r
981 @param SystemTable Pointer to the EFI System Table.\r
982\r
983 @retval EFI_SUCCESS Register successfully.\r
984 @retval EFI_OUT_OF_RESOURCES No enough memory to register this handler.\r
985**/\r
986EFI_STATUS\r
987EFIAPI\r
988DxeTpmMeasureBootLibConstructor (\r
989 IN EFI_HANDLE ImageHandle,\r
990 IN EFI_SYSTEM_TABLE *SystemTable\r
991 )\r
992{\r
2aadc920 993 EFI_HOB_GUID_TYPE *GuidHob;\r
994\r
995 GuidHob = NULL;\r
996\r
0758c830 997 GuidHob = GetFirstGuidHob (&gMeasuredFvHobGuid);\r
2aadc920 998\r
999 if (GuidHob != NULL) {\r
0758c830 1000 mMeasuredHobData = GET_GUID_HOB_DATA (GuidHob);\r
2aadc920 1001 }\r
1002\r
5db28a67 1003 return RegisterSecurity2Handler (\r
0c18794e 1004 DxeTpmMeasureBootHandler,\r
1005 EFI_AUTH_OPERATION_MEASURE_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED\r
1006 );\r
1007}\r