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