xref: /openbmc/linux/drivers/char/tpm/tpm2-cmd.c (revision 69fad28c)
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, TPM2_ALG_SHA1},
37 	{HASH_ALGO_SHA256, TPM2_ALG_SHA256},
38 	{HASH_ALGO_SHA384, TPM2_ALG_SHA384},
39 	{HASH_ALGO_SHA512, TPM2_ALG_SHA512},
40 	{HASH_ALGO_SM3_256, TPM2_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  * @res_buf:	buffer to store the resulting hash.
175  *
176  * Return: Same as with tpm_transmit_cmd.
177  */
178 int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx, u8 *res_buf)
179 {
180 	int rc;
181 	struct tpm_buf buf;
182 	struct tpm2_pcr_read_out *out;
183 	u8 pcr_select[TPM2_PCR_SELECT_MIN] = {0};
184 
185 	if (pcr_idx >= TPM2_PLATFORM_PCR)
186 		return -EINVAL;
187 
188 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_PCR_READ);
189 	if (rc)
190 		return rc;
191 
192 	pcr_select[pcr_idx >> 3] = 1 << (pcr_idx & 0x7);
193 
194 	tpm_buf_append_u32(&buf, 1);
195 	tpm_buf_append_u16(&buf, TPM2_ALG_SHA1);
196 	tpm_buf_append_u8(&buf, TPM2_PCR_SELECT_MIN);
197 	tpm_buf_append(&buf, (const unsigned char *)pcr_select,
198 		       sizeof(pcr_select));
199 
200 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 0, 0,
201 			res_buf ? "attempting to read a pcr value" : NULL);
202 	if (rc == 0 && res_buf) {
203 		out = (struct tpm2_pcr_read_out *)&buf.data[TPM_HEADER_SIZE];
204 		memcpy(res_buf, out->digest, SHA1_DIGEST_SIZE);
205 	}
206 
207 	tpm_buf_destroy(&buf);
208 	return rc;
209 }
210 
211 struct tpm2_null_auth_area {
212 	__be32  handle;
213 	__be16  nonce_size;
214 	u8  attributes;
215 	__be16  auth_size;
216 } __packed;
217 
218 /**
219  * tpm2_pcr_extend() - extend a PCR value
220  *
221  * @chip:	TPM chip to use.
222  * @pcr_idx:	index of the PCR.
223  * @count:	number of digests passed.
224  * @digests:	list of pcr banks and corresponding digest values to extend.
225  *
226  * Return: Same as with tpm_transmit_cmd.
227  */
228 int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx, u32 count,
229 		    struct tpm2_digest *digests)
230 {
231 	struct tpm_buf buf;
232 	struct tpm2_null_auth_area auth_area;
233 	int rc;
234 	int i;
235 	int j;
236 
237 	if (count > ARRAY_SIZE(chip->active_banks))
238 		return -EINVAL;
239 
240 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
241 	if (rc)
242 		return rc;
243 
244 	tpm_buf_append_u32(&buf, pcr_idx);
245 
246 	auth_area.handle = cpu_to_be32(TPM2_RS_PW);
247 	auth_area.nonce_size = 0;
248 	auth_area.attributes = 0;
249 	auth_area.auth_size = 0;
250 
251 	tpm_buf_append_u32(&buf, sizeof(struct tpm2_null_auth_area));
252 	tpm_buf_append(&buf, (const unsigned char *)&auth_area,
253 		       sizeof(auth_area));
254 	tpm_buf_append_u32(&buf, count);
255 
256 	for (i = 0; i < count; i++) {
257 		for (j = 0; j < ARRAY_SIZE(tpm2_hash_map); j++) {
258 			if (digests[i].alg_id != tpm2_hash_map[j].tpm_id)
259 				continue;
260 			tpm_buf_append_u16(&buf, digests[i].alg_id);
261 			tpm_buf_append(&buf, (const unsigned char
262 					      *)&digests[i].digest,
263 			       hash_digest_size[tpm2_hash_map[j].crypto_id]);
264 		}
265 	}
266 
267 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 0, 0,
268 			      "attempting extend a PCR value");
269 
270 	tpm_buf_destroy(&buf);
271 
272 	return rc;
273 }
274 
275 struct tpm2_get_random_out {
276 	__be16 size;
277 	u8 buffer[TPM_MAX_RNG_DATA];
278 } __packed;
279 
280 /**
281  * tpm2_get_random() - get random bytes from the TPM RNG
282  *
283  * @chip:	a &tpm_chip instance
284  * @dest:	destination buffer
285  * @max:	the max number of random bytes to pull
286  *
287  * Return:
288  *   size of the buffer on success,
289  *   -errno otherwise
290  */
291 int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
292 {
293 	struct tpm2_get_random_out *out;
294 	struct tpm_buf buf;
295 	u32 recd;
296 	u32 num_bytes = max;
297 	int err;
298 	int total = 0;
299 	int retries = 5;
300 	u8 *dest_ptr = dest;
301 
302 	if (!num_bytes || max > TPM_MAX_RNG_DATA)
303 		return -EINVAL;
304 
305 	err = tpm_buf_init(&buf, 0, 0);
306 	if (err)
307 		return err;
308 
309 	do {
310 		tpm_buf_reset(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_RANDOM);
311 		tpm_buf_append_u16(&buf, num_bytes);
312 		err = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE,
313 				       offsetof(struct tpm2_get_random_out,
314 						buffer),
315 				       0, "attempting get random");
316 		if (err)
317 			goto out;
318 
319 		out = (struct tpm2_get_random_out *)
320 			&buf.data[TPM_HEADER_SIZE];
321 		recd = min_t(u32, be16_to_cpu(out->size), num_bytes);
322 		if (tpm_buf_length(&buf) <
323 		    TPM_HEADER_SIZE +
324 		    offsetof(struct tpm2_get_random_out, buffer) +
325 		    recd) {
326 			err = -EFAULT;
327 			goto out;
328 		}
329 		memcpy(dest_ptr, out->buffer, recd);
330 
331 		dest_ptr += recd;
332 		total += recd;
333 		num_bytes -= recd;
334 	} while (retries-- && total < max);
335 
336 	tpm_buf_destroy(&buf);
337 	return total ? total : -EIO;
338 out:
339 	tpm_buf_destroy(&buf);
340 	return err;
341 }
342 
343 /**
344  * tpm2_flush_context_cmd() - execute a TPM2_FlushContext command
345  * @chip:	TPM chip to use
346  * @handle:	context handle
347  * @flags:	tpm transmit flags - bitmap
348  *
349  */
350 void tpm2_flush_context_cmd(struct tpm_chip *chip, u32 handle,
351 			    unsigned int flags)
352 {
353 	struct tpm_buf buf;
354 	int rc;
355 
356 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_FLUSH_CONTEXT);
357 	if (rc) {
358 		dev_warn(&chip->dev, "0x%08x was not flushed, out of memory\n",
359 			 handle);
360 		return;
361 	}
362 
363 	tpm_buf_append_u32(&buf, handle);
364 
365 	(void) tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 0, flags,
366 				"flushing context");
367 
368 	tpm_buf_destroy(&buf);
369 }
370 
371 /**
372  * tpm_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer.
373  *
374  * @buf: an allocated tpm_buf instance
375  * @session_handle: session handle
376  * @nonce: the session nonce, may be NULL if not used
377  * @nonce_len: the session nonce length, may be 0 if not used
378  * @attributes: the session attributes
379  * @hmac: the session HMAC or password, may be NULL if not used
380  * @hmac_len: the session HMAC or password length, maybe 0 if not used
381  */
382 static void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle,
383 				 const u8 *nonce, u16 nonce_len,
384 				 u8 attributes,
385 				 const u8 *hmac, u16 hmac_len)
386 {
387 	tpm_buf_append_u32(buf, 9 + nonce_len + hmac_len);
388 	tpm_buf_append_u32(buf, session_handle);
389 	tpm_buf_append_u16(buf, nonce_len);
390 
391 	if (nonce && nonce_len)
392 		tpm_buf_append(buf, nonce, nonce_len);
393 
394 	tpm_buf_append_u8(buf, attributes);
395 	tpm_buf_append_u16(buf, hmac_len);
396 
397 	if (hmac && hmac_len)
398 		tpm_buf_append(buf, hmac, hmac_len);
399 }
400 
401 /**
402  * tpm2_seal_trusted() - seal the payload of a trusted key
403  *
404  * @chip: TPM chip to use
405  * @payload: the key data in clear and encrypted form
406  * @options: authentication values and other options
407  *
408  * Return: < 0 on error and 0 on success.
409  */
410 int tpm2_seal_trusted(struct tpm_chip *chip,
411 		      struct trusted_key_payload *payload,
412 		      struct trusted_key_options *options)
413 {
414 	unsigned int blob_len;
415 	struct tpm_buf buf;
416 	u32 hash;
417 	int i;
418 	int rc;
419 
420 	for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) {
421 		if (options->hash == tpm2_hash_map[i].crypto_id) {
422 			hash = tpm2_hash_map[i].tpm_id;
423 			break;
424 		}
425 	}
426 
427 	if (i == ARRAY_SIZE(tpm2_hash_map))
428 		return -EINVAL;
429 
430 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
431 	if (rc)
432 		return rc;
433 
434 	tpm_buf_append_u32(&buf, options->keyhandle);
435 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
436 			     NULL /* nonce */, 0,
437 			     0 /* session_attributes */,
438 			     options->keyauth /* hmac */,
439 			     TPM_DIGEST_SIZE);
440 
441 	/* sensitive */
442 	tpm_buf_append_u16(&buf, 4 + TPM_DIGEST_SIZE + payload->key_len + 1);
443 
444 	tpm_buf_append_u16(&buf, TPM_DIGEST_SIZE);
445 	tpm_buf_append(&buf, options->blobauth, TPM_DIGEST_SIZE);
446 	tpm_buf_append_u16(&buf, payload->key_len + 1);
447 	tpm_buf_append(&buf, payload->key, payload->key_len);
448 	tpm_buf_append_u8(&buf, payload->migratable);
449 
450 	/* public */
451 	tpm_buf_append_u16(&buf, 14 + options->policydigest_len);
452 	tpm_buf_append_u16(&buf, TPM2_ALG_KEYEDHASH);
453 	tpm_buf_append_u16(&buf, hash);
454 
455 	/* policy */
456 	if (options->policydigest_len) {
457 		tpm_buf_append_u32(&buf, 0);
458 		tpm_buf_append_u16(&buf, options->policydigest_len);
459 		tpm_buf_append(&buf, options->policydigest,
460 			       options->policydigest_len);
461 	} else {
462 		tpm_buf_append_u32(&buf, TPM2_OA_USER_WITH_AUTH);
463 		tpm_buf_append_u16(&buf, 0);
464 	}
465 
466 	/* public parameters */
467 	tpm_buf_append_u16(&buf, TPM2_ALG_NULL);
468 	tpm_buf_append_u16(&buf, 0);
469 
470 	/* outside info */
471 	tpm_buf_append_u16(&buf, 0);
472 
473 	/* creation PCR */
474 	tpm_buf_append_u32(&buf, 0);
475 
476 	if (buf.flags & TPM_BUF_OVERFLOW) {
477 		rc = -E2BIG;
478 		goto out;
479 	}
480 
481 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 4, 0,
482 			      "sealing data");
483 	if (rc)
484 		goto out;
485 
486 	blob_len = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]);
487 	if (blob_len > MAX_BLOB_SIZE) {
488 		rc = -E2BIG;
489 		goto out;
490 	}
491 	if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 4 + blob_len) {
492 		rc = -EFAULT;
493 		goto out;
494 	}
495 
496 	memcpy(payload->blob, &buf.data[TPM_HEADER_SIZE + 4], blob_len);
497 	payload->blob_len = blob_len;
498 
499 out:
500 	tpm_buf_destroy(&buf);
501 
502 	if (rc > 0) {
503 		if (tpm2_rc_value(rc) == TPM2_RC_HASH)
504 			rc = -EINVAL;
505 		else
506 			rc = -EPERM;
507 	}
508 
509 	return rc;
510 }
511 
512 /**
513  * tpm2_load_cmd() - execute a TPM2_Load command
514  *
515  * @chip: TPM chip to use
516  * @payload: the key data in clear and encrypted form
517  * @options: authentication values and other options
518  * @blob_handle: returned blob handle
519  * @flags: tpm transmit flags
520  *
521  * Return: 0 on success.
522  *        -E2BIG on wrong payload size.
523  *        -EPERM on tpm error status.
524  *        < 0 error from tpm_transmit_cmd.
525  */
526 static int tpm2_load_cmd(struct tpm_chip *chip,
527 			 struct trusted_key_payload *payload,
528 			 struct trusted_key_options *options,
529 			 u32 *blob_handle, unsigned int flags)
530 {
531 	struct tpm_buf buf;
532 	unsigned int private_len;
533 	unsigned int public_len;
534 	unsigned int blob_len;
535 	int rc;
536 
537 	private_len = be16_to_cpup((__be16 *) &payload->blob[0]);
538 	if (private_len > (payload->blob_len - 2))
539 		return -E2BIG;
540 
541 	public_len = be16_to_cpup((__be16 *) &payload->blob[2 + private_len]);
542 	blob_len = private_len + public_len + 4;
543 	if (blob_len > payload->blob_len)
544 		return -E2BIG;
545 
546 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
547 	if (rc)
548 		return rc;
549 
550 	tpm_buf_append_u32(&buf, options->keyhandle);
551 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
552 			     NULL /* nonce */, 0,
553 			     0 /* session_attributes */,
554 			     options->keyauth /* hmac */,
555 			     TPM_DIGEST_SIZE);
556 
557 	tpm_buf_append(&buf, payload->blob, blob_len);
558 
559 	if (buf.flags & TPM_BUF_OVERFLOW) {
560 		rc = -E2BIG;
561 		goto out;
562 	}
563 
564 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 4, flags,
565 			      "loading blob");
566 	if (!rc)
567 		*blob_handle = be32_to_cpup(
568 			(__be32 *) &buf.data[TPM_HEADER_SIZE]);
569 
570 out:
571 	tpm_buf_destroy(&buf);
572 
573 	if (rc > 0)
574 		rc = -EPERM;
575 
576 	return rc;
577 }
578 
579 /**
580  * tpm2_unseal_cmd() - execute a TPM2_Unload command
581  *
582  * @chip: TPM chip to use
583  * @payload: the key data in clear and encrypted form
584  * @options: authentication values and other options
585  * @blob_handle: blob handle
586  * @flags: tpm_transmit_cmd flags
587  *
588  * Return: 0 on success
589  *         -EPERM on tpm error status
590  *         < 0 error from tpm_transmit_cmd
591  */
592 static int tpm2_unseal_cmd(struct tpm_chip *chip,
593 			   struct trusted_key_payload *payload,
594 			   struct trusted_key_options *options,
595 			   u32 blob_handle, unsigned int flags)
596 {
597 	struct tpm_buf buf;
598 	u16 data_len;
599 	u8 *data;
600 	int rc;
601 
602 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
603 	if (rc)
604 		return rc;
605 
606 	tpm_buf_append_u32(&buf, blob_handle);
607 	tpm2_buf_append_auth(&buf,
608 			     options->policyhandle ?
609 			     options->policyhandle : TPM2_RS_PW,
610 			     NULL /* nonce */, 0,
611 			     TPM2_SA_CONTINUE_SESSION,
612 			     options->blobauth /* hmac */,
613 			     TPM_DIGEST_SIZE);
614 
615 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 6, flags,
616 			      "unsealing");
617 	if (rc > 0)
618 		rc = -EPERM;
619 
620 	if (!rc) {
621 		data_len = be16_to_cpup(
622 			(__be16 *) &buf.data[TPM_HEADER_SIZE + 4]);
623 		if (data_len < MIN_KEY_SIZE ||  data_len > MAX_KEY_SIZE + 1) {
624 			rc = -EFAULT;
625 			goto out;
626 		}
627 
628 		if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 6 + data_len) {
629 			rc = -EFAULT;
630 			goto out;
631 		}
632 		data = &buf.data[TPM_HEADER_SIZE + 6];
633 
634 		memcpy(payload->key, data, data_len - 1);
635 		payload->key_len = data_len - 1;
636 		payload->migratable = data[data_len - 1];
637 	}
638 
639 out:
640 	tpm_buf_destroy(&buf);
641 	return rc;
642 }
643 
644 /**
645  * tpm2_unseal_trusted() - unseal the payload of a trusted key
646  *
647  * @chip: TPM chip to use
648  * @payload: the key data in clear and encrypted form
649  * @options: authentication values and other options
650  *
651  * Return: Same as with tpm_transmit_cmd.
652  */
653 int tpm2_unseal_trusted(struct tpm_chip *chip,
654 			struct trusted_key_payload *payload,
655 			struct trusted_key_options *options)
656 {
657 	u32 blob_handle;
658 	int rc;
659 
660 	mutex_lock(&chip->tpm_mutex);
661 	rc = tpm2_load_cmd(chip, payload, options, &blob_handle,
662 			   TPM_TRANSMIT_UNLOCKED);
663 	if (rc)
664 		goto out;
665 
666 	rc = tpm2_unseal_cmd(chip, payload, options, blob_handle,
667 			     TPM_TRANSMIT_UNLOCKED);
668 	tpm2_flush_context_cmd(chip, blob_handle, TPM_TRANSMIT_UNLOCKED);
669 out:
670 	mutex_unlock(&chip->tpm_mutex);
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, NULL, buf.data, PAGE_SIZE, 0, 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, NULL, buf.data, PAGE_SIZE, 0, 0,
737 			 "stopping the TPM");
738 	tpm_buf_destroy(&buf);
739 }
740 
741 /**
742  * tpm2_do_selftest() - ensure that all self tests have passed
743  *
744  * @chip: TPM chip to use
745  *
746  * Return: Same as with tpm_transmit_cmd.
747  *
748  * The TPM can either run all self tests synchronously and then return
749  * RC_SUCCESS once all tests were successful. Or it can choose to run the tests
750  * asynchronously and return RC_TESTING immediately while the self tests still
751  * execute in the background. This function handles both cases and waits until
752  * all tests have completed.
753  */
754 static int tpm2_do_selftest(struct tpm_chip *chip)
755 {
756 	struct tpm_buf buf;
757 	int full;
758 	int rc;
759 
760 	for (full = 0; full < 2; full++) {
761 		rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
762 		if (rc)
763 			return rc;
764 
765 		tpm_buf_append_u8(&buf, full);
766 		rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 0, 0,
767 				      "attempting the self test");
768 		tpm_buf_destroy(&buf);
769 
770 		if (rc == TPM2_RC_TESTING)
771 			rc = TPM2_RC_SUCCESS;
772 		if (rc == TPM2_RC_INITIALIZE || rc == TPM2_RC_SUCCESS)
773 			return rc;
774 	}
775 
776 	return rc;
777 }
778 
779 /**
780  * tpm2_probe() - probe for the TPM 2.0 protocol
781  * @chip:	a &tpm_chip instance
782  *
783  * Send an idempotent TPM 2.0 command and see whether there is TPM2 chip in the
784  * other end based on the response tag. The flag TPM_CHIP_FLAG_TPM2 is set by
785  * this function if this is the case.
786  *
787  * Return:
788  *   0 on success,
789  *   -errno otherwise
790  */
791 int tpm2_probe(struct tpm_chip *chip)
792 {
793 	struct tpm_output_header *out;
794 	struct tpm_buf buf;
795 	int rc;
796 
797 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
798 	if (rc)
799 		return rc;
800 	tpm_buf_append_u32(&buf, TPM2_CAP_TPM_PROPERTIES);
801 	tpm_buf_append_u32(&buf, TPM_PT_TOTAL_COMMANDS);
802 	tpm_buf_append_u32(&buf, 1);
803 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 0, 0, NULL);
804 	/* We ignore TPM return codes on purpose. */
805 	if (rc >=  0) {
806 		out = (struct tpm_output_header *)buf.data;
807 		if (be16_to_cpu(out->tag) == TPM2_ST_NO_SESSIONS)
808 			chip->flags |= TPM_CHIP_FLAG_TPM2;
809 	}
810 	tpm_buf_destroy(&buf);
811 	return 0;
812 }
813 EXPORT_SYMBOL_GPL(tpm2_probe);
814 
815 struct tpm2_pcr_selection {
816 	__be16  hash_alg;
817 	u8  size_of_select;
818 	u8  pcr_select[3];
819 } __packed;
820 
821 static ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
822 {
823 	struct tpm2_pcr_selection pcr_selection;
824 	struct tpm_buf buf;
825 	void *marker;
826 	void *end;
827 	void *pcr_select_offset;
828 	unsigned int count;
829 	u32 sizeof_pcr_selection;
830 	u32 rsp_len;
831 	int rc;
832 	int i = 0;
833 
834 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
835 	if (rc)
836 		return rc;
837 
838 	tpm_buf_append_u32(&buf, TPM2_CAP_PCRS);
839 	tpm_buf_append_u32(&buf, 0);
840 	tpm_buf_append_u32(&buf, 1);
841 
842 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 9, 0,
843 			      "get tpm pcr allocation");
844 	if (rc)
845 		goto out;
846 
847 	count = be32_to_cpup(
848 		(__be32 *)&buf.data[TPM_HEADER_SIZE + 5]);
849 
850 	if (count > ARRAY_SIZE(chip->active_banks)) {
851 		rc = -ENODEV;
852 		goto out;
853 	}
854 
855 	marker = &buf.data[TPM_HEADER_SIZE + 9];
856 
857 	rsp_len = be32_to_cpup((__be32 *)&buf.data[2]);
858 	end = &buf.data[rsp_len];
859 
860 	for (i = 0; i < count; i++) {
861 		pcr_select_offset = marker +
862 			offsetof(struct tpm2_pcr_selection, size_of_select);
863 		if (pcr_select_offset >= end) {
864 			rc = -EFAULT;
865 			break;
866 		}
867 
868 		memcpy(&pcr_selection, marker, sizeof(pcr_selection));
869 		chip->active_banks[i] = be16_to_cpu(pcr_selection.hash_alg);
870 		sizeof_pcr_selection = sizeof(pcr_selection.hash_alg) +
871 			sizeof(pcr_selection.size_of_select) +
872 			pcr_selection.size_of_select;
873 		marker = marker + sizeof_pcr_selection;
874 	}
875 
876 out:
877 	if (i < ARRAY_SIZE(chip->active_banks))
878 		chip->active_banks[i] = TPM2_ALG_ERROR;
879 
880 	tpm_buf_destroy(&buf);
881 
882 	return rc;
883 }
884 
885 static int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip)
886 {
887 	struct tpm_buf buf;
888 	u32 nr_commands;
889 	__be32 *attrs;
890 	u32 cc;
891 	int i;
892 	int rc;
893 
894 	rc = tpm2_get_tpm_pt(chip, TPM_PT_TOTAL_COMMANDS, &nr_commands, NULL);
895 	if (rc)
896 		goto out;
897 
898 	if (nr_commands > 0xFFFFF) {
899 		rc = -EFAULT;
900 		goto out;
901 	}
902 
903 	chip->cc_attrs_tbl = devm_kcalloc(&chip->dev, 4, nr_commands,
904 					  GFP_KERNEL);
905 
906 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
907 	if (rc)
908 		goto out;
909 
910 	tpm_buf_append_u32(&buf, TPM2_CAP_COMMANDS);
911 	tpm_buf_append_u32(&buf, TPM2_CC_FIRST);
912 	tpm_buf_append_u32(&buf, nr_commands);
913 
914 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE,
915 			      9 + 4 * nr_commands, 0, NULL);
916 	if (rc) {
917 		tpm_buf_destroy(&buf);
918 		goto out;
919 	}
920 
921 	if (nr_commands !=
922 	    be32_to_cpup((__be32 *)&buf.data[TPM_HEADER_SIZE + 5])) {
923 		tpm_buf_destroy(&buf);
924 		goto out;
925 	}
926 
927 	chip->nr_commands = nr_commands;
928 
929 	attrs = (__be32 *)&buf.data[TPM_HEADER_SIZE + 9];
930 	for (i = 0; i < nr_commands; i++, attrs++) {
931 		chip->cc_attrs_tbl[i] = be32_to_cpup(attrs);
932 		cc = chip->cc_attrs_tbl[i] & 0xFFFF;
933 
934 		if (cc == TPM2_CC_CONTEXT_SAVE || cc == TPM2_CC_FLUSH_CONTEXT) {
935 			chip->cc_attrs_tbl[i] &=
936 				~(GENMASK(2, 0) << TPM2_CC_ATTR_CHANDLES);
937 			chip->cc_attrs_tbl[i] |= 1 << TPM2_CC_ATTR_CHANDLES;
938 		}
939 	}
940 
941 	tpm_buf_destroy(&buf);
942 
943 out:
944 	if (rc > 0)
945 		rc = -ENODEV;
946 	return rc;
947 }
948 
949 /**
950  * tpm2_startup - turn on the TPM
951  * @chip: TPM chip to use
952  *
953  * Normally the firmware should start the TPM. This function is provided as a
954  * workaround if this does not happen. A legal case for this could be for
955  * example when a TPM emulator is used.
956  *
957  * Return: same as tpm_transmit_cmd()
958  */
959 
960 static int tpm2_startup(struct tpm_chip *chip)
961 {
962 	struct tpm_buf buf;
963 	int rc;
964 
965 	dev_info(&chip->dev, "starting up the TPM manually\n");
966 
967 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_STARTUP);
968 	if (rc < 0)
969 		return rc;
970 
971 	tpm_buf_append_u16(&buf, TPM2_SU_CLEAR);
972 	rc = tpm_transmit_cmd(chip, NULL, buf.data, PAGE_SIZE, 0, 0,
973 			      "attempting to start the TPM");
974 	tpm_buf_destroy(&buf);
975 
976 	return rc;
977 }
978 
979 /**
980  * tpm2_auto_startup - Perform the standard automatic TPM initialization
981  *                     sequence
982  * @chip: TPM chip to use
983  *
984  * Returns 0 on success, < 0 in case of fatal error.
985  */
986 int tpm2_auto_startup(struct tpm_chip *chip)
987 {
988 	int rc;
989 
990 	rc = tpm2_get_timeouts(chip);
991 	if (rc)
992 		goto out;
993 
994 	rc = tpm2_do_selftest(chip);
995 	if (rc && rc != TPM2_RC_INITIALIZE)
996 		goto out;
997 
998 	if (rc == TPM2_RC_INITIALIZE) {
999 		rc = tpm2_startup(chip);
1000 		if (rc)
1001 			goto out;
1002 
1003 		rc = tpm2_do_selftest(chip);
1004 		if (rc)
1005 			goto out;
1006 	}
1007 
1008 	rc = tpm2_get_pcr_allocation(chip);
1009 	if (rc)
1010 		goto out;
1011 
1012 	rc = tpm2_get_cc_attrs_tbl(chip);
1013 
1014 out:
1015 	if (rc > 0)
1016 		rc = -ENODEV;
1017 	return rc;
1018 }
1019 
1020 int tpm2_find_cc(struct tpm_chip *chip, u32 cc)
1021 {
1022 	int i;
1023 
1024 	for (i = 0; i < chip->nr_commands; i++)
1025 		if (cc == (chip->cc_attrs_tbl[i] & GENMASK(15, 0)))
1026 			return i;
1027 
1028 	return -1;
1029 }
1030