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