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