d11ec13373c2b1b0454bf0cdbdef932c1109b384
[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 - 2013, 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 EFI_GUID mZeroGuid = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};
54 UINTN mMeasureGptCount = 0;
55 VOID *mFileBuffer;
56 UINTN mImageSize;
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 > mImageSize) {
99 *ReadSize = (UINT32)(mImageSize - FileOffset);
100 }
101
102 if (FileOffset >= mImageSize) {
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, &mZeroGuid)) {
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, &mZeroGuid)) {
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 @param[in] TcgProtocol Pointer to the located TCG protocol instance.
283 @param[in] ImageAddress Start address of image buffer.
284 @param[in] ImageSize Image size
285 @param[in] LinkTimeBase Address that the image is loaded into memory.
286 @param[in] ImageType Image subsystem type.
287 @param[in] FilePath File path is corresponding to the input image.
288
289 @retval EFI_SUCCESS Successfully measure image.
290 @retval EFI_OUT_OF_RESOURCES No enough resource to measure image.
291 @retval EFI_UNSUPPORTED ImageType is unsupported or PE image is mal-format.
292 @retval other error value
293
294 **/
295 EFI_STATUS
296 EFIAPI
297 TcgMeasurePeImage (
298 IN EFI_TCG_PROTOCOL *TcgProtocol,
299 IN EFI_PHYSICAL_ADDRESS ImageAddress,
300 IN UINTN ImageSize,
301 IN UINTN LinkTimeBase,
302 IN UINT16 ImageType,
303 IN EFI_DEVICE_PATH_PROTOCOL *FilePath
304 )
305 {
306 EFI_STATUS Status;
307 TCG_PCR_EVENT *TcgEvent;
308 EFI_IMAGE_LOAD_EVENT *ImageLoad;
309 UINT32 FilePathSize;
310 VOID *Sha1Ctx;
311 UINTN CtxSize;
312 EFI_IMAGE_DOS_HEADER *DosHdr;
313 UINT32 PeCoffHeaderOffset;
314 EFI_IMAGE_SECTION_HEADER *Section;
315 UINT8 *HashBase;
316 UINTN HashSize;
317 UINTN SumOfBytesHashed;
318 EFI_IMAGE_SECTION_HEADER *SectionHeader;
319 UINTN Index;
320 UINTN Pos;
321 UINT16 Magic;
322 UINT32 EventSize;
323 UINT32 EventNumber;
324 EFI_PHYSICAL_ADDRESS EventLogLastEntry;
325 EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
326 UINT32 NumberOfRvaAndSizes;
327 BOOLEAN HashStatus;
328 UINT32 CertSize;
329
330 Status = EFI_UNSUPPORTED;
331 ImageLoad = NULL;
332 SectionHeader = NULL;
333 Sha1Ctx = NULL;
334 FilePathSize = (UINT32) GetDevicePathSize (FilePath);
335
336 //
337 // Determine destination PCR by BootPolicy
338 //
339 EventSize = sizeof (*ImageLoad) - sizeof (ImageLoad->DevicePath) + FilePathSize;
340 TcgEvent = AllocateZeroPool (EventSize + sizeof (TCG_PCR_EVENT));
341 if (TcgEvent == NULL) {
342 return EFI_OUT_OF_RESOURCES;
343 }
344
345 TcgEvent->EventSize = EventSize;
346 ImageLoad = (EFI_IMAGE_LOAD_EVENT *) TcgEvent->Event;
347
348 switch (ImageType) {
349 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
350 TcgEvent->EventType = EV_EFI_BOOT_SERVICES_APPLICATION;
351 TcgEvent->PCRIndex = 4;
352 break;
353 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
354 TcgEvent->EventType = EV_EFI_BOOT_SERVICES_DRIVER;
355 TcgEvent->PCRIndex = 2;
356 break;
357 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
358 TcgEvent->EventType = EV_EFI_RUNTIME_SERVICES_DRIVER;
359 TcgEvent->PCRIndex = 2;
360 break;
361 default:
362 DEBUG ((
363 EFI_D_ERROR,
364 "TcgMeasurePeImage: Unknown subsystem type %d",
365 ImageType
366 ));
367 goto Finish;
368 }
369
370 ImageLoad->ImageLocationInMemory = ImageAddress;
371 ImageLoad->ImageLengthInMemory = ImageSize;
372 ImageLoad->ImageLinkTimeAddress = LinkTimeBase;
373 ImageLoad->LengthOfDevicePath = FilePathSize;
374 CopyMem (ImageLoad->DevicePath, FilePath, FilePathSize);
375
376 //
377 // Check PE/COFF image
378 //
379 DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress;
380 PeCoffHeaderOffset = 0;
381 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
382 PeCoffHeaderOffset = DosHdr->e_lfanew;
383 }
384
385 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset);
386 if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
387 goto Finish;
388 }
389
390 //
391 // PE/COFF Image Measurement
392 //
393 // NOTE: The following codes/steps are based upon the authenticode image hashing in
394 // PE/COFF Specification 8.0 Appendix A.
395 //
396 //
397
398 // 1. Load the image header into memory.
399
400 // 2. Initialize a SHA hash context.
401 CtxSize = Sha1GetContextSize ();
402 Sha1Ctx = AllocatePool (CtxSize);
403 if (Sha1Ctx == NULL) {
404 Status = EFI_OUT_OF_RESOURCES;
405 goto Finish;
406 }
407
408 HashStatus = Sha1Init (Sha1Ctx);
409 if (!HashStatus) {
410 goto Finish;
411 }
412
413 //
414 // Measuring PE/COFF Image Header;
415 // But CheckSum field and SECURITY data directory (certificate) are excluded
416 //
417 if (Hdr.Pe32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 && Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
418 //
419 // NOTE: Some versions of Linux ELILO for Itanium have an incorrect magic value
420 // in the PE/COFF Header. If the MachineType is Itanium(IA64) and the
421 // Magic value in the OptionalHeader is EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC
422 // then override the magic value to EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC
423 //
424 Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
425 } else {
426 //
427 // Get the magic value from the PE/COFF Optional Header
428 //
429 Magic = Hdr.Pe32->OptionalHeader.Magic;
430 }
431
432 //
433 // 3. Calculate the distance from the base of the image header to the image checksum address.
434 // 4. Hash the image header from its base to beginning of the image checksum.
435 //
436 HashBase = (UINT8 *) (UINTN) ImageAddress;
437 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
438 //
439 // Use PE32 offset
440 //
441 NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
442 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
443 } else {
444 //
445 // Use PE32+ offset
446 //
447 NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
448 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
449 }
450
451 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
452 if (!HashStatus) {
453 goto Finish;
454 }
455
456 //
457 // 5. Skip over the image checksum (it occupies a single ULONG).
458 //
459 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
460 //
461 // 6. Since there is no Cert Directory in optional header, hash everything
462 // from the end of the checksum to the end of image header.
463 //
464 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
465 //
466 // Use PE32 offset.
467 //
468 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
469 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);
470 } else {
471 //
472 // Use PE32+ offset.
473 //
474 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
475 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);
476 }
477
478 if (HashSize != 0) {
479 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
480 if (!HashStatus) {
481 goto Finish;
482 }
483 }
484 } else {
485 //
486 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
487 //
488 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
489 //
490 // Use PE32 offset
491 //
492 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
493 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
494 } else {
495 //
496 // Use PE32+ offset
497 //
498 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
499 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
500 }
501
502 if (HashSize != 0) {
503 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
504 if (!HashStatus) {
505 goto Finish;
506 }
507 }
508
509 //
510 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
511 // 9. Hash everything from the end of the Cert Directory to the end of image header.
512 //
513 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
514 //
515 // Use PE32 offset
516 //
517 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
518 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);
519 } else {
520 //
521 // Use PE32+ offset
522 //
523 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
524 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - ImageAddress);
525 }
526
527 if (HashSize != 0) {
528 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
529 if (!HashStatus) {
530 goto Finish;
531 }
532 }
533 }
534
535 //
536 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header
537 //
538 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
539 //
540 // Use PE32 offset
541 //
542 SumOfBytesHashed = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
543 } else {
544 //
545 // Use PE32+ offset
546 //
547 SumOfBytesHashed = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
548 }
549
550 //
551 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
552 // structures in the image. The 'NumberOfSections' field of the image
553 // header indicates how big the table should be. Do not include any
554 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
555 //
556 SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * Hdr.Pe32->FileHeader.NumberOfSections);
557 if (SectionHeader == NULL) {
558 Status = EFI_OUT_OF_RESOURCES;
559 goto Finish;
560 }
561
562 //
563 // 12. Using the 'PointerToRawData' in the referenced section headers as
564 // a key, arrange the elements in the table in ascending order. In other
565 // words, sort the section headers according to the disk-file offset of
566 // the section.
567 //
568 Section = (EFI_IMAGE_SECTION_HEADER *) (
569 (UINT8 *) (UINTN) ImageAddress +
570 PeCoffHeaderOffset +
571 sizeof(UINT32) +
572 sizeof(EFI_IMAGE_FILE_HEADER) +
573 Hdr.Pe32->FileHeader.SizeOfOptionalHeader
574 );
575 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
576 Pos = Index;
577 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
578 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof(EFI_IMAGE_SECTION_HEADER));
579 Pos--;
580 }
581 CopyMem (&SectionHeader[Pos], Section, sizeof(EFI_IMAGE_SECTION_HEADER));
582 Section += 1;
583 }
584
585 //
586 // 13. Walk through the sorted table, bring the corresponding section
587 // into memory, and hash the entire section (using the 'SizeOfRawData'
588 // field in the section header to determine the amount of data to hash).
589 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
590 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
591 //
592 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
593 Section = (EFI_IMAGE_SECTION_HEADER *) &SectionHeader[Index];
594 if (Section->SizeOfRawData == 0) {
595 continue;
596 }
597 HashBase = (UINT8 *) (UINTN) ImageAddress + Section->PointerToRawData;
598 HashSize = (UINTN) Section->SizeOfRawData;
599
600 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
601 if (!HashStatus) {
602 goto Finish;
603 }
604
605 SumOfBytesHashed += HashSize;
606 }
607
608 //
609 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
610 // data in the file that needs to be added to the hash. This data begins
611 // at file offset SUM_OF_BYTES_HASHED and its length is:
612 // FileSize - (CertDirectory->Size)
613 //
614 if (ImageSize > SumOfBytesHashed) {
615 HashBase = (UINT8 *) (UINTN) ImageAddress + SumOfBytesHashed;
616
617 if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
618 CertSize = 0;
619 } else {
620 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
621 //
622 // Use PE32 offset.
623 //
624 CertSize = Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
625 } else {
626 //
627 // Use PE32+ offset.
628 //
629 CertSize = Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
630 }
631 }
632
633 if (ImageSize > CertSize + SumOfBytesHashed) {
634 HashSize = (UINTN) (ImageSize - CertSize - SumOfBytesHashed);
635
636 HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
637 if (!HashStatus) {
638 goto Finish;
639 }
640 } else if (ImageSize < CertSize + SumOfBytesHashed) {
641 goto Finish;
642 }
643 }
644
645 //
646 // 17. Finalize the SHA hash.
647 //
648 HashStatus = Sha1Final (Sha1Ctx, (UINT8 *) &TcgEvent->Digest);
649 if (!HashStatus) {
650 goto Finish;
651 }
652
653 //
654 // Log the PE data
655 //
656 EventNumber = 1;
657 Status = TcgProtocol->HashLogExtendEvent (
658 TcgProtocol,
659 (EFI_PHYSICAL_ADDRESS) (UINTN) (VOID *) NULL,
660 0,
661 TPM_ALG_SHA,
662 TcgEvent,
663 &EventNumber,
664 &EventLogLastEntry
665 );
666 if (Status == EFI_OUT_OF_RESOURCES) {
667 //
668 // Out of resource here means the image is hashed and its result is extended to PCR.
669 // But the event log cann't be saved since log area is full.
670 // Just return EFI_SUCCESS in order not to block the image load.
671 //
672 Status = EFI_SUCCESS;
673 }
674
675 Finish:
676 FreePool (TcgEvent);
677
678 if (SectionHeader != NULL) {
679 FreePool (SectionHeader);
680 }
681
682 if (Sha1Ctx != NULL ) {
683 FreePool (Sha1Ctx);
684 }
685 return Status;
686 }
687
688 /**
689 The security handler is used to abstract platform-specific policy
690 from the DXE core response to an attempt to use a file that returns a
691 given status for the authentication check from the section extraction protocol.
692
693 The possible responses in a given SAP implementation may include locking
694 flash upon failure to authenticate, attestation logging for all signed drivers,
695 and other exception operations. The File parameter allows for possible logging
696 within the SAP of the driver.
697
698 If File is NULL, then EFI_INVALID_PARAMETER is returned.
699
700 If the file specified by File with an authentication status specified by
701 AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.
702
703 If the file specified by File with an authentication status specified by
704 AuthenticationStatus is not safe for the DXE Core to use under any circumstances,
705 then EFI_ACCESS_DENIED is returned.
706
707 If the file specified by File with an authentication status specified by
708 AuthenticationStatus is not safe for the DXE Core to use right now, but it
709 might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is
710 returned.
711
712 @param[in] AuthenticationStatus This is the authentication status returned
713 from the securitymeasurement services for the
714 input file.
715 @param[in] File This is a pointer to the device path of the file that is
716 being dispatched. This will optionally be used for logging.
717 @param[in] FileBuffer File buffer matches the input file device path.
718 @param[in] FileSize Size of File buffer matches the input file device path.
719 @param[in] BootPolicy A boot policy that was used to call LoadImage() UEFI service.
720
721 @retval EFI_SUCCESS The file specified by DevicePath and non-NULL
722 FileBuffer did authenticate, and the platform policy dictates
723 that the DXE Foundation may use the file.
724 @retval other error value
725 **/
726 EFI_STATUS
727 EFIAPI
728 DxeTpmMeasureBootHandler (
729 IN UINT32 AuthenticationStatus,
730 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
731 IN VOID *FileBuffer,
732 IN UINTN FileSize,
733 IN BOOLEAN BootPolicy
734 )
735 {
736 EFI_TCG_PROTOCOL *TcgProtocol;
737 EFI_STATUS Status;
738 TCG_EFI_BOOT_SERVICE_CAPABILITY ProtocolCapability;
739 UINT32 TCGFeatureFlags;
740 EFI_PHYSICAL_ADDRESS EventLogLocation;
741 EFI_PHYSICAL_ADDRESS EventLogLastEntry;
742 EFI_DEVICE_PATH_PROTOCOL *DevicePathNode;
743 EFI_DEVICE_PATH_PROTOCOL *OrigDevicePathNode;
744 EFI_HANDLE Handle;
745 EFI_HANDLE TempHandle;
746 BOOLEAN ApplicationRequired;
747 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
748 EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;
749 EFI_PHYSICAL_ADDRESS FvAddress;
750 UINT32 Index;
751
752 Status = gBS->LocateProtocol (&gEfiTcgProtocolGuid, NULL, (VOID **) &TcgProtocol);
753 if (EFI_ERROR (Status)) {
754 //
755 // TCG protocol is not installed. So, TPM is not present.
756 // Don't do any measurement, and directly return EFI_SUCCESS.
757 //
758 return EFI_SUCCESS;
759 }
760
761 ProtocolCapability.Size = (UINT8) sizeof (ProtocolCapability);
762 Status = TcgProtocol->StatusCheck (
763 TcgProtocol,
764 &ProtocolCapability,
765 &TCGFeatureFlags,
766 &EventLogLocation,
767 &EventLogLastEntry
768 );
769 if (EFI_ERROR (Status) || ProtocolCapability.TPMDeactivatedFlag) {
770 //
771 // TPM device doesn't work or activate.
772 //
773 return EFI_SUCCESS;
774 }
775
776 //
777 // Copy File Device Path
778 //
779 OrigDevicePathNode = DuplicateDevicePath (File);
780
781 //
782 // 1. Check whether this device path support BlockIo protocol.
783 // Is so, this device path may be a GPT device path.
784 //
785 DevicePathNode = OrigDevicePathNode;
786 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &DevicePathNode, &Handle);
787 if (!EFI_ERROR (Status) && !mMeasureGptTableFlag) {
788 //
789 // Find the gpt partion on the given devicepath
790 //
791 DevicePathNode = OrigDevicePathNode;
792 ASSERT (DevicePathNode != NULL);
793 while (!IsDevicePathEnd (DevicePathNode)) {
794 //
795 // Find the Gpt partition
796 //
797 if (DevicePathType (DevicePathNode) == MEDIA_DEVICE_PATH &&
798 DevicePathSubType (DevicePathNode) == MEDIA_HARDDRIVE_DP) {
799 //
800 // Check whether it is a gpt partition or not
801 //
802 if (((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER &&
803 ((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->SignatureType == SIGNATURE_TYPE_GUID) {
804
805 //
806 // Change the partition device path to its parent device path (disk) and get the handle.
807 //
808 DevicePathNode->Type = END_DEVICE_PATH_TYPE;
809 DevicePathNode->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
810 DevicePathNode = OrigDevicePathNode;
811 Status = gBS->LocateDevicePath (
812 &gEfiDiskIoProtocolGuid,
813 &DevicePathNode,
814 &Handle
815 );
816 if (!EFI_ERROR (Status)) {
817 //
818 // Measure GPT disk.
819 //
820 Status = TcgMeasureGptTable (TcgProtocol, Handle);
821 if (!EFI_ERROR (Status)) {
822 //
823 // GPT disk check done.
824 //
825 mMeasureGptTableFlag = TRUE;
826 }
827 }
828 FreePool (OrigDevicePathNode);
829 OrigDevicePathNode = DuplicateDevicePath (File);
830 ASSERT (OrigDevicePathNode != NULL);
831 break;
832 }
833 }
834 DevicePathNode = NextDevicePathNode (DevicePathNode);
835 }
836 }
837
838 //
839 // 2. Measure PE image.
840 //
841 ApplicationRequired = FALSE;
842
843 //
844 // Check whether this device path support FVB protocol.
845 //
846 DevicePathNode = OrigDevicePathNode;
847 Status = gBS->LocateDevicePath (&gEfiFirmwareVolumeBlockProtocolGuid, &DevicePathNode, &Handle);
848 if (!EFI_ERROR (Status)) {
849 //
850 // Don't check FV image, and directly return EFI_SUCCESS.
851 // It can be extended to the specific FV authentication according to the different requirement.
852 //
853 if (IsDevicePathEnd (DevicePathNode)) {
854 return EFI_SUCCESS;
855 }
856 //
857 // The PE image from unmeasured Firmware volume need be measured
858 // The PE image from measured Firmware volume will be mearsured according to policy below.
859 // If it is driver, do not measure
860 // If it is application, still measure.
861 //
862 ApplicationRequired = TRUE;
863
864 if (mCacheMeasuredHandle != Handle && mMeasuredHobData != NULL) {
865 //
866 // Search for Root FV of this PE image
867 //
868 TempHandle = Handle;
869 do {
870 Status = gBS->HandleProtocol(
871 TempHandle,
872 &gEfiFirmwareVolumeBlockProtocolGuid,
873 (VOID**)&FvbProtocol
874 );
875 TempHandle = FvbProtocol->ParentHandle;
876 } while (!EFI_ERROR(Status) && FvbProtocol->ParentHandle != NULL);
877
878 //
879 // Search in measured FV Hob
880 //
881 Status = FvbProtocol->GetPhysicalAddress(FvbProtocol, &FvAddress);
882 if (EFI_ERROR(Status)){
883 return Status;
884 }
885
886 ApplicationRequired = FALSE;
887
888 for (Index = 0; Index < mMeasuredHobData->Num; Index++) {
889 if(mMeasuredHobData->MeasuredFvBuf[Index].BlobBase == FvAddress) {
890 //
891 // Cache measured FV for next measurement
892 //
893 mCacheMeasuredHandle = Handle;
894 ApplicationRequired = TRUE;
895 break;
896 }
897 }
898 }
899 }
900
901 //
902 // File is not found.
903 //
904 if (FileBuffer == NULL) {
905 Status = EFI_SECURITY_VIOLATION;
906 goto Finish;
907 }
908
909 mImageSize = FileSize;
910 mFileBuffer = FileBuffer;
911
912 //
913 // Measure PE Image
914 //
915 DevicePathNode = OrigDevicePathNode;
916 ZeroMem (&ImageContext, sizeof (ImageContext));
917 ImageContext.Handle = (VOID *) FileBuffer;
918 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) DxeTpmMeasureBootLibImageRead;
919
920 //
921 // Get information about the image being loaded
922 //
923 Status = PeCoffLoaderGetImageInfo (&ImageContext);
924 if (EFI_ERROR (Status)) {
925 //
926 // The information can't be got from the invalid PeImage
927 //
928 goto Finish;
929 }
930
931 //
932 // Measure only application if Application flag is set
933 // Measure drivers and applications if Application flag is not set
934 //
935 if ((!ApplicationRequired) ||
936 (ApplicationRequired && ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) {
937 //
938 // Print the image path to be measured.
939 //
940 DEBUG_CODE_BEGIN ();
941 CHAR16 *ToText;
942 ToText = ConvertDevicePathToText (
943 DevicePathNode,
944 FALSE,
945 TRUE
946 );
947 if (ToText != NULL) {
948 DEBUG ((DEBUG_INFO, "The measured image path is %s.\n", ToText));
949 FreePool (ToText);
950 }
951 DEBUG_CODE_END ();
952
953 //
954 // Measure PE image into TPM log.
955 //
956 Status = TcgMeasurePeImage (
957 TcgProtocol,
958 (EFI_PHYSICAL_ADDRESS) (UINTN) FileBuffer,
959 FileSize,
960 (UINTN) ImageContext.ImageAddress,
961 ImageContext.ImageType,
962 DevicePathNode
963 );
964 }
965
966 //
967 // Done, free the allocated resource.
968 //
969 Finish:
970 if (OrigDevicePathNode != NULL) {
971 FreePool (OrigDevicePathNode);
972 }
973
974 return Status;
975 }
976
977 /**
978 Register the security handler to provide TPM measure boot service.
979
980 @param ImageHandle ImageHandle of the loaded driver.
981 @param SystemTable Pointer to the EFI System Table.
982
983 @retval EFI_SUCCESS Register successfully.
984 @retval EFI_OUT_OF_RESOURCES No enough memory to register this handler.
985 **/
986 EFI_STATUS
987 EFIAPI
988 DxeTpmMeasureBootLibConstructor (
989 IN EFI_HANDLE ImageHandle,
990 IN EFI_SYSTEM_TABLE *SystemTable
991 )
992 {
993 EFI_HOB_GUID_TYPE *GuidHob;
994
995 GuidHob = NULL;
996
997 GuidHob = GetFirstGuidHob (&gMeasuredFvHobGuid);
998
999 if (GuidHob != NULL) {
1000 mMeasuredHobData = GET_GUID_HOB_DATA (GuidHob);
1001 }
1002
1003 return RegisterSecurity2Handler (
1004 DxeTpmMeasureBootHandler,
1005 EFI_AUTH_OPERATION_MEASURE_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
1006 );
1007 }