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