Add security package to repository.
[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 - 2011, 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 ASSERT (FALSE);
308 TcgEvent->EventType = ImageType;
309 Status = EFI_UNSUPPORTED;
310 goto Finish;
311 }
312
313 ImageLoad->ImageLocationInMemory = ImageAddress;
314 ImageLoad->ImageLengthInMemory = ImageSize;
315 ImageLoad->ImageLinkTimeAddress = LinkTimeBase;
316 ImageLoad->LengthOfDevicePath = FilePathSize;
317 CopyMem (ImageLoad->DevicePath, FilePath, FilePathSize);
318
319 //
320 // Check PE/COFF image
321 //
322 DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress;
323 PeCoffHeaderOffset = 0;
324 if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
325 PeCoffHeaderOffset = DosHdr->e_lfanew;
326 }
327 if (((EFI_TE_IMAGE_HEADER *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset))->Signature
328 == EFI_TE_IMAGE_HEADER_SIGNATURE) {
329 goto Finish;
330 }
331
332 //
333 // PE/COFF Image Measurement
334 //
335 // NOTE: The following codes/steps are based upon the authenticode image hashing in
336 // PE/COFF Specification 8.0 Appendix A.
337 //
338 //
339
340 // 1. Load the image header into memory.
341
342 // 2. Initialize a SHA hash context.
343 CtxSize = Sha1GetContextSize ();
344 Sha1Ctx = AllocatePool (CtxSize);
345 if (Sha1Ctx == NULL) {
346 Status = EFI_OUT_OF_RESOURCES;
347 goto Finish;
348 }
349
350 Sha1Init (Sha1Ctx);
351
352 //
353 // Measuring PE/COFF Image Header;
354 // But CheckSum field and SECURITY data directory (certificate) are excluded
355 //
356 Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset);
357 Magic = Hdr.Pe32->OptionalHeader.Magic;
358
359 //
360 // 3. Calculate the distance from the base of the image header to the image checksum address.
361 // 4. Hash the image header from its base to beginning of the image checksum.
362 //
363 HashBase = (UINT8 *) (UINTN) ImageAddress;
364 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
365 //
366 // Use PE32 offset
367 //
368 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
369 } else {
370 //
371 // Use PE32+ offset
372 //
373 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
374 }
375
376 Sha1Update (Sha1Ctx, HashBase, HashSize);
377
378 //
379 // 5. Skip over the image checksum (it occupies a single ULONG).
380 // 6. Get the address of the beginning of the Cert Directory.
381 // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
382 //
383 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
384 //
385 // Use PE32 offset
386 //
387 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
388 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
389 } else {
390 //
391 // Use PE32+ offset
392 //
393 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
394 HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
395 }
396
397 Sha1Update (Sha1Ctx, HashBase, HashSize);
398
399 //
400 // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
401 // 9. Hash everything from the end of the Cert Directory to the end of image header.
402 //
403 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
404 //
405 // Use PE32 offset
406 //
407 HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
408 HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders -
409 (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - (UINT8 *) (UINTN) ImageAddress);
410 } else {
411 //
412 // Use PE32+ offset
413 //
414 HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
415 HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders -
416 (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - (UINT8 *) (UINTN) ImageAddress);
417 }
418
419 Sha1Update (Sha1Ctx, HashBase, HashSize);
420
421 //
422 // 10. Set the SUM_OF_BYTES_HASHED to the size of the header
423 //
424 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
425 //
426 // Use PE32 offset
427 //
428 SumOfBytesHashed = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
429 } else {
430 //
431 // Use PE32+ offset
432 //
433 SumOfBytesHashed = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
434 }
435
436 //
437 // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
438 // structures in the image. The 'NumberOfSections' field of the image
439 // header indicates how big the table should be. Do not include any
440 // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
441 //
442 SectionHeader = (EFI_IMAGE_SECTION_HEADER *)AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * Hdr.Pe32->FileHeader.NumberOfSections);
443 if (SectionHeader == NULL) {
444 Status = EFI_OUT_OF_RESOURCES;
445 goto Finish;
446 }
447
448 //
449 // 12. Using the 'PointerToRawData' in the referenced section headers as
450 // a key, arrange the elements in the table in ascending order. In other
451 // words, sort the section headers according to the disk-file offset of
452 // the section.
453 //
454 Section = (EFI_IMAGE_SECTION_HEADER *) (
455 (UINT8 *) (UINTN) ImageAddress +
456 PeCoffHeaderOffset +
457 sizeof(UINT32) +
458 sizeof(EFI_IMAGE_FILE_HEADER) +
459 Hdr.Pe32->FileHeader.SizeOfOptionalHeader
460 );
461 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
462 Pos = Index;
463 while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
464 CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof(EFI_IMAGE_SECTION_HEADER));
465 Pos--;
466 }
467 CopyMem (&SectionHeader[Pos], Section, sizeof(EFI_IMAGE_SECTION_HEADER));
468 Section += 1;
469 }
470
471 //
472 // 13. Walk through the sorted table, bring the corresponding section
473 // into memory, and hash the entire section (using the 'SizeOfRawData'
474 // field in the section header to determine the amount of data to hash).
475 // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
476 // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
477 //
478 for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
479 Section = (EFI_IMAGE_SECTION_HEADER *) &SectionHeader[Index];
480 if (Section->SizeOfRawData == 0) {
481 continue;
482 }
483 HashBase = (UINT8 *) (UINTN) ImageAddress + Section->PointerToRawData;
484 HashSize = (UINTN) Section->SizeOfRawData;
485
486 Sha1Update (Sha1Ctx, HashBase, HashSize);
487
488 SumOfBytesHashed += HashSize;
489 }
490
491 //
492 // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
493 // data in the file that needs to be added to the hash. This data begins
494 // at file offset SUM_OF_BYTES_HASHED and its length is:
495 // FileSize - (CertDirectory->Size)
496 //
497 if (ImageSize > SumOfBytesHashed) {
498 HashBase = (UINT8 *) (UINTN) ImageAddress + SumOfBytesHashed;
499 if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
500 //
501 // Use PE32 offset
502 //
503 HashSize = (UINTN)(ImageSize -
504 Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size -
505 SumOfBytesHashed);
506 } else {
507 //
508 // Use PE32+ offset
509 //
510 HashSize = (UINTN)(ImageSize -
511 Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size -
512 SumOfBytesHashed);
513 }
514
515 Sha1Update (Sha1Ctx, HashBase, HashSize);
516 }
517
518 //
519 // 17. Finalize the SHA hash.
520 //
521 Sha1Final (Sha1Ctx, (UINT8 *)&TcgEvent->Digest);
522
523 //
524 // Log the PE data
525 //
526 EventNumber = 1;
527 Status = TcgProtocol->HashLogExtendEvent (
528 TcgProtocol,
529 (EFI_PHYSICAL_ADDRESS) (UINTN) (VOID *) NULL,
530 0,
531 TPM_ALG_SHA,
532 TcgEvent,
533 &EventNumber,
534 &EventLogLastEntry
535 );
536
537 Finish:
538 FreePool (TcgEvent);
539
540 if (SectionHeader != NULL) {
541 FreePool (SectionHeader);
542 }
543
544 if (Sha1Ctx != NULL ) {
545 FreePool (Sha1Ctx);
546 }
547 return Status;
548 }
549
550 /**
551 The security handler is used to abstract platform-specific policy
552 from the DXE core response to an attempt to use a file that returns a
553 given status for the authentication check from the section extraction protocol.
554
555 The possible responses in a given SAP implementation may include locking
556 flash upon failure to authenticate, attestation logging for all signed drivers,
557 and other exception operations. The File parameter allows for possible logging
558 within the SAP of the driver.
559
560 If File is NULL, then EFI_INVALID_PARAMETER is returned.
561
562 If the file specified by File with an authentication status specified by
563 AuthenticationStatus is safe for the DXE Core to use, then EFI_SUCCESS is returned.
564
565 If the file specified by File with an authentication status specified by
566 AuthenticationStatus is not safe for the DXE Core to use under any circumstances,
567 then EFI_ACCESS_DENIED is returned.
568
569 If the file specified by File with an authentication status specified by
570 AuthenticationStatus is not safe for the DXE Core to use right now, but it
571 might be possible to use it at a future time, then EFI_SECURITY_VIOLATION is
572 returned.
573
574 @param[in, out] AuthenticationStatus This is the authentication status returned
575 from the securitymeasurement services for the
576 input file.
577 @param[in] File This is a pointer to the device path of the file that is
578 being dispatched. This will optionally be used for logging.
579 @param[in] FileBuffer File buffer matches the input file device path.
580 @param[in] FileSize Size of File buffer matches the input file device path.
581
582 @retval EFI_SUCCESS The file specified by File did authenticate, and the
583 platform policy dictates that the DXE Core may use File.
584 @retval EFI_INVALID_PARAMETER File is NULL.
585 @retval EFI_SECURITY_VIOLATION The file specified by File did not authenticate, and
586 the platform policy dictates that File should be placed
587 in the untrusted state. A file may be promoted from
588 the untrusted to the trusted state at a future time
589 with a call to the Trust() DXE Service.
590 @retval EFI_ACCESS_DENIED The file specified by File did not authenticate, and
591 the platform policy dictates that File should not be
592 used for any purpose.
593
594 **/
595 EFI_STATUS
596 EFIAPI
597 DxeTpmMeasureBootHandler (
598 IN OUT UINT32 AuthenticationStatus,
599 IN CONST EFI_DEVICE_PATH_PROTOCOL *File,
600 IN VOID *FileBuffer OPTIONAL,
601 IN UINTN FileSize OPTIONAL
602 )
603 {
604 EFI_TCG_PROTOCOL *TcgProtocol;
605 EFI_STATUS Status;
606 TCG_EFI_BOOT_SERVICE_CAPABILITY ProtocolCapability;
607 UINT32 TCGFeatureFlags;
608 EFI_PHYSICAL_ADDRESS EventLogLocation;
609 EFI_PHYSICAL_ADDRESS EventLogLastEntry;
610 EFI_DEVICE_PATH_PROTOCOL *DevicePathNode;
611 EFI_DEVICE_PATH_PROTOCOL *OrigDevicePathNode;
612 EFI_HANDLE Handle;
613 BOOLEAN ApplicationRequired;
614 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
615
616 if (File == NULL) {
617 return EFI_INVALID_PARAMETER;
618 }
619
620 Status = gBS->LocateProtocol (&gEfiTcgProtocolGuid, NULL, (VOID **) &TcgProtocol);
621 if (EFI_ERROR (Status)) {
622 //
623 // TCG protocol is not installed. So, TPM is not present.
624 // Don't do any measurement, and directly return EFI_SUCCESS.
625 //
626 return EFI_SUCCESS;
627 }
628
629 ProtocolCapability.Size = (UINT8) sizeof (ProtocolCapability);
630 Status = TcgProtocol->StatusCheck (
631 TcgProtocol,
632 &ProtocolCapability,
633 &TCGFeatureFlags,
634 &EventLogLocation,
635 &EventLogLastEntry
636 );
637 if (EFI_ERROR (Status) || ProtocolCapability.TPMDeactivatedFlag) {
638 //
639 // TPM device doesn't work or activate.
640 //
641 return EFI_SUCCESS;
642 }
643
644 //
645 // Copy File Device Path
646 //
647 OrigDevicePathNode = DuplicateDevicePath (File);
648 ASSERT (OrigDevicePathNode != NULL);
649
650 //
651 // 1. Check whether this device path support BlockIo protocol.
652 // Is so, this device path may be a GPT device path.
653 //
654 DevicePathNode = OrigDevicePathNode;
655 Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &DevicePathNode, &Handle);
656 if (!EFI_ERROR (Status) && !mMeasureGptTableFlag) {
657 //
658 // Find the gpt partion on the given devicepath
659 //
660 DevicePathNode = OrigDevicePathNode;
661 while (!IsDevicePathEnd (DevicePathNode)) {
662 //
663 // Find the Gpt partition
664 //
665 if (DevicePathType (DevicePathNode) == MEDIA_DEVICE_PATH &&
666 DevicePathSubType (DevicePathNode) == MEDIA_HARDDRIVE_DP) {
667 //
668 // Check whether it is a gpt partition or not
669 //
670 if (((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER &&
671 ((HARDDRIVE_DEVICE_PATH *) DevicePathNode)->SignatureType == SIGNATURE_TYPE_GUID) {
672
673 //
674 // Change the partition device path to its parent device path (disk) and get the handle.
675 //
676 DevicePathNode->Type = END_DEVICE_PATH_TYPE;
677 DevicePathNode->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
678 DevicePathNode = OrigDevicePathNode;
679 Status = gBS->LocateDevicePath (
680 &gEfiDiskIoProtocolGuid,
681 &DevicePathNode,
682 &Handle
683 );
684 if (!EFI_ERROR (Status)) {
685 //
686 // Measure GPT disk.
687 //
688 Status = TcgMeasureGptTable (TcgProtocol, Handle);
689 if (!EFI_ERROR (Status)) {
690 //
691 // GPT disk check done.
692 //
693 mMeasureGptTableFlag = TRUE;
694 }
695 }
696 FreePool (OrigDevicePathNode);
697 OrigDevicePathNode = DuplicateDevicePath (File);
698 ASSERT (OrigDevicePathNode != NULL);
699 break;
700 }
701 }
702 DevicePathNode = NextDevicePathNode (DevicePathNode);
703 }
704 }
705
706 //
707 // 2. Measure PE image.
708 //
709 ApplicationRequired = FALSE;
710
711 //
712 // Check whether this device path support FV2 protocol.
713 //
714 DevicePathNode = OrigDevicePathNode;
715 Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &DevicePathNode, &Handle);
716 if (!EFI_ERROR (Status)) {
717 //
718 // Don't check FV image, and directly return EFI_SUCCESS.
719 // It can be extended to the specific FV authentication according to the different requirement.
720 //
721 if (IsDevicePathEnd (DevicePathNode)) {
722 return EFI_SUCCESS;
723 }
724 //
725 // The image from Firmware image will not be mearsured.
726 // Current policy doesn't measure PeImage from Firmware if it is driver
727 // If the got PeImage is application, it will be still be measured.
728 //
729 ApplicationRequired = TRUE;
730 }
731
732 //
733 // File is not found.
734 //
735 if (FileBuffer == NULL) {
736 Status = EFI_SECURITY_VIOLATION;
737 goto Finish;
738 }
739
740 //
741 // Measure PE Image
742 //
743 DevicePathNode = OrigDevicePathNode;
744 ZeroMem (&ImageContext, sizeof (ImageContext));
745 ImageContext.Handle = (VOID *) FileBuffer;
746 ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE) ImageRead;
747
748 //
749 // Get information about the image being loaded
750 //
751 Status = PeCoffLoaderGetImageInfo (&ImageContext);
752 if (EFI_ERROR (Status)) {
753 //
754 // The information can't be got from the invalid PeImage
755 //
756 goto Finish;
757 }
758
759 //
760 // Measure only application if Application flag is set
761 // Measure drivers and applications if Application flag is not set
762 //
763 if ((!ApplicationRequired) ||
764 (ApplicationRequired && ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) {
765 //
766 // Print the image path to be measured.
767 //
768 DEBUG_CODE_BEGIN ();
769 CHAR16 *ToText;
770 EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText;
771 Status = gBS->LocateProtocol (
772 &gEfiDevicePathToTextProtocolGuid,
773 NULL,
774 (VOID **) &DevPathToText
775 );
776 if (!EFI_ERROR (Status)) {
777 ToText = DevPathToText->ConvertDevicePathToText (
778 DevicePathNode,
779 FALSE,
780 TRUE
781 );
782 if (ToText != NULL) {
783 DEBUG ((DEBUG_INFO, "The measured image path is %s.\n", ToText));
784 }
785 }
786 DEBUG_CODE_END ();
787
788 //
789 // Measure PE image into TPM log.
790 //
791 Status = TcgMeasurePeImage (
792 TcgProtocol,
793 (EFI_PHYSICAL_ADDRESS) (UINTN) FileBuffer,
794 FileSize,
795 (UINTN) ImageContext.ImageAddress,
796 ImageContext.ImageType,
797 DevicePathNode
798 );
799 }
800
801 //
802 // Done, free the allocated resource.
803 //
804 Finish:
805 FreePool (OrigDevicePathNode);
806
807 return Status;
808 }
809
810 /**
811 Register the security handler to provide TPM measure boot service.
812
813 @param ImageHandle ImageHandle of the loaded driver.
814 @param SystemTable Pointer to the EFI System Table.
815
816 @retval EFI_SUCCESS Register successfully.
817 @retval EFI_OUT_OF_RESOURCES No enough memory to register this handler.
818 **/
819 EFI_STATUS
820 EFIAPI
821 DxeTpmMeasureBootLibConstructor (
822 IN EFI_HANDLE ImageHandle,
823 IN EFI_SYSTEM_TABLE *SystemTable
824 )
825 {
826 return RegisterSecurityHandler (
827 DxeTpmMeasureBootHandler,
828 EFI_AUTH_OPERATION_MEASURE_IMAGE | EFI_AUTH_OPERATION_IMAGE_REQUIRED
829 );
830 }