e74c5b7b64bfbd3e4b0cc16352063bcc968ecfdd
[linux-2.6-microblaze.git] / drivers / char / tpm / tpm2-cmd.c
1 /*
2  * Copyright (C) 2014, 2015 Intel Corporation
3  *
4  * Authors:
5  * Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
6  *
7  * Maintained by: <tpmdd-devel@lists.sourceforge.net>
8  *
9  * This file contains TPM2 protocol implementations of the commands
10  * used by the kernel internally.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; version 2
15  * of the License.
16  */
17
18 #include "tpm.h"
19 #include <crypto/hash_info.h>
20 #include <keys/trusted-type.h>
21
22 enum tpm2_object_attributes {
23         TPM2_OA_USER_WITH_AUTH          = BIT(6),
24 };
25
26 enum tpm2_session_attributes {
27         TPM2_SA_CONTINUE_SESSION        = BIT(0),
28 };
29
30 struct tpm2_hash {
31         unsigned int crypto_id;
32         unsigned int tpm_id;
33 };
34
35 static struct tpm2_hash tpm2_hash_map[] = {
36         {HASH_ALGO_SHA1, TPM_ALG_SHA1},
37         {HASH_ALGO_SHA256, TPM_ALG_SHA256},
38         {HASH_ALGO_SHA384, TPM_ALG_SHA384},
39         {HASH_ALGO_SHA512, TPM_ALG_SHA512},
40         {HASH_ALGO_SM3_256, TPM_ALG_SM3_256},
41 };
42
43 int tpm2_get_timeouts(struct tpm_chip *chip)
44 {
45         /* Fixed timeouts for TPM2 */
46         chip->timeout_a = msecs_to_jiffies(TPM2_TIMEOUT_A);
47         chip->timeout_b = msecs_to_jiffies(TPM2_TIMEOUT_B);
48         chip->timeout_c = msecs_to_jiffies(TPM2_TIMEOUT_C);
49         chip->timeout_d = msecs_to_jiffies(TPM2_TIMEOUT_D);
50
51         /* PTP spec timeouts */
52         chip->duration[TPM_SHORT] = msecs_to_jiffies(TPM2_DURATION_SHORT);
53         chip->duration[TPM_MEDIUM] = msecs_to_jiffies(TPM2_DURATION_MEDIUM);
54         chip->duration[TPM_LONG] = msecs_to_jiffies(TPM2_DURATION_LONG);
55
56         /* Key creation commands long timeouts */
57         chip->duration[TPM_LONG_LONG] =
58                 msecs_to_jiffies(TPM2_DURATION_LONG_LONG);
59
60         chip->flags |= TPM_CHIP_FLAG_HAVE_TIMEOUTS;
61
62         return 0;
63 }
64
65 /**
66  * tpm2_ordinal_duration_index() - returns an index to the chip duration table
67  * @ordinal: TPM command ordinal.
68  *
69  * The function returns an index to the chip duration table
70  * (enum tpm_duration), that describes the maximum amount of
71  * time the chip could take to return the result for a  particular ordinal.
72  *
73  * The values of the MEDIUM, and LONG durations are taken
74  * from the PC Client Profile (PTP) specification (750, 2000 msec)
75  *
76  * LONG_LONG is for commands that generates keys which empirically takes
77  * a longer time on some systems.
78  *
79  * Return:
80  * * TPM_MEDIUM
81  * * TPM_LONG
82  * * TPM_LONG_LONG
83  * * TPM_UNDEFINED
84  */
85 static u8 tpm2_ordinal_duration_index(u32 ordinal)
86 {
87         switch (ordinal) {
88         /* Startup */
89         case TPM2_CC_STARTUP:                 /* 144 */
90                 return TPM_MEDIUM;
91
92         case TPM2_CC_SELF_TEST:               /* 143 */
93                 return TPM_LONG;
94
95         case TPM2_CC_GET_RANDOM:              /* 17B */
96                 return TPM_LONG;
97
98         case TPM2_CC_SEQUENCE_UPDATE:         /* 15C */
99                 return TPM_MEDIUM;
100         case TPM2_CC_SEQUENCE_COMPLETE:       /* 13E */
101                 return TPM_MEDIUM;
102         case TPM2_CC_EVENT_SEQUENCE_COMPLETE: /* 185 */
103                 return TPM_MEDIUM;
104         case TPM2_CC_HASH_SEQUENCE_START:     /* 186 */
105                 return TPM_MEDIUM;
106
107         case TPM2_CC_VERIFY_SIGNATURE:        /* 177 */
108                 return TPM_LONG;
109
110         case TPM2_CC_PCR_EXTEND:              /* 182 */
111                 return TPM_MEDIUM;
112
113         case TPM2_CC_HIERARCHY_CONTROL:       /* 121 */
114                 return TPM_LONG;
115         case TPM2_CC_HIERARCHY_CHANGE_AUTH:   /* 129 */
116                 return TPM_LONG;
117
118         case TPM2_CC_GET_CAPABILITY:          /* 17A */
119                 return TPM_MEDIUM;
120
121         case TPM2_CC_NV_READ:                 /* 14E */
122                 return TPM_LONG;
123
124         case TPM2_CC_CREATE_PRIMARY:          /* 131 */
125                 return TPM_LONG_LONG;
126         case TPM2_CC_CREATE:                  /* 153 */
127                 return TPM_LONG_LONG;
128         case TPM2_CC_CREATE_LOADED:           /* 191 */
129                 return TPM_LONG_LONG;
130
131         default:
132                 return TPM_UNDEFINED;
133         }
134 }
135
136 /**
137  * tpm2_calc_ordinal_duration() - calculate the maximum command duration
138  * @chip:    TPM chip to use.
139  * @ordinal: TPM command ordinal.
140  *
141  * The function returns the maximum amount of time the chip could take
142  * to return the result for a particular ordinal in jiffies.
143  *
144  * Return: A maximal duration time for an ordinal in jiffies.
145  */
146 unsigned long tpm2_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal)
147 {
148         unsigned int index;
149
150         index = tpm2_ordinal_duration_index(ordinal);
151
152         if (index != TPM_UNDEFINED)
153                 return chip->duration[index];
154         else
155                 return msecs_to_jiffies(TPM2_DURATION_DEFAULT);
156 }
157
158
159 struct tpm2_pcr_read_out {
160         __be32  update_cnt;
161         __be32  pcr_selects_cnt;
162         __be16  hash_alg;
163         u8      pcr_select_size;
164         u8      pcr_select[TPM2_PCR_SELECT_MIN];
165         __be32  digests_cnt;
166         __be16  digest_size;
167         u8      digest[];
168 } __packed;
169
170 /**
171  * tpm2_pcr_read() - read a PCR value
172  * @chip:       TPM chip to use.
173  * @pcr_idx:    index of the PCR to read.
174  * @digest:     PCR bank and buffer current PCR value is written to.
175  * @digest_size_ptr:    pointer to variable that stores the digest size.
176  *
177  * Return: Same as with tpm_transmit_cmd.
178  */
179 int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
180                   struct tpm_digest *digest, u16 *digest_size_ptr)
181 {
182         int i;
183         int rc;
184         struct tpm_buf buf;
185         struct tpm2_pcr_read_out *out;
186         u8 pcr_select[TPM2_PCR_SELECT_MIN] = {0};
187         u16 digest_size;
188         u16 expected_digest_size = 0;
189
190         if (pcr_idx >= TPM2_PLATFORM_PCR)
191                 return -EINVAL;
192
193         if (!digest_size_ptr) {
194                 for (i = 0; i < chip->nr_allocated_banks &&
195                      chip->allocated_banks[i].alg_id != digest->alg_id; i++)
196                         ;
197
198                 if (i == chip->nr_allocated_banks)
199                         return -EINVAL;
200
201                 expected_digest_size = chip->allocated_banks[i].digest_size;
202         }
203
204         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_PCR_READ);
205         if (rc)
206                 return rc;
207
208         pcr_select[pcr_idx >> 3] = 1 << (pcr_idx & 0x7);
209
210         tpm_buf_append_u32(&buf, 1);
211         tpm_buf_append_u16(&buf, digest->alg_id);
212         tpm_buf_append_u8(&buf, TPM2_PCR_SELECT_MIN);
213         tpm_buf_append(&buf, (const unsigned char *)pcr_select,
214                        sizeof(pcr_select));
215
216         rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to read a pcr value");
217         if (rc)
218                 goto out;
219
220         out = (struct tpm2_pcr_read_out *)&buf.data[TPM_HEADER_SIZE];
221         digest_size = be16_to_cpu(out->digest_size);
222         if (digest_size > sizeof(digest->digest) ||
223             (!digest_size_ptr && digest_size != expected_digest_size)) {
224                 rc = -EINVAL;
225                 goto out;
226         }
227
228         if (digest_size_ptr)
229                 *digest_size_ptr = digest_size;
230
231         memcpy(digest->digest, out->digest, digest_size);
232 out:
233         tpm_buf_destroy(&buf);
234         return rc;
235 }
236
237 struct tpm2_null_auth_area {
238         __be32  handle;
239         __be16  nonce_size;
240         u8  attributes;
241         __be16  auth_size;
242 } __packed;
243
244 /**
245  * tpm2_pcr_extend() - extend a PCR value
246  *
247  * @chip:       TPM chip to use.
248  * @pcr_idx:    index of the PCR.
249  * @digests:    list of pcr banks and corresponding digest values to extend.
250  *
251  * Return: Same as with tpm_transmit_cmd.
252  */
253 int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
254                     struct tpm_digest *digests)
255 {
256         struct tpm_buf buf;
257         struct tpm2_null_auth_area auth_area;
258         int rc;
259         int i;
260
261         rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
262         if (rc)
263                 return rc;
264
265         tpm_buf_append_u32(&buf, pcr_idx);
266
267         auth_area.handle = cpu_to_be32(TPM2_RS_PW);
268         auth_area.nonce_size = 0;
269         auth_area.attributes = 0;
270         auth_area.auth_size = 0;
271
272         tpm_buf_append_u32(&buf, sizeof(struct tpm2_null_auth_area));
273         tpm_buf_append(&buf, (const unsigned char *)&auth_area,
274                        sizeof(auth_area));
275         tpm_buf_append_u32(&buf, chip->nr_allocated_banks);
276
277         for (i = 0; i < chip->nr_allocated_banks; i++) {
278                 tpm_buf_append_u16(&buf, digests[i].alg_id);
279                 tpm_buf_append(&buf, (const unsigned char *)&digests[i].digest,
280                                chip->allocated_banks[i].digest_size);
281         }
282
283         rc = tpm_transmit_cmd(chip, &buf, 0, "attempting extend a PCR value");
284
285         tpm_buf_destroy(&buf);
286
287         return rc;
288 }
289
290 struct tpm2_get_random_out {
291         __be16 size;
292         u8 buffer[TPM_MAX_RNG_DATA];
293 } __packed;
294
295 /**
296  * tpm2_get_random() - get random bytes from the TPM RNG
297  *
298  * @chip:       a &tpm_chip instance
299  * @dest:       destination buffer
300  * @max:        the max number of random bytes to pull
301  *
302  * Return:
303  *   size of the buffer on success,
304  *   -errno otherwise
305  */
306 int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
307 {
308         struct tpm2_get_random_out *out;
309         struct tpm_buf buf;
310         u32 recd;
311         u32 num_bytes = max;
312         int err;
313         int total = 0;
314         int retries = 5;
315         u8 *dest_ptr = dest;
316
317         if (!num_bytes || max > TPM_MAX_RNG_DATA)
318                 return -EINVAL;
319
320         err = tpm_buf_init(&buf, 0, 0);
321         if (err)
322                 return err;
323
324         do {
325                 tpm_buf_reset(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_RANDOM);
326                 tpm_buf_append_u16(&buf, num_bytes);
327                 err = tpm_transmit_cmd(chip, &buf,
328                                        offsetof(struct tpm2_get_random_out,
329                                                 buffer),
330                                        "attempting get random");
331                 if (err)
332                         goto out;
333
334                 out = (struct tpm2_get_random_out *)
335                         &buf.data[TPM_HEADER_SIZE];
336                 recd = min_t(u32, be16_to_cpu(out->size), num_bytes);
337                 if (tpm_buf_length(&buf) <
338                     TPM_HEADER_SIZE +
339                     offsetof(struct tpm2_get_random_out, buffer) +
340                     recd) {
341                         err = -EFAULT;
342                         goto out;
343                 }
344                 memcpy(dest_ptr, out->buffer, recd);
345
346                 dest_ptr += recd;
347                 total += recd;
348                 num_bytes -= recd;
349         } while (retries-- && total < max);
350
351         tpm_buf_destroy(&buf);
352         return total ? total : -EIO;
353 out:
354         tpm_buf_destroy(&buf);
355         return err;
356 }
357
358 /**
359  * tpm2_flush_context() - execute a TPM2_FlushContext command
360  * @chip:       TPM chip to use
361  * @handle:     context handle
362  */
363 void tpm2_flush_context(struct tpm_chip *chip, u32 handle)
364 {
365         struct tpm_buf buf;
366         int rc;
367
368         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_FLUSH_CONTEXT);
369         if (rc) {
370                 dev_warn(&chip->dev, "0x%08x was not flushed, out of memory\n",
371                          handle);
372                 return;
373         }
374
375         tpm_buf_append_u32(&buf, handle);
376
377         tpm_transmit_cmd(chip, &buf, 0, "flushing context");
378         tpm_buf_destroy(&buf);
379 }
380
381 /**
382  * tpm_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer.
383  *
384  * @buf: an allocated tpm_buf instance
385  * @session_handle: session handle
386  * @nonce: the session nonce, may be NULL if not used
387  * @nonce_len: the session nonce length, may be 0 if not used
388  * @attributes: the session attributes
389  * @hmac: the session HMAC or password, may be NULL if not used
390  * @hmac_len: the session HMAC or password length, maybe 0 if not used
391  */
392 static void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle,
393                                  const u8 *nonce, u16 nonce_len,
394                                  u8 attributes,
395                                  const u8 *hmac, u16 hmac_len)
396 {
397         tpm_buf_append_u32(buf, 9 + nonce_len + hmac_len);
398         tpm_buf_append_u32(buf, session_handle);
399         tpm_buf_append_u16(buf, nonce_len);
400
401         if (nonce && nonce_len)
402                 tpm_buf_append(buf, nonce, nonce_len);
403
404         tpm_buf_append_u8(buf, attributes);
405         tpm_buf_append_u16(buf, hmac_len);
406
407         if (hmac && hmac_len)
408                 tpm_buf_append(buf, hmac, hmac_len);
409 }
410
411 /**
412  * tpm2_seal_trusted() - seal the payload of a trusted key
413  *
414  * @chip: TPM chip to use
415  * @payload: the key data in clear and encrypted form
416  * @options: authentication values and other options
417  *
418  * Return: < 0 on error and 0 on success.
419  */
420 int tpm2_seal_trusted(struct tpm_chip *chip,
421                       struct trusted_key_payload *payload,
422                       struct trusted_key_options *options)
423 {
424         unsigned int blob_len;
425         struct tpm_buf buf;
426         u32 hash;
427         int i;
428         int rc;
429
430         for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) {
431                 if (options->hash == tpm2_hash_map[i].crypto_id) {
432                         hash = tpm2_hash_map[i].tpm_id;
433                         break;
434                 }
435         }
436
437         if (i == ARRAY_SIZE(tpm2_hash_map))
438                 return -EINVAL;
439
440         rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
441         if (rc)
442                 return rc;
443
444         tpm_buf_append_u32(&buf, options->keyhandle);
445         tpm2_buf_append_auth(&buf, TPM2_RS_PW,
446                              NULL /* nonce */, 0,
447                              0 /* session_attributes */,
448                              options->keyauth /* hmac */,
449                              TPM_DIGEST_SIZE);
450
451         /* sensitive */
452         tpm_buf_append_u16(&buf, 4 + TPM_DIGEST_SIZE + payload->key_len + 1);
453
454         tpm_buf_append_u16(&buf, TPM_DIGEST_SIZE);
455         tpm_buf_append(&buf, options->blobauth, TPM_DIGEST_SIZE);
456         tpm_buf_append_u16(&buf, payload->key_len + 1);
457         tpm_buf_append(&buf, payload->key, payload->key_len);
458         tpm_buf_append_u8(&buf, payload->migratable);
459
460         /* public */
461         tpm_buf_append_u16(&buf, 14 + options->policydigest_len);
462         tpm_buf_append_u16(&buf, TPM_ALG_KEYEDHASH);
463         tpm_buf_append_u16(&buf, hash);
464
465         /* policy */
466         if (options->policydigest_len) {
467                 tpm_buf_append_u32(&buf, 0);
468                 tpm_buf_append_u16(&buf, options->policydigest_len);
469                 tpm_buf_append(&buf, options->policydigest,
470                                options->policydigest_len);
471         } else {
472                 tpm_buf_append_u32(&buf, TPM2_OA_USER_WITH_AUTH);
473                 tpm_buf_append_u16(&buf, 0);
474         }
475
476         /* public parameters */
477         tpm_buf_append_u16(&buf, TPM_ALG_NULL);
478         tpm_buf_append_u16(&buf, 0);
479
480         /* outside info */
481         tpm_buf_append_u16(&buf, 0);
482
483         /* creation PCR */
484         tpm_buf_append_u32(&buf, 0);
485
486         if (buf.flags & TPM_BUF_OVERFLOW) {
487                 rc = -E2BIG;
488                 goto out;
489         }
490
491         rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data");
492         if (rc)
493                 goto out;
494
495         blob_len = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]);
496         if (blob_len > MAX_BLOB_SIZE) {
497                 rc = -E2BIG;
498                 goto out;
499         }
500         if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 4 + blob_len) {
501                 rc = -EFAULT;
502                 goto out;
503         }
504
505         memcpy(payload->blob, &buf.data[TPM_HEADER_SIZE + 4], blob_len);
506         payload->blob_len = blob_len;
507
508 out:
509         tpm_buf_destroy(&buf);
510
511         if (rc > 0) {
512                 if (tpm2_rc_value(rc) == TPM2_RC_HASH)
513                         rc = -EINVAL;
514                 else
515                         rc = -EPERM;
516         }
517
518         return rc;
519 }
520
521 /**
522  * tpm2_load_cmd() - execute a TPM2_Load command
523  *
524  * @chip: TPM chip to use
525  * @payload: the key data in clear and encrypted form
526  * @options: authentication values and other options
527  * @blob_handle: returned blob handle
528  *
529  * Return: 0 on success.
530  *        -E2BIG on wrong payload size.
531  *        -EPERM on tpm error status.
532  *        < 0 error from tpm_transmit_cmd.
533  */
534 static int tpm2_load_cmd(struct tpm_chip *chip,
535                          struct trusted_key_payload *payload,
536                          struct trusted_key_options *options,
537                          u32 *blob_handle)
538 {
539         struct tpm_buf buf;
540         unsigned int private_len;
541         unsigned int public_len;
542         unsigned int blob_len;
543         int rc;
544
545         private_len = be16_to_cpup((__be16 *) &payload->blob[0]);
546         if (private_len > (payload->blob_len - 2))
547                 return -E2BIG;
548
549         public_len = be16_to_cpup((__be16 *) &payload->blob[2 + private_len]);
550         blob_len = private_len + public_len + 4;
551         if (blob_len > payload->blob_len)
552                 return -E2BIG;
553
554         rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
555         if (rc)
556                 return rc;
557
558         tpm_buf_append_u32(&buf, options->keyhandle);
559         tpm2_buf_append_auth(&buf, TPM2_RS_PW,
560                              NULL /* nonce */, 0,
561                              0 /* session_attributes */,
562                              options->keyauth /* hmac */,
563                              TPM_DIGEST_SIZE);
564
565         tpm_buf_append(&buf, payload->blob, blob_len);
566
567         if (buf.flags & TPM_BUF_OVERFLOW) {
568                 rc = -E2BIG;
569                 goto out;
570         }
571
572         rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob");
573         if (!rc)
574                 *blob_handle = be32_to_cpup(
575                         (__be32 *) &buf.data[TPM_HEADER_SIZE]);
576
577 out:
578         tpm_buf_destroy(&buf);
579
580         if (rc > 0)
581                 rc = -EPERM;
582
583         return rc;
584 }
585
586 /**
587  * tpm2_unseal_cmd() - execute a TPM2_Unload command
588  *
589  * @chip: TPM chip to use
590  * @payload: the key data in clear and encrypted form
591  * @options: authentication values and other options
592  * @blob_handle: blob handle
593  *
594  * Return: 0 on success
595  *         -EPERM on tpm error status
596  *         < 0 error from tpm_transmit_cmd
597  */
598 static int tpm2_unseal_cmd(struct tpm_chip *chip,
599                            struct trusted_key_payload *payload,
600                            struct trusted_key_options *options,
601                            u32 blob_handle)
602 {
603         struct tpm_buf buf;
604         u16 data_len;
605         u8 *data;
606         int rc;
607
608         rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
609         if (rc)
610                 return rc;
611
612         tpm_buf_append_u32(&buf, blob_handle);
613         tpm2_buf_append_auth(&buf,
614                              options->policyhandle ?
615                              options->policyhandle : TPM2_RS_PW,
616                              NULL /* nonce */, 0,
617                              TPM2_SA_CONTINUE_SESSION,
618                              options->blobauth /* hmac */,
619                              TPM_DIGEST_SIZE);
620
621         rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing");
622         if (rc > 0)
623                 rc = -EPERM;
624
625         if (!rc) {
626                 data_len = be16_to_cpup(
627                         (__be16 *) &buf.data[TPM_HEADER_SIZE + 4]);
628                 if (data_len < MIN_KEY_SIZE ||  data_len > MAX_KEY_SIZE + 1) {
629                         rc = -EFAULT;
630                         goto out;
631                 }
632
633                 if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 6 + data_len) {
634                         rc = -EFAULT;
635                         goto out;
636                 }
637                 data = &buf.data[TPM_HEADER_SIZE + 6];
638
639                 memcpy(payload->key, data, data_len - 1);
640                 payload->key_len = data_len - 1;
641                 payload->migratable = data[data_len - 1];
642         }
643
644 out:
645         tpm_buf_destroy(&buf);
646         return rc;
647 }
648
649 /**
650  * tpm2_unseal_trusted() - unseal the payload of a trusted key
651  *
652  * @chip: TPM chip to use
653  * @payload: the key data in clear and encrypted form
654  * @options: authentication values and other options
655  *
656  * Return: Same as with tpm_transmit_cmd.
657  */
658 int tpm2_unseal_trusted(struct tpm_chip *chip,
659                         struct trusted_key_payload *payload,
660                         struct trusted_key_options *options)
661 {
662         u32 blob_handle;
663         int rc;
664
665         rc = tpm2_load_cmd(chip, payload, options, &blob_handle);
666         if (rc)
667                 return rc;
668
669         rc = tpm2_unseal_cmd(chip, payload, options, blob_handle);
670         tpm2_flush_context(chip, blob_handle);
671         return rc;
672 }
673
674 struct tpm2_get_cap_out {
675         u8 more_data;
676         __be32 subcap_id;
677         __be32 property_cnt;
678         __be32 property_id;
679         __be32 value;
680 } __packed;
681
682 /**
683  * tpm2_get_tpm_pt() - get value of a TPM_CAP_TPM_PROPERTIES type property
684  * @chip:               a &tpm_chip instance
685  * @property_id:        property ID.
686  * @value:              output variable.
687  * @desc:               passed to tpm_transmit_cmd()
688  *
689  * Return:
690  *   0 on success,
691  *   -errno or a TPM return code otherwise
692  */
693 ssize_t tpm2_get_tpm_pt(struct tpm_chip *chip, u32 property_id,  u32 *value,
694                         const char *desc)
695 {
696         struct tpm2_get_cap_out *out;
697         struct tpm_buf buf;
698         int rc;
699
700         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
701         if (rc)
702                 return rc;
703         tpm_buf_append_u32(&buf, TPM2_CAP_TPM_PROPERTIES);
704         tpm_buf_append_u32(&buf, property_id);
705         tpm_buf_append_u32(&buf, 1);
706         rc = tpm_transmit_cmd(chip, &buf, 0, NULL);
707         if (!rc) {
708                 out = (struct tpm2_get_cap_out *)
709                         &buf.data[TPM_HEADER_SIZE];
710                 *value = be32_to_cpu(out->value);
711         }
712         tpm_buf_destroy(&buf);
713         return rc;
714 }
715 EXPORT_SYMBOL_GPL(tpm2_get_tpm_pt);
716
717 /**
718  * tpm2_shutdown() - send a TPM shutdown command
719  *
720  * Sends a TPM shutdown command. The shutdown command is used in call
721  * sites where the system is going down. If it fails, there is not much
722  * that can be done except print an error message.
723  *
724  * @chip:               a &tpm_chip instance
725  * @shutdown_type:      TPM_SU_CLEAR or TPM_SU_STATE.
726  */
727 void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
728 {
729         struct tpm_buf buf;
730         int rc;
731
732         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SHUTDOWN);
733         if (rc)
734                 return;
735         tpm_buf_append_u16(&buf, shutdown_type);
736         tpm_transmit_cmd(chip, &buf, 0, "stopping the TPM");
737         tpm_buf_destroy(&buf);
738 }
739
740 /**
741  * tpm2_do_selftest() - ensure that all self tests have passed
742  *
743  * @chip: TPM chip to use
744  *
745  * Return: Same as with tpm_transmit_cmd.
746  *
747  * The TPM can either run all self tests synchronously and then return
748  * RC_SUCCESS once all tests were successful. Or it can choose to run the tests
749  * asynchronously and return RC_TESTING immediately while the self tests still
750  * execute in the background. This function handles both cases and waits until
751  * all tests have completed.
752  */
753 static int tpm2_do_selftest(struct tpm_chip *chip)
754 {
755         struct tpm_buf buf;
756         int full;
757         int rc;
758
759         for (full = 0; full < 2; full++) {
760                 rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
761                 if (rc)
762                         return rc;
763
764                 tpm_buf_append_u8(&buf, full);
765                 rc = tpm_transmit_cmd(chip, &buf, 0,
766                                       "attempting the self test");
767                 tpm_buf_destroy(&buf);
768
769                 if (rc == TPM2_RC_TESTING)
770                         rc = TPM2_RC_SUCCESS;
771                 if (rc == TPM2_RC_INITIALIZE || rc == TPM2_RC_SUCCESS)
772                         return rc;
773         }
774
775         return rc;
776 }
777
778 /**
779  * tpm2_probe() - probe for the TPM 2.0 protocol
780  * @chip:       a &tpm_chip instance
781  *
782  * Send an idempotent TPM 2.0 command and see whether there is TPM2 chip in the
783  * other end based on the response tag. The flag TPM_CHIP_FLAG_TPM2 is set by
784  * this function if this is the case.
785  *
786  * Return:
787  *   0 on success,
788  *   -errno otherwise
789  */
790 int tpm2_probe(struct tpm_chip *chip)
791 {
792         struct tpm_header *out;
793         struct tpm_buf buf;
794         int rc;
795
796         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
797         if (rc)
798                 return rc;
799         tpm_buf_append_u32(&buf, TPM2_CAP_TPM_PROPERTIES);
800         tpm_buf_append_u32(&buf, TPM_PT_TOTAL_COMMANDS);
801         tpm_buf_append_u32(&buf, 1);
802         rc = tpm_transmit_cmd(chip, &buf, 0, NULL);
803         /* We ignore TPM return codes on purpose. */
804         if (rc >=  0) {
805                 out = (struct tpm_header *)buf.data;
806                 if (be16_to_cpu(out->tag) == TPM2_ST_NO_SESSIONS)
807                         chip->flags |= TPM_CHIP_FLAG_TPM2;
808         }
809         tpm_buf_destroy(&buf);
810         return 0;
811 }
812 EXPORT_SYMBOL_GPL(tpm2_probe);
813
814 static int tpm2_init_bank_info(struct tpm_chip *chip, u32 bank_index)
815 {
816         struct tpm_bank_info *bank = chip->allocated_banks + bank_index;
817         struct tpm_digest digest = { .alg_id = bank->alg_id };
818         int i;
819
820         /*
821          * Avoid unnecessary PCR read operations to reduce overhead
822          * and obtain identifiers of the crypto subsystem.
823          */
824         for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) {
825                 enum hash_algo crypto_algo = tpm2_hash_map[i].crypto_id;
826
827                 if (bank->alg_id != tpm2_hash_map[i].tpm_id)
828                         continue;
829
830                 bank->digest_size = hash_digest_size[crypto_algo];
831                 bank->crypto_id = crypto_algo;
832                 return 0;
833         }
834
835         return tpm2_pcr_read(chip, 0, &digest, &bank->digest_size);
836 }
837
838 struct tpm2_pcr_selection {
839         __be16  hash_alg;
840         u8  size_of_select;
841         u8  pcr_select[3];
842 } __packed;
843
844 static ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
845 {
846         struct tpm2_pcr_selection pcr_selection;
847         struct tpm_buf buf;
848         void *marker;
849         void *end;
850         void *pcr_select_offset;
851         u32 sizeof_pcr_selection;
852         u32 nr_possible_banks;
853         u32 nr_alloc_banks = 0;
854         u16 hash_alg;
855         u32 rsp_len;
856         int rc;
857         int i = 0;
858
859         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
860         if (rc)
861                 return rc;
862
863         tpm_buf_append_u32(&buf, TPM2_CAP_PCRS);
864         tpm_buf_append_u32(&buf, 0);
865         tpm_buf_append_u32(&buf, 1);
866
867         rc = tpm_transmit_cmd(chip, &buf, 9, "get tpm pcr allocation");
868         if (rc)
869                 goto out;
870
871         nr_possible_banks = be32_to_cpup(
872                 (__be32 *)&buf.data[TPM_HEADER_SIZE + 5]);
873
874         chip->allocated_banks = kcalloc(nr_possible_banks,
875                                         sizeof(*chip->allocated_banks),
876                                         GFP_KERNEL);
877         if (!chip->allocated_banks) {
878                 rc = -ENOMEM;
879                 goto out;
880         }
881
882         marker = &buf.data[TPM_HEADER_SIZE + 9];
883
884         rsp_len = be32_to_cpup((__be32 *)&buf.data[2]);
885         end = &buf.data[rsp_len];
886
887         for (i = 0; i < nr_possible_banks; i++) {
888                 pcr_select_offset = marker +
889                         offsetof(struct tpm2_pcr_selection, size_of_select);
890                 if (pcr_select_offset >= end) {
891                         rc = -EFAULT;
892                         break;
893                 }
894
895                 memcpy(&pcr_selection, marker, sizeof(pcr_selection));
896                 hash_alg = be16_to_cpu(pcr_selection.hash_alg);
897
898                 pcr_select_offset = memchr_inv(pcr_selection.pcr_select, 0,
899                                                pcr_selection.size_of_select);
900                 if (pcr_select_offset) {
901                         chip->allocated_banks[nr_alloc_banks].alg_id = hash_alg;
902
903                         rc = tpm2_init_bank_info(chip, nr_alloc_banks);
904                         if (rc < 0)
905                                 break;
906
907                         nr_alloc_banks++;
908                 }
909
910                 sizeof_pcr_selection = sizeof(pcr_selection.hash_alg) +
911                         sizeof(pcr_selection.size_of_select) +
912                         pcr_selection.size_of_select;
913                 marker = marker + sizeof_pcr_selection;
914         }
915
916         chip->nr_allocated_banks = nr_alloc_banks;
917 out:
918         tpm_buf_destroy(&buf);
919
920         return rc;
921 }
922
923 static int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip)
924 {
925         struct tpm_buf buf;
926         u32 nr_commands;
927         __be32 *attrs;
928         u32 cc;
929         int i;
930         int rc;
931
932         rc = tpm2_get_tpm_pt(chip, TPM_PT_TOTAL_COMMANDS, &nr_commands, NULL);
933         if (rc)
934                 goto out;
935
936         if (nr_commands > 0xFFFFF) {
937                 rc = -EFAULT;
938                 goto out;
939         }
940
941         chip->cc_attrs_tbl = devm_kcalloc(&chip->dev, 4, nr_commands,
942                                           GFP_KERNEL);
943
944         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
945         if (rc)
946                 goto out;
947
948         tpm_buf_append_u32(&buf, TPM2_CAP_COMMANDS);
949         tpm_buf_append_u32(&buf, TPM2_CC_FIRST);
950         tpm_buf_append_u32(&buf, nr_commands);
951
952         rc = tpm_transmit_cmd(chip, &buf, 9 + 4 * nr_commands, NULL);
953         if (rc) {
954                 tpm_buf_destroy(&buf);
955                 goto out;
956         }
957
958         if (nr_commands !=
959             be32_to_cpup((__be32 *)&buf.data[TPM_HEADER_SIZE + 5])) {
960                 tpm_buf_destroy(&buf);
961                 goto out;
962         }
963
964         chip->nr_commands = nr_commands;
965
966         attrs = (__be32 *)&buf.data[TPM_HEADER_SIZE + 9];
967         for (i = 0; i < nr_commands; i++, attrs++) {
968                 chip->cc_attrs_tbl[i] = be32_to_cpup(attrs);
969                 cc = chip->cc_attrs_tbl[i] & 0xFFFF;
970
971                 if (cc == TPM2_CC_CONTEXT_SAVE || cc == TPM2_CC_FLUSH_CONTEXT) {
972                         chip->cc_attrs_tbl[i] &=
973                                 ~(GENMASK(2, 0) << TPM2_CC_ATTR_CHANDLES);
974                         chip->cc_attrs_tbl[i] |= 1 << TPM2_CC_ATTR_CHANDLES;
975                 }
976         }
977
978         tpm_buf_destroy(&buf);
979
980 out:
981         if (rc > 0)
982                 rc = -ENODEV;
983         return rc;
984 }
985
986 /**
987  * tpm2_startup - turn on the TPM
988  * @chip: TPM chip to use
989  *
990  * Normally the firmware should start the TPM. This function is provided as a
991  * workaround if this does not happen. A legal case for this could be for
992  * example when a TPM emulator is used.
993  *
994  * Return: same as tpm_transmit_cmd()
995  */
996
997 static int tpm2_startup(struct tpm_chip *chip)
998 {
999         struct tpm_buf buf;
1000         int rc;
1001
1002         dev_info(&chip->dev, "starting up the TPM manually\n");
1003
1004         rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_STARTUP);
1005         if (rc < 0)
1006                 return rc;
1007
1008         tpm_buf_append_u16(&buf, TPM2_SU_CLEAR);
1009         rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to start the TPM");
1010         tpm_buf_destroy(&buf);
1011
1012         return rc;
1013 }
1014
1015 /**
1016  * tpm2_auto_startup - Perform the standard automatic TPM initialization
1017  *                     sequence
1018  * @chip: TPM chip to use
1019  *
1020  * Returns 0 on success, < 0 in case of fatal error.
1021  */
1022 int tpm2_auto_startup(struct tpm_chip *chip)
1023 {
1024         int rc;
1025
1026         rc = tpm2_get_timeouts(chip);
1027         if (rc)
1028                 goto out;
1029
1030         rc = tpm2_do_selftest(chip);
1031         if (rc && rc != TPM2_RC_INITIALIZE)
1032                 goto out;
1033
1034         if (rc == TPM2_RC_INITIALIZE) {
1035                 rc = tpm2_startup(chip);
1036                 if (rc)
1037                         goto out;
1038
1039                 rc = tpm2_do_selftest(chip);
1040                 if (rc)
1041                         goto out;
1042         }
1043
1044         rc = tpm2_get_pcr_allocation(chip);
1045         if (rc)
1046                 goto out;
1047
1048         rc = tpm2_get_cc_attrs_tbl(chip);
1049
1050 out:
1051         if (rc > 0)
1052                 rc = -ENODEV;
1053         return rc;
1054 }
1055
1056 int tpm2_find_cc(struct tpm_chip *chip, u32 cc)
1057 {
1058         int i;
1059
1060         for (i = 0; i < chip->nr_commands; i++)
1061                 if (cc == (chip->cc_attrs_tbl[i] & GENMASK(15, 0)))
1062                         return i;
1063
1064         return -1;
1065 }