xref: /openbmc/linux/drivers/char/tpm/tpm2-cmd.c (revision e5c86679)
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_startup_in {
31 	__be16	startup_type;
32 } __packed;
33 
34 struct tpm2_self_test_in {
35 	u8	full_test;
36 } __packed;
37 
38 struct tpm2_pcr_read_in {
39 	__be32	pcr_selects_cnt;
40 	__be16	hash_alg;
41 	u8	pcr_select_size;
42 	u8	pcr_select[TPM2_PCR_SELECT_MIN];
43 } __packed;
44 
45 struct tpm2_pcr_read_out {
46 	__be32	update_cnt;
47 	__be32	pcr_selects_cnt;
48 	__be16	hash_alg;
49 	u8	pcr_select_size;
50 	u8	pcr_select[TPM2_PCR_SELECT_MIN];
51 	__be32	digests_cnt;
52 	__be16	digest_size;
53 	u8	digest[TPM_DIGEST_SIZE];
54 } __packed;
55 
56 struct tpm2_get_tpm_pt_in {
57 	__be32	cap_id;
58 	__be32	property_id;
59 	__be32	property_cnt;
60 } __packed;
61 
62 struct tpm2_get_tpm_pt_out {
63 	u8	more_data;
64 	__be32	subcap_id;
65 	__be32	property_cnt;
66 	__be32	property_id;
67 	__be32	value;
68 } __packed;
69 
70 struct tpm2_get_random_in {
71 	__be16	size;
72 } __packed;
73 
74 struct tpm2_get_random_out {
75 	__be16	size;
76 	u8	buffer[TPM_MAX_RNG_DATA];
77 } __packed;
78 
79 union tpm2_cmd_params {
80 	struct	tpm2_startup_in		startup_in;
81 	struct	tpm2_self_test_in	selftest_in;
82 	struct	tpm2_pcr_read_in	pcrread_in;
83 	struct	tpm2_pcr_read_out	pcrread_out;
84 	struct	tpm2_get_tpm_pt_in	get_tpm_pt_in;
85 	struct	tpm2_get_tpm_pt_out	get_tpm_pt_out;
86 	struct	tpm2_get_random_in	getrandom_in;
87 	struct	tpm2_get_random_out	getrandom_out;
88 };
89 
90 struct tpm2_cmd {
91 	tpm_cmd_header		header;
92 	union tpm2_cmd_params	params;
93 } __packed;
94 
95 struct tpm2_hash {
96 	unsigned int crypto_id;
97 	unsigned int tpm_id;
98 };
99 
100 static struct tpm2_hash tpm2_hash_map[] = {
101 	{HASH_ALGO_SHA1, TPM2_ALG_SHA1},
102 	{HASH_ALGO_SHA256, TPM2_ALG_SHA256},
103 	{HASH_ALGO_SHA384, TPM2_ALG_SHA384},
104 	{HASH_ALGO_SHA512, TPM2_ALG_SHA512},
105 	{HASH_ALGO_SM3_256, TPM2_ALG_SM3_256},
106 };
107 
108 /*
109  * Array with one entry per ordinal defining the maximum amount
110  * of time the chip could take to return the result. The values
111  * of the SHORT, MEDIUM, and LONG durations are taken from the
112  * PC Client Profile (PTP) specification.
113  */
114 static const u8 tpm2_ordinal_duration[TPM2_CC_LAST - TPM2_CC_FIRST + 1] = {
115 	TPM_UNDEFINED,		/* 11F */
116 	TPM_UNDEFINED,		/* 120 */
117 	TPM_LONG,		/* 121 */
118 	TPM_UNDEFINED,		/* 122 */
119 	TPM_UNDEFINED,		/* 123 */
120 	TPM_UNDEFINED,		/* 124 */
121 	TPM_UNDEFINED,		/* 125 */
122 	TPM_UNDEFINED,		/* 126 */
123 	TPM_UNDEFINED,		/* 127 */
124 	TPM_UNDEFINED,		/* 128 */
125 	TPM_LONG,		/* 129 */
126 	TPM_UNDEFINED,		/* 12a */
127 	TPM_UNDEFINED,		/* 12b */
128 	TPM_UNDEFINED,		/* 12c */
129 	TPM_UNDEFINED,		/* 12d */
130 	TPM_UNDEFINED,		/* 12e */
131 	TPM_UNDEFINED,		/* 12f */
132 	TPM_UNDEFINED,		/* 130 */
133 	TPM_UNDEFINED,		/* 131 */
134 	TPM_UNDEFINED,		/* 132 */
135 	TPM_UNDEFINED,		/* 133 */
136 	TPM_UNDEFINED,		/* 134 */
137 	TPM_UNDEFINED,		/* 135 */
138 	TPM_UNDEFINED,		/* 136 */
139 	TPM_UNDEFINED,		/* 137 */
140 	TPM_UNDEFINED,		/* 138 */
141 	TPM_UNDEFINED,		/* 139 */
142 	TPM_UNDEFINED,		/* 13a */
143 	TPM_UNDEFINED,		/* 13b */
144 	TPM_UNDEFINED,		/* 13c */
145 	TPM_UNDEFINED,		/* 13d */
146 	TPM_MEDIUM,		/* 13e */
147 	TPM_UNDEFINED,		/* 13f */
148 	TPM_UNDEFINED,		/* 140 */
149 	TPM_UNDEFINED,		/* 141 */
150 	TPM_UNDEFINED,		/* 142 */
151 	TPM_LONG,		/* 143 */
152 	TPM_MEDIUM,		/* 144 */
153 	TPM_UNDEFINED,		/* 145 */
154 	TPM_UNDEFINED,		/* 146 */
155 	TPM_UNDEFINED,		/* 147 */
156 	TPM_UNDEFINED,		/* 148 */
157 	TPM_UNDEFINED,		/* 149 */
158 	TPM_UNDEFINED,		/* 14a */
159 	TPM_UNDEFINED,		/* 14b */
160 	TPM_UNDEFINED,		/* 14c */
161 	TPM_UNDEFINED,		/* 14d */
162 	TPM_LONG,		/* 14e */
163 	TPM_UNDEFINED,		/* 14f */
164 	TPM_UNDEFINED,		/* 150 */
165 	TPM_UNDEFINED,		/* 151 */
166 	TPM_UNDEFINED,		/* 152 */
167 	TPM_UNDEFINED,		/* 153 */
168 	TPM_UNDEFINED,		/* 154 */
169 	TPM_UNDEFINED,		/* 155 */
170 	TPM_UNDEFINED,		/* 156 */
171 	TPM_UNDEFINED,		/* 157 */
172 	TPM_UNDEFINED,		/* 158 */
173 	TPM_UNDEFINED,		/* 159 */
174 	TPM_UNDEFINED,		/* 15a */
175 	TPM_UNDEFINED,		/* 15b */
176 	TPM_MEDIUM,		/* 15c */
177 	TPM_UNDEFINED,		/* 15d */
178 	TPM_UNDEFINED,		/* 15e */
179 	TPM_UNDEFINED,		/* 15f */
180 	TPM_UNDEFINED,		/* 160 */
181 	TPM_UNDEFINED,		/* 161 */
182 	TPM_UNDEFINED,		/* 162 */
183 	TPM_UNDEFINED,		/* 163 */
184 	TPM_UNDEFINED,		/* 164 */
185 	TPM_UNDEFINED,		/* 165 */
186 	TPM_UNDEFINED,		/* 166 */
187 	TPM_UNDEFINED,		/* 167 */
188 	TPM_UNDEFINED,		/* 168 */
189 	TPM_UNDEFINED,		/* 169 */
190 	TPM_UNDEFINED,		/* 16a */
191 	TPM_UNDEFINED,		/* 16b */
192 	TPM_UNDEFINED,		/* 16c */
193 	TPM_UNDEFINED,		/* 16d */
194 	TPM_UNDEFINED,		/* 16e */
195 	TPM_UNDEFINED,		/* 16f */
196 	TPM_UNDEFINED,		/* 170 */
197 	TPM_UNDEFINED,		/* 171 */
198 	TPM_UNDEFINED,		/* 172 */
199 	TPM_UNDEFINED,		/* 173 */
200 	TPM_UNDEFINED,		/* 174 */
201 	TPM_UNDEFINED,		/* 175 */
202 	TPM_UNDEFINED,		/* 176 */
203 	TPM_LONG,		/* 177 */
204 	TPM_UNDEFINED,		/* 178 */
205 	TPM_UNDEFINED,		/* 179 */
206 	TPM_MEDIUM,		/* 17a */
207 	TPM_LONG,		/* 17b */
208 	TPM_UNDEFINED,		/* 17c */
209 	TPM_UNDEFINED,		/* 17d */
210 	TPM_UNDEFINED,		/* 17e */
211 	TPM_UNDEFINED,		/* 17f */
212 	TPM_UNDEFINED,		/* 180 */
213 	TPM_UNDEFINED,		/* 181 */
214 	TPM_MEDIUM,		/* 182 */
215 	TPM_UNDEFINED,		/* 183 */
216 	TPM_UNDEFINED,		/* 184 */
217 	TPM_MEDIUM,		/* 185 */
218 	TPM_MEDIUM,		/* 186 */
219 	TPM_UNDEFINED,		/* 187 */
220 	TPM_UNDEFINED,		/* 188 */
221 	TPM_UNDEFINED,		/* 189 */
222 	TPM_UNDEFINED,		/* 18a */
223 	TPM_UNDEFINED,		/* 18b */
224 	TPM_UNDEFINED,		/* 18c */
225 	TPM_UNDEFINED,		/* 18d */
226 	TPM_UNDEFINED,		/* 18e */
227 	TPM_UNDEFINED		/* 18f */
228 };
229 
230 #define TPM2_PCR_READ_IN_SIZE \
231 	(sizeof(struct tpm_input_header) + \
232 	 sizeof(struct tpm2_pcr_read_in))
233 
234 #define TPM2_PCR_READ_RESP_BODY_SIZE \
235 	 sizeof(struct tpm2_pcr_read_out)
236 
237 static const struct tpm_input_header tpm2_pcrread_header = {
238 	.tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
239 	.length = cpu_to_be32(TPM2_PCR_READ_IN_SIZE),
240 	.ordinal = cpu_to_be32(TPM2_CC_PCR_READ)
241 };
242 
243 /**
244  * tpm2_pcr_read() - read a PCR value
245  * @chip:	TPM chip to use.
246  * @pcr_idx:	index of the PCR to read.
247  * @res_buf:	buffer to store the resulting hash.
248  *
249  * Return: Same as with tpm_transmit_cmd.
250  */
251 int tpm2_pcr_read(struct tpm_chip *chip, int pcr_idx, u8 *res_buf)
252 {
253 	int rc;
254 	struct tpm2_cmd cmd;
255 	u8 *buf;
256 
257 	if (pcr_idx >= TPM2_PLATFORM_PCR)
258 		return -EINVAL;
259 
260 	cmd.header.in = tpm2_pcrread_header;
261 	cmd.params.pcrread_in.pcr_selects_cnt = cpu_to_be32(1);
262 	cmd.params.pcrread_in.hash_alg = cpu_to_be16(TPM2_ALG_SHA1);
263 	cmd.params.pcrread_in.pcr_select_size = TPM2_PCR_SELECT_MIN;
264 
265 	memset(cmd.params.pcrread_in.pcr_select, 0,
266 	       sizeof(cmd.params.pcrread_in.pcr_select));
267 	cmd.params.pcrread_in.pcr_select[pcr_idx >> 3] = 1 << (pcr_idx & 0x7);
268 
269 	rc = tpm_transmit_cmd(chip, &cmd, sizeof(cmd),
270 			      TPM2_PCR_READ_RESP_BODY_SIZE,
271 			      0, "attempting to read a pcr value");
272 	if (rc == 0) {
273 		buf = cmd.params.pcrread_out.digest;
274 		memcpy(res_buf, buf, TPM_DIGEST_SIZE);
275 	}
276 
277 	return rc;
278 }
279 
280 struct tpm2_null_auth_area {
281 	__be32  handle;
282 	__be16  nonce_size;
283 	u8  attributes;
284 	__be16  auth_size;
285 } __packed;
286 
287 /**
288  * tpm2_pcr_extend() - extend a PCR value
289  *
290  * @chip:	TPM chip to use.
291  * @pcr_idx:	index of the PCR.
292  * @count:	number of digests passed.
293  * @digests:	list of pcr banks and corresponding digest values to extend.
294  *
295  * Return: Same as with tpm_transmit_cmd.
296  */
297 int tpm2_pcr_extend(struct tpm_chip *chip, int pcr_idx, u32 count,
298 		    struct tpm2_digest *digests)
299 {
300 	struct tpm_buf buf;
301 	struct tpm2_null_auth_area auth_area;
302 	int rc;
303 	int i;
304 	int j;
305 
306 	if (count > ARRAY_SIZE(chip->active_banks))
307 		return -EINVAL;
308 
309 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
310 	if (rc)
311 		return rc;
312 
313 	tpm_buf_append_u32(&buf, pcr_idx);
314 
315 	auth_area.handle = cpu_to_be32(TPM2_RS_PW);
316 	auth_area.nonce_size = 0;
317 	auth_area.attributes = 0;
318 	auth_area.auth_size = 0;
319 
320 	tpm_buf_append_u32(&buf, sizeof(struct tpm2_null_auth_area));
321 	tpm_buf_append(&buf, (const unsigned char *)&auth_area,
322 		       sizeof(auth_area));
323 	tpm_buf_append_u32(&buf, count);
324 
325 	for (i = 0; i < count; i++) {
326 		for (j = 0; j < ARRAY_SIZE(tpm2_hash_map); j++) {
327 			if (digests[i].alg_id != tpm2_hash_map[j].tpm_id)
328 				continue;
329 			tpm_buf_append_u16(&buf, digests[i].alg_id);
330 			tpm_buf_append(&buf, (const unsigned char
331 					      *)&digests[i].digest,
332 			       hash_digest_size[tpm2_hash_map[j].crypto_id]);
333 		}
334 	}
335 
336 	rc = tpm_transmit_cmd(chip, buf.data, PAGE_SIZE, 0, 0,
337 			      "attempting extend a PCR value");
338 
339 	tpm_buf_destroy(&buf);
340 
341 	return rc;
342 }
343 
344 
345 #define TPM2_GETRANDOM_IN_SIZE \
346 	(sizeof(struct tpm_input_header) + \
347 	 sizeof(struct tpm2_get_random_in))
348 
349 static const struct tpm_input_header tpm2_getrandom_header = {
350 	.tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
351 	.length = cpu_to_be32(TPM2_GETRANDOM_IN_SIZE),
352 	.ordinal = cpu_to_be32(TPM2_CC_GET_RANDOM)
353 };
354 
355 /**
356  * tpm2_get_random() - get random bytes from the TPM RNG
357  *
358  * @chip: TPM chip to use
359  * @out: destination buffer for the random bytes
360  * @max: the max number of bytes to write to @out
361  *
362  * Return:
363  *    Size of the output buffer, or -EIO on error.
364  */
365 int tpm2_get_random(struct tpm_chip *chip, u8 *out, size_t max)
366 {
367 	struct tpm2_cmd cmd;
368 	u32 recd, rlength;
369 	u32 num_bytes;
370 	int err;
371 	int total = 0;
372 	int retries = 5;
373 	u8 *dest = out;
374 
375 	num_bytes = min_t(u32, max, sizeof(cmd.params.getrandom_out.buffer));
376 
377 	if (!out || !num_bytes ||
378 	    max > sizeof(cmd.params.getrandom_out.buffer))
379 		return -EINVAL;
380 
381 	do {
382 		cmd.header.in = tpm2_getrandom_header;
383 		cmd.params.getrandom_in.size = cpu_to_be16(num_bytes);
384 
385 		err = tpm_transmit_cmd(chip, &cmd, sizeof(cmd),
386 				       offsetof(struct tpm2_get_random_out,
387 						buffer),
388 				       0, "attempting get random");
389 		if (err)
390 			break;
391 
392 		recd = min_t(u32, be16_to_cpu(cmd.params.getrandom_out.size),
393 			     num_bytes);
394 		rlength = be32_to_cpu(cmd.header.out.length);
395 		if (rlength < offsetof(struct tpm2_get_random_out, buffer) +
396 			      recd)
397 			return -EFAULT;
398 		memcpy(dest, cmd.params.getrandom_out.buffer, recd);
399 
400 		dest += recd;
401 		total += recd;
402 		num_bytes -= recd;
403 	} while (retries-- && total < max);
404 
405 	return total ? total : -EIO;
406 }
407 
408 #define TPM2_GET_TPM_PT_IN_SIZE \
409 	(sizeof(struct tpm_input_header) + \
410 	 sizeof(struct tpm2_get_tpm_pt_in))
411 
412 #define TPM2_GET_TPM_PT_OUT_BODY_SIZE \
413 	 sizeof(struct tpm2_get_tpm_pt_out)
414 
415 static const struct tpm_input_header tpm2_get_tpm_pt_header = {
416 	.tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
417 	.length = cpu_to_be32(TPM2_GET_TPM_PT_IN_SIZE),
418 	.ordinal = cpu_to_be32(TPM2_CC_GET_CAPABILITY)
419 };
420 
421 /**
422  * tpm_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer.
423  *
424  * @buf: an allocated tpm_buf instance
425  * @session_handle: session handle
426  * @nonce: the session nonce, may be NULL if not used
427  * @nonce_len: the session nonce length, may be 0 if not used
428  * @attributes: the session attributes
429  * @hmac: the session HMAC or password, may be NULL if not used
430  * @hmac_len: the session HMAC or password length, maybe 0 if not used
431  */
432 static void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle,
433 				 const u8 *nonce, u16 nonce_len,
434 				 u8 attributes,
435 				 const u8 *hmac, u16 hmac_len)
436 {
437 	tpm_buf_append_u32(buf, 9 + nonce_len + hmac_len);
438 	tpm_buf_append_u32(buf, session_handle);
439 	tpm_buf_append_u16(buf, nonce_len);
440 
441 	if (nonce && nonce_len)
442 		tpm_buf_append(buf, nonce, nonce_len);
443 
444 	tpm_buf_append_u8(buf, attributes);
445 	tpm_buf_append_u16(buf, hmac_len);
446 
447 	if (hmac && hmac_len)
448 		tpm_buf_append(buf, hmac, hmac_len);
449 }
450 
451 /**
452  * tpm2_seal_trusted() - seal the payload of a trusted key
453  *
454  * @chip: TPM chip to use
455  * @payload: the key data in clear and encrypted form
456  * @options: authentication values and other options
457  *
458  * Return: < 0 on error and 0 on success.
459  */
460 int tpm2_seal_trusted(struct tpm_chip *chip,
461 		      struct trusted_key_payload *payload,
462 		      struct trusted_key_options *options)
463 {
464 	unsigned int blob_len;
465 	struct tpm_buf buf;
466 	u32 hash, rlength;
467 	int i;
468 	int rc;
469 
470 	for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) {
471 		if (options->hash == tpm2_hash_map[i].crypto_id) {
472 			hash = tpm2_hash_map[i].tpm_id;
473 			break;
474 		}
475 	}
476 
477 	if (i == ARRAY_SIZE(tpm2_hash_map))
478 		return -EINVAL;
479 
480 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
481 	if (rc)
482 		return rc;
483 
484 	tpm_buf_append_u32(&buf, options->keyhandle);
485 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
486 			     NULL /* nonce */, 0,
487 			     0 /* session_attributes */,
488 			     options->keyauth /* hmac */,
489 			     TPM_DIGEST_SIZE);
490 
491 	/* sensitive */
492 	tpm_buf_append_u16(&buf, 4 + TPM_DIGEST_SIZE + payload->key_len + 1);
493 
494 	tpm_buf_append_u16(&buf, TPM_DIGEST_SIZE);
495 	tpm_buf_append(&buf, options->blobauth, TPM_DIGEST_SIZE);
496 	tpm_buf_append_u16(&buf, payload->key_len + 1);
497 	tpm_buf_append(&buf, payload->key, payload->key_len);
498 	tpm_buf_append_u8(&buf, payload->migratable);
499 
500 	/* public */
501 	tpm_buf_append_u16(&buf, 14 + options->policydigest_len);
502 	tpm_buf_append_u16(&buf, TPM2_ALG_KEYEDHASH);
503 	tpm_buf_append_u16(&buf, hash);
504 
505 	/* policy */
506 	if (options->policydigest_len) {
507 		tpm_buf_append_u32(&buf, 0);
508 		tpm_buf_append_u16(&buf, options->policydigest_len);
509 		tpm_buf_append(&buf, options->policydigest,
510 			       options->policydigest_len);
511 	} else {
512 		tpm_buf_append_u32(&buf, TPM2_OA_USER_WITH_AUTH);
513 		tpm_buf_append_u16(&buf, 0);
514 	}
515 
516 	/* public parameters */
517 	tpm_buf_append_u16(&buf, TPM2_ALG_NULL);
518 	tpm_buf_append_u16(&buf, 0);
519 
520 	/* outside info */
521 	tpm_buf_append_u16(&buf, 0);
522 
523 	/* creation PCR */
524 	tpm_buf_append_u32(&buf, 0);
525 
526 	if (buf.flags & TPM_BUF_OVERFLOW) {
527 		rc = -E2BIG;
528 		goto out;
529 	}
530 
531 	rc = tpm_transmit_cmd(chip, buf.data, PAGE_SIZE, 4, 0,
532 			      "sealing data");
533 	if (rc)
534 		goto out;
535 
536 	blob_len = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]);
537 	if (blob_len > MAX_BLOB_SIZE) {
538 		rc = -E2BIG;
539 		goto out;
540 	}
541 	rlength = be32_to_cpu(((struct tpm2_cmd *)&buf)->header.out.length);
542 	if (rlength < TPM_HEADER_SIZE + 4 + blob_len) {
543 		rc = -EFAULT;
544 		goto out;
545 	}
546 
547 	memcpy(payload->blob, &buf.data[TPM_HEADER_SIZE + 4], blob_len);
548 	payload->blob_len = blob_len;
549 
550 out:
551 	tpm_buf_destroy(&buf);
552 
553 	if (rc > 0) {
554 		if (tpm2_rc_value(rc) == TPM2_RC_HASH)
555 			rc = -EINVAL;
556 		else
557 			rc = -EPERM;
558 	}
559 
560 	return rc;
561 }
562 
563 /**
564  * tpm2_load_cmd() - execute a TPM2_Load command
565  *
566  * @chip: TPM chip to use
567  * @payload: the key data in clear and encrypted form
568  * @options: authentication values and other options
569  * @blob_handle: returned blob handle
570  * @flags: tpm transmit flags
571  *
572  * Return: 0 on success.
573  *        -E2BIG on wrong payload size.
574  *        -EPERM on tpm error status.
575  *        < 0 error from tpm_transmit_cmd.
576  */
577 static int tpm2_load_cmd(struct tpm_chip *chip,
578 			 struct trusted_key_payload *payload,
579 			 struct trusted_key_options *options,
580 			 u32 *blob_handle, unsigned int flags)
581 {
582 	struct tpm_buf buf;
583 	unsigned int private_len;
584 	unsigned int public_len;
585 	unsigned int blob_len;
586 	int rc;
587 
588 	private_len = be16_to_cpup((__be16 *) &payload->blob[0]);
589 	if (private_len > (payload->blob_len - 2))
590 		return -E2BIG;
591 
592 	public_len = be16_to_cpup((__be16 *) &payload->blob[2 + private_len]);
593 	blob_len = private_len + public_len + 4;
594 	if (blob_len > payload->blob_len)
595 		return -E2BIG;
596 
597 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
598 	if (rc)
599 		return rc;
600 
601 	tpm_buf_append_u32(&buf, options->keyhandle);
602 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
603 			     NULL /* nonce */, 0,
604 			     0 /* session_attributes */,
605 			     options->keyauth /* hmac */,
606 			     TPM_DIGEST_SIZE);
607 
608 	tpm_buf_append(&buf, payload->blob, blob_len);
609 
610 	if (buf.flags & TPM_BUF_OVERFLOW) {
611 		rc = -E2BIG;
612 		goto out;
613 	}
614 
615 	rc = tpm_transmit_cmd(chip, buf.data, PAGE_SIZE, 4, flags,
616 			      "loading blob");
617 	if (!rc)
618 		*blob_handle = be32_to_cpup(
619 			(__be32 *) &buf.data[TPM_HEADER_SIZE]);
620 
621 out:
622 	tpm_buf_destroy(&buf);
623 
624 	if (rc > 0)
625 		rc = -EPERM;
626 
627 	return rc;
628 }
629 
630 /**
631  * tpm2_flush_context_cmd() - execute a TPM2_FlushContext command
632  *
633  * @chip: TPM chip to use
634  * @handle: the key data in clear and encrypted form
635  * @flags: tpm transmit flags
636  *
637  * Return: Same as with tpm_transmit_cmd.
638  */
639 static void tpm2_flush_context_cmd(struct tpm_chip *chip, u32 handle,
640 				   unsigned int flags)
641 {
642 	struct tpm_buf buf;
643 	int rc;
644 
645 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_FLUSH_CONTEXT);
646 	if (rc) {
647 		dev_warn(&chip->dev, "0x%08x was not flushed, out of memory\n",
648 			 handle);
649 		return;
650 	}
651 
652 	tpm_buf_append_u32(&buf, handle);
653 
654 	rc = tpm_transmit_cmd(chip, buf.data, PAGE_SIZE, 0, flags,
655 			      "flushing context");
656 	if (rc)
657 		dev_warn(&chip->dev, "0x%08x was not flushed, rc=%d\n", handle,
658 			 rc);
659 
660 	tpm_buf_destroy(&buf);
661 }
662 
663 /**
664  * tpm2_unseal_cmd() - execute a TPM2_Unload command
665  *
666  * @chip: TPM chip to use
667  * @payload: the key data in clear and encrypted form
668  * @options: authentication values and other options
669  * @blob_handle: blob handle
670  * @flags: tpm_transmit_cmd flags
671  *
672  * Return: 0 on success
673  *         -EPERM on tpm error status
674  *         < 0 error from tpm_transmit_cmd
675  */
676 static int tpm2_unseal_cmd(struct tpm_chip *chip,
677 			   struct trusted_key_payload *payload,
678 			   struct trusted_key_options *options,
679 			   u32 blob_handle, unsigned int flags)
680 {
681 	struct tpm_buf buf;
682 	u16 data_len;
683 	u8 *data;
684 	int rc;
685 	u32 rlength;
686 
687 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
688 	if (rc)
689 		return rc;
690 
691 	tpm_buf_append_u32(&buf, blob_handle);
692 	tpm2_buf_append_auth(&buf,
693 			     options->policyhandle ?
694 			     options->policyhandle : TPM2_RS_PW,
695 			     NULL /* nonce */, 0,
696 			     TPM2_SA_CONTINUE_SESSION,
697 			     options->blobauth /* hmac */,
698 			     TPM_DIGEST_SIZE);
699 
700 	rc = tpm_transmit_cmd(chip, buf.data, PAGE_SIZE, 6, flags,
701 			      "unsealing");
702 	if (rc > 0)
703 		rc = -EPERM;
704 
705 	if (!rc) {
706 		data_len = be16_to_cpup(
707 			(__be16 *) &buf.data[TPM_HEADER_SIZE + 4]);
708 
709 		rlength = be32_to_cpu(((struct tpm2_cmd *)&buf)
710 					->header.out.length);
711 		if (rlength < TPM_HEADER_SIZE + 6 + data_len) {
712 			rc = -EFAULT;
713 			goto out;
714 		}
715 		data = &buf.data[TPM_HEADER_SIZE + 6];
716 
717 		memcpy(payload->key, data, data_len - 1);
718 		payload->key_len = data_len - 1;
719 		payload->migratable = data[data_len - 1];
720 	}
721 
722 out:
723 	tpm_buf_destroy(&buf);
724 	return rc;
725 }
726 
727 /**
728  * tpm2_unseal_trusted() - unseal the payload of a trusted key
729  *
730  * @chip: TPM chip to use
731  * @payload: the key data in clear and encrypted form
732  * @options: authentication values and other options
733  *
734  * Return: Same as with tpm_transmit_cmd.
735  */
736 int tpm2_unseal_trusted(struct tpm_chip *chip,
737 			struct trusted_key_payload *payload,
738 			struct trusted_key_options *options)
739 {
740 	u32 blob_handle;
741 	int rc;
742 
743 	mutex_lock(&chip->tpm_mutex);
744 	rc = tpm2_load_cmd(chip, payload, options, &blob_handle,
745 			   TPM_TRANSMIT_UNLOCKED);
746 	if (rc)
747 		goto out;
748 
749 	rc = tpm2_unseal_cmd(chip, payload, options, blob_handle,
750 			     TPM_TRANSMIT_UNLOCKED);
751 	tpm2_flush_context_cmd(chip, blob_handle, TPM_TRANSMIT_UNLOCKED);
752 out:
753 	mutex_unlock(&chip->tpm_mutex);
754 	return rc;
755 }
756 
757 /**
758  * tpm2_get_tpm_pt() - get value of a TPM_CAP_TPM_PROPERTIES type property
759  * @chip:		TPM chip to use.
760  * @property_id:	property ID.
761  * @value:		output variable.
762  * @desc:		passed to tpm_transmit_cmd()
763  *
764  * Return: Same as with tpm_transmit_cmd.
765  */
766 ssize_t tpm2_get_tpm_pt(struct tpm_chip *chip, u32 property_id,  u32 *value,
767 			const char *desc)
768 {
769 	struct tpm2_cmd cmd;
770 	int rc;
771 
772 	cmd.header.in = tpm2_get_tpm_pt_header;
773 	cmd.params.get_tpm_pt_in.cap_id = cpu_to_be32(TPM2_CAP_TPM_PROPERTIES);
774 	cmd.params.get_tpm_pt_in.property_id = cpu_to_be32(property_id);
775 	cmd.params.get_tpm_pt_in.property_cnt = cpu_to_be32(1);
776 
777 	rc = tpm_transmit_cmd(chip, &cmd, sizeof(cmd),
778 			      TPM2_GET_TPM_PT_OUT_BODY_SIZE, 0, desc);
779 	if (!rc)
780 		*value = be32_to_cpu(cmd.params.get_tpm_pt_out.value);
781 
782 	return rc;
783 }
784 EXPORT_SYMBOL_GPL(tpm2_get_tpm_pt);
785 
786 #define TPM2_STARTUP_IN_SIZE \
787 	(sizeof(struct tpm_input_header) + \
788 	 sizeof(struct tpm2_startup_in))
789 
790 static const struct tpm_input_header tpm2_startup_header = {
791 	.tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
792 	.length = cpu_to_be32(TPM2_STARTUP_IN_SIZE),
793 	.ordinal = cpu_to_be32(TPM2_CC_STARTUP)
794 };
795 
796 /**
797  * tpm2_startup() - send startup command to the TPM chip
798  *
799  * @chip:		TPM chip to use.
800  * @startup_type:	startup type. The value is either
801  *			TPM_SU_CLEAR or TPM_SU_STATE.
802  *
803  * Return: Same as with tpm_transmit_cmd.
804  */
805 static int tpm2_startup(struct tpm_chip *chip, u16 startup_type)
806 {
807 	struct tpm2_cmd cmd;
808 
809 	cmd.header.in = tpm2_startup_header;
810 
811 	cmd.params.startup_in.startup_type = cpu_to_be16(startup_type);
812 	return tpm_transmit_cmd(chip, &cmd, sizeof(cmd), 0, 0,
813 				"attempting to start the TPM");
814 }
815 
816 #define TPM2_SHUTDOWN_IN_SIZE \
817 	(sizeof(struct tpm_input_header) + \
818 	 sizeof(struct tpm2_startup_in))
819 
820 static const struct tpm_input_header tpm2_shutdown_header = {
821 	.tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
822 	.length = cpu_to_be32(TPM2_SHUTDOWN_IN_SIZE),
823 	.ordinal = cpu_to_be32(TPM2_CC_SHUTDOWN)
824 };
825 
826 /**
827  * tpm2_shutdown() - send shutdown command to the TPM chip
828  *
829  * @chip:		TPM chip to use.
830  * @shutdown_type:	shutdown type. The value is either
831  *			TPM_SU_CLEAR or TPM_SU_STATE.
832  */
833 void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
834 {
835 	struct tpm2_cmd cmd;
836 	int rc;
837 
838 	cmd.header.in = tpm2_shutdown_header;
839 	cmd.params.startup_in.startup_type = cpu_to_be16(shutdown_type);
840 
841 	rc = tpm_transmit_cmd(chip, &cmd, sizeof(cmd), 0, 0,
842 			      "stopping the TPM");
843 
844 	/* In places where shutdown command is sent there's no much we can do
845 	 * except print the error code on a system failure.
846 	 */
847 	if (rc < 0)
848 		dev_warn(&chip->dev, "transmit returned %d while stopping the TPM",
849 			 rc);
850 }
851 
852 /*
853  * tpm2_calc_ordinal_duration() - maximum duration for a command
854  *
855  * @chip:	TPM chip to use.
856  * @ordinal:	command code number.
857  *
858  * Return: maximum duration for a command
859  */
860 unsigned long tpm2_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal)
861 {
862 	int index = TPM_UNDEFINED;
863 	int duration = 0;
864 
865 	if (ordinal >= TPM2_CC_FIRST && ordinal <= TPM2_CC_LAST)
866 		index = tpm2_ordinal_duration[ordinal - TPM2_CC_FIRST];
867 
868 	if (index != TPM_UNDEFINED)
869 		duration = chip->duration[index];
870 
871 	if (duration <= 0)
872 		duration = 2 * 60 * HZ;
873 
874 	return duration;
875 }
876 EXPORT_SYMBOL_GPL(tpm2_calc_ordinal_duration);
877 
878 #define TPM2_SELF_TEST_IN_SIZE \
879 	(sizeof(struct tpm_input_header) + \
880 	 sizeof(struct tpm2_self_test_in))
881 
882 static const struct tpm_input_header tpm2_selftest_header = {
883 	.tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
884 	.length = cpu_to_be32(TPM2_SELF_TEST_IN_SIZE),
885 	.ordinal = cpu_to_be32(TPM2_CC_SELF_TEST)
886 };
887 
888 /**
889  * tpm2_continue_selftest() - start a self test
890  *
891  * @chip: TPM chip to use
892  * @full: test all commands instead of testing only those that were not
893  *        previously tested.
894  *
895  * Return: Same as with tpm_transmit_cmd with exception of RC_TESTING.
896  */
897 static int tpm2_start_selftest(struct tpm_chip *chip, bool full)
898 {
899 	int rc;
900 	struct tpm2_cmd cmd;
901 
902 	cmd.header.in = tpm2_selftest_header;
903 	cmd.params.selftest_in.full_test = full;
904 
905 	rc = tpm_transmit_cmd(chip, &cmd, TPM2_SELF_TEST_IN_SIZE, 0, 0,
906 			      "continue selftest");
907 
908 	/* At least some prototype chips seem to give RC_TESTING error
909 	 * immediately. This is a workaround for that.
910 	 */
911 	if (rc == TPM2_RC_TESTING) {
912 		dev_warn(&chip->dev, "Got RC_TESTING, ignoring\n");
913 		rc = 0;
914 	}
915 
916 	return rc;
917 }
918 
919 /**
920  * tpm2_do_selftest() - run a full self test
921  *
922  * @chip: TPM chip to use
923  *
924  * Return: Same as with tpm_transmit_cmd.
925  *
926  * During the self test TPM2 commands return with the error code RC_TESTING.
927  * Waiting is done by issuing PCR read until it executes successfully.
928  */
929 static int tpm2_do_selftest(struct tpm_chip *chip)
930 {
931 	int rc;
932 	unsigned int loops;
933 	unsigned int delay_msec = 100;
934 	unsigned long duration;
935 	struct tpm2_cmd cmd;
936 	int i;
937 
938 	duration = tpm2_calc_ordinal_duration(chip, TPM2_CC_SELF_TEST);
939 
940 	loops = jiffies_to_msecs(duration) / delay_msec;
941 
942 	rc = tpm2_start_selftest(chip, true);
943 	if (rc)
944 		return rc;
945 
946 	for (i = 0; i < loops; i++) {
947 		/* Attempt to read a PCR value */
948 		cmd.header.in = tpm2_pcrread_header;
949 		cmd.params.pcrread_in.pcr_selects_cnt = cpu_to_be32(1);
950 		cmd.params.pcrread_in.hash_alg = cpu_to_be16(TPM2_ALG_SHA1);
951 		cmd.params.pcrread_in.pcr_select_size = TPM2_PCR_SELECT_MIN;
952 		cmd.params.pcrread_in.pcr_select[0] = 0x01;
953 		cmd.params.pcrread_in.pcr_select[1] = 0x00;
954 		cmd.params.pcrread_in.pcr_select[2] = 0x00;
955 
956 		rc = tpm_transmit_cmd(chip, &cmd, sizeof(cmd), 0, 0, NULL);
957 		if (rc < 0)
958 			break;
959 
960 		rc = be32_to_cpu(cmd.header.out.return_code);
961 		if (rc != TPM2_RC_TESTING)
962 			break;
963 
964 		msleep(delay_msec);
965 	}
966 
967 	return rc;
968 }
969 
970 /**
971  * tpm2_probe() - probe TPM 2.0
972  * @chip: TPM chip to use
973  *
974  * Return: < 0 error and 0 on success.
975  *
976  * Send idempotent TPM 2.0 command and see whether TPM 2.0 chip replied based on
977  * the reply tag.
978  */
979 int tpm2_probe(struct tpm_chip *chip)
980 {
981 	struct tpm2_cmd cmd;
982 	int rc;
983 
984 	cmd.header.in = tpm2_get_tpm_pt_header;
985 	cmd.params.get_tpm_pt_in.cap_id = cpu_to_be32(TPM2_CAP_TPM_PROPERTIES);
986 	cmd.params.get_tpm_pt_in.property_id = cpu_to_be32(0x100);
987 	cmd.params.get_tpm_pt_in.property_cnt = cpu_to_be32(1);
988 
989 	rc = tpm_transmit_cmd(chip, &cmd, sizeof(cmd), 0, 0, NULL);
990 	if (rc <  0)
991 		return rc;
992 
993 	if (be16_to_cpu(cmd.header.out.tag) == TPM2_ST_NO_SESSIONS)
994 		chip->flags |= TPM_CHIP_FLAG_TPM2;
995 
996 	return 0;
997 }
998 EXPORT_SYMBOL_GPL(tpm2_probe);
999 
1000 struct tpm2_pcr_selection {
1001 	__be16  hash_alg;
1002 	u8  size_of_select;
1003 	u8  pcr_select[3];
1004 } __packed;
1005 
1006 static ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
1007 {
1008 	struct tpm2_pcr_selection pcr_selection;
1009 	struct tpm_buf buf;
1010 	void *marker;
1011 	void *end;
1012 	void *pcr_select_offset;
1013 	unsigned int count;
1014 	u32 sizeof_pcr_selection;
1015 	u32 rsp_len;
1016 	int rc;
1017 	int i = 0;
1018 
1019 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
1020 	if (rc)
1021 		return rc;
1022 
1023 	tpm_buf_append_u32(&buf, TPM2_CAP_PCRS);
1024 	tpm_buf_append_u32(&buf, 0);
1025 	tpm_buf_append_u32(&buf, 1);
1026 
1027 	rc = tpm_transmit_cmd(chip, buf.data, PAGE_SIZE, 9, 0,
1028 			      "get tpm pcr allocation");
1029 	if (rc)
1030 		goto out;
1031 
1032 	count = be32_to_cpup(
1033 		(__be32 *)&buf.data[TPM_HEADER_SIZE + 5]);
1034 
1035 	if (count > ARRAY_SIZE(chip->active_banks)) {
1036 		rc = -ENODEV;
1037 		goto out;
1038 	}
1039 
1040 	marker = &buf.data[TPM_HEADER_SIZE + 9];
1041 
1042 	rsp_len = be32_to_cpup((__be32 *)&buf.data[2]);
1043 	end = &buf.data[rsp_len];
1044 
1045 	for (i = 0; i < count; i++) {
1046 		pcr_select_offset = marker +
1047 			offsetof(struct tpm2_pcr_selection, size_of_select);
1048 		if (pcr_select_offset >= end) {
1049 			rc = -EFAULT;
1050 			break;
1051 		}
1052 
1053 		memcpy(&pcr_selection, marker, sizeof(pcr_selection));
1054 		chip->active_banks[i] = be16_to_cpu(pcr_selection.hash_alg);
1055 		sizeof_pcr_selection = sizeof(pcr_selection.hash_alg) +
1056 			sizeof(pcr_selection.size_of_select) +
1057 			pcr_selection.size_of_select;
1058 		marker = marker + sizeof_pcr_selection;
1059 	}
1060 
1061 out:
1062 	if (i < ARRAY_SIZE(chip->active_banks))
1063 		chip->active_banks[i] = TPM2_ALG_ERROR;
1064 
1065 	tpm_buf_destroy(&buf);
1066 
1067 	return rc;
1068 }
1069 
1070 /**
1071  * tpm2_auto_startup - Perform the standard automatic TPM initialization
1072  *                     sequence
1073  * @chip: TPM chip to use
1074  *
1075  * Initializes timeout values for operation and command durations, conducts
1076  * a self-test and reads the list of active PCR banks.
1077  *
1078  * Return: 0 on success. Otherwise, a system error code is returned.
1079  */
1080 int tpm2_auto_startup(struct tpm_chip *chip)
1081 {
1082 	int rc;
1083 
1084 	rc = tpm_get_timeouts(chip);
1085 	if (rc)
1086 		goto out;
1087 
1088 	rc = tpm2_do_selftest(chip);
1089 	if (rc != 0 && rc != TPM2_RC_INITIALIZE) {
1090 		dev_err(&chip->dev, "TPM self test failed\n");
1091 		goto out;
1092 	}
1093 
1094 	if (rc == TPM2_RC_INITIALIZE) {
1095 		rc = tpm2_startup(chip, TPM2_SU_CLEAR);
1096 		if (rc)
1097 			goto out;
1098 
1099 		rc = tpm2_do_selftest(chip);
1100 		if (rc) {
1101 			dev_err(&chip->dev, "TPM self test failed\n");
1102 			goto out;
1103 		}
1104 	}
1105 
1106 	rc = tpm2_get_pcr_allocation(chip);
1107 
1108 out:
1109 	if (rc > 0)
1110 		rc = -ENODEV;
1111 	return rc;
1112 }
1113