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