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