]> git.proxmox.com Git - mirror_edk2.git/blame_incremental - SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
Add check to avoid null pointer deference.
[mirror_edk2.git] / SecurityPkg / Library / DxeTpmMeasureBootLib / DxeTpmMeasureBootLib.c
... / ...
CommitLineData
1/** @file\r
2 The library instance provides security service of TPM measure boot. \r
3\r
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
18Copyright (c) 2009 - 2013, Intel Corporation. All rights reserved.<BR>\r
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
32#include <Protocol/BlockIo.h>\r
33#include <Protocol/DiskIo.h>\r
34#include <Protocol/FirmwareVolumeBlock.h>\r
35\r
36#include <Guid/MeasuredFvHob.h>\r
37\r
38#include <Library/BaseLib.h>\r
39#include <Library/DebugLib.h>\r
40#include <Library/BaseMemoryLib.h>\r
41#include <Library/MemoryAllocationLib.h>\r
42#include <Library/DevicePathLib.h>\r
43#include <Library/UefiBootServicesTableLib.h>\r
44#include <Library/BaseCryptLib.h>\r
45#include <Library/PeCoffLib.h>\r
46#include <Library/SecurityManagementLib.h>\r
47#include <Library/HobLib.h>\r
48\r
49//\r
50// Flag to check GPT partition. It only need be measured once.\r
51//\r
52BOOLEAN mMeasureGptTableFlag = FALSE;\r
53EFI_GUID mZeroGuid = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};\r
54UINTN mMeasureGptCount = 0;\r
55VOID *mFileBuffer;\r
56UINTN mImageSize;\r
57//\r
58// Measured FV handle cache\r
59//\r
60EFI_HANDLE mCacheMeasuredHandle = NULL;\r
61MEASURED_HOB_DATA *mMeasuredHobData = NULL;\r
62\r
63/**\r
64 Reads contents of a PE/COFF image in memory buffer.\r
65\r
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
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
80DxeTpmMeasureBootLibImageRead (\r
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
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
106 CopyMem (Buffer, (UINT8 *)((UINTN) FileHandle + FileOffset), *ReadSize);\r
107\r
108 return EFI_SUCCESS;\r
109}\r
110\r
111/**\r
112 Measure GPT table data into TPM log.\r
113\r
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
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
205 if (!CompareGuid (&PartitionEntry->PartitionTypeGUID, &mZeroGuid)) {\r
206 NumberOfPartition++; \r
207 }\r
208 PartitionEntry = (EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);\r
209 }\r
210\r
211 //\r
212 // Prepare Data for Measurement\r
213 // \r
214 EventSize = (UINT32)(sizeof (EFI_GPT_DATA) - sizeof (GptData->Partitions) \r
215 + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry);\r
216 TcgEvent = (TCG_PCR_EVENT *) AllocateZeroPool (EventSize + sizeof (TCG_PCR_EVENT_HDR));\r
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
239 if (!CompareGuid (&PartitionEntry->PartitionTypeGUID, &mZeroGuid)) {\r
240 CopyMem (\r
241 (UINT8 *)&GptData->Partitions + NumberOfPartition * PrimaryHeader->SizeOfPartitionEntry,\r
242 (UINT8 *)PartitionEntry,\r
243 PrimaryHeader->SizeOfPartitionEntry\r
244 );\r
245 NumberOfPartition++;\r
246 }\r
247 PartitionEntry =(EFI_PARTITION_ENTRY *)((UINT8 *)PartitionEntry + PrimaryHeader->SizeOfPartitionEntry);\r
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
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
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
291 @retval EFI_UNSUPPORTED ImageType is unsupported or PE image is mal-format. \r
292 @retval other error value\r
293\r
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
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
325 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;\r
326 UINT32 NumberOfRvaAndSizes;\r
327 BOOLEAN HashStatus;\r
328 UINT32 CertSize;\r
329\r
330 Status = EFI_UNSUPPORTED;\r
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
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
374 CopyMem (ImageLoad->DevicePath, FilePath, FilePathSize);\r
375\r
376 //\r
377 // Check PE/COFF image\r
378 //\r
379 DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress;\r
380 PeCoffHeaderOffset = 0;\r
381 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {\r
382 PeCoffHeaderOffset = DosHdr->e_lfanew;\r
383 }\r
384\r
385 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset);\r
386 if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {\r
387 goto Finish;\r
388 }\r
389\r
390 //\r
391 // PE/COFF Image Measurement\r
392 //\r
393 // NOTE: The following codes/steps are based upon the authenticode image hashing in\r
394 // PE/COFF Specification 8.0 Appendix A.\r
395 //\r
396 //\r
397\r
398 // 1. Load the image header into memory.\r
399\r
400 // 2. Initialize a SHA hash context.\r
401 CtxSize = Sha1GetContextSize ();\r
402 Sha1Ctx = AllocatePool (CtxSize);\r
403 if (Sha1Ctx == NULL) {\r
404 Status = EFI_OUT_OF_RESOURCES;\r
405 goto Finish;\r
406 }\r
407\r
408 HashStatus = Sha1Init (Sha1Ctx);\r
409 if (!HashStatus) {\r
410 goto Finish;\r
411 }\r
412\r
413 //\r
414 // Measuring PE/COFF Image Header;\r
415 // But CheckSum field and SECURITY data directory (certificate) are excluded\r
416 //\r
417 if (Hdr.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
418 //\r
419 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value \r
420 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the \r
421 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC\r
422 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC\r
423 //\r
424 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;\r
425 } else {\r
426 //\r
427 // Get the magic value from the PE/COFF Optional Header\r
428 //\r
429 Magic = Hdr.Pe32->OptionalHeader.Magic;\r
430 }\r
431 \r
432 //\r
433 // 3. Calculate the distance from the base of the image header to the image checksum address.\r
434 // 4. Hash the image header from its base to beginning of the image checksum.\r
435 //\r
436 HashBase = (UINT8 *) (UINTN) ImageAddress;\r
437 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
438 //\r
439 // Use PE32 offset\r
440 //\r
441 NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;\r
442 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);\r
443 } else {\r
444 //\r
445 // Use PE32+ offset\r
446 //\r
447 NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;\r
448 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);\r
449 }\r
450\r
451 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
452 if (!HashStatus) {\r
453 goto Finish;\r
454 } \r
455\r
456 //\r
457 // 5. Skip over the image checksum (it occupies a single ULONG).\r
458 //\r
459 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {\r
460 //\r
461 // 6. Since there is no Cert Directory in optional header, hash everything\r
462 // from the end of the checksum to the end of image header.\r
463 //\r
464 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
465 //\r
466 // Use PE32 offset.\r
467 //\r
468 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);\r
469 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
470 } else {\r
471 //\r
472 // Use PE32+ offset.\r
473 //\r
474 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);\r
475 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
476 }\r
477\r
478 if (HashSize != 0) {\r
479 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
480 if (!HashStatus) {\r
481 goto Finish;\r
482 }\r
483 } \r
484 } else {\r
485 //\r
486 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.\r
487 //\r
488 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
489 //\r
490 // Use PE32 offset\r
491 //\r
492 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);\r
493 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);\r
494 } else {\r
495 //\r
496 // Use PE32+ offset\r
497 // \r
498 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);\r
499 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);\r
500 }\r
501\r
502 if (HashSize != 0) {\r
503 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
504 if (!HashStatus) {\r
505 goto Finish;\r
506 }\r
507 }\r
508\r
509 //\r
510 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)\r
511 // 9. Hash everything from the end of the Cert Directory to the end of image header.\r
512 //\r
513 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
514 //\r
515 // Use PE32 offset\r
516 //\r
517 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];\r
518 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
519 } else {\r
520 //\r
521 // Use PE32+ offset\r
522 //\r
523 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];\r
524 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);\r
525 }\r
526 \r
527 if (HashSize != 0) {\r
528 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
529 if (!HashStatus) {\r
530 goto Finish;\r
531 }\r
532 }\r
533 }\r
534\r
535 //\r
536 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header\r
537 //\r
538 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
539 //\r
540 // Use PE32 offset\r
541 //\r
542 SumOfBytesHashed = Hdr.Pe32->OptionalHeader.SizeOfHeaders;\r
543 } else {\r
544 //\r
545 // Use PE32+ offset\r
546 //\r
547 SumOfBytesHashed = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;\r
548 }\r
549\r
550 //\r
551 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER\r
552 // structures in the image. The 'NumberOfSections' field of the image\r
553 // header indicates how big the table should be. Do not include any\r
554 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.\r
555 //\r
556 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * Hdr.Pe32->FileHeader.NumberOfSections);\r
557 if (SectionHeader == NULL) {\r
558 Status = EFI_OUT_OF_RESOURCES;\r
559 goto Finish;\r
560 }\r
561\r
562 //\r
563 // 12. Using the 'PointerToRawData' in the referenced section headers as\r
564 // a key, arrange the elements in the table in ascending order. In other\r
565 // words, sort the section headers according to the disk-file offset of\r
566 // the section.\r
567 //\r
568 Section = (EFI_IMAGE_SECTION_HEADER *) (\r
569 (UINT8 *) (UINTN) ImageAddress +\r
570 PeCoffHeaderOffset +\r
571 sizeof(UINT32) +\r
572 sizeof(EFI_IMAGE_FILE_HEADER) +\r
573 Hdr.Pe32->FileHeader.SizeOfOptionalHeader\r
574 );\r
575 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {\r
576 Pos = Index;\r
577 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {\r
578 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof(EFI_IMAGE_SECTION_HEADER));\r
579 Pos--;\r
580 }\r
581 CopyMem (&SectionHeader[Pos], Section, sizeof(EFI_IMAGE_SECTION_HEADER));\r
582 Section += 1;\r
583 }\r
584\r
585 //\r
586 // 13. Walk through the sorted table, bring the corresponding section\r
587 // into memory, and hash the entire section (using the 'SizeOfRawData'\r
588 // field in the section header to determine the amount of data to hash).\r
589 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .\r
590 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.\r
591 //\r
592 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {\r
593 Section = (EFI_IMAGE_SECTION_HEADER *) &SectionHeader[Index];\r
594 if (Section->SizeOfRawData == 0) {\r
595 continue;\r
596 }\r
597 HashBase = (UINT8 *) (UINTN) ImageAddress + Section->PointerToRawData;\r
598 HashSize = (UINTN) Section->SizeOfRawData;\r
599\r
600 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
601 if (!HashStatus) {\r
602 goto Finish;\r
603 }\r
604\r
605 SumOfBytesHashed += HashSize;\r
606 }\r
607\r
608 //\r
609 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra\r
610 // data in the file that needs to be added to the hash. This data begins\r
611 // at file offset SUM_OF_BYTES_HASHED and its length is:\r
612 // FileSize - (CertDirectory->Size)\r
613 //\r
614 if (ImageSize > SumOfBytesHashed) {\r
615 HashBase = (UINT8 *) (UINTN) ImageAddress + SumOfBytesHashed;\r
616\r
617 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {\r
618 CertSize = 0;\r
619 } else {\r
620 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {\r
621 //\r
622 // Use PE32 offset.\r
623 //\r
624 CertSize = Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;\r
625 } else {\r
626 //\r
627 // Use PE32+ offset.\r
628 //\r
629 CertSize = Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;\r
630 }\r
631 }\r
632\r
633 if (ImageSize > CertSize + SumOfBytesHashed) {\r
634 HashSize = (UINTN) (ImageSize - CertSize - SumOfBytesHashed);\r
635\r
636 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);\r
637 if (!HashStatus) {\r
638 goto Finish;\r
639 }\r
640 } else if (ImageSize < CertSize + SumOfBytesHashed) {\r
641 goto Finish;\r
642 }\r
643 }\r
644\r
645 //\r
646 // 17. Finalize the SHA hash.\r
647 //\r
648 HashStatus = Sha1Final (Sha1Ctx, (UINT8 *) &TcgEvent->Digest);\r
649 if (!HashStatus) {\r
650 goto Finish;\r
651 }\r
652\r
653 //\r
654 // Log the PE data\r
655 //\r
656 EventNumber = 1;\r
657 Status = TcgProtocol->HashLogExtendEvent (\r
658 TcgProtocol,\r
659 (EFI_PHYSICAL_ADDRESS) (UINTN) (VOID *) NULL,\r
660 0,\r
661 TPM_ALG_SHA,\r
662 TcgEvent,\r
663 &EventNumber,\r
664 &EventLogLastEntry\r
665 );\r
666 if (Status == EFI_OUT_OF_RESOURCES) {\r
667 //\r
668 // Out of resource here means the image is hashed and its result is extended to PCR.\r
669 // But the event log cann't be saved since log area is full.\r
670 // Just return EFI_SUCCESS in order not to block the image load.\r
671 //\r
672 Status = EFI_SUCCESS;\r
673 }\r
674\r
675Finish:\r
676 FreePool (TcgEvent);\r
677\r
678 if (SectionHeader != NULL) {\r
679 FreePool (SectionHeader);\r
680 }\r
681\r
682 if (Sha1Ctx != NULL ) {\r
683 FreePool (Sha1Ctx);\r
684 }\r
685 return Status;\r
686}\r
687\r
688/**\r
689 The security handler is used to abstract platform-specific policy \r
690 from the DXE core response to an attempt to use a file that returns a \r
691 given status for the authentication check from the section extraction protocol. \r
692\r
693 The possible responses in a given SAP implementation may include locking \r
694 flash upon failure to authenticate, attestation logging for all signed drivers, \r
695 and other exception operations. The File parameter allows for possible logging \r
696 within the SAP of the driver.\r
697\r
698 If File is NULL, then EFI_INVALID_PARAMETER is returned.\r
699\r
700 If the file specified by File with an authentication status specified by \r
701 AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.\r
702\r
703 If the file specified by File with an authentication status specified by \r
704 AuthenticationStatus is not safe for the DXE Core to use under any circumstances, \r
705 then EFI_ACCESS_DENIED is returned.\r
706\r
707 If the file specified by File with an authentication status specified by \r
708 AuthenticationStatus is not safe for the DXE Core to use right now, but it \r
709 might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is \r
710 returned.\r
711\r
712 @param[in] AuthenticationStatus This is the authentication status returned\r
713 from the securitymeasurement services for the\r
714 input file.\r
715 @param[in] File This is a pointer to the device path of the file that is\r
716 being dispatched. This will optionally be used for logging.\r
717 @param[in] FileBuffer File buffer matches the input file device path.\r
718 @param[in] FileSize Size of File buffer matches the input file device path.\r
719 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.\r
720\r
721 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL\r
722 FileBuffer did authenticate, and the platform policy dictates\r
723 that the DXE Foundation may use the file.\r
724 @retval other error value\r
725**/\r
726EFI_STATUS\r
727EFIAPI\r
728DxeTpmMeasureBootHandler (\r
729 IN UINT32 AuthenticationStatus,\r
730 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,\r
731 IN VOID *FileBuffer,\r
732 IN UINTN FileSize,\r
733 IN BOOLEAN BootPolicy\r
734 )\r
735{\r
736 EFI_TCG_PROTOCOL *TcgProtocol;\r
737 EFI_STATUS Status;\r
738 TCG_EFI_BOOT_SERVICE_CAPABILITY ProtocolCapability;\r
739 UINT32 TCGFeatureFlags;\r
740 EFI_PHYSICAL_ADDRESS EventLogLocation;\r
741 EFI_PHYSICAL_ADDRESS EventLogLastEntry;\r
742 EFI_DEVICE_PATH_PROTOCOL *DevicePathNode;\r
743 EFI_DEVICE_PATH_PROTOCOL *OrigDevicePathNode;\r
744 EFI_HANDLE Handle;\r
745 EFI_HANDLE TempHandle;\r
746 BOOLEAN ApplicationRequired;\r
747 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;\r
748 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;\r
749 EFI_PHYSICAL_ADDRESS FvAddress;\r
750 UINT32 Index;\r
751\r
752 Status = gBS->LocateProtocol (&gEfiTcgProtocolGuid, NULL, (VOID **) &TcgProtocol);\r
753 if (EFI_ERROR (Status)) {\r
754 //\r
755 // TCG protocol is not installed. So, TPM is not present.\r
756 // Don't do any measurement, and directly return EFI_SUCCESS.\r
757 //\r
758 return EFI_SUCCESS;\r
759 }\r
760\r
761 ProtocolCapability.Size = (UINT8) sizeof (ProtocolCapability);\r
762 Status = TcgProtocol->StatusCheck (\r
763 TcgProtocol, \r
764 &ProtocolCapability,\r
765 &TCGFeatureFlags,\r
766 &EventLogLocation,\r
767 &EventLogLastEntry\r
768 );\r
769 if (EFI_ERROR (Status) || ProtocolCapability.TPMDeactivatedFlag) {\r
770 //\r
771 // TPM device doesn't work or activate.\r
772 //\r
773 return EFI_SUCCESS;\r
774 }\r
775\r
776 //\r
777 // Copy File Device Path\r
778 //\r
779 OrigDevicePathNode = DuplicateDevicePath (File);\r
780 \r
781 //\r
782 // 1. Check whether this device path support BlockIo protocol.\r
783 // Is so, this device path may be a GPT device path.\r
784 //\r
785 DevicePathNode = OrigDevicePathNode;\r
786 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &DevicePathNode, &Handle);\r
787 if (!EFI_ERROR (Status) && !mMeasureGptTableFlag) {\r
788 //\r
789 // Find the gpt partion on the given devicepath\r
790 //\r
791 DevicePathNode = OrigDevicePathNode;\r
792 ASSERT (DevicePathNode != NULL);\r
793 while (!IsDevicePathEnd (DevicePathNode)) {\r
794 //\r
795 // Find the Gpt partition\r
796 //\r
797 if (DevicePathType (DevicePathNode) == MEDIA_DEVICE_PATH &&\r
798 DevicePathSubType (DevicePathNode) == MEDIA_HARDDRIVE_DP) {\r
799 //\r
800 // Check whether it is a gpt partition or not\r
801 // \r
802 if (((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER && \r
803 ((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->SignatureType == SIGNATURE_TYPE_GUID) {\r
804\r
805 //\r
806 // Change the partition device path to its parent device path (disk) and get the handle.\r
807 //\r
808 DevicePathNode->Type = END_DEVICE_PATH_TYPE;\r
809 DevicePathNode->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;\r
810 DevicePathNode = OrigDevicePathNode;\r
811 Status = gBS->LocateDevicePath (\r
812 &gEfiDiskIoProtocolGuid,\r
813 &DevicePathNode,\r
814 &Handle\r
815 );\r
816 if (!EFI_ERROR (Status)) {\r
817 //\r
818 // Measure GPT disk.\r
819 //\r
820 Status = TcgMeasureGptTable (TcgProtocol, Handle);\r
821 if (!EFI_ERROR (Status)) {\r
822 //\r
823 // GPT disk check done.\r
824 //\r
825 mMeasureGptTableFlag = TRUE;\r
826 }\r
827 }\r
828 FreePool (OrigDevicePathNode);\r
829 OrigDevicePathNode = DuplicateDevicePath (File);\r
830 ASSERT (OrigDevicePathNode != NULL);\r
831 break;\r
832 }\r
833 }\r
834 DevicePathNode = NextDevicePathNode (DevicePathNode);\r
835 }\r
836 }\r
837 \r
838 //\r
839 // 2. Measure PE image.\r
840 //\r
841 ApplicationRequired = FALSE;\r
842\r
843 //\r
844 // Check whether this device path support FVB protocol.\r
845 //\r
846 DevicePathNode = OrigDevicePathNode;\r
847 Status = gBS->LocateDevicePath (&gEfiFirmwareVolumeBlockProtocolGuid, &DevicePathNode, &Handle);\r
848 if (!EFI_ERROR (Status)) {\r
849 //\r
850 // Don't check FV image, and directly return EFI_SUCCESS.\r
851 // It can be extended to the specific FV authentication according to the different requirement.\r
852 //\r
853 if (IsDevicePathEnd (DevicePathNode)) {\r
854 return EFI_SUCCESS;\r
855 }\r
856 //\r
857 // The PE image from unmeasured Firmware volume need be measured\r
858 // The PE image from measured Firmware volume will be mearsured according to policy below.\r
859 // If it is driver, do not measure\r
860 // If it is application, still measure.\r
861 //\r
862 ApplicationRequired = TRUE;\r
863\r
864 if (mCacheMeasuredHandle != Handle && mMeasuredHobData != NULL) {\r
865 //\r
866 // Search for Root FV of this PE image\r
867 //\r
868 TempHandle = Handle;\r
869 do {\r
870 Status = gBS->HandleProtocol(\r
871 TempHandle, \r
872 &gEfiFirmwareVolumeBlockProtocolGuid,\r
873 (VOID**)&FvbProtocol\r
874 );\r
875 TempHandle = FvbProtocol->ParentHandle;\r
876 } while (!EFI_ERROR(Status) && FvbProtocol->ParentHandle != NULL);\r
877\r
878 //\r
879 // Search in measured FV Hob\r
880 //\r
881 Status = FvbProtocol->GetPhysicalAddress(FvbProtocol, &FvAddress);\r
882 if (EFI_ERROR(Status)){\r
883 return Status;\r
884 }\r
885\r
886 ApplicationRequired = FALSE;\r
887\r
888 for (Index = 0; Index < mMeasuredHobData->Num; Index++) {\r
889 if(mMeasuredHobData->MeasuredFvBuf[Index].BlobBase == FvAddress) {\r
890 //\r
891 // Cache measured FV for next measurement\r
892 //\r
893 mCacheMeasuredHandle = Handle;\r
894 ApplicationRequired = TRUE;\r
895 break;\r
896 }\r
897 }\r
898 }\r
899 }\r
900\r
901 //\r
902 // File is not found.\r
903 //\r
904 if (FileBuffer == NULL) {\r
905 Status = EFI_SECURITY_VIOLATION;\r
906 goto Finish;\r
907 }\r
908\r
909 mImageSize = FileSize;\r
910 mFileBuffer = FileBuffer;\r
911\r
912 //\r
913 // Measure PE Image\r
914 //\r
915 DevicePathNode = OrigDevicePathNode;\r
916 ZeroMem (&ImageContext, sizeof (ImageContext));\r
917 ImageContext.Handle = (VOID *) FileBuffer;\r
918 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeTpmMeasureBootLibImageRead;\r
919\r
920 //\r
921 // Get information about the image being loaded\r
922 //\r
923 Status = PeCoffLoaderGetImageInfo (&ImageContext);\r
924 if (EFI_ERROR (Status)) {\r
925 //\r
926 // The information can't be got from the invalid PeImage\r
927 //\r
928 goto Finish;\r
929 }\r
930 \r
931 //\r
932 // Measure only application if Application flag is set\r
933 // Measure drivers and applications if Application flag is not set\r
934 //\r
935 if ((!ApplicationRequired) || \r
936 (ApplicationRequired && ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) { \r
937 //\r
938 // Print the image path to be measured.\r
939 // \r
940 DEBUG_CODE_BEGIN ();\r
941 CHAR16 *ToText;\r
942 ToText = 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 FreePool (ToText);\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
970 if (OrigDevicePathNode != NULL) {\r
971 FreePool (OrigDevicePathNode);\r
972 }\r
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
993 EFI_HOB_GUID_TYPE *GuidHob;\r
994\r
995 GuidHob = NULL;\r
996\r
997 GuidHob = GetFirstGuidHob (&gMeasuredFvHobGuid);\r
998\r
999 if (GuidHob != NULL) {\r
1000 mMeasuredHobData = GET_GUID_HOB_DATA (GuidHob);\r
1001 }\r
1002\r
1003 return RegisterSecurity2Handler (\r
1004 DxeTpmMeasureBootHandler,\r
1005 EFI_AUTH_OPERATION_MEASURE_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED\r
1006 );\r
1007}\r