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