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