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