6e32f520895184b48c55db977ced758576b78b2c
[platform/kernel/u-boot.git] / lib / efi_loader / efi_tcg2.c
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 <common.h>
12 #include <dm.h>
13 #include <efi_loader.h>
14 #include <efi_variable.h>
15 #include <efi_tcg2.h>
16 #include <log.h>
17 #include <malloc.h>
18 #include <smbios.h>
19 #include <version_string.h>
20 #include <tpm-v2.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  */
41 struct 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
52 static struct event_log_buffer event_log;
53 static 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
65 static const efi_guid_t efi_guid_tcg2_protocol = EFI_TCG2_PROTOCOL_GUID;
66 static const efi_guid_t efi_guid_final_events = EFI_TCG2_FINAL_EVENTS_TABLE_GUID;
67
68 struct digest_info {
69         u16 hash_alg;
70         u32 hash_mask;
71         u16 hash_len;
72 };
73
74 static const struct digest_info hash_algo_list[] = {
75         {
76                 TPM2_ALG_SHA1,
77                 EFI_TCG2_BOOT_HASH_ALG_SHA1,
78                 TPM2_SHA1_DIGEST_SIZE,
79         },
80         {
81                 TPM2_ALG_SHA256,
82                 EFI_TCG2_BOOT_HASH_ALG_SHA256,
83                 TPM2_SHA256_DIGEST_SIZE,
84         },
85         {
86                 TPM2_ALG_SHA384,
87                 EFI_TCG2_BOOT_HASH_ALG_SHA384,
88                 TPM2_SHA384_DIGEST_SIZE,
89         },
90         {
91                 TPM2_ALG_SHA512,
92                 EFI_TCG2_BOOT_HASH_ALG_SHA512,
93                 TPM2_SHA512_DIGEST_SIZE,
94         },
95 };
96
97 struct variable_info {
98         const u16       *name;
99         bool            accept_empty;
100         u32             pcr_index;
101 };
102
103 static struct variable_info secure_variables[] = {
104         {u"SecureBoot",         true,   7},
105         {u"PK",                 true,   7},
106         {u"KEK",                true,   7},
107         {u"db",                 true,   7},
108         {u"dbx",                true,   7},
109         {u"dbt",                false,  7},
110         {u"dbr",                false,  7},
111         {u"DeployedMode",       false,  1},
112         {u"AuditMode",          false,  1},
113 };
114
115 #define MAX_HASH_COUNT ARRAY_SIZE(hash_algo_list)
116
117 /**
118  * alg_to_mask - Get a TCG hash mask for algorithms
119  *
120  * @hash_alg: TCG defined algorithm
121  *
122  * @Return: TCG hashing algorithm bitmaps, 0 if the algorithm is not supported
123  */
124 static u32 alg_to_mask(u16 hash_alg)
125 {
126         size_t i;
127
128         for (i = 0; i < MAX_HASH_COUNT; i++) {
129                 if (hash_algo_list[i].hash_alg == hash_alg)
130                         return hash_algo_list[i].hash_mask;
131         }
132
133         return 0;
134 }
135
136 /**
137  * alg_to_len - Get a TCG hash len for algorithms
138  *
139  * @hash_alg: TCG defined algorithm
140  *
141  * @Return: len of chosen algorithm, 0 if the algorithm is not supported
142  */
143 static u16 alg_to_len(u16 hash_alg)
144 {
145         size_t i;
146
147         for (i = 0; i < MAX_HASH_COUNT; i++) {
148                 if (hash_algo_list[i].hash_alg == hash_alg)
149                         return hash_algo_list[i].hash_len;
150         }
151
152         return 0;
153 }
154
155 static u32 tcg_event_final_size(struct tpml_digest_values *digest_list)
156 {
157         u32 len;
158         size_t i;
159
160         len = offsetof(struct tcg_pcr_event2, digests);
161         len += offsetof(struct tpml_digest_values, digests);
162         for (i = 0; i < digest_list->count; i++) {
163                 u16 hash_alg = digest_list->digests[i].hash_alg;
164
165                 len += offsetof(struct tpmt_ha, digest);
166                 len += alg_to_len(hash_alg);
167         }
168         len += sizeof(u32); /* tcg_pcr_event2 event_size*/
169
170         return len;
171 }
172
173 /* tcg2_pcr_extend - Extend PCRs for a TPM2 device for a given tpml_digest_values
174  *
175  * @dev:                device
176  * @digest_list:        list of digest algorithms to extend
177  *
178  * @Return: status code
179  */
180 static efi_status_t tcg2_pcr_extend(struct udevice *dev, u32 pcr_index,
181                                     struct tpml_digest_values *digest_list)
182 {
183         u32 rc;
184         size_t i;
185
186         for (i = 0; i < digest_list->count; i++) {
187                 u32 alg = digest_list->digests[i].hash_alg;
188
189                 rc = tpm2_pcr_extend(dev, pcr_index, alg,
190                                      (u8 *)&digest_list->digests[i].digest,
191                                      alg_to_len(alg));
192                 if (rc) {
193                         EFI_PRINT("Failed to extend PCR\n");
194                         return EFI_DEVICE_ERROR;
195                 }
196         }
197
198         return EFI_SUCCESS;
199 }
200
201 /* put_event - Append an agile event to an eventlog
202  *
203  * @pcr_index:          PCR index
204  * @event_type:         type of event added
205  * @digest_list:        list of digest algorithms to add
206  * @size:               size of event
207  * @event:              event to add
208  * @log:                log buffer to append the event
209  *
210  */
211 static void put_event(u32 pcr_index, u32 event_type,
212                       struct tpml_digest_values *digest_list, u32 size,
213                       u8 event[], void *log)
214 {
215         size_t pos;
216         size_t i;
217         u32 event_size;
218
219         /*
220          * size refers to the length of event[] only, we need to check against
221          * the final tcg_pcr_event2 size
222          */
223         event_size = size + tcg_event_final_size(digest_list);
224
225         put_unaligned_le32(pcr_index, log);
226         pos = offsetof(struct tcg_pcr_event2, event_type);
227         put_unaligned_le32(event_type, (void *)((uintptr_t)log + pos));
228         pos = offsetof(struct tcg_pcr_event2, digests); /* count */
229         put_unaligned_le32(digest_list->count, (void *)((uintptr_t)log + pos));
230
231         pos += offsetof(struct tpml_digest_values, digests);
232         for (i = 0; i < digest_list->count; i++) {
233                 u16 hash_alg = digest_list->digests[i].hash_alg;
234                 u8 *digest = (u8 *)&digest_list->digests[i].digest;
235
236                 put_unaligned_le16(hash_alg, (void *)((uintptr_t)log + pos));
237                 pos += offsetof(struct tpmt_ha, digest);
238                 memcpy((void *)((uintptr_t)log + pos), digest, alg_to_len(hash_alg));
239                 pos += alg_to_len(hash_alg);
240         }
241
242         put_unaligned_le32(size, (void *)((uintptr_t)log + pos));
243         pos += sizeof(u32); /* tcg_pcr_event2 event_size*/
244         memcpy((void *)((uintptr_t)log + pos), event, size);
245         pos += size;
246
247         /*
248          * make sure the calculated buffer is what we checked against
249          * This check should never fail.  It checks the code above is
250          * calculating the right length for the event we are adding
251          */
252         if (pos != event_size)
253                 log_err("Appending to the EventLog failed\n");
254 }
255
256 /* tcg2_agile_log_append - Append an agile event to an eventlog
257  *
258  * @pcr_index:          PCR index
259  * @event_type:         type of event added
260  * @digest_list:        list of digest algorithms to add
261  * @size:               size of event
262  * @event:              event to add
263  * @log:                log buffer to append the event
264  *
265  * @Return: status code
266  */
267 static efi_status_t tcg2_agile_log_append(u32 pcr_index, u32 event_type,
268                                           struct tpml_digest_values *digest_list,
269                                           u32 size, u8 event[])
270 {
271         void *log = (void *)((uintptr_t)event_log.buffer + event_log.pos);
272         u32 event_size = size + tcg_event_final_size(digest_list);
273         struct efi_tcg2_final_events_table *final_event;
274         efi_status_t ret = EFI_SUCCESS;
275
276         /* if ExitBootServices hasn't been called update the normal log */
277         if (!event_log.ebs_called) {
278                 if (event_log.truncated ||
279                     event_log.pos + event_size > TPM2_EVENT_LOG_SIZE) {
280                         event_log.truncated = true;
281                         return EFI_VOLUME_FULL;
282                 }
283                 put_event(pcr_index, event_type, digest_list, size, event, log);
284                 event_log.pos += event_size;
285                 event_log.last_event_size = event_size;
286         }
287
288         if (!event_log.get_event_called)
289                 return ret;
290
291         /* if GetEventLog has been called update FinalEventLog as well */
292         if (event_log.final_pos + event_size > TPM2_EVENT_LOG_SIZE)
293                 return EFI_VOLUME_FULL;
294
295         log = (void *)((uintptr_t)event_log.final_buffer + event_log.final_pos);
296         put_event(pcr_index, event_type, digest_list, size, event, log);
297
298         final_event = event_log.final_buffer;
299         final_event->number_of_events++;
300         event_log.final_pos += event_size;
301
302         return ret;
303 }
304
305 /**
306  * platform_get_tpm_device() - retrieve TPM device
307  *
308  * This function retrieves the udevice implementing a TPM
309  *
310  * This function may be overridden if special initialization is needed.
311  *
312  * @dev:        udevice
313  * Return:      status code
314  */
315 __weak efi_status_t platform_get_tpm2_device(struct udevice **dev)
316 {
317         for_each_tpm_device(*dev) {
318                 /* Only support TPMv2 devices */
319                 if (tpm_get_version(*dev) == TPM_V2)
320                         return EFI_SUCCESS;
321         }
322
323         return EFI_NOT_FOUND;
324 }
325
326 /**
327  * tpm2_get_max_command_size() - get the supported max command size
328  *
329  * @dev:                TPM device
330  * @max_command_size:   output buffer for the size
331  *
332  * Return: 0 on success, -1 on error
333  */
334 static int tpm2_get_max_command_size(struct udevice *dev, u16 *max_command_size)
335 {
336         u8 response[TPM2_RESPONSE_BUFFER_SIZE];
337         u32 ret;
338
339         memset(response, 0, sizeof(response));
340         ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
341                                   TPM2_PT_MAX_COMMAND_SIZE, response, 1);
342         if (ret)
343                 return -1;
344
345         *max_command_size = (uint16_t)get_unaligned_be32(response +
346                                                          properties_offset);
347
348         return 0;
349 }
350
351 /**
352  * tpm2_get_max_response_size() - get the supported max response size
353  *
354  * @dev:                TPM device
355  * @max_response_size:  output buffer for the size
356  *
357  * Return: 0 on success, -1 on error
358  */
359 static int tpm2_get_max_response_size(struct udevice *dev,
360                                       u16 *max_response_size)
361 {
362         u8 response[TPM2_RESPONSE_BUFFER_SIZE];
363         u32 ret;
364
365         memset(response, 0, sizeof(response));
366         ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
367                                   TPM2_PT_MAX_RESPONSE_SIZE, response, 1);
368         if (ret)
369                 return -1;
370
371         *max_response_size = (uint16_t)get_unaligned_be32(response +
372                                                           properties_offset);
373
374         return 0;
375 }
376
377 /**
378  * tpm2_get_manufacturer_id() - get the manufacturer ID
379  *
380  * @dev:                TPM device
381  * @manufacturer_id:    output buffer for the id
382  *
383  * Return: 0 on success, -1 on error
384  */
385 static int tpm2_get_manufacturer_id(struct udevice *dev, u32 *manufacturer_id)
386 {
387         u8 response[TPM2_RESPONSE_BUFFER_SIZE];
388         u32 ret;
389
390         memset(response, 0, sizeof(response));
391         ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
392                                   TPM2_PT_MANUFACTURER, response, 1);
393         if (ret)
394                 return -1;
395
396         *manufacturer_id = get_unaligned_be32(response + properties_offset);
397
398         return 0;
399 }
400
401 /**
402  * tpm2_get_num_pcr() - get the number of PCRs
403  *
404  * @dev:                TPM device
405  * @manufacturer_id:    output buffer for the number
406  *
407  * Return: 0 on success, -1 on error
408  */
409 static int tpm2_get_num_pcr(struct udevice *dev, u32 *num_pcr)
410 {
411         u8 response[TPM2_RESPONSE_BUFFER_SIZE];
412         u32 ret;
413
414         memset(response, 0, sizeof(response));
415         ret = tpm2_get_capability(dev, TPM2_CAP_TPM_PROPERTIES,
416                                   TPM2_PT_PCR_COUNT, response, 1);
417         if (ret)
418                 return -1;
419
420         *num_pcr = get_unaligned_be32(response + properties_offset);
421         if (*num_pcr > TPM2_MAX_PCRS)
422                 return -1;
423
424         return 0;
425 }
426
427 /**
428  * is_active_pcr() - Check if a supported algorithm is active
429  *
430  * @dev:                TPM device
431  * @selection:          struct of PCR information
432  *
433  * Return: true if PCR is active
434  */
435 static bool is_active_pcr(struct tpms_pcr_selection *selection)
436 {
437         int i;
438         /*
439          * check the pcr_select. If at least one of the PCRs supports the
440          * algorithm add it on the active ones
441          */
442         for (i = 0; i < selection->size_of_select; i++) {
443                 if (selection->pcr_select[i])
444                         return true;
445         }
446
447         return false;
448 }
449
450 /**
451  * tpm2_get_pcr_info() - get the supported, active PCRs and number of banks
452  *
453  * @dev:                TPM device
454  * @supported_pcr:      bitmask with the algorithms supported
455  * @active_pcr:         bitmask with the active algorithms
456  * @pcr_banks:          number of PCR banks
457  *
458  * Return: 0 on success, -1 on error
459  */
460 static int tpm2_get_pcr_info(struct udevice *dev, u32 *supported_pcr,
461                              u32 *active_pcr, u32 *pcr_banks)
462 {
463         u8 response[TPM2_RESPONSE_BUFFER_SIZE];
464         struct tpml_pcr_selection pcrs;
465         u32 ret, num_pcr;
466         size_t i;
467         int tpm_ret;
468
469         *supported_pcr = 0;
470         *active_pcr = 0;
471         *pcr_banks = 0;
472         memset(response, 0, sizeof(response));
473         ret = tpm2_get_capability(dev, TPM2_CAP_PCRS, 0, response, 1);
474         if (ret)
475                 goto out;
476
477         pcrs.count = get_unaligned_be32(response);
478         /*
479          * We only support 5 algorithms for now so check against that
480          * instead of TPM2_NUM_PCR_BANKS
481          */
482         if (pcrs.count > MAX_HASH_COUNT || pcrs.count < 1)
483                 goto out;
484
485         tpm_ret = tpm2_get_num_pcr(dev, &num_pcr);
486         if (tpm_ret)
487                 goto out;
488
489         for (i = 0; i < pcrs.count; i++) {
490                 /*
491                  * Definition of TPMS_PCR_SELECTION Structure
492                  * hash: u16
493                  * size_of_select: u8
494                  * pcr_select: u8 array
495                  *
496                  * The offsets depend on the number of the device PCRs
497                  * so we have to calculate them based on that
498                  */
499                 u32 hash_offset = offsetof(struct tpml_pcr_selection, selection) +
500                         i * offsetof(struct tpms_pcr_selection, pcr_select) +
501                         i * ((num_pcr + 7) / 8);
502                 u32 size_select_offset =
503                         hash_offset + offsetof(struct tpms_pcr_selection,
504                                                size_of_select);
505                 u32 pcr_select_offset =
506                         hash_offset + offsetof(struct tpms_pcr_selection,
507                                                pcr_select);
508
509                 pcrs.selection[i].hash =
510                         get_unaligned_be16(response + hash_offset);
511                 pcrs.selection[i].size_of_select =
512                         __get_unaligned_be(response + size_select_offset);
513                 if (pcrs.selection[i].size_of_select > TPM2_PCR_SELECT_MAX)
514                         goto out;
515                 /* copy the array of pcr_select */
516                 memcpy(pcrs.selection[i].pcr_select, response + pcr_select_offset,
517                        pcrs.selection[i].size_of_select);
518         }
519
520         for (i = 0; i < pcrs.count; i++) {
521                 u32 hash_mask = alg_to_mask(pcrs.selection[i].hash);
522
523                 if (hash_mask) {
524                         *supported_pcr |= hash_mask;
525                         if (is_active_pcr(&pcrs.selection[i]))
526                                 *active_pcr |= hash_mask;
527                 } else {
528                         EFI_PRINT("Unknown algorithm %x\n", pcrs.selection[i].hash);
529                 }
530         }
531
532         *pcr_banks = pcrs.count;
533
534         return 0;
535 out:
536         return -1;
537 }
538
539 /**
540  * __get_active_pcr_banks() - returns the currently active PCR banks
541  *
542  * @active_pcr_banks:           pointer for receiving the bitmap of currently
543  *                              active PCR banks
544  *
545  * Return:      status code
546  */
547 static efi_status_t __get_active_pcr_banks(u32 *active_pcr_banks)
548 {
549         struct udevice *dev;
550         u32 active = 0, supported = 0, pcr_banks = 0;
551         efi_status_t ret;
552         int err;
553
554         ret = platform_get_tpm2_device(&dev);
555         if (ret != EFI_SUCCESS)
556                 goto out;
557
558         err = tpm2_get_pcr_info(dev, &supported, &active, &pcr_banks);
559         if (err) {
560                 ret = EFI_DEVICE_ERROR;
561                 goto out;
562         }
563
564         *active_pcr_banks = active;
565
566 out:
567         return ret;
568 }
569
570 /* tcg2_create_digest - create a list of digests of the supported PCR banks
571  *                      for a given memory range
572  *
573  * @input:              input memory
574  * @length:             length of buffer to calculate the digest
575  * @digest_list:        list of digests to fill in
576  *
577  * Return:              status code
578  */
579 static efi_status_t tcg2_create_digest(const u8 *input, u32 length,
580                                        struct tpml_digest_values *digest_list)
581 {
582         sha1_context ctx;
583         sha256_context ctx_256;
584         sha512_context ctx_512;
585         u8 final[TPM2_SHA512_DIGEST_SIZE];
586         efi_status_t ret;
587         u32 active;
588         size_t i;
589
590         ret = __get_active_pcr_banks(&active);
591         if (ret != EFI_SUCCESS)
592                 return ret;
593
594         digest_list->count = 0;
595         for (i = 0; i < MAX_HASH_COUNT; i++) {
596                 u16 hash_alg = hash_algo_list[i].hash_alg;
597
598                 if (!(active & alg_to_mask(hash_alg)))
599                         continue;
600                 switch (hash_alg) {
601                 case TPM2_ALG_SHA1:
602                         sha1_starts(&ctx);
603                         sha1_update(&ctx, input, length);
604                         sha1_finish(&ctx, final);
605                         break;
606                 case TPM2_ALG_SHA256:
607                         sha256_starts(&ctx_256);
608                         sha256_update(&ctx_256, input, length);
609                         sha256_finish(&ctx_256, final);
610                         break;
611                 case TPM2_ALG_SHA384:
612                         sha384_starts(&ctx_512);
613                         sha384_update(&ctx_512, input, length);
614                         sha384_finish(&ctx_512, final);
615                         break;
616                 case TPM2_ALG_SHA512:
617                         sha512_starts(&ctx_512);
618                         sha512_update(&ctx_512, input, length);
619                         sha512_finish(&ctx_512, final);
620                         break;
621                 default:
622                         EFI_PRINT("Unsupported algorithm %x\n", hash_alg);
623                         return EFI_INVALID_PARAMETER;
624                 }
625                 digest_list->digests[digest_list->count].hash_alg = hash_alg;
626                 memcpy(&digest_list->digests[digest_list->count].digest, final,
627                        (u32)alg_to_len(hash_alg));
628                 digest_list->count++;
629         }
630
631         return EFI_SUCCESS;
632 }
633
634 /**
635  * efi_tcg2_get_capability() - protocol capability information and state information
636  *
637  * @this:               TCG2 protocol instance
638  * @capability:         caller allocated memory with size field to the size of
639  *                      the structure allocated
640
641  * Return:      status code
642  */
643 static efi_status_t EFIAPI
644 efi_tcg2_get_capability(struct efi_tcg2_protocol *this,
645                         struct efi_tcg2_boot_service_capability *capability)
646 {
647         struct udevice *dev;
648         efi_status_t efi_ret;
649         int ret;
650
651         EFI_ENTRY("%p, %p", this, capability);
652
653         if (!this || !capability) {
654                 efi_ret = EFI_INVALID_PARAMETER;
655                 goto out;
656         }
657
658         if (capability->size < BOOT_SERVICE_CAPABILITY_MIN) {
659                 capability->size = BOOT_SERVICE_CAPABILITY_MIN;
660                 efi_ret = EFI_BUFFER_TOO_SMALL;
661                 goto out;
662         }
663
664         if (capability->size < sizeof(*capability)) {
665                 capability->size = sizeof(*capability);
666                 efi_ret = EFI_BUFFER_TOO_SMALL;
667                 goto out;
668         }
669
670         capability->structure_version.major = 1;
671         capability->structure_version.minor = 1;
672         capability->protocol_version.major = 1;
673         capability->protocol_version.minor = 1;
674
675         efi_ret = platform_get_tpm2_device(&dev);
676         if (efi_ret != EFI_SUCCESS) {
677                 capability->supported_event_logs = 0;
678                 capability->hash_algorithm_bitmap = 0;
679                 capability->tpm_present_flag = false;
680                 capability->max_command_size = 0;
681                 capability->max_response_size = 0;
682                 capability->manufacturer_id = 0;
683                 capability->number_of_pcr_banks = 0;
684                 capability->active_pcr_banks = 0;
685
686                 efi_ret = EFI_SUCCESS;
687                 goto out;
688         }
689
690         /* We only allow a TPMv2 device to register the EFI protocol */
691         capability->supported_event_logs = TCG2_EVENT_LOG_FORMAT_TCG_2;
692
693         capability->tpm_present_flag = true;
694
695         /* Supported and active PCRs */
696         capability->hash_algorithm_bitmap = 0;
697         capability->active_pcr_banks = 0;
698         ret = tpm2_get_pcr_info(dev, &capability->hash_algorithm_bitmap,
699                                 &capability->active_pcr_banks,
700                                 &capability->number_of_pcr_banks);
701         if (ret) {
702                 efi_ret = EFI_DEVICE_ERROR;
703                 goto out;
704         }
705
706         /* Max command size */
707         ret = tpm2_get_max_command_size(dev, &capability->max_command_size);
708         if (ret) {
709                 efi_ret = EFI_DEVICE_ERROR;
710                 goto out;
711         }
712
713         /* Max response size */
714         ret = tpm2_get_max_response_size(dev, &capability->max_response_size);
715         if (ret) {
716                 efi_ret = EFI_DEVICE_ERROR;
717                 goto out;
718         }
719
720         /* Manufacturer ID */
721         ret = tpm2_get_manufacturer_id(dev, &capability->manufacturer_id);
722         if (ret) {
723                 efi_ret = EFI_DEVICE_ERROR;
724                 goto out;
725         }
726
727         return EFI_EXIT(EFI_SUCCESS);
728 out:
729         return EFI_EXIT(efi_ret);
730 }
731
732 /**
733  * efi_tcg2_get_eventlog() -    retrieve the the address of an event log and its
734  *                              last entry
735  *
736  * @this:                       TCG2 protocol instance
737  * @log_format:                 type of event log format
738  * @event_log_location:         pointer to the memory address of the event log
739  * @event_log_last_entry:       pointer to the address of the start of the last
740  *                              entry in the event log in memory, if log contains
741  *                              more than 1 entry
742  * @event_log_truncated:        set to true, if the Event Log is missing at i
743  *                              least one entry
744  *
745  * Return:      status code
746  */
747 static efi_status_t EFIAPI
748 efi_tcg2_get_eventlog(struct efi_tcg2_protocol *this,
749                       efi_tcg_event_log_format log_format,
750                       u64 *event_log_location, u64 *event_log_last_entry,
751                       bool *event_log_truncated)
752 {
753         efi_status_t ret = EFI_SUCCESS;
754         struct udevice *dev;
755
756         EFI_ENTRY("%p, %u, %p, %p,  %p", this, log_format, event_log_location,
757                   event_log_last_entry, event_log_truncated);
758
759         if (!this || !event_log_location || !event_log_last_entry ||
760             !event_log_truncated) {
761                 ret = EFI_INVALID_PARAMETER;
762                 goto out;
763         }
764
765         /* Only support TPMV2 */
766         if (log_format != TCG2_EVENT_LOG_FORMAT_TCG_2) {
767                 ret = EFI_INVALID_PARAMETER;
768                 goto out;
769         }
770
771         ret = platform_get_tpm2_device(&dev);
772         if (ret != EFI_SUCCESS) {
773                 event_log_location = NULL;
774                 event_log_last_entry = NULL;
775                 *event_log_truncated = false;
776                 ret = EFI_SUCCESS;
777                 goto out;
778         }
779         *event_log_location = (uintptr_t)event_log.buffer;
780         *event_log_last_entry = (uintptr_t)(event_log.buffer + event_log.pos -
781                                             event_log.last_event_size);
782         *event_log_truncated = event_log.truncated;
783         event_log.get_event_called = true;
784
785 out:
786         return EFI_EXIT(ret);
787 }
788
789 /**
790  * tcg2_hash_pe_image() - calculate PE/COFF image hash
791  *
792  * @efi:                pointer to the EFI binary
793  * @efi_size:           size of @efi binary
794  * @digest_list:        list of digest algorithms to extend
795  *
796  * Return:      status code
797  */
798 static efi_status_t tcg2_hash_pe_image(void *efi, u64 efi_size,
799                                        struct tpml_digest_values *digest_list)
800 {
801         WIN_CERTIFICATE *wincerts = NULL;
802         size_t wincerts_len;
803         struct efi_image_regions *regs = NULL;
804         void *new_efi = NULL;
805         u8 hash[TPM2_SHA512_DIGEST_SIZE];
806         efi_status_t ret;
807         u32 active;
808         int i;
809
810         new_efi = efi_prepare_aligned_image(efi, &efi_size);
811         if (!new_efi)
812                 return EFI_OUT_OF_RESOURCES;
813
814         if (!efi_image_parse(new_efi, efi_size, &regs, &wincerts,
815                              &wincerts_len)) {
816                 log_err("Parsing PE executable image failed\n");
817                 ret = EFI_UNSUPPORTED;
818                 goto out;
819         }
820
821         ret = __get_active_pcr_banks(&active);
822         if (ret != EFI_SUCCESS) {
823                 goto out;
824         }
825
826         digest_list->count = 0;
827         for (i = 0; i < MAX_HASH_COUNT; i++) {
828                 u16 hash_alg = hash_algo_list[i].hash_alg;
829
830                 if (!(active & alg_to_mask(hash_alg)))
831                         continue;
832                 switch (hash_alg) {
833                 case TPM2_ALG_SHA1:
834                         hash_calculate("sha1", regs->reg, regs->num, hash);
835                         break;
836                 case TPM2_ALG_SHA256:
837                         hash_calculate("sha256", regs->reg, regs->num, hash);
838                         break;
839                 case TPM2_ALG_SHA384:
840                         hash_calculate("sha384", regs->reg, regs->num, hash);
841                         break;
842                 case TPM2_ALG_SHA512:
843                         hash_calculate("sha512", regs->reg, regs->num, hash);
844                         break;
845                 default:
846                         EFI_PRINT("Unsupported algorithm %x\n", hash_alg);
847                         return EFI_INVALID_PARAMETER;
848                 }
849                 digest_list->digests[digest_list->count].hash_alg = hash_alg;
850                 memcpy(&digest_list->digests[digest_list->count].digest, hash,
851                        (u32)alg_to_len(hash_alg));
852                 digest_list->count++;
853         }
854
855 out:
856         if (new_efi != efi)
857                 free(new_efi);
858         free(regs);
859
860         return ret;
861 }
862
863 /**
864  * tcg2_measure_pe_image() - measure PE/COFF image
865  *
866  * @efi:                pointer to the EFI binary
867  * @efi_size:           size of @efi binary
868  * @handle:             loaded image handle
869  * @loaded_image:       loaded image protocol
870  *
871  * Return:      status code
872  */
873 efi_status_t tcg2_measure_pe_image(void *efi, u64 efi_size,
874                                    struct efi_loaded_image_obj *handle,
875                                    struct efi_loaded_image *loaded_image)
876 {
877         struct tpml_digest_values digest_list;
878         efi_status_t ret;
879         struct udevice *dev;
880         u32 pcr_index, event_type, event_size;
881         struct uefi_image_load_event *image_load_event;
882         struct efi_device_path *device_path;
883         u32 device_path_length;
884         IMAGE_DOS_HEADER *dos;
885         IMAGE_NT_HEADERS32 *nt;
886         struct efi_handler *handler;
887
888         ret = platform_get_tpm2_device(&dev);
889         if (ret != EFI_SUCCESS)
890                 return ret;
891
892         switch (handle->image_type) {
893         case IMAGE_SUBSYSTEM_EFI_APPLICATION:
894                 pcr_index = 4;
895                 event_type = EV_EFI_BOOT_SERVICES_APPLICATION;
896                 break;
897         case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
898                 pcr_index = 2;
899                 event_type = EV_EFI_BOOT_SERVICES_DRIVER;
900                 break;
901         case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
902                 pcr_index = 2;
903                 event_type = EV_EFI_RUNTIME_SERVICES_DRIVER;
904                 break;
905         default:
906                 return EFI_UNSUPPORTED;
907         }
908
909         ret = tcg2_hash_pe_image(efi, efi_size, &digest_list);
910         if (ret != EFI_SUCCESS)
911                 return ret;
912
913         ret = tcg2_pcr_extend(dev, pcr_index, &digest_list);
914         if (ret != EFI_SUCCESS)
915                 return ret;
916
917         ret = efi_search_protocol(&handle->header,
918                                   &efi_guid_loaded_image_device_path, &handler);
919         if (ret != EFI_SUCCESS)
920                 return ret;
921
922         device_path = handler->protocol_interface;
923         device_path_length = efi_dp_size(device_path);
924         if (device_path_length > 0) {
925                 /* add end node size */
926                 device_path_length += sizeof(struct efi_device_path);
927         }
928         event_size = sizeof(struct uefi_image_load_event) + device_path_length;
929         image_load_event = calloc(1, event_size);
930         if (!image_load_event)
931                 return EFI_OUT_OF_RESOURCES;
932
933         image_load_event->image_location_in_memory = (uintptr_t)efi;
934         image_load_event->image_length_in_memory = efi_size;
935         image_load_event->length_of_device_path = device_path_length;
936
937         dos = (IMAGE_DOS_HEADER *)efi;
938         nt = (IMAGE_NT_HEADERS32 *)(efi + dos->e_lfanew);
939         if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
940                 IMAGE_NT_HEADERS64 *nt64 = (IMAGE_NT_HEADERS64 *)nt;
941
942                 image_load_event->image_link_time_address =
943                                 nt64->OptionalHeader.ImageBase;
944         } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
945                 image_load_event->image_link_time_address =
946                                 nt->OptionalHeader.ImageBase;
947         } else {
948                 ret = EFI_INVALID_PARAMETER;
949                 goto out;
950         }
951
952         /* device_path_length might be zero */
953         memcpy(image_load_event->device_path, device_path, device_path_length);
954
955         ret = tcg2_agile_log_append(pcr_index, event_type, &digest_list,
956                                     event_size, (u8 *)image_load_event);
957
958 out:
959         free(image_load_event);
960
961         return ret;
962 }
963
964 /**
965  * efi_tcg2_hash_log_extend_event() - extend and optionally log events
966  *
967  * @this:                       TCG2 protocol instance
968  * @flags:                      bitmap providing additional information on the
969  *                              operation
970  * @data_to_hash:               physical address of the start of the data buffer
971  *                              to be hashed
972  * @data_to_hash_len:           the length in bytes of the buffer referenced by
973  *                              data_to_hash
974  * @efi_tcg_event:              pointer to data buffer containing information
975  *                              about the event
976  *
977  * Return:      status code
978  */
979 static efi_status_t EFIAPI
980 efi_tcg2_hash_log_extend_event(struct efi_tcg2_protocol *this, u64 flags,
981                                u64 data_to_hash, u64 data_to_hash_len,
982                                struct efi_tcg2_event *efi_tcg_event)
983 {
984         struct udevice *dev;
985         efi_status_t ret;
986         u32 event_type, pcr_index, event_size;
987         struct tpml_digest_values digest_list;
988
989         EFI_ENTRY("%p, %llu, %llu, %llu, %p", this, flags, data_to_hash,
990                   data_to_hash_len, efi_tcg_event);
991
992         if (!this || !data_to_hash || !efi_tcg_event) {
993                 ret = EFI_INVALID_PARAMETER;
994                 goto out;
995         }
996
997         ret = platform_get_tpm2_device(&dev);
998         if (ret != EFI_SUCCESS)
999                 goto out;
1000
1001         if (efi_tcg_event->size < efi_tcg_event->header.header_size +
1002             sizeof(u32)) {
1003                 ret = EFI_INVALID_PARAMETER;
1004                 goto out;
1005         }
1006
1007         if (efi_tcg_event->header.pcr_index > EFI_TCG2_MAX_PCR_INDEX) {
1008                 ret = EFI_INVALID_PARAMETER;
1009                 goto out;
1010         }
1011
1012         /*
1013          * if PE_COFF_IMAGE is set we need to make sure the image is not
1014          * corrupted, verify it and hash the PE/COFF image in accordance with
1015          * the procedure specified in "Calculating the PE Image Hash"
1016          * section of the "Windows Authenticode Portable Executable Signature
1017          * Format"
1018          */
1019         if (flags & PE_COFF_IMAGE) {
1020                 IMAGE_NT_HEADERS32 *nt;
1021
1022                 ret = efi_check_pe((void *)(uintptr_t)data_to_hash,
1023                                    data_to_hash_len, (void **)&nt);
1024                 if (ret != EFI_SUCCESS) {
1025                         log_err("Not a valid PE-COFF file\n");
1026                         ret = EFI_UNSUPPORTED;
1027                         goto out;
1028                 }
1029                 ret = tcg2_hash_pe_image((void *)(uintptr_t)data_to_hash,
1030                                          data_to_hash_len, &digest_list);
1031         } else {
1032                 ret = tcg2_create_digest((u8 *)(uintptr_t)data_to_hash,
1033                                          data_to_hash_len, &digest_list);
1034         }
1035
1036         if (ret != EFI_SUCCESS)
1037                 goto out;
1038
1039         pcr_index = efi_tcg_event->header.pcr_index;
1040         event_type = efi_tcg_event->header.event_type;
1041
1042         ret = tcg2_pcr_extend(dev, pcr_index, &digest_list);
1043         if (ret != EFI_SUCCESS)
1044                 goto out;
1045
1046         if (flags & EFI_TCG2_EXTEND_ONLY) {
1047                 if (event_log.truncated)
1048                         ret = EFI_VOLUME_FULL;
1049                 goto out;
1050         }
1051
1052         /*
1053          * The efi_tcg_event size includes the size component and the
1054          * headersize
1055          */
1056         event_size = efi_tcg_event->size - sizeof(efi_tcg_event->size) -
1057                 efi_tcg_event->header.header_size;
1058         ret = tcg2_agile_log_append(pcr_index, event_type, &digest_list,
1059                                     event_size, efi_tcg_event->event);
1060 out:
1061         return EFI_EXIT(ret);
1062 }
1063
1064 /**
1065  * efi_tcg2_submit_command() - Send command to the TPM
1066  *
1067  * @this:                       TCG2 protocol instance
1068  * @input_param_block_size:     size of the TPM input parameter block
1069  * @input_param_block:          pointer to the TPM input parameter block
1070  * @output_param_block_size:    size of the TPM output parameter block
1071  * @output_param_block:         pointer to the TPM output parameter block
1072  *
1073  * Return:      status code
1074  */
1075 static efi_status_t EFIAPI
1076 efi_tcg2_submit_command(struct efi_tcg2_protocol *this,
1077                         u32 input_param_block_size,
1078                         u8 *input_param_block,
1079                         u32 output_param_block_size,
1080                         u8 *output_param_block)
1081 {
1082         struct udevice *dev;
1083         efi_status_t ret;
1084         u32 rc;
1085         size_t resp_buf_size = output_param_block_size;
1086
1087         EFI_ENTRY("%p, %u, %p, %u, %p", this, input_param_block_size,
1088                   input_param_block, output_param_block_size, output_param_block);
1089
1090         if (!this || !input_param_block || !input_param_block_size) {
1091                 ret = EFI_INVALID_PARAMETER;
1092                 goto out;
1093         }
1094
1095         ret = platform_get_tpm2_device(&dev);
1096         if (ret != EFI_SUCCESS)
1097                 goto out;
1098
1099         rc = tpm2_submit_command(dev, input_param_block,
1100                                  output_param_block, &resp_buf_size);
1101         if (rc) {
1102                 ret = (rc == -ENOSPC) ? EFI_OUT_OF_RESOURCES : EFI_DEVICE_ERROR;
1103
1104                 goto out;
1105         }
1106
1107 out:
1108         return EFI_EXIT(ret);
1109 }
1110
1111 /**
1112  * efi_tcg2_get_active_pcr_banks() - returns the currently active PCR banks
1113  *
1114  * @this:                       TCG2 protocol instance
1115  * @active_pcr_banks:           pointer for receiving the bitmap of currently
1116  *                              active PCR banks
1117  *
1118  * Return:      status code
1119  */
1120 static efi_status_t EFIAPI
1121 efi_tcg2_get_active_pcr_banks(struct efi_tcg2_protocol *this,
1122                               u32 *active_pcr_banks)
1123 {
1124         efi_status_t ret;
1125
1126         if (!this || !active_pcr_banks) {
1127                 ret = EFI_INVALID_PARAMETER;
1128                 goto out;
1129         }
1130
1131         EFI_ENTRY("%p, %p", this, active_pcr_banks);
1132         ret = __get_active_pcr_banks(active_pcr_banks);
1133
1134 out:
1135         return EFI_EXIT(ret);
1136 }
1137
1138 /**
1139  * efi_tcg2_set_active_pcr_banks() - sets the currently active PCR banks
1140  *
1141  * @this:                       TCG2 protocol instance
1142  * @active_pcr_banks:           bitmap of the requested active PCR banks
1143  *
1144  * Return:      status code
1145  */
1146 static efi_status_t EFIAPI
1147 efi_tcg2_set_active_pcr_banks(__maybe_unused struct efi_tcg2_protocol *this,
1148                               u32 __maybe_unused active_pcr_banks)
1149 {
1150         return EFI_UNSUPPORTED;
1151 }
1152
1153 /**
1154  * efi_tcg2_get_result_of_set_active_pcr_banks() - retrieve result for previous
1155  *                                                 set_active_pcr_banks()
1156  *
1157  * @this:                       TCG2 protocol instance
1158  * @operation_present:          non-zero value to indicate a
1159  *                              set_active_pcr_banks operation was
1160  *                              invoked during last boot
1161  * @response:                   result value could be returned
1162  *
1163  * Return:      status code
1164  */
1165 static efi_status_t EFIAPI
1166 efi_tcg2_get_result_of_set_active_pcr_banks(__maybe_unused struct efi_tcg2_protocol *this,
1167                                             u32 __maybe_unused *operation_present,
1168                                             u32 __maybe_unused *response)
1169 {
1170         return EFI_UNSUPPORTED;
1171 }
1172
1173 static const struct efi_tcg2_protocol efi_tcg2_protocol = {
1174         .get_capability = efi_tcg2_get_capability,
1175         .get_eventlog = efi_tcg2_get_eventlog,
1176         .hash_log_extend_event = efi_tcg2_hash_log_extend_event,
1177         .submit_command = efi_tcg2_submit_command,
1178         .get_active_pcr_banks = efi_tcg2_get_active_pcr_banks,
1179         .set_active_pcr_banks = efi_tcg2_set_active_pcr_banks,
1180         .get_result_of_set_active_pcr_banks = efi_tcg2_get_result_of_set_active_pcr_banks,
1181 };
1182
1183 /**
1184  * create_specid_event() - Create the first event in the eventlog
1185  *
1186  * @dev:                        tpm device
1187  * @event_header:               Pointer to the final event header
1188  * @event_size:                 final spec event size
1189  *
1190  * Return:      status code
1191  */
1192 static efi_status_t create_specid_event(struct udevice *dev, void *buffer,
1193                                         size_t *event_size)
1194 {
1195         struct tcg_efi_spec_id_event *spec_event;
1196         size_t spec_event_size;
1197         efi_status_t ret = EFI_DEVICE_ERROR;
1198         u32 active = 0, supported = 0, pcr_count = 0, alg_count = 0;
1199         int err;
1200         size_t i;
1201
1202         /*
1203          * Create Spec event. This needs to be the first event in the log
1204          * according to the TCG EFI protocol spec
1205          */
1206
1207         /* Setup specID event data */
1208         spec_event = (struct tcg_efi_spec_id_event *)buffer;
1209         memcpy(spec_event->signature, TCG_EFI_SPEC_ID_EVENT_SIGNATURE_03,
1210                sizeof(spec_event->signature));
1211         put_unaligned_le32(0, &spec_event->platform_class); /* type client */
1212         spec_event->spec_version_minor =
1213                 TCG_EFI_SPEC_ID_EVENT_SPEC_VERSION_MINOR_TPM2;
1214         spec_event->spec_version_major =
1215                 TCG_EFI_SPEC_ID_EVENT_SPEC_VERSION_MAJOR_TPM2;
1216         spec_event->spec_errata =
1217                 TCG_EFI_SPEC_ID_EVENT_SPEC_VERSION_ERRATA_TPM2;
1218         spec_event->uintn_size = sizeof(efi_uintn_t) / sizeof(u32);
1219
1220         err = tpm2_get_pcr_info(dev, &supported, &active, &pcr_count);
1221
1222         if (err)
1223                 goto out;
1224
1225         for (i = 0; i < pcr_count; i++) {
1226                 u16 hash_alg = hash_algo_list[i].hash_alg;
1227                 u16 hash_len = hash_algo_list[i].hash_len;
1228
1229                 if (active & alg_to_mask(hash_alg)) {
1230                         put_unaligned_le16(hash_alg,
1231                                            &spec_event->digest_sizes[alg_count].algorithm_id);
1232                         put_unaligned_le16(hash_len,
1233                                            &spec_event->digest_sizes[alg_count].digest_size);
1234                         alg_count++;
1235                 }
1236         }
1237
1238         spec_event->number_of_algorithms = alg_count;
1239         if (spec_event->number_of_algorithms > MAX_HASH_COUNT ||
1240             spec_event->number_of_algorithms < 1)
1241                 goto out;
1242
1243         /*
1244          * the size of the spec event and placement of vendor_info_size
1245          * depends on supported algoriths
1246          */
1247         spec_event_size =
1248                 offsetof(struct tcg_efi_spec_id_event, digest_sizes) +
1249                 spec_event->number_of_algorithms * sizeof(spec_event->digest_sizes[0]);
1250         /* no vendor info for us */
1251         memset(buffer + spec_event_size, 0, 1);
1252         /* add a byte for vendor_info_size in the spec event */
1253         spec_event_size += 1;
1254         *event_size = spec_event_size;
1255
1256         return EFI_SUCCESS;
1257
1258 out:
1259         return ret;
1260 }
1261
1262 /**
1263  * tcg2_uninit - remove the final event table and free efi memory on failures
1264  */
1265 void tcg2_uninit(void)
1266 {
1267         efi_status_t ret;
1268
1269         ret = efi_install_configuration_table(&efi_guid_final_events, NULL);
1270         if (ret != EFI_SUCCESS)
1271                 log_err("Failed to delete final events config table\n");
1272
1273         efi_free_pool(event_log.buffer);
1274         event_log.buffer = NULL;
1275         efi_free_pool(event_log.final_buffer);
1276         event_log.final_buffer = NULL;
1277 }
1278
1279 /**
1280  * create_final_event() - Create the final event and install the config
1281  *                      defined by the TCG EFI spec
1282  */
1283 static efi_status_t create_final_event(void)
1284 {
1285         struct efi_tcg2_final_events_table *final_event;
1286         efi_status_t ret;
1287
1288         /*
1289          * All events generated after the invocation of
1290          * EFI_TCG2_GET_EVENT_LOGS need to be stored in an instance of an
1291          * EFI_CONFIGURATION_TABLE
1292          */
1293         ret = efi_allocate_pool(EFI_ACPI_MEMORY_NVS, TPM2_EVENT_LOG_SIZE,
1294                                 &event_log.final_buffer);
1295         if (ret != EFI_SUCCESS)
1296                 goto out;
1297
1298         memset(event_log.final_buffer, 0xff, TPM2_EVENT_LOG_SIZE);
1299         final_event = event_log.final_buffer;
1300         final_event->number_of_events = 0;
1301         final_event->version = EFI_TCG2_FINAL_EVENTS_TABLE_VERSION;
1302         event_log.final_pos = sizeof(*final_event);
1303         ret = efi_install_configuration_table(&efi_guid_final_events,
1304                                               final_event);
1305         if (ret != EFI_SUCCESS) {
1306                 efi_free_pool(event_log.final_buffer);
1307                 event_log.final_buffer = NULL;
1308         }
1309
1310 out:
1311         return ret;
1312 }
1313
1314 /**
1315  * efi_init_event_log() - initialize an eventlog
1316  */
1317 static efi_status_t efi_init_event_log(void)
1318 {
1319         /*
1320          * vendor_info_size is currently set to 0, we need to change the length
1321          * and allocate the flexible array member if this changes
1322          */
1323         struct tcg_pcr_event *event_header = NULL;
1324         struct udevice *dev;
1325         size_t spec_event_size;
1326         efi_status_t ret;
1327
1328         ret = platform_get_tpm2_device(&dev);
1329         if (ret != EFI_SUCCESS)
1330                 goto out;
1331
1332         ret = efi_allocate_pool(EFI_BOOT_SERVICES_DATA, TPM2_EVENT_LOG_SIZE,
1333                                 (void **)&event_log.buffer);
1334         if (ret != EFI_SUCCESS)
1335                 goto out;
1336
1337         /*
1338          * initialize log area as 0xff so the OS can easily figure out the
1339          * last log entry
1340          */
1341         memset(event_log.buffer, 0xff, TPM2_EVENT_LOG_SIZE);
1342         event_log.pos = 0;
1343         event_log.last_event_size = 0;
1344         event_log.get_event_called = false;
1345         event_log.ebs_called = false;
1346         event_log.truncated = false;
1347
1348         /*
1349          * The log header is defined to be in SHA1 event log entry format.
1350          * Setup event header
1351          */
1352         event_header =  (struct tcg_pcr_event *)event_log.buffer;
1353         put_unaligned_le32(0, &event_header->pcr_index);
1354         put_unaligned_le32(EV_NO_ACTION, &event_header->event_type);
1355         memset(&event_header->digest, 0, sizeof(event_header->digest));
1356         ret = create_specid_event(dev, (void *)((uintptr_t)event_log.buffer + sizeof(*event_header)),
1357                                   &spec_event_size);
1358         if (ret != EFI_SUCCESS)
1359                 goto free_pool;
1360         put_unaligned_le32(spec_event_size, &event_header->event_size);
1361         event_log.pos = spec_event_size + sizeof(*event_header);
1362         event_log.last_event_size = event_log.pos;
1363
1364         ret = create_final_event();
1365         if (ret != EFI_SUCCESS)
1366                 goto free_pool;
1367
1368 out:
1369         return ret;
1370
1371 free_pool:
1372         efi_free_pool(event_log.buffer);
1373         event_log.buffer = NULL;
1374         return ret;
1375 }
1376
1377 /**
1378  * tcg2_measure_event() - common function to add event log and extend PCR
1379  *
1380  * @dev:                TPM device
1381  * @pcr_index:          PCR index
1382  * @event_type:         type of event added
1383  * @size:               event size
1384  * @event:              event data
1385  *
1386  * Return:      status code
1387  */
1388 static efi_status_t
1389 tcg2_measure_event(struct udevice *dev, u32 pcr_index, u32 event_type,
1390                    u32 size, u8 event[])
1391 {
1392         struct tpml_digest_values digest_list;
1393         efi_status_t ret;
1394
1395         ret = tcg2_create_digest(event, size, &digest_list);
1396         if (ret != EFI_SUCCESS)
1397                 goto out;
1398
1399         ret = tcg2_pcr_extend(dev, pcr_index, &digest_list);
1400         if (ret != EFI_SUCCESS)
1401                 goto out;
1402
1403         ret = tcg2_agile_log_append(pcr_index, event_type, &digest_list,
1404                                     size, event);
1405
1406 out:
1407         return ret;
1408 }
1409
1410 /**
1411  * efi_append_scrtm_version - Append an S-CRTM EV_S_CRTM_VERSION event on the
1412  *                            eventlog and extend the PCRs
1413  *
1414  * @dev:        TPM device
1415  *
1416  * @Return:     status code
1417  */
1418 static efi_status_t efi_append_scrtm_version(struct udevice *dev)
1419 {
1420         efi_status_t ret;
1421
1422         ret = tcg2_measure_event(dev, 0, EV_S_CRTM_VERSION,
1423                                  strlen(version_string) + 1,
1424                                  (u8 *)version_string);
1425
1426         return ret;
1427 }
1428
1429 /**
1430  * tcg2_measure_variable() - add variable event log and extend PCR
1431  *
1432  * @dev:                TPM device
1433  * @pcr_index:          PCR index
1434  * @event_type:         type of event added
1435  * @var_name:           variable name
1436  * @guid:               guid
1437  * @data_size:          variable data size
1438  * @data:               variable data
1439  *
1440  * Return:      status code
1441  */
1442 static efi_status_t tcg2_measure_variable(struct udevice *dev, u32 pcr_index,
1443                                           u32 event_type, const u16 *var_name,
1444                                           const efi_guid_t *guid,
1445                                           efi_uintn_t data_size, u8 *data)
1446 {
1447         u32 event_size;
1448         efi_status_t ret;
1449         struct efi_tcg2_uefi_variable_data *event;
1450
1451         event_size = sizeof(event->variable_name) +
1452                      sizeof(event->unicode_name_length) +
1453                      sizeof(event->variable_data_length) +
1454                      (u16_strlen(var_name) * sizeof(u16)) + data_size;
1455         event = malloc(event_size);
1456         if (!event)
1457                 return EFI_OUT_OF_RESOURCES;
1458
1459         guidcpy(&event->variable_name, guid);
1460         event->unicode_name_length = u16_strlen(var_name);
1461         event->variable_data_length = data_size;
1462         memcpy(event->unicode_name, var_name,
1463                (event->unicode_name_length * sizeof(u16)));
1464         if (data) {
1465                 memcpy((u16 *)event->unicode_name + event->unicode_name_length,
1466                        data, data_size);
1467         }
1468         ret = tcg2_measure_event(dev, pcr_index, event_type, event_size,
1469                                  (u8 *)event);
1470         free(event);
1471         return ret;
1472 }
1473
1474 /**
1475  * tcg2_measure_boot_variable() - measure boot variables
1476  *
1477  * @dev:        TPM device
1478  *
1479  * Return:      status code
1480  */
1481 static efi_status_t tcg2_measure_boot_variable(struct udevice *dev)
1482 {
1483         u16 *boot_order;
1484         u16 *boot_index;
1485         u16 var_name[] = L"BootOrder";
1486         u16 boot_name[] = L"Boot####";
1487         u8 *bootvar;
1488         efi_uintn_t var_data_size;
1489         u32 count, i;
1490         efi_status_t ret;
1491
1492         boot_order = efi_get_var(var_name, &efi_global_variable_guid,
1493                                  &var_data_size);
1494         if (!boot_order) {
1495                 /* If "BootOrder" is not defined, skip the boot variable measurement */
1496                 return EFI_SUCCESS;
1497         }
1498
1499         ret = tcg2_measure_variable(dev, 1, EV_EFI_VARIABLE_BOOT2, var_name,
1500                                     &efi_global_variable_guid, var_data_size,
1501                                     (u8 *)boot_order);
1502         if (ret != EFI_SUCCESS)
1503                 goto error;
1504
1505         count = var_data_size / sizeof(*boot_order);
1506         boot_index = boot_order;
1507         for (i = 0; i < count; i++) {
1508                 efi_create_indexed_name(boot_name, sizeof(boot_name),
1509                                         "Boot", *boot_index++);
1510
1511                 bootvar = efi_get_var(boot_name, &efi_global_variable_guid,
1512                                       &var_data_size);
1513
1514                 if (!bootvar) {
1515                         log_debug("%ls not found\n", boot_name);
1516                         continue;
1517                 }
1518
1519                 ret = tcg2_measure_variable(dev, 1, EV_EFI_VARIABLE_BOOT2,
1520                                             boot_name,
1521                                             &efi_global_variable_guid,
1522                                             var_data_size, bootvar);
1523                 free(bootvar);
1524                 if (ret != EFI_SUCCESS)
1525                         goto error;
1526         }
1527
1528 error:
1529         free(boot_order);
1530         return ret;
1531 }
1532
1533 /**
1534  * tcg2_measure_smbios() - measure smbios table
1535  *
1536  * @dev:        TPM device
1537  * @entry:      pointer to the smbios_entry structure
1538  *
1539  * Return:      status code
1540  */
1541 static efi_status_t
1542 tcg2_measure_smbios(struct udevice *dev,
1543                     const struct smbios_entry *entry)
1544 {
1545         efi_status_t ret;
1546         struct smbios_header *smbios_copy;
1547         struct smbios_handoff_table_pointers2 *event = NULL;
1548         u32 event_size;
1549
1550         /*
1551          * TCG PC Client PFP Spec says
1552          * "SMBIOS structures that contain static configuration information
1553          * (e.g. Platform Manufacturer Enterprise Number assigned by IANA,
1554          * platform model number, Vendor and Device IDs for each SMBIOS table)
1555          * that is relevant to the security of the platform MUST be measured".
1556          * Device dependent parameters such as serial number are cleared to
1557          * zero or spaces for the measurement.
1558          */
1559         event_size = sizeof(struct smbios_handoff_table_pointers2) +
1560                      FIELD_SIZEOF(struct efi_configuration_table, guid) +
1561                      entry->struct_table_length;
1562         event = calloc(1, event_size);
1563         if (!event) {
1564                 ret = EFI_OUT_OF_RESOURCES;
1565                 goto out;
1566         }
1567
1568         event->table_description_size = sizeof(SMBIOS_HANDOFF_TABLE_DESC);
1569         memcpy(event->table_description, SMBIOS_HANDOFF_TABLE_DESC,
1570                sizeof(SMBIOS_HANDOFF_TABLE_DESC));
1571         put_unaligned_le64(1, &event->number_of_tables);
1572         guidcpy(&event->table_entry[0].guid, &smbios_guid);
1573         smbios_copy = (struct smbios_header *)((uintptr_t)&event->table_entry[0].table);
1574         memcpy(&event->table_entry[0].table,
1575                (void *)((uintptr_t)entry->struct_table_address),
1576                entry->struct_table_length);
1577
1578         smbios_prepare_measurement(entry, smbios_copy);
1579
1580         ret = tcg2_measure_event(dev, 1, EV_EFI_HANDOFF_TABLES2, event_size,
1581                                  (u8 *)event);
1582         if (ret != EFI_SUCCESS)
1583                 goto out;
1584
1585 out:
1586         free(event);
1587
1588         return ret;
1589 }
1590
1591 /**
1592  * find_smbios_table() - find smbios table
1593  *
1594  * Return:      pointer to the smbios table
1595  */
1596 static void *find_smbios_table(void)
1597 {
1598         u32 i;
1599
1600         for (i = 0; i < systab.nr_tables; i++) {
1601                 if (!guidcmp(&smbios_guid, &systab.tables[i].guid))
1602                         return systab.tables[i].table;
1603         }
1604
1605         return NULL;
1606 }
1607
1608 /**
1609  * tcg2_measure_gpt_table() - measure gpt table
1610  *
1611  * @dev:                TPM device
1612  * @loaded_image:       handle to the loaded image
1613  *
1614  * Return:      status code
1615  */
1616 static efi_status_t
1617 tcg2_measure_gpt_data(struct udevice *dev,
1618                       struct efi_loaded_image_obj *loaded_image)
1619 {
1620         efi_status_t ret;
1621         efi_handle_t handle;
1622         struct efi_handler *dp_handler;
1623         struct efi_device_path *orig_device_path;
1624         struct efi_device_path *device_path;
1625         struct efi_device_path *dp;
1626         struct efi_block_io *block_io;
1627         struct efi_gpt_data *event = NULL;
1628         efi_guid_t null_guid = NULL_GUID;
1629         gpt_header *gpt_h;
1630         gpt_entry *entry = NULL;
1631         gpt_entry *gpt_e;
1632         u32 num_of_valid_entry = 0;
1633         u32 event_size;
1634         u32 i;
1635         u32 total_gpt_entry_size;
1636
1637         ret = efi_search_protocol(&loaded_image->header,
1638                                   &efi_guid_loaded_image_device_path,
1639                                   &dp_handler);
1640         if (ret != EFI_SUCCESS)
1641                 return ret;
1642
1643         orig_device_path = dp_handler->protocol_interface;
1644         if (!orig_device_path) /* no device path, skip GPT measurement */
1645                 return EFI_SUCCESS;
1646
1647         device_path = efi_dp_dup(orig_device_path);
1648         if (!device_path)
1649                 return EFI_OUT_OF_RESOURCES;
1650
1651         dp = search_gpt_dp_node(device_path);
1652         if (!dp) {
1653                 /* no GPT device path node found, skip GPT measurement */
1654                 ret = EFI_SUCCESS;
1655                 goto out1;
1656         }
1657
1658         /* read GPT header */
1659         dp->type = DEVICE_PATH_TYPE_END;
1660         dp->sub_type = DEVICE_PATH_SUB_TYPE_END;
1661         dp = device_path;
1662         ret = EFI_CALL(systab.boottime->locate_device_path(&efi_block_io_guid,
1663                                                            &dp, &handle));
1664         if (ret != EFI_SUCCESS)
1665                 goto out1;
1666
1667         ret = EFI_CALL(efi_handle_protocol(handle,
1668                                            &efi_block_io_guid, (void **)&block_io));
1669         if (ret != EFI_SUCCESS)
1670                 goto out1;
1671
1672         gpt_h = memalign(block_io->media->io_align, block_io->media->block_size);
1673         if (!gpt_h) {
1674                 ret = EFI_OUT_OF_RESOURCES;
1675                 goto out2;
1676         }
1677
1678         ret = block_io->read_blocks(block_io, block_io->media->media_id, 1,
1679                                     block_io->media->block_size, gpt_h);
1680         if (ret != EFI_SUCCESS)
1681                 goto out2;
1682
1683         /* read GPT entry */
1684         total_gpt_entry_size = gpt_h->num_partition_entries *
1685                                gpt_h->sizeof_partition_entry;
1686         entry = memalign(block_io->media->io_align, total_gpt_entry_size);
1687         if (!entry) {
1688                 ret = EFI_OUT_OF_RESOURCES;
1689                 goto out2;
1690         }
1691
1692         ret = block_io->read_blocks(block_io, block_io->media->media_id,
1693                                     gpt_h->partition_entry_lba,
1694                                     total_gpt_entry_size, entry);
1695         if (ret != EFI_SUCCESS)
1696                 goto out2;
1697
1698         /* count valid GPT entry */
1699         gpt_e = entry;
1700         for (i = 0; i < gpt_h->num_partition_entries; i++) {
1701                 if (guidcmp(&null_guid, &gpt_e->partition_type_guid))
1702                         num_of_valid_entry++;
1703
1704                 gpt_e = (gpt_entry *)((u8 *)gpt_e + gpt_h->sizeof_partition_entry);
1705         }
1706
1707         /* prepare event data for measurement */
1708         event_size = sizeof(struct efi_gpt_data) +
1709                 (num_of_valid_entry * gpt_h->sizeof_partition_entry);
1710         event = calloc(1, event_size);
1711         if (!event) {
1712                 ret = EFI_OUT_OF_RESOURCES;
1713                 goto out2;
1714         }
1715         memcpy(event, gpt_h, sizeof(gpt_header));
1716         put_unaligned_le64(num_of_valid_entry, &event->number_of_partitions);
1717
1718         /* copy valid GPT entry */
1719         gpt_e = entry;
1720         num_of_valid_entry = 0;
1721         for (i = 0; i < gpt_h->num_partition_entries; i++) {
1722                 if (guidcmp(&null_guid, &gpt_e->partition_type_guid)) {
1723                         memcpy((u8 *)event->partitions +
1724                                (num_of_valid_entry * gpt_h->sizeof_partition_entry),
1725                                gpt_e, gpt_h->sizeof_partition_entry);
1726                         num_of_valid_entry++;
1727                 }
1728
1729                 gpt_e = (gpt_entry *)((u8 *)gpt_e + gpt_h->sizeof_partition_entry);
1730         }
1731
1732         ret = tcg2_measure_event(dev, 5, EV_EFI_GPT_EVENT, event_size, (u8 *)event);
1733         if (ret != EFI_SUCCESS)
1734                 goto out2;
1735
1736 out2:
1737         EFI_CALL(efi_close_protocol((efi_handle_t)block_io, &efi_block_io_guid,
1738                                     NULL, NULL));
1739         free(gpt_h);
1740         free(entry);
1741         free(event);
1742 out1:
1743         efi_free_pool(device_path);
1744
1745         return ret;
1746 }
1747
1748 /**
1749  * efi_tcg2_measure_efi_app_invocation() - measure efi app invocation
1750  *
1751  * Return:      status code
1752  */
1753 efi_status_t efi_tcg2_measure_efi_app_invocation(struct efi_loaded_image_obj *handle)
1754 {
1755         efi_status_t ret;
1756         u32 pcr_index;
1757         struct udevice *dev;
1758         u32 event = 0;
1759         struct smbios_entry *entry;
1760
1761         if (tcg2_efi_app_invoked)
1762                 return EFI_SUCCESS;
1763
1764         ret = platform_get_tpm2_device(&dev);
1765         if (ret != EFI_SUCCESS)
1766                 return ret;
1767
1768         ret = tcg2_measure_boot_variable(dev);
1769         if (ret != EFI_SUCCESS)
1770                 goto out;
1771
1772         ret = tcg2_measure_event(dev, 4, EV_EFI_ACTION,
1773                                  strlen(EFI_CALLING_EFI_APPLICATION),
1774                                  (u8 *)EFI_CALLING_EFI_APPLICATION);
1775         if (ret != EFI_SUCCESS)
1776                 goto out;
1777
1778         entry = (struct smbios_entry *)find_smbios_table();
1779         if (entry) {
1780                 ret = tcg2_measure_smbios(dev, entry);
1781                 if (ret != EFI_SUCCESS)
1782                         goto out;
1783         }
1784
1785         ret = tcg2_measure_gpt_data(dev, handle);
1786         if (ret != EFI_SUCCESS)
1787                 goto out;
1788
1789         for (pcr_index = 0; pcr_index <= 7; pcr_index++) {
1790                 ret = tcg2_measure_event(dev, pcr_index, EV_SEPARATOR,
1791                                          sizeof(event), (u8 *)&event);
1792                 if (ret != EFI_SUCCESS)
1793                         goto out;
1794         }
1795
1796         tcg2_efi_app_invoked = true;
1797 out:
1798         return ret;
1799 }
1800
1801 /**
1802  * efi_tcg2_measure_efi_app_exit() - measure efi app exit
1803  *
1804  * Return:      status code
1805  */
1806 efi_status_t efi_tcg2_measure_efi_app_exit(void)
1807 {
1808         efi_status_t ret;
1809         struct udevice *dev;
1810
1811         ret = platform_get_tpm2_device(&dev);
1812         if (ret != EFI_SUCCESS)
1813                 return ret;
1814
1815         ret = tcg2_measure_event(dev, 4, EV_EFI_ACTION,
1816                                  strlen(EFI_RETURNING_FROM_EFI_APPLICATION),
1817                                  (u8 *)EFI_RETURNING_FROM_EFI_APPLICATION);
1818         return ret;
1819 }
1820
1821 /**
1822  * efi_tcg2_notify_exit_boot_services() - ExitBootService callback
1823  *
1824  * @event:      callback event
1825  * @context:    callback context
1826  */
1827 static void EFIAPI
1828 efi_tcg2_notify_exit_boot_services(struct efi_event *event, void *context)
1829 {
1830         efi_status_t ret;
1831         struct udevice *dev;
1832
1833         EFI_ENTRY("%p, %p", event, context);
1834
1835         event_log.ebs_called = true;
1836         ret = platform_get_tpm2_device(&dev);
1837         if (ret != EFI_SUCCESS)
1838                 goto out;
1839
1840         ret = tcg2_measure_event(dev, 5, EV_EFI_ACTION,
1841                                  strlen(EFI_EXIT_BOOT_SERVICES_INVOCATION),
1842                                  (u8 *)EFI_EXIT_BOOT_SERVICES_INVOCATION);
1843         if (ret != EFI_SUCCESS)
1844                 goto out;
1845
1846         ret = tcg2_measure_event(dev, 5, EV_EFI_ACTION,
1847                                  strlen(EFI_EXIT_BOOT_SERVICES_SUCCEEDED),
1848                                  (u8 *)EFI_EXIT_BOOT_SERVICES_SUCCEEDED);
1849
1850 out:
1851         EFI_EXIT(ret);
1852 }
1853
1854 /**
1855  * efi_tcg2_notify_exit_boot_services_failed()
1856  *  - notify ExitBootServices() is failed
1857  *
1858  * Return:      status code
1859  */
1860 efi_status_t efi_tcg2_notify_exit_boot_services_failed(void)
1861 {
1862         struct udevice *dev;
1863         efi_status_t ret;
1864
1865         ret = platform_get_tpm2_device(&dev);
1866         if (ret != EFI_SUCCESS)
1867                 goto out;
1868
1869         ret = tcg2_measure_event(dev, 5, EV_EFI_ACTION,
1870                                  strlen(EFI_EXIT_BOOT_SERVICES_INVOCATION),
1871                                  (u8 *)EFI_EXIT_BOOT_SERVICES_INVOCATION);
1872         if (ret != EFI_SUCCESS)
1873                 goto out;
1874
1875         ret = tcg2_measure_event(dev, 5, EV_EFI_ACTION,
1876                                  strlen(EFI_EXIT_BOOT_SERVICES_FAILED),
1877                                  (u8 *)EFI_EXIT_BOOT_SERVICES_FAILED);
1878
1879 out:
1880         return ret;
1881 }
1882
1883 /**
1884  * tcg2_measure_secure_boot_variable() - measure secure boot variables
1885  *
1886  * @dev:        TPM device
1887  *
1888  * Return:      status code
1889  */
1890 static efi_status_t tcg2_measure_secure_boot_variable(struct udevice *dev)
1891 {
1892         u8 *data;
1893         efi_uintn_t data_size;
1894         u32 count, i;
1895         efi_status_t ret;
1896         u8 deployed_mode;
1897         efi_uintn_t size;
1898         u32 deployed_audit_pcr_index = 1;
1899
1900         size = sizeof(deployed_mode);
1901         ret = efi_get_variable_int(u"DeployedMode", &efi_global_variable_guid,
1902                                    NULL, &size, &deployed_mode, NULL);
1903         if (ret != EFI_SUCCESS || !deployed_mode)
1904                 deployed_audit_pcr_index = 7;
1905
1906         count = ARRAY_SIZE(secure_variables);
1907         for (i = 0; i < count; i++) {
1908                 const efi_guid_t *guid;
1909
1910                 guid = efi_auth_var_get_guid(secure_variables[i].name);
1911
1912                 data = efi_get_var(secure_variables[i].name, guid, &data_size);
1913                 if (!data && !secure_variables[i].accept_empty)
1914                         continue;
1915
1916                 if (u16_strcmp(u"DeployedMode", secure_variables[i].name))
1917                         secure_variables[i].pcr_index = deployed_audit_pcr_index;
1918                 if (u16_strcmp(u"AuditMode", secure_variables[i].name))
1919                         secure_variables[i].pcr_index = deployed_audit_pcr_index;
1920
1921                 ret = tcg2_measure_variable(dev, secure_variables[i].pcr_index,
1922                                             EV_EFI_VARIABLE_DRIVER_CONFIG,
1923                                             secure_variables[i].name, guid,
1924                                             data_size, data);
1925                 free(data);
1926                 if (ret != EFI_SUCCESS)
1927                         goto error;
1928         }
1929
1930 error:
1931         return ret;
1932 }
1933
1934 /**
1935  * efi_tcg2_register() - register EFI_TCG2_PROTOCOL
1936  *
1937  * If a TPM2 device is available, the TPM TCG2 Protocol is registered
1938  *
1939  * Return:      An error status is only returned if adding the protocol fails.
1940  */
1941 efi_status_t efi_tcg2_register(void)
1942 {
1943         efi_status_t ret = EFI_SUCCESS;
1944         struct udevice *dev;
1945         struct efi_event *event;
1946
1947         ret = platform_get_tpm2_device(&dev);
1948         if (ret != EFI_SUCCESS) {
1949                 log_warning("Unable to find TPMv2 device\n");
1950                 return EFI_SUCCESS;
1951         }
1952
1953         ret = efi_init_event_log();
1954         if (ret != EFI_SUCCESS)
1955                 goto fail;
1956
1957         ret = efi_append_scrtm_version(dev);
1958         if (ret != EFI_SUCCESS) {
1959                 tcg2_uninit();
1960                 goto fail;
1961         }
1962
1963         ret = efi_add_protocol(efi_root, &efi_guid_tcg2_protocol,
1964                                (void *)&efi_tcg2_protocol);
1965         if (ret != EFI_SUCCESS) {
1966                 tcg2_uninit();
1967                 goto fail;
1968         }
1969
1970         ret = efi_create_event(EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_CALLBACK,
1971                                efi_tcg2_notify_exit_boot_services, NULL,
1972                                NULL, &event);
1973         if (ret != EFI_SUCCESS) {
1974                 tcg2_uninit();
1975                 goto fail;
1976         }
1977
1978         ret = tcg2_measure_secure_boot_variable(dev);
1979         if (ret != EFI_SUCCESS) {
1980                 tcg2_uninit();
1981                 goto fail;
1982         }
1983
1984         return ret;
1985
1986 fail:
1987         log_err("Cannot install EFI_TCG2_PROTOCOL\n");
1988         /*
1989          * Return EFI_SUCCESS and don't stop the EFI subsystem.
1990          * That's done for 2 reasons
1991          * - If the protocol is not installed the PCRs won't be extended.  So
1992          *   someone later in the boot flow will notice that and take the
1993          *   necessary actions.
1994          * - The TPM sandbox is limited and we won't be able to run any efi
1995          *   related tests with TCG2 enabled
1996          */
1997         return EFI_SUCCESS;
1998 }