1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Defines APIs that allow an OS to interact with UEFI firmware to query
4 * information about the device.
5 * https://trustedcomputinggroup.org/resource/tcg-efi-protocol-specification/
6 *
7 * Copyright (c) 2020, Linaro Limited
8 */
9
10#define LOG_CATEGORY LOGC_EFI
11#include <dm.h>
12#include <efi_loader.h>
13#include <efi_variable.h>
14#include <efi_tcg2.h>
15#include <log.h>
16#include <malloc.h>
17#include <smbios.h>
18#include <version_string.h>
19#include <tpm-v2.h>
20#include <tpm_api.h>
21#include <u-boot/hash-checksum.h>
22#include <u-boot/sha1.h>
23#include <u-boot/sha256.h>
24#include <u-boot/sha512.h>
25#include <linux/unaligned/be_byteshift.h>
26#include <linux/unaligned/le_byteshift.h>
27#include <linux/unaligned/generic.h>
28#include <hexdump.h>
29
30/**
31 * struct event_log_buffer - internal eventlog management structure
32 *
33 * @buffer:		eventlog buffer
34 * @final_buffer:	finalevent config table buffer
35 * @pos:		current position of 'buffer'
36 * @final_pos:		current position of 'final_buffer'
37 * @get_event_called:	true if GetEventLog has been invoked at least once
38 * @ebs_called:		true if ExitBootServices has been invoked
39 * @truncated:		true if the 'buffer' is truncated
40 */
41struct event_log_buffer {
42	void *buffer;
43	void *final_buffer;
44	size_t pos; /* eventlog position */
45	size_t final_pos; /* final events config table position */
46	size_t last_event_size;
47	bool get_event_called;
48	bool ebs_called;
49	bool truncated;
50};
51
52static struct event_log_buffer event_log;
53static bool tcg2_efi_app_invoked;
54/*
55 * When requesting TPM2_CAP_TPM_PROPERTIES the value is on a standard offset.
56 * Since the current tpm2_get_capability() response buffers starts at
57 * 'union tpmu_capabilities data' of 'struct tpms_capability_data', calculate
58 * the response size and offset once for all consumers
59 */
60#define TPM2_RESPONSE_BUFFER_SIZE (sizeof(struct tpms_capability_data) - \
61				   offsetof(struct tpms_capability_data, data))
62#define properties_offset (offsetof(struct tpml_tagged_tpm_property, tpm_property) + \
63			   offsetof(struct tpms_tagged_property, value))
64
65static const efi_guid_t efi_guid_tcg2_protocol = EFI_TCG2_PROTOCOL_GUID;
66static const efi_guid_t efi_guid_final_events = EFI_TCG2_FINAL_EVENTS_TABLE_GUID;
67
68struct variable_info {
69	const u16	*name;
70	bool		accept_empty;
71	u32		pcr_index;
72};
73
74static struct variable_info secure_variables[] = {
75	{u"SecureBoot",		true,	7},
76	{u"PK",			true,	7},
77	{u"KEK",		true,	7},
78	{u"db",			true,	7},
79	{u"dbx",		true,	7},
80	{u"dbt",		false,	7},
81	{u"dbr",		false,	7},
82	{u"DeployedMode",	false,	1},
83	{u"AuditMode",		false,	1},
84};
85
86static bool is_tcg2_protocol_installed(void)
87{
88	struct efi_handler *handler;
89	efi_status_t ret;
90
91	ret = efi_search_protocol(efi_root, &efi_guid_tcg2_protocol, &handler);
92	return ret == EFI_SUCCESS;
93}
94
95/* tcg2_agile_log_append - Append an agile event to an eventlog
96 *
97 * @pcr_index:		PCR index
98 * @event_type:		type of event added
99 * @digest_list:	list of digest algorithms to add
100 * @size:		size of event
101 * @event:		event to add
102 * @log:		log buffer to append the event
103 *
104 * @Return: status code
105 */
106static efi_status_t tcg2_agile_log_append(u32 pcr_index, u32 event_type,
107					  struct tpml_digest_values *digest_list,
108					  u32 size, u8 event[])
109{
110	void *log = (void *)((uintptr_t)event_log.buffer + event_log.pos);
111	u32 event_size = size + tcg2_event_get_size(digest_list);
112	struct efi_tcg2_final_events_table *final_event;
113	efi_status_t ret = EFI_SUCCESS;
114
115	/* if ExitBootServices hasn't been called update the normal log */
116	if (!event_log.ebs_called) {
117		if (event_log.truncated ||
118		    event_log.pos + event_size > TPM2_EVENT_LOG_SIZE) {
119			event_log.truncated = true;
120			return EFI_VOLUME_FULL;
121		}
122		tcg2_log_append(pcr_index, event_type, digest_list, size, event, log);
123		event_log.pos += event_size;
124		event_log.last_event_size = event_size;
125	}
126
127	if (!event_log.get_event_called)
128		return ret;
129
130	/* if GetEventLog has been called update FinalEventLog as well */
131	if (event_log.final_pos + event_size > TPM2_EVENT_LOG_SIZE)
132		return EFI_VOLUME_FULL;
133
134	log = (void *)((uintptr_t)event_log.final_buffer + event_log.final_pos);
135	tcg2_log_append(pcr_index, event_type, digest_list, size, event, log);
136
137	final_event = event_log.final_buffer;
138	final_event->number_of_events++;
139	event_log.final_pos += event_size;
140
141	return ret;
142}
143
144/**
145 * tpm2_get_max_command_size() - get the supported max command size
146 *
147 * @dev:		TPM device
148 * @max_command_size:	output buffer for the size
149 *
150 * Return: 0 on success, -1 on error
151 */
152static int tpm2_get_max_command_size(struct udevice *dev, u16 *max_command_size)
153{
154	u8 response[TPM2_RESPONSE_BUFFER_SIZE];
155	u32 ret;
156
157	memset(response, 0, sizeof(response));
158	ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
159				  TPM2_PT_MAX_COMMAND_SIZE, response, 1);
160	if (ret)
161		return -1;
162
163	*max_command_size = (uint16_t)get_unaligned_be32(response +
164							 properties_offset);
165
166	return 0;
167}
168
169/**
170 * tpm2_get_max_response_size() - get the supported max response size
171 *
172 * @dev:		TPM device
173 * @max_response_size:	output buffer for the size
174 *
175 * Return: 0 on success, -1 on error
176 */
177static int tpm2_get_max_response_size(struct udevice *dev,
178				      u16 *max_response_size)
179{
180	u8 response[TPM2_RESPONSE_BUFFER_SIZE];
181	u32 ret;
182
183	memset(response, 0, sizeof(response));
184	ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
185				  TPM2_PT_MAX_RESPONSE_SIZE, response, 1);
186	if (ret)
187		return -1;
188
189	*max_response_size = (uint16_t)get_unaligned_be32(response +
190							  properties_offset);
191
192	return 0;
193}
194
195/**
196 * tpm2_get_manufacturer_id() - get the manufacturer ID
197 *
198 * @dev:		TPM device
199 * @manufacturer_id:	output buffer for the id
200 *
201 * Return: 0 on success, -1 on error
202 */
203static int tpm2_get_manufacturer_id(struct udevice *dev, u32 *manufacturer_id)
204{
205	u8 response[TPM2_RESPONSE_BUFFER_SIZE];
206	u32 ret;
207
208	memset(response, 0, sizeof(response));
209	ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
210				  TPM2_PT_MANUFACTURER, response, 1);
211	if (ret)
212		return -1;
213
214	*manufacturer_id = get_unaligned_be32(response + properties_offset);
215
216	return 0;
217}
218
219/**
220 * efi_tcg2_get_capability() - protocol capability information and state information
221 *
222 * @this:		TCG2 protocol instance
223 * @capability:		caller allocated memory with size field to the size of
224 *			the structure allocated
225
226 * Return:	status code
227 */
228static efi_status_t EFIAPI
229efi_tcg2_get_capability(struct efi_tcg2_protocol *this,
230			struct efi_tcg2_boot_service_capability *capability)
231{
232	struct udevice *dev;
233	efi_status_t efi_ret;
234	int ret;
235
236	EFI_ENTRY("%p, %p", this, capability);
237
238	if (!this || !capability) {
239		efi_ret = EFI_INVALID_PARAMETER;
240		goto out;
241	}
242
243	if (capability->size < BOOT_SERVICE_CAPABILITY_MIN) {
244		capability->size = BOOT_SERVICE_CAPABILITY_MIN;
245		efi_ret = EFI_BUFFER_TOO_SMALL;
246		goto out;
247	}
248
249	if (capability->size < sizeof(*capability)) {
250		capability->size = sizeof(*capability);
251		efi_ret = EFI_BUFFER_TOO_SMALL;
252		goto out;
253	}
254
255	capability->structure_version.major = 1;
256	capability->structure_version.minor = 1;
257	capability->protocol_version.major = 1;
258	capability->protocol_version.minor = 1;
259
260	efi_ret = tcg2_platform_get_tpm2(&dev);
261	if (efi_ret != EFI_SUCCESS) {
262		capability->supported_event_logs = 0;
263		capability->hash_algorithm_bitmap = 0;
264		capability->tpm_present_flag = false;
265		capability->max_command_size = 0;
266		capability->max_response_size = 0;
267		capability->manufacturer_id = 0;
268		capability->number_of_pcr_banks = 0;
269		capability->active_pcr_banks = 0;
270
271		efi_ret = EFI_SUCCESS;
272		goto out;
273	}
274
275	/* We only allow a TPMv2 device to register the EFI protocol */
276	capability->supported_event_logs = TCG2_EVENT_LOG_FORMAT_TCG_2;
277
278	capability->tpm_present_flag = true;
279
280	/* Supported and active PCRs */
281	capability->hash_algorithm_bitmap = 0;
282	capability->active_pcr_banks = 0;
283	ret = tpm2_get_pcr_info(dev, &capability->hash_algorithm_bitmap,
284				&capability->active_pcr_banks,
285				&capability->number_of_pcr_banks);
286	if (ret) {
287		efi_ret = EFI_DEVICE_ERROR;
288		goto out;
289	}
290
291	/* Max command size */
292	ret = tpm2_get_max_command_size(dev, &capability->max_command_size);
293	if (ret) {
294		efi_ret = EFI_DEVICE_ERROR;
295		goto out;
296	}
297
298	/* Max response size */
299	ret = tpm2_get_max_response_size(dev, &capability->max_response_size);
300	if (ret) {
301		efi_ret = EFI_DEVICE_ERROR;
302		goto out;
303	}
304
305	/* Manufacturer ID */
306	ret = tpm2_get_manufacturer_id(dev, &capability->manufacturer_id);
307	if (ret) {
308		efi_ret = EFI_DEVICE_ERROR;
309		goto out;
310	}
311
312	return EFI_EXIT(EFI_SUCCESS);
313out:
314	return EFI_EXIT(efi_ret);
315}
316
317/**
318 * efi_tcg2_get_eventlog() -	retrieve the the address of an event log and its
319 *				last entry
320 *
321 * @this:			TCG2 protocol instance
322 * @log_format:			type of event log format
323 * @event_log_location:		pointer to the memory address of the event log
324 * @event_log_last_entry:	pointer to the address of the start of the last
325 *				entry in the event log in memory, if log contains
326 *				more than 1 entry
327 * @event_log_truncated:	set to true, if the Event Log is missing at i
328 *				least one entry
329 *
330 * Return:	status code
331 */
332static efi_status_t EFIAPI
333efi_tcg2_get_eventlog(struct efi_tcg2_protocol *this,
334		      efi_tcg_event_log_format log_format,
335		      u64 *event_log_location, u64 *event_log_last_entry,
336		      bool *event_log_truncated)
337{
338	efi_status_t ret = EFI_SUCCESS;
339	struct udevice *dev;
340
341	EFI_ENTRY("%p, %u, %p, %p,  %p", this, log_format, event_log_location,
342		  event_log_last_entry, event_log_truncated);
343
344	if (!this || !event_log_location || !event_log_last_entry ||
345	    !event_log_truncated) {
346		ret = EFI_INVALID_PARAMETER;
347		goto out;
348	}
349
350	/* Only support TPMV2 */
351	if (log_format != TCG2_EVENT_LOG_FORMAT_TCG_2) {
352		ret = EFI_INVALID_PARAMETER;
353		goto out;
354	}
355
356	ret = tcg2_platform_get_tpm2(&dev);
357	if (ret != EFI_SUCCESS) {
358		event_log_location = NULL;
359		event_log_last_entry = NULL;
360		*event_log_truncated = false;
361		ret = EFI_SUCCESS;
362		goto out;
363	}
364	*event_log_location = (uintptr_t)event_log.buffer;
365	*event_log_last_entry = (uintptr_t)(event_log.buffer + event_log.pos -
366					    event_log.last_event_size);
367	*event_log_truncated = event_log.truncated;
368	event_log.get_event_called = true;
369
370out:
371	return EFI_EXIT(ret);
372}
373
374/**
375 * tcg2_hash_pe_image() - calculate PE/COFF image hash
376 *
377 * @efi:		pointer to the EFI binary
378 * @efi_size:		size of @efi binary
379 * @digest_list:	list of digest algorithms to extend
380 *
381 * Return:	status code
382 */
383static efi_status_t tcg2_hash_pe_image(void *efi, u64 efi_size,
384				       struct tpml_digest_values *digest_list)
385{
386	WIN_CERTIFICATE *wincerts = NULL;
387	size_t wincerts_len;
388	struct efi_image_regions *regs = NULL;
389	void *new_efi = NULL;
390	u8 hash[TPM2_SHA512_DIGEST_SIZE];
391	struct udevice *dev;
392	efi_status_t ret;
393	u32 active;
394	int i;
395
396	new_efi = efi_prepare_aligned_image(efi, &efi_size);
397	if (!new_efi)
398		return EFI_OUT_OF_RESOURCES;
399
400	if (!efi_image_parse(new_efi, efi_size, &regs, &wincerts,
401			     &wincerts_len)) {
402		log_err("Parsing PE executable image failed\n");
403		ret = EFI_UNSUPPORTED;
404		goto out;
405	}
406
407	ret = tcg2_platform_get_tpm2(&dev);
408	if (ret != EFI_SUCCESS)
409		goto out;
410
411	ret = tcg2_get_active_pcr_banks(dev, &active);
412	if (ret != EFI_SUCCESS) {
413		goto out;
414	}
415
416	digest_list->count = 0;
417	for (i = 0; i < ARRAY_SIZE(tpm2_supported_algorithms); i++) {
418		u16 hash_alg = tpm2_supported_algorithms[i];
419
420		if (!(active & tpm2_algorithm_to_mask(hash_alg)))
421			continue;
422		switch (hash_alg) {
423		case TPM2_ALG_SHA1:
424			hash_calculate("sha1", regs->reg, regs->num, hash);
425			break;
426		case TPM2_ALG_SHA256:
427			hash_calculate("sha256", regs->reg, regs->num, hash);
428			break;
429		case TPM2_ALG_SHA384:
430			hash_calculate("sha384", regs->reg, regs->num, hash);
431			break;
432		case TPM2_ALG_SHA512:
433			hash_calculate("sha512", regs->reg, regs->num, hash);
434			break;
435		default:
436			continue;
437		}
438		digest_list->digests[digest_list->count].hash_alg = hash_alg;
439		memcpy(&digest_list->digests[digest_list->count].digest, hash,
440		       (u32)tpm2_algorithm_to_len(hash_alg));
441		digest_list->count++;
442	}
443
444out:
445	if (new_efi != efi)
446		free(new_efi);
447	free(regs);
448
449	return ret;
450}
451
452/**
453 * tcg2_measure_pe_image() - measure PE/COFF image
454 *
455 * @efi:		pointer to the EFI binary
456 * @efi_size:		size of @efi binary
457 * @handle:		loaded image handle
458 * @loaded_image:	loaded image protocol
459 *
460 * Return:	status code
461 */
462efi_status_t tcg2_measure_pe_image(void *efi, u64 efi_size,
463				   struct efi_loaded_image_obj *handle,
464				   struct efi_loaded_image *loaded_image)
465{
466	struct tpml_digest_values digest_list;
467	efi_status_t ret;
468	struct udevice *dev;
469	u32 pcr_index, event_type, event_size;
470	struct uefi_image_load_event *image_load_event;
471	struct efi_device_path *device_path;
472	u32 device_path_length;
473	IMAGE_DOS_HEADER *dos;
474	IMAGE_NT_HEADERS32 *nt;
475	struct efi_handler *handler;
476
477	if (!is_tcg2_protocol_installed())
478		return EFI_SUCCESS;
479
480	ret = tcg2_platform_get_tpm2(&dev);
481	if (ret != EFI_SUCCESS)
482		return EFI_SECURITY_VIOLATION;
483
484	switch (handle->image_type) {
485	case IMAGE_SUBSYSTEM_EFI_APPLICATION:
486		pcr_index = 4;
487		event_type = EV_EFI_BOOT_SERVICES_APPLICATION;
488		break;
489	case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
490		pcr_index = 2;
491		event_type = EV_EFI_BOOT_SERVICES_DRIVER;
492		break;
493	case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
494		pcr_index = 2;
495		event_type = EV_EFI_RUNTIME_SERVICES_DRIVER;
496		break;
497	default:
498		return EFI_UNSUPPORTED;
499	}
500
501	ret = tcg2_hash_pe_image(efi, efi_size, &digest_list);
502	if (ret != EFI_SUCCESS)
503		return ret;
504
505	ret = tcg2_pcr_extend(dev, pcr_index, &digest_list);
506	if (ret != EFI_SUCCESS)
507		return ret;
508
509	ret = efi_search_protocol(&handle->header,
510				  &efi_guid_loaded_image_device_path, &handler);
511	if (ret != EFI_SUCCESS)
512		return ret;
513
514	device_path = handler->protocol_interface;
515	device_path_length = efi_dp_size(device_path);
516	if (device_path_length > 0) {
517		/* add end node size */
518		device_path_length += sizeof(struct efi_device_path);
519	}
520	event_size = sizeof(struct uefi_image_load_event) + device_path_length;
521	image_load_event = calloc(1, event_size);
522	if (!image_load_event)
523		return EFI_OUT_OF_RESOURCES;
524
525	image_load_event->image_location_in_memory = (uintptr_t)efi;
526	image_load_event->image_length_in_memory = efi_size;
527	image_load_event->length_of_device_path = device_path_length;
528
529	dos = (IMAGE_DOS_HEADER *)efi;
530	nt = (IMAGE_NT_HEADERS32 *)(efi + dos->e_lfanew);
531	if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
532		IMAGE_NT_HEADERS64 *nt64 = (IMAGE_NT_HEADERS64 *)nt;
533
534		image_load_event->image_link_time_address =
535				nt64->OptionalHeader.ImageBase;
536	} else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
537		image_load_event->image_link_time_address =
538				nt->OptionalHeader.ImageBase;
539	} else {
540		ret = EFI_INVALID_PARAMETER;
541		goto out;
542	}
543
544	/* device_path_length might be zero */
545	memcpy(image_load_event->device_path, device_path, device_path_length);
546
547	ret = tcg2_agile_log_append(pcr_index, event_type, &digest_list,
548				    event_size, (u8 *)image_load_event);
549
550out:
551	free(image_load_event);
552
553	return ret;
554}
555
556/**
557 * efi_tcg2_hash_log_extend_event() - extend and optionally log events
558 *
559 * @this:			TCG2 protocol instance
560 * @flags:			bitmap providing additional information on the
561 *				operation
562 * @data_to_hash:		physical address of the start of the data buffer
563 *				to be hashed
564 * @data_to_hash_len:		the length in bytes of the buffer referenced by
565 *				data_to_hash
566 * @efi_tcg_event:		pointer to data buffer containing information
567 *				about the event
568 *
569 * Return:	status code
570 */
571static efi_status_t EFIAPI
572efi_tcg2_hash_log_extend_event(struct efi_tcg2_protocol *this, u64 flags,
573			       u64 data_to_hash, u64 data_to_hash_len,
574			       struct efi_tcg2_event *efi_tcg_event)
575{
576	struct udevice *dev;
577	efi_status_t ret;
578	u32 event_type, pcr_index, event_size;
579	struct tpml_digest_values digest_list;
580
581	EFI_ENTRY("%p, %llu, %llu, %llu, %p", this, flags, data_to_hash,
582		  data_to_hash_len, efi_tcg_event);
583
584	if (!this || !data_to_hash || !efi_tcg_event) {
585		ret = EFI_INVALID_PARAMETER;
586		goto out;
587	}
588
589	ret = tcg2_platform_get_tpm2(&dev);
590	if (ret != EFI_SUCCESS)
591		goto out;
592
593	if (efi_tcg_event->size < efi_tcg_event->header.header_size +
594	    sizeof(u32)) {
595		ret = EFI_INVALID_PARAMETER;
596		goto out;
597	}
598
599	if (efi_tcg_event->header.pcr_index > EFI_TCG2_MAX_PCR_INDEX) {
600		ret = EFI_INVALID_PARAMETER;
601		goto out;
602	}
603
604	/*
605	 * if PE_COFF_IMAGE is set we need to make sure the image is not
606	 * corrupted, verify it and hash the PE/COFF image in accordance with
607	 * the procedure specified in "Calculating the PE Image Hash"
608	 * section of the "Windows Authenticode Portable Executable Signature
609	 * Format"
610	 */
611	if (flags & PE_COFF_IMAGE) {
612		IMAGE_NT_HEADERS32 *nt;
613
614		ret = efi_check_pe((void *)(uintptr_t)data_to_hash,
615				   data_to_hash_len, (void **)&nt);
616		if (ret != EFI_SUCCESS) {
617			log_err("Not a valid PE-COFF file\n");
618			ret = EFI_UNSUPPORTED;
619			goto out;
620		}
621		ret = tcg2_hash_pe_image((void *)(uintptr_t)data_to_hash,
622					 data_to_hash_len, &digest_list);
623	} else {
624		ret = tcg2_create_digest(dev, (u8 *)(uintptr_t)data_to_hash,
625					 data_to_hash_len, &digest_list);
626	}
627
628	if (ret != EFI_SUCCESS)
629		goto out;
630
631	pcr_index = efi_tcg_event->header.pcr_index;
632	event_type = efi_tcg_event->header.event_type;
633
634	ret = tcg2_pcr_extend(dev, pcr_index, &digest_list);
635	if (ret != EFI_SUCCESS)
636		goto out;
637
638	if (flags & EFI_TCG2_EXTEND_ONLY) {
639		if (event_log.truncated)
640			ret = EFI_VOLUME_FULL;
641		goto out;
642	}
643
644	/*
645	 * The efi_tcg_event size includes the size component and the
646	 * headersize
647	 */
648	event_size = efi_tcg_event->size - sizeof(efi_tcg_event->size) -
649		efi_tcg_event->header.header_size;
650	ret = tcg2_agile_log_append(pcr_index, event_type, &digest_list,
651				    event_size, efi_tcg_event->event);
652out:
653	return EFI_EXIT(ret);
654}
655
656/**
657 * efi_tcg2_submit_command() - Send command to the TPM
658 *
659 * @this:			TCG2 protocol instance
660 * @input_param_block_size:	size of the TPM input parameter block
661 * @input_param_block:		pointer to the TPM input parameter block
662 * @output_param_block_size:	size of the TPM output parameter block
663 * @output_param_block:		pointer to the TPM output parameter block
664 *
665 * Return:	status code
666 */
667static efi_status_t EFIAPI
668efi_tcg2_submit_command(struct efi_tcg2_protocol *this,
669			u32 input_param_block_size,
670			u8 *input_param_block,
671			u32 output_param_block_size,
672			u8 *output_param_block)
673{
674	struct udevice *dev;
675	efi_status_t ret;
676	u32 rc;
677	size_t resp_buf_size = output_param_block_size;
678
679	EFI_ENTRY("%p, %u, %p, %u, %p", this, input_param_block_size,
680		  input_param_block, output_param_block_size, output_param_block);
681
682	if (!this || !input_param_block || !input_param_block_size) {
683		ret = EFI_INVALID_PARAMETER;
684		goto out;
685	}
686
687	ret = tcg2_platform_get_tpm2(&dev);
688	if (ret != EFI_SUCCESS)
689		goto out;
690
691	rc = tpm2_submit_command(dev, input_param_block,
692				 output_param_block, &resp_buf_size);
693	if (rc) {
694		ret = (rc == -ENOSPC) ? EFI_OUT_OF_RESOURCES : EFI_DEVICE_ERROR;
695
696		goto out;
697	}
698
699out:
700	return EFI_EXIT(ret);
701}
702
703/**
704 * efi_tcg2_get_active_pcr_banks() - returns the currently active PCR banks
705 *
706 * @this:			TCG2 protocol instance
707 * @active_pcr_banks:		pointer for receiving the bitmap of currently
708 *				active PCR banks
709 *
710 * Return:	status code
711 */
712static efi_status_t EFIAPI
713efi_tcg2_get_active_pcr_banks(struct efi_tcg2_protocol *this,
714			      u32 *active_pcr_banks)
715{
716	struct udevice *dev;
717	efi_status_t ret;
718
719	EFI_ENTRY("%p, %p", this, active_pcr_banks);
720
721	if (!this || !active_pcr_banks) {
722		ret = EFI_INVALID_PARAMETER;
723		goto out;
724	}
725	ret = tcg2_platform_get_tpm2(&dev);
726	if (ret != EFI_SUCCESS)
727		goto out;
728
729	ret = tcg2_get_active_pcr_banks(dev, active_pcr_banks);
730
731out:
732	return EFI_EXIT(ret);
733}
734
735/**
736 * efi_tcg2_set_active_pcr_banks() - sets the currently active PCR banks
737 *
738 * @this:			TCG2 protocol instance
739 * @active_pcr_banks:		bitmap of the requested active PCR banks
740 *
741 * Return:	status code
742 */
743static efi_status_t EFIAPI
744efi_tcg2_set_active_pcr_banks(__maybe_unused struct efi_tcg2_protocol *this,
745			      u32 __maybe_unused active_pcr_banks)
746{
747	return EFI_UNSUPPORTED;
748}
749
750/**
751 * efi_tcg2_get_result_of_set_active_pcr_banks() - retrieve result for previous
752 *						   set_active_pcr_banks()
753 *
754 * @this:			TCG2 protocol instance
755 * @operation_present:		non-zero value to indicate a
756 *				set_active_pcr_banks operation was
757 *				invoked during last boot
758 * @response:			result value could be returned
759 *
760 * Return:	status code
761 */
762static efi_status_t EFIAPI
763efi_tcg2_get_result_of_set_active_pcr_banks(__maybe_unused struct efi_tcg2_protocol *this,
764					    u32 __maybe_unused *operation_present,
765					    u32 __maybe_unused *response)
766{
767	return EFI_UNSUPPORTED;
768}
769
770static const struct efi_tcg2_protocol efi_tcg2_protocol = {
771	.get_capability = efi_tcg2_get_capability,
772	.get_eventlog = efi_tcg2_get_eventlog,
773	.hash_log_extend_event = efi_tcg2_hash_log_extend_event,
774	.submit_command = efi_tcg2_submit_command,
775	.get_active_pcr_banks = efi_tcg2_get_active_pcr_banks,
776	.set_active_pcr_banks = efi_tcg2_set_active_pcr_banks,
777	.get_result_of_set_active_pcr_banks = efi_tcg2_get_result_of_set_active_pcr_banks,
778};
779
780/**
781 * tcg2_uninit - remove the final event table and free efi memory on failures
782 */
783void tcg2_uninit(void)
784{
785	efi_status_t ret;
786
787	ret = efi_install_configuration_table(&efi_guid_final_events, NULL);
788	if (ret != EFI_SUCCESS)
789		log_err("Failed to delete final events config table\n");
790
791	efi_free_pool(event_log.buffer);
792	event_log.buffer = NULL;
793	efi_free_pool(event_log.final_buffer);
794	event_log.final_buffer = NULL;
795
796	if (!is_tcg2_protocol_installed())
797		return;
798
799	ret = efi_uninstall_multiple_protocol_interfaces(efi_root, &efi_guid_tcg2_protocol,
800							 &efi_tcg2_protocol, NULL);
801	if (ret != EFI_SUCCESS)
802		log_err("Failed to remove EFI TCG2 protocol\n");
803}
804
805/**
806 * create_final_event() - Create the final event and install the config
807 *			defined by the TCG EFI spec
808 */
809static efi_status_t create_final_event(void)
810{
811	struct efi_tcg2_final_events_table *final_event;
812	efi_status_t ret;
813
814	/*
815	 * All events generated after the invocation of
816	 * EFI_TCG2_GET_EVENT_LOGS need to be stored in an instance of an
817	 * EFI_CONFIGURATION_TABLE
818	 */
819	ret = efi_allocate_pool(EFI_ACPI_MEMORY_NVS, TPM2_EVENT_LOG_SIZE,
820				&event_log.final_buffer);
821	if (ret != EFI_SUCCESS)
822		goto out;
823
824	memset(event_log.final_buffer, 0xff, TPM2_EVENT_LOG_SIZE);
825	final_event = event_log.final_buffer;
826	final_event->number_of_events = 0;
827	final_event->version = EFI_TCG2_FINAL_EVENTS_TABLE_VERSION;
828	event_log.final_pos = sizeof(*final_event);
829	ret = efi_install_configuration_table(&efi_guid_final_events,
830					      final_event);
831	if (ret != EFI_SUCCESS) {
832		efi_free_pool(event_log.final_buffer);
833		event_log.final_buffer = NULL;
834	}
835
836out:
837	return ret;
838}
839
840/**
841 * measure_event() - common function to add event log and extend PCR
842 *
843 * @dev:		TPM device
844 * @pcr_index:		PCR index
845 * @event_type:		type of event added
846 * @size:		event size
847 * @event:		event data
848 *
849 * Return:	status code
850 */
851static efi_status_t measure_event(struct udevice *dev, u32 pcr_index,
852				  u32 event_type, u32 size, u8 event[])
853{
854	struct tpml_digest_values digest_list;
855	efi_status_t ret;
856
857	ret = tcg2_create_digest(dev, event, size, &digest_list);
858	if (ret != EFI_SUCCESS)
859		goto out;
860
861	ret = tcg2_pcr_extend(dev, pcr_index, &digest_list);
862	if (ret != EFI_SUCCESS)
863		goto out;
864
865	ret = tcg2_agile_log_append(pcr_index, event_type, &digest_list,
866				    size, event);
867
868out:
869	return ret;
870}
871
872/**
873 * efi_append_scrtm_version - Append an S-CRTM EV_S_CRTM_VERSION event on the
874 *			      eventlog and extend the PCRs
875 *
876 * @dev:	TPM device
877 *
878 * @Return:	status code
879 */
880static efi_status_t efi_append_scrtm_version(struct udevice *dev)
881{
882	efi_status_t ret;
883
884	ret = measure_event(dev, 0, EV_S_CRTM_VERSION,
885			    strlen(version_string) + 1, (u8 *)version_string);
886
887	return ret;
888}
889
890/**
891 * efi_init_event_log() - initialize an eventlog
892 *
893 * Return:		status code
894 */
895static efi_status_t efi_init_event_log(void)
896{
897	/*
898	 * vendor_info_size is currently set to 0, we need to change the length
899	 * and allocate the flexible array member if this changes
900	 */
901	struct tcg2_event_log elog;
902	struct udevice *dev;
903	efi_status_t ret;
904
905	ret = tcg2_platform_get_tpm2(&dev);
906	if (ret != EFI_SUCCESS)
907		return ret;
908
909	ret = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, TPM2_EVENT_LOG_SIZE,
910				(void **)&event_log.buffer);
911	if (ret != EFI_SUCCESS)
912		return ret;
913
914	/*
915	 * initialize log area as 0xff so the OS can easily figure out the
916	 * last log entry
917	 */
918	memset(event_log.buffer, 0xff, TPM2_EVENT_LOG_SIZE);
919
920	/*
921	 * The log header is defined to be in SHA1 event log entry format.
922	 * Setup event header
923	 */
924	event_log.pos = 0;
925	event_log.last_event_size = 0;
926	event_log.get_event_called = false;
927	event_log.ebs_called = false;
928	event_log.truncated = false;
929
930	/*
931	 * Check if earlier firmware have passed any eventlog. Different
932	 * platforms can use different ways to do so.
933	 */
934	elog.log = event_log.buffer;
935	elog.log_size = TPM2_EVENT_LOG_SIZE;
936	ret = tcg2_log_prepare_buffer(dev, &elog, false);
937	if (ret != EFI_SUCCESS)
938		goto free_pool;
939
940	event_log.pos = elog.log_position;
941
942	/*
943	 * Add SCRTM version to the log if previous firmmware
944	 * doesn't pass an eventlog.
945	 */
946	if (!elog.found) {
947		ret = efi_append_scrtm_version(dev);
948		if (ret != EFI_SUCCESS)
949			goto free_pool;
950	}
951
952	ret = create_final_event();
953	if (ret != EFI_SUCCESS)
954		goto free_pool;
955
956	return ret;
957
958free_pool:
959	efi_free_pool(event_log.buffer);
960	event_log.buffer = NULL;
961	return ret;
962}
963
964/**
965 * tcg2_measure_variable() - add variable event log and extend PCR
966 *
967 * @dev:		TPM device
968 * @pcr_index:		PCR index
969 * @event_type:		type of event added
970 * @var_name:		variable name
971 * @guid:		guid
972 * @data_size:		variable data size
973 * @data:		variable data
974 *
975 * Return:	status code
976 */
977static efi_status_t tcg2_measure_variable(struct udevice *dev, u32 pcr_index,
978					  u32 event_type, const u16 *var_name,
979					  const efi_guid_t *guid,
980					  efi_uintn_t data_size, u8 *data)
981{
982	u32 event_size;
983	efi_status_t ret;
984	struct efi_tcg2_uefi_variable_data *event;
985
986	event_size = sizeof(event->variable_name) +
987		     sizeof(event->unicode_name_length) +
988		     sizeof(event->variable_data_length) +
989		     (u16_strlen(var_name) * sizeof(u16)) + data_size;
990	event = malloc(event_size);
991	if (!event)
992		return EFI_OUT_OF_RESOURCES;
993
994	guidcpy(&event->variable_name, guid);
995	event->unicode_name_length = u16_strlen(var_name);
996	event->variable_data_length = data_size;
997	memcpy(event->unicode_name, var_name,
998	       (event->unicode_name_length * sizeof(u16)));
999	if (data) {
1000		memcpy((u16 *)event->unicode_name + event->unicode_name_length,
1001		       data, data_size);
1002	}
1003	ret = measure_event(dev, pcr_index, event_type, event_size,
1004			    (u8 *)event);
1005	free(event);
1006	return ret;
1007}
1008
1009/**
1010 * tcg2_measure_boot_variable() - measure boot variables
1011 *
1012 * @dev:	TPM device
1013 *
1014 * Return:	status code
1015 */
1016static efi_status_t tcg2_measure_boot_variable(struct udevice *dev)
1017{
1018	u16 *boot_order;
1019	u16 *boot_index;
1020	u16 var_name[] = u"BootOrder";
1021	u16 boot_name[] = u"Boot####";
1022	u8 *bootvar;
1023	efi_uintn_t var_data_size;
1024	u32 count, i;
1025	efi_status_t ret;
1026
1027	boot_order = efi_get_var(var_name, &efi_global_variable_guid,
1028				 &var_data_size);
1029	if (!boot_order) {
1030		/* If "BootOrder" is not defined, skip the boot variable measurement */
1031		return EFI_SUCCESS;
1032	}
1033
1034	ret = tcg2_measure_variable(dev, 1, EV_EFI_VARIABLE_BOOT2, var_name,
1035				    &efi_global_variable_guid, var_data_size,
1036				    (u8 *)boot_order);
1037	if (ret != EFI_SUCCESS)
1038		goto error;
1039
1040	count = var_data_size / sizeof(*boot_order);
1041	boot_index = boot_order;
1042	for (i = 0; i < count; i++) {
1043		efi_create_indexed_name(boot_name, sizeof(boot_name),
1044					"Boot", *boot_index++);
1045
1046		bootvar = efi_get_var(boot_name, &efi_global_variable_guid,
1047				      &var_data_size);
1048
1049		if (!bootvar) {
1050			log_debug("%ls not found\n", boot_name);
1051			continue;
1052		}
1053
1054		ret = tcg2_measure_variable(dev, 1, EV_EFI_VARIABLE_BOOT2,
1055					    boot_name,
1056					    &efi_global_variable_guid,
1057					    var_data_size, bootvar);
1058		free(bootvar);
1059		if (ret != EFI_SUCCESS)
1060			goto error;
1061	}
1062
1063error:
1064	free(boot_order);
1065	return ret;
1066}
1067
1068/**
1069 * tcg2_measure_smbios() - measure smbios table
1070 *
1071 * @dev:	TPM device
1072 * @entry:	pointer to the smbios_entry structure
1073 *
1074 * Return:	status code
1075 */
1076static efi_status_t
1077tcg2_measure_smbios(struct udevice *dev,
1078		    const struct smbios3_entry *entry)
1079{
1080	efi_status_t ret;
1081	struct smbios_header *smbios_copy;
1082	struct smbios_handoff_table_pointers2 *event = NULL;
1083	u32 event_size;
1084	const char smbios3_anchor[] = "_SM3_";
1085
1086	/* We only support SMBIOS 3.0 Entry Point structure */
1087	if (memcmp(entry->anchor, smbios3_anchor, sizeof(smbios3_anchor) - 1))
1088		return EFI_UNSUPPORTED;
1089
1090	/*
1091	 * TCG PC Client PFP Spec says
1092	 * "SMBIOS structures that contain static configuration information
1093	 * (e.g. Platform Manufacturer Enterprise Number assigned by IANA,
1094	 * platform model number, Vendor and Device IDs for each SMBIOS table)
1095	 * that is relevant to the security of the platform MUST be measured".
1096	 * Device dependent parameters such as serial number are cleared to
1097	 * zero or spaces for the measurement.
1098	 */
1099	event_size = sizeof(struct smbios_handoff_table_pointers2) +
1100		     FIELD_SIZEOF(struct efi_configuration_table, guid) +
1101		     entry->table_maximum_size;
1102	event = calloc(1, event_size);
1103	if (!event) {
1104		ret = EFI_OUT_OF_RESOURCES;
1105		goto out;
1106	}
1107
1108	event->table_description_size = sizeof(SMBIOS_HANDOFF_TABLE_DESC);
1109	memcpy(event->table_description, SMBIOS_HANDOFF_TABLE_DESC,
1110	       sizeof(SMBIOS_HANDOFF_TABLE_DESC));
1111	put_unaligned_le64(1, &event->number_of_tables);
1112	guidcpy(&event->table_entry[0].guid, &smbios3_guid);
1113	smbios_copy = (struct smbios_header *)((uintptr_t)&event->table_entry[0].table);
1114	memcpy(&event->table_entry[0].table,
1115	       (void *)((uintptr_t)entry->struct_table_address),
1116	       entry->table_maximum_size);
1117
1118	smbios_prepare_measurement(entry, smbios_copy);
1119
1120	ret = measure_event(dev, 1, EV_EFI_HANDOFF_TABLES2, event_size,
1121			    (u8 *)event);
1122	if (ret != EFI_SUCCESS)
1123		goto out;
1124
1125out:
1126	free(event);
1127
1128	return ret;
1129}
1130
1131/**
1132 * tcg2_measure_gpt_table() - measure gpt table
1133 *
1134 * @dev:		TPM device
1135 * @loaded_image:	handle to the loaded image
1136 *
1137 * Return:	status code
1138 */
1139static efi_status_t
1140tcg2_measure_gpt_data(struct udevice *dev,
1141		      struct efi_loaded_image_obj *loaded_image)
1142{
1143	efi_status_t ret;
1144	efi_handle_t handle;
1145	struct efi_handler *dp_handler, *io_handler;
1146	struct efi_device_path *orig_device_path;
1147	struct efi_device_path *device_path;
1148	struct efi_device_path *dp;
1149	struct efi_block_io *block_io;
1150	struct efi_gpt_data *event = NULL;
1151	efi_guid_t null_guid = NULL_GUID;
1152	gpt_header *gpt_h;
1153	gpt_entry *entry = NULL;
1154	gpt_entry *gpt_e;
1155	u32 num_of_valid_entry = 0;
1156	u32 event_size;
1157	u32 i;
1158	u32 total_gpt_entry_size;
1159
1160	ret = efi_search_protocol(&loaded_image->header,
1161				  &efi_guid_loaded_image_device_path,
1162				  &dp_handler);
1163	if (ret != EFI_SUCCESS)
1164		return ret;
1165
1166	orig_device_path = dp_handler->protocol_interface;
1167	if (!orig_device_path) /* no device path, skip GPT measurement */
1168		return EFI_SUCCESS;
1169
1170	device_path = efi_dp_dup(orig_device_path);
1171	if (!device_path)
1172		return EFI_OUT_OF_RESOURCES;
1173
1174	dp = search_gpt_dp_node(device_path);
1175	if (!dp) {
1176		/* no GPT device path node found, skip GPT measurement */
1177		ret = EFI_SUCCESS;
1178		goto out1;
1179	}
1180
1181	/* read GPT header */
1182	dp->type = DEVICE_PATH_TYPE_END;
1183	dp->sub_type = DEVICE_PATH_SUB_TYPE_END;
1184	dp = device_path;
1185	ret = EFI_CALL(systab.boottime->locate_device_path(&efi_block_io_guid,
1186							   &dp, &handle));
1187	if (ret != EFI_SUCCESS)
1188		goto out1;
1189
1190	ret = efi_search_protocol(handle, &efi_block_io_guid, &io_handler);
1191	if (ret != EFI_SUCCESS)
1192		goto out1;
1193	block_io = io_handler->protocol_interface;
1194
1195	gpt_h = memalign(block_io->media->io_align, block_io->media->block_size);
1196	if (!gpt_h) {
1197		ret = EFI_OUT_OF_RESOURCES;
1198		goto out2;
1199	}
1200
1201	ret = block_io->read_blocks(block_io, block_io->media->media_id, 1,
1202				    block_io->media->block_size, gpt_h);
1203	if (ret != EFI_SUCCESS)
1204		goto out2;
1205
1206	/* read GPT entry */
1207	total_gpt_entry_size = gpt_h->num_partition_entries *
1208			       gpt_h->sizeof_partition_entry;
1209	entry = memalign(block_io->media->io_align, total_gpt_entry_size);
1210	if (!entry) {
1211		ret = EFI_OUT_OF_RESOURCES;
1212		goto out2;
1213	}
1214
1215	ret = block_io->read_blocks(block_io, block_io->media->media_id,
1216				    gpt_h->partition_entry_lba,
1217				    total_gpt_entry_size, entry);
1218	if (ret != EFI_SUCCESS)
1219		goto out2;
1220
1221	/* count valid GPT entry */
1222	gpt_e = entry;
1223	for (i = 0; i < gpt_h->num_partition_entries; i++) {
1224		if (guidcmp(&null_guid, &gpt_e->partition_type_guid))
1225			num_of_valid_entry++;
1226
1227		gpt_e = (gpt_entry *)((u8 *)gpt_e + gpt_h->sizeof_partition_entry);
1228	}
1229
1230	/* prepare event data for measurement */
1231	event_size = sizeof(struct efi_gpt_data) +
1232		(num_of_valid_entry * gpt_h->sizeof_partition_entry);
1233	event = calloc(1, event_size);
1234	if (!event) {
1235		ret = EFI_OUT_OF_RESOURCES;
1236		goto out2;
1237	}
1238	memcpy(event, gpt_h, sizeof(gpt_header));
1239	put_unaligned_le64(num_of_valid_entry, &event->number_of_partitions);
1240
1241	/* copy valid GPT entry */
1242	gpt_e = entry;
1243	num_of_valid_entry = 0;
1244	for (i = 0; i < gpt_h->num_partition_entries; i++) {
1245		if (guidcmp(&null_guid, &gpt_e->partition_type_guid)) {
1246			memcpy((u8 *)event->partitions +
1247			       (num_of_valid_entry * gpt_h->sizeof_partition_entry),
1248			       gpt_e, gpt_h->sizeof_partition_entry);
1249			num_of_valid_entry++;
1250		}
1251
1252		gpt_e = (gpt_entry *)((u8 *)gpt_e + gpt_h->sizeof_partition_entry);
1253	}
1254
1255	ret = measure_event(dev, 5, EV_EFI_GPT_EVENT, event_size, (u8 *)event);
1256
1257out2:
1258	free(gpt_h);
1259	free(entry);
1260	free(event);
1261out1:
1262	efi_free_pool(device_path);
1263
1264	return ret;
1265}
1266
1267/* Return the byte size of reserved map area in DTB or -1 upon error */
1268static ssize_t size_of_rsvmap(void *dtb)
1269{
1270	struct fdt_reserve_entry e;
1271	ssize_t size_max;
1272	ssize_t size;
1273	u8 *rsvmap_base;
1274
1275	rsvmap_base = (u8 *)dtb + fdt_off_mem_rsvmap(dtb);
1276	size_max = fdt_totalsize(dtb) - fdt_off_mem_rsvmap(dtb);
1277	size = 0;
1278
1279	do {
1280		memcpy(&e, rsvmap_base + size, sizeof(e));
1281		size += sizeof(e);
1282		if (size > size_max)
1283			return -1;
1284	} while (e.size);
1285
1286	return size;
1287}
1288
1289/**
1290 * efi_tcg2_measure_dtb() - measure DTB passed to the OS
1291 *
1292 * @dtb: pointer to the device tree blob
1293 *
1294 * Return:	status code
1295 */
1296efi_status_t efi_tcg2_measure_dtb(void *dtb)
1297{
1298	struct uefi_platform_firmware_blob2 *blob;
1299	struct fdt_header *header;
1300	sha256_context hash_ctx;
1301	struct udevice *dev;
1302	ssize_t rsvmap_size;
1303	efi_status_t ret;
1304	u32 event_size;
1305
1306	if (!is_tcg2_protocol_installed())
1307		return EFI_SUCCESS;
1308
1309	ret = tcg2_platform_get_tpm2(&dev);
1310	if (ret != EFI_SUCCESS)
1311		return EFI_SECURITY_VIOLATION;
1312
1313	rsvmap_size = size_of_rsvmap(dtb);
1314	if (rsvmap_size < 0)
1315		return EFI_SECURITY_VIOLATION;
1316
1317	event_size = sizeof(*blob) + sizeof(EFI_DTB_EVENT_STRING) + SHA256_SUM_LEN;
1318	blob = calloc(1, event_size);
1319	if (!blob)
1320		return EFI_OUT_OF_RESOURCES;
1321
1322	blob->blob_description_size = sizeof(EFI_DTB_EVENT_STRING);
1323	memcpy(blob->data, EFI_DTB_EVENT_STRING, blob->blob_description_size);
1324
1325	/* Measure populated areas of the DTB */
1326	header = dtb;
1327	sha256_starts(&hash_ctx);
1328	sha256_update(&hash_ctx, (u8 *)header, sizeof(struct fdt_header));
1329	sha256_update(&hash_ctx, (u8 *)dtb + fdt_off_dt_struct(dtb), fdt_size_dt_strings(dtb));
1330	sha256_update(&hash_ctx, (u8 *)dtb + fdt_off_dt_strings(dtb), fdt_size_dt_struct(dtb));
1331	sha256_update(&hash_ctx, (u8 *)dtb + fdt_off_mem_rsvmap(dtb), rsvmap_size);
1332	sha256_finish(&hash_ctx, blob->data + blob->blob_description_size);
1333
1334	ret = measure_event(dev, 0, EV_POST_CODE, event_size, (u8 *)blob);
1335
1336	free(blob);
1337	return ret;
1338}
1339
1340/**
1341 * efi_tcg2_measure_efi_app_invocation() - measure efi app invocation
1342 *
1343 * Return:	status code
1344 */
1345efi_status_t efi_tcg2_measure_efi_app_invocation(struct efi_loaded_image_obj *handle)
1346{
1347	efi_status_t ret;
1348	u32 pcr_index;
1349	struct udevice *dev;
1350	u32 event = 0;
1351	struct smbios3_entry *entry;
1352
1353	if (!is_tcg2_protocol_installed())
1354		return EFI_SUCCESS;
1355
1356	if (tcg2_efi_app_invoked)
1357		return EFI_SUCCESS;
1358
1359	ret = tcg2_platform_get_tpm2(&dev);
1360	if (ret != EFI_SUCCESS)
1361		return EFI_SECURITY_VIOLATION;
1362
1363	ret = tcg2_measure_boot_variable(dev);
1364	if (ret != EFI_SUCCESS)
1365		goto out;
1366
1367	ret = measure_event(dev, 4, EV_EFI_ACTION,
1368			    strlen(EFI_CALLING_EFI_APPLICATION),
1369			    (u8 *)EFI_CALLING_EFI_APPLICATION);
1370	if (ret != EFI_SUCCESS)
1371		goto out;
1372
1373	entry = efi_get_configuration_table(&smbios3_guid);
1374	if (entry) {
1375		ret = tcg2_measure_smbios(dev, entry);
1376		if (ret != EFI_SUCCESS)
1377			goto out;
1378	}
1379
1380	ret = tcg2_measure_gpt_data(dev, handle);
1381	if (ret != EFI_SUCCESS)
1382		goto out;
1383
1384	for (pcr_index = 0; pcr_index <= 7; pcr_index++) {
1385		ret = measure_event(dev, pcr_index, EV_SEPARATOR,
1386				    sizeof(event), (u8 *)&event);
1387		if (ret != EFI_SUCCESS)
1388			goto out;
1389	}
1390
1391	tcg2_efi_app_invoked = true;
1392out:
1393	return ret;
1394}
1395
1396/**
1397 * efi_tcg2_measure_efi_app_exit() - measure efi app exit
1398 *
1399 * Return:	status code
1400 */
1401efi_status_t efi_tcg2_measure_efi_app_exit(void)
1402{
1403	efi_status_t ret;
1404	struct udevice *dev;
1405
1406	if (!is_tcg2_protocol_installed())
1407		return EFI_SUCCESS;
1408
1409	ret = tcg2_platform_get_tpm2(&dev);
1410	if (ret != EFI_SUCCESS)
1411		return ret;
1412
1413	ret = measure_event(dev, 4, EV_EFI_ACTION,
1414			    strlen(EFI_RETURNING_FROM_EFI_APPLICATION),
1415			    (u8 *)EFI_RETURNING_FROM_EFI_APPLICATION);
1416	return ret;
1417}
1418
1419/**
1420 * efi_tcg2_notify_exit_boot_services() - ExitBootService callback
1421 *
1422 * @event:	callback event
1423 * @context:	callback context
1424 */
1425static void EFIAPI
1426efi_tcg2_notify_exit_boot_services(struct efi_event *event, void *context)
1427{
1428	efi_status_t ret;
1429	struct udevice *dev;
1430
1431	EFI_ENTRY("%p, %p", event, context);
1432
1433	event_log.ebs_called = true;
1434
1435	if (!is_tcg2_protocol_installed()) {
1436		ret = EFI_SUCCESS;
1437		goto out;
1438	}
1439
1440	ret = tcg2_platform_get_tpm2(&dev);
1441	if (ret != EFI_SUCCESS)
1442		goto out;
1443
1444	ret = measure_event(dev, 5, EV_EFI_ACTION,
1445			    strlen(EFI_EXIT_BOOT_SERVICES_INVOCATION),
1446			    (u8 *)EFI_EXIT_BOOT_SERVICES_INVOCATION);
1447	if (ret != EFI_SUCCESS)
1448		goto out;
1449
1450	ret = measure_event(dev, 5, EV_EFI_ACTION,
1451			    strlen(EFI_EXIT_BOOT_SERVICES_SUCCEEDED),
1452			    (u8 *)EFI_EXIT_BOOT_SERVICES_SUCCEEDED);
1453
1454out:
1455	EFI_EXIT(ret);
1456}
1457
1458/**
1459 * efi_tcg2_notify_exit_boot_services_failed()
1460 *  - notify ExitBootServices() is failed
1461 *
1462 * Return:	status code
1463 */
1464efi_status_t efi_tcg2_notify_exit_boot_services_failed(void)
1465{
1466	struct udevice *dev;
1467	efi_status_t ret;
1468
1469	if (!is_tcg2_protocol_installed())
1470		return EFI_SUCCESS;
1471
1472	ret = tcg2_platform_get_tpm2(&dev);
1473	if (ret != EFI_SUCCESS)
1474		goto out;
1475
1476	ret = measure_event(dev, 5, EV_EFI_ACTION,
1477			    strlen(EFI_EXIT_BOOT_SERVICES_INVOCATION),
1478			    (u8 *)EFI_EXIT_BOOT_SERVICES_INVOCATION);
1479	if (ret != EFI_SUCCESS)
1480		goto out;
1481
1482	ret = measure_event(dev, 5, EV_EFI_ACTION,
1483			    strlen(EFI_EXIT_BOOT_SERVICES_FAILED),
1484			    (u8 *)EFI_EXIT_BOOT_SERVICES_FAILED);
1485
1486out:
1487	return ret;
1488}
1489
1490/**
1491 * tcg2_measure_secure_boot_variable() - measure secure boot variables
1492 *
1493 * @dev:	TPM device
1494 *
1495 * Return:	status code
1496 */
1497static efi_status_t tcg2_measure_secure_boot_variable(struct udevice *dev)
1498{
1499	u8 *data;
1500	efi_uintn_t data_size;
1501	u32 count, i;
1502	efi_status_t ret;
1503	u8 deployed_mode;
1504	efi_uintn_t size;
1505	u32 deployed_audit_pcr_index = 1;
1506
1507	size = sizeof(deployed_mode);
1508	ret = efi_get_variable_int(u"DeployedMode", &efi_global_variable_guid,
1509				   NULL, &size, &deployed_mode, NULL);
1510	if (ret != EFI_SUCCESS || !deployed_mode)
1511		deployed_audit_pcr_index = 7;
1512
1513	count = ARRAY_SIZE(secure_variables);
1514	for (i = 0; i < count; i++) {
1515		const efi_guid_t *guid;
1516
1517		guid = efi_auth_var_get_guid(secure_variables[i].name);
1518
1519		data = efi_get_var(secure_variables[i].name, guid, &data_size);
1520		if (!data && !secure_variables[i].accept_empty)
1521			continue;
1522
1523		if (u16_strcmp(u"DeployedMode", secure_variables[i].name))
1524			secure_variables[i].pcr_index = deployed_audit_pcr_index;
1525		if (u16_strcmp(u"AuditMode", secure_variables[i].name))
1526			secure_variables[i].pcr_index = deployed_audit_pcr_index;
1527
1528		ret = tcg2_measure_variable(dev, secure_variables[i].pcr_index,
1529					    EV_EFI_VARIABLE_DRIVER_CONFIG,
1530					    secure_variables[i].name, guid,
1531					    data_size, data);
1532		free(data);
1533		if (ret != EFI_SUCCESS)
1534			goto error;
1535	}
1536
1537error:
1538	return ret;
1539}
1540
1541/**
1542 * efi_tcg2_do_initial_measurement() - do initial measurement
1543 *
1544 * Return:	status code
1545 */
1546efi_status_t efi_tcg2_do_initial_measurement(void)
1547{
1548	efi_status_t ret;
1549	struct udevice *dev;
1550
1551	if (!is_tcg2_protocol_installed())
1552		return EFI_SUCCESS;
1553
1554	ret = tcg2_platform_get_tpm2(&dev);
1555	if (ret != EFI_SUCCESS)
1556		return EFI_SECURITY_VIOLATION;
1557
1558	ret = tcg2_measure_secure_boot_variable(dev);
1559	if (ret != EFI_SUCCESS)
1560		goto out;
1561
1562out:
1563	return ret;
1564}
1565
1566/**
1567 * efi_tcg2_register() - register EFI_TCG2_PROTOCOL
1568 *
1569 * If a TPM2 device is available, the TPM TCG2 Protocol is registered
1570 *
1571 * Return:	status code
1572 */
1573efi_status_t efi_tcg2_register(void)
1574{
1575	efi_status_t ret = EFI_SUCCESS;
1576	struct udevice *dev;
1577	struct efi_event *event;
1578	u32 err;
1579
1580	ret = tcg2_platform_get_tpm2(&dev);
1581	if (ret != EFI_SUCCESS) {
1582		log_warning("Missing TPMv2 device for EFI_TCG_PROTOCOL\n");
1583		return EFI_SUCCESS;
1584	}
1585
1586	/* initialize the TPM as early as possible. */
1587	err = tpm_auto_start(dev);
1588	if (err) {
1589		log_err("TPM startup failed\n");
1590		goto fail;
1591	}
1592
1593	ret = efi_init_event_log();
1594	if (ret != EFI_SUCCESS) {
1595		tcg2_uninit();
1596		goto fail;
1597	}
1598
1599	ret = efi_install_multiple_protocol_interfaces(&efi_root, &efi_guid_tcg2_protocol,
1600						       &efi_tcg2_protocol, NULL);
1601	if (ret != EFI_SUCCESS) {
1602		tcg2_uninit();
1603		goto fail;
1604	}
1605
1606	ret = efi_create_event(EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
1607			       efi_tcg2_notify_exit_boot_services, NULL,
1608			       NULL, &event);
1609	if (ret != EFI_SUCCESS) {
1610		tcg2_uninit();
1611		goto fail;
1612	}
1613
1614	return ret;
1615
1616fail:
1617	log_err("Cannot install EFI_TCG2_PROTOCOL\n");
1618	return ret;
1619}
1620