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