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