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