xref: /linux/security/keys/trusted-keys/trusted_tpm1.c (revision afe0579334f622c803f2864f22c04c20c320bd80)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2010 IBM Corporation
4  * Copyright (c) 2019-2021, Linaro Limited
5  *
6  * See Documentation/security/keys/trusted-encrypted.rst
7  */
8 
9 #include <crypto/hash_info.h>
10 #include <crypto/sha1.h>
11 #include <crypto/utils.h>
12 #include <linux/hex.h>
13 #include <linux/init.h>
14 #include <linux/slab.h>
15 #include <linux/parser.h>
16 #include <linux/string.h>
17 #include <linux/err.h>
18 #include <keys/trusted-type.h>
19 #include <linux/key-type.h>
20 #include <linux/tpm.h>
21 
22 #include <keys/trusted_tpm.h>
23 
24 static struct tpm_chip *chip;
25 static struct tpm_digest *digests;
26 
27 /* implementation specific TPM constants */
28 #define TPM_SIZE_OFFSET			2
29 #define TPM_RETURN_OFFSET		6
30 #define TPM_DATA_OFFSET			10
31 
32 #define LOAD32(buffer, offset)	(ntohl(*(uint32_t *)&buffer[offset]))
33 #define LOAD32N(buffer, offset)	(*(uint32_t *)&buffer[offset])
34 #define LOAD16(buffer, offset)	(ntohs(*(uint16_t *)&buffer[offset]))
35 
36 struct osapsess {
37 	uint32_t handle;
38 	unsigned char secret[SHA1_DIGEST_SIZE];
39 	unsigned char enonce[TPM_NONCE_SIZE];
40 };
41 
42 /* discrete values, but have to store in uint16_t for TPM use */
43 enum {
44 	SEAL_keytype = 1,
45 	SRK_keytype = 4
46 };
47 
48 #ifdef CONFIG_TRUSTED_KEYS_DEBUG
49 static inline void dump_options(struct trusted_key_options *o)
50 {
51 	if (!trusted_debug)
52 		return;
53 
54 	pr_debug("sealing key type %d\n", o->keytype);
55 	pr_debug("sealing key handle %0X\n", o->keyhandle);
56 	pr_debug("pcrlock %d\n", o->pcrlock);
57 	pr_debug("pcrinfo %d\n", o->pcrinfo_len);
58 	print_hex_dump_debug("pcrinfo ", DUMP_PREFIX_NONE,
59 			     16, 1, o->pcrinfo, o->pcrinfo_len, 0);
60 }
61 
62 static inline void dump_sess(struct osapsess *s)
63 {
64 	if (!trusted_debug)
65 		return;
66 
67 	print_hex_dump_debug("trusted-key: handle ", DUMP_PREFIX_NONE,
68 			     16, 1, &s->handle, 4, 0);
69 	pr_debug("secret:\n");
70 	print_hex_dump_debug("", DUMP_PREFIX_NONE,
71 			     16, 1, &s->secret, SHA1_DIGEST_SIZE, 0);
72 	pr_debug("trusted-key: enonce:\n");
73 	print_hex_dump_debug("", DUMP_PREFIX_NONE,
74 			     16, 1, &s->enonce, SHA1_DIGEST_SIZE, 0);
75 }
76 
77 static inline void dump_tpm_buf(unsigned char *buf)
78 {
79 	int len;
80 
81 	if (!trusted_debug)
82 		return;
83 	pr_debug("\ntpm buffer\n");
84 	len = LOAD32(buf, TPM_SIZE_OFFSET);
85 	print_hex_dump_debug("", DUMP_PREFIX_NONE, 16, 1, buf, len, 0);
86 }
87 #else
88 static inline void dump_options(struct trusted_key_options *o)
89 {
90 }
91 
92 static inline void dump_sess(struct osapsess *s)
93 {
94 }
95 
96 static inline void dump_tpm_buf(unsigned char *buf)
97 {
98 }
99 #endif
100 
101 static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
102 		       unsigned int keylen, ...)
103 {
104 	struct hmac_sha1_ctx hmac_ctx;
105 	va_list argp;
106 	unsigned int dlen;
107 	unsigned char *data;
108 	int ret = 0;
109 
110 	hmac_sha1_init_usingrawkey(&hmac_ctx, key, keylen);
111 
112 	va_start(argp, keylen);
113 	for (;;) {
114 		dlen = va_arg(argp, unsigned int);
115 		if (dlen == 0)
116 			break;
117 		data = va_arg(argp, unsigned char *);
118 		if (data == NULL) {
119 			ret = -EINVAL;
120 			break;
121 		}
122 		hmac_sha1_update(&hmac_ctx, data, dlen);
123 	}
124 	va_end(argp);
125 	if (!ret)
126 		hmac_sha1_final(&hmac_ctx, digest);
127 	return ret;
128 }
129 
130 /*
131  * calculate authorization info fields to send to TPM
132  */
133 static int TSS_authhmac(unsigned char *digest, const unsigned char *key,
134 			unsigned int keylen, unsigned char *h1,
135 			unsigned char *h2, unsigned int h3, ...)
136 {
137 	unsigned char paramdigest[SHA1_DIGEST_SIZE];
138 	struct sha1_ctx sha_ctx;
139 	unsigned int dlen;
140 	unsigned char *data;
141 	unsigned char c;
142 	int ret = 0;
143 	va_list argp;
144 
145 	if (!chip)
146 		return -ENODEV;
147 
148 	c = !!h3;
149 	sha1_init(&sha_ctx);
150 	va_start(argp, h3);
151 	for (;;) {
152 		dlen = va_arg(argp, unsigned int);
153 		if (dlen == 0)
154 			break;
155 		data = va_arg(argp, unsigned char *);
156 		if (!data) {
157 			ret = -EINVAL;
158 			break;
159 		}
160 		sha1_update(&sha_ctx, data, dlen);
161 	}
162 	va_end(argp);
163 	if (!ret)
164 		sha1_final(&sha_ctx, paramdigest);
165 	if (!ret)
166 		ret = TSS_rawhmac(digest, key, keylen, SHA1_DIGEST_SIZE,
167 				  paramdigest, TPM_NONCE_SIZE, h1,
168 				  TPM_NONCE_SIZE, h2, 1, &c, 0, 0);
169 	return ret;
170 }
171 
172 /*
173  * verify the AUTH1_COMMAND (Seal) result from TPM
174  */
175 static int TSS_checkhmac1(unsigned char *buffer,
176 			  const uint32_t command,
177 			  const unsigned char *ononce,
178 			  const unsigned char *key,
179 			  unsigned int keylen, ...)
180 {
181 	uint32_t bufsize;
182 	uint16_t tag;
183 	uint32_t ordinal;
184 	uint32_t result;
185 	unsigned char *enonce;
186 	unsigned char *continueflag;
187 	unsigned char *authdata;
188 	unsigned char testhmac[SHA1_DIGEST_SIZE];
189 	unsigned char paramdigest[SHA1_DIGEST_SIZE];
190 	struct sha1_ctx sha_ctx;
191 	unsigned int dlen;
192 	unsigned int dpos;
193 	va_list argp;
194 	int ret;
195 
196 	if (!chip)
197 		return -ENODEV;
198 
199 	bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
200 	tag = LOAD16(buffer, 0);
201 	ordinal = command;
202 	result = LOAD32N(buffer, TPM_RETURN_OFFSET);
203 	if (tag == TPM_TAG_RSP_COMMAND)
204 		return 0;
205 	if (tag != TPM_TAG_RSP_AUTH1_COMMAND)
206 		return -EINVAL;
207 	authdata = buffer + bufsize - SHA1_DIGEST_SIZE;
208 	continueflag = authdata - 1;
209 	enonce = continueflag - TPM_NONCE_SIZE;
210 
211 	sha1_init(&sha_ctx);
212 	sha1_update(&sha_ctx, (const u8 *)&result, sizeof(result));
213 	sha1_update(&sha_ctx, (const u8 *)&ordinal, sizeof(ordinal));
214 	va_start(argp, keylen);
215 	for (;;) {
216 		dlen = va_arg(argp, unsigned int);
217 		if (dlen == 0)
218 			break;
219 		dpos = va_arg(argp, unsigned int);
220 		sha1_update(&sha_ctx, buffer + dpos, dlen);
221 	}
222 	va_end(argp);
223 	sha1_final(&sha_ctx, paramdigest);
224 
225 	ret = TSS_rawhmac(testhmac, key, keylen, SHA1_DIGEST_SIZE, paramdigest,
226 			  TPM_NONCE_SIZE, enonce, TPM_NONCE_SIZE, ononce,
227 			  1, continueflag, 0, 0);
228 	if (ret < 0)
229 		return ret;
230 
231 	if (crypto_memneq(testhmac, authdata, SHA1_DIGEST_SIZE))
232 		return -EINVAL;
233 	return 0;
234 }
235 
236 /*
237  * verify the AUTH2_COMMAND (unseal) result from TPM
238  */
239 static int TSS_checkhmac2(unsigned char *buffer,
240 			  const uint32_t command,
241 			  const unsigned char *ononce,
242 			  const unsigned char *key1,
243 			  unsigned int keylen1,
244 			  const unsigned char *key2,
245 			  unsigned int keylen2, ...)
246 {
247 	uint32_t bufsize;
248 	uint16_t tag;
249 	uint32_t ordinal;
250 	uint32_t result;
251 	unsigned char *enonce1;
252 	unsigned char *continueflag1;
253 	unsigned char *authdata1;
254 	unsigned char *enonce2;
255 	unsigned char *continueflag2;
256 	unsigned char *authdata2;
257 	unsigned char testhmac1[SHA1_DIGEST_SIZE];
258 	unsigned char testhmac2[SHA1_DIGEST_SIZE];
259 	unsigned char paramdigest[SHA1_DIGEST_SIZE];
260 	struct sha1_ctx sha_ctx;
261 	unsigned int dlen;
262 	unsigned int dpos;
263 	va_list argp;
264 	int ret;
265 
266 	bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
267 	tag = LOAD16(buffer, 0);
268 	ordinal = command;
269 	result = LOAD32N(buffer, TPM_RETURN_OFFSET);
270 
271 	if (tag == TPM_TAG_RSP_COMMAND)
272 		return 0;
273 	if (tag != TPM_TAG_RSP_AUTH2_COMMAND)
274 		return -EINVAL;
275 	authdata1 = buffer + bufsize - (SHA1_DIGEST_SIZE + 1
276 			+ SHA1_DIGEST_SIZE + SHA1_DIGEST_SIZE);
277 	authdata2 = buffer + bufsize - (SHA1_DIGEST_SIZE);
278 	continueflag1 = authdata1 - 1;
279 	continueflag2 = authdata2 - 1;
280 	enonce1 = continueflag1 - TPM_NONCE_SIZE;
281 	enonce2 = continueflag2 - TPM_NONCE_SIZE;
282 
283 	sha1_init(&sha_ctx);
284 	sha1_update(&sha_ctx, (const u8 *)&result, sizeof(result));
285 	sha1_update(&sha_ctx, (const u8 *)&ordinal, sizeof(ordinal));
286 
287 	va_start(argp, keylen2);
288 	for (;;) {
289 		dlen = va_arg(argp, unsigned int);
290 		if (dlen == 0)
291 			break;
292 		dpos = va_arg(argp, unsigned int);
293 		sha1_update(&sha_ctx, buffer + dpos, dlen);
294 	}
295 	va_end(argp);
296 	sha1_final(&sha_ctx, paramdigest);
297 
298 	ret = TSS_rawhmac(testhmac1, key1, keylen1, SHA1_DIGEST_SIZE,
299 			  paramdigest, TPM_NONCE_SIZE, enonce1,
300 			  TPM_NONCE_SIZE, ononce, 1, continueflag1, 0, 0);
301 	if (ret < 0)
302 		return ret;
303 	if (crypto_memneq(testhmac1, authdata1, SHA1_DIGEST_SIZE))
304 		return -EINVAL;
305 	ret = TSS_rawhmac(testhmac2, key2, keylen2, SHA1_DIGEST_SIZE,
306 			  paramdigest, TPM_NONCE_SIZE, enonce2,
307 			  TPM_NONCE_SIZE, ononce, 1, continueflag2, 0, 0);
308 	if (ret < 0)
309 		return ret;
310 	if (crypto_memneq(testhmac2, authdata2, SHA1_DIGEST_SIZE))
311 		return -EINVAL;
312 	return 0;
313 }
314 
315 /*
316  * For key specific tpm requests, we will generate and send our
317  * own TPM command packets using the drivers send function.
318  */
319 static int trusted_tpm_send(struct tpm_buf *buf)
320 {
321 	int rc;
322 
323 	if (!chip)
324 		return -ENODEV;
325 
326 	rc = tpm_try_get_ops(chip);
327 	if (rc)
328 		return rc;
329 
330 	dump_tpm_buf(buf->data);
331 	rc = tpm_transmit_cmd(chip, buf, 4, "sending data");
332 	dump_tpm_buf(buf->data);
333 
334 	if (rc > 0)
335 		/* TPM error */
336 		rc = -EPERM;
337 
338 	tpm_put_ops(chip);
339 	return rc;
340 }
341 
342 /*
343  * Lock a trusted key, by extending a selected PCR.
344  *
345  * Prevents a trusted key that is sealed to PCRs from being accessed.
346  * This uses the tpm driver's extend function.
347  */
348 static int pcrlock(const int pcrnum)
349 {
350 	if (!capable(CAP_SYS_ADMIN))
351 		return -EPERM;
352 
353 	return tpm_pcr_extend(chip, pcrnum, digests) ? -EINVAL : 0;
354 }
355 
356 /*
357  * Create an object specific authorisation protocol (OSAP) session
358  */
359 static int osap(struct tpm_buf *tb, struct osapsess *s,
360 		const unsigned char *key, uint16_t type, uint32_t handle)
361 {
362 	unsigned char enonce[TPM_NONCE_SIZE];
363 	unsigned char ononce[TPM_NONCE_SIZE];
364 	int ret;
365 
366 	ret = tpm_get_random(chip, ononce, TPM_NONCE_SIZE);
367 	if (ret < 0)
368 		return ret;
369 
370 	if (ret != TPM_NONCE_SIZE)
371 		return -EIO;
372 
373 	tpm_buf_reset(tb, TPM_TAG_RQU_COMMAND, TPM_ORD_OSAP);
374 	tpm_buf_append_u16(tb, type);
375 	tpm_buf_append_u32(tb, handle);
376 	tpm_buf_append(tb, ononce, TPM_NONCE_SIZE);
377 
378 	ret = trusted_tpm_send(tb);
379 	if (ret < 0)
380 		return ret;
381 
382 	s->handle = LOAD32(tb->data, TPM_DATA_OFFSET);
383 	memcpy(s->enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)]),
384 	       TPM_NONCE_SIZE);
385 	memcpy(enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t) +
386 				  TPM_NONCE_SIZE]), TPM_NONCE_SIZE);
387 	return TSS_rawhmac(s->secret, key, SHA1_DIGEST_SIZE, TPM_NONCE_SIZE,
388 			   enonce, TPM_NONCE_SIZE, ononce, 0, 0);
389 }
390 
391 /*
392  * Create an object independent authorisation protocol (oiap) session
393  */
394 static int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
395 {
396 	int ret;
397 
398 	if (!chip)
399 		return -ENODEV;
400 
401 	tpm_buf_reset(tb, TPM_TAG_RQU_COMMAND, TPM_ORD_OIAP);
402 	ret = trusted_tpm_send(tb);
403 	if (ret < 0)
404 		return ret;
405 
406 	*handle = LOAD32(tb->data, TPM_DATA_OFFSET);
407 	memcpy(nonce, &tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)],
408 	       TPM_NONCE_SIZE);
409 	return 0;
410 }
411 
412 struct tpm_digests {
413 	unsigned char encauth[SHA1_DIGEST_SIZE];
414 	unsigned char pubauth[SHA1_DIGEST_SIZE];
415 	unsigned char xorwork[SHA1_DIGEST_SIZE * 2];
416 	unsigned char xorhash[SHA1_DIGEST_SIZE];
417 	unsigned char nonceodd[TPM_NONCE_SIZE];
418 };
419 
420 /*
421  * Have the TPM seal(encrypt) the trusted key, possibly based on
422  * Platform Configuration Registers (PCRs). AUTH1 for sealing key.
423  */
424 static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
425 		    uint32_t keyhandle, const unsigned char *keyauth,
426 		    const unsigned char *data, uint32_t datalen,
427 		    unsigned char *blob, uint32_t *bloblen,
428 		    const unsigned char *blobauth,
429 		    const unsigned char *pcrinfo, uint32_t pcrinfosize)
430 {
431 	struct osapsess sess;
432 	struct tpm_digests *td;
433 	unsigned char cont;
434 	uint32_t ordinal;
435 	uint32_t pcrsize;
436 	uint32_t datsize;
437 	int sealinfosize;
438 	int encdatasize;
439 	int storedsize;
440 	int ret;
441 	int i;
442 
443 	/* alloc some work space for all the hashes */
444 	td = kmalloc_obj(*td);
445 	if (!td)
446 		return -ENOMEM;
447 
448 	/* get session for sealing key */
449 	ret = osap(tb, &sess, keyauth, keytype, keyhandle);
450 	if (ret < 0)
451 		goto out;
452 	dump_sess(&sess);
453 
454 	/* calculate encrypted authorization value */
455 	memcpy(td->xorwork, sess.secret, SHA1_DIGEST_SIZE);
456 	memcpy(td->xorwork + SHA1_DIGEST_SIZE, sess.enonce, SHA1_DIGEST_SIZE);
457 	sha1(td->xorwork, SHA1_DIGEST_SIZE * 2, td->xorhash);
458 
459 	ret = tpm_get_random(chip, td->nonceodd, TPM_NONCE_SIZE);
460 	if (ret < 0)
461 		goto out;
462 
463 	if (ret != TPM_NONCE_SIZE) {
464 		ret = -EIO;
465 		goto out;
466 	}
467 
468 	ordinal = htonl(TPM_ORD_SEAL);
469 	datsize = htonl(datalen);
470 	pcrsize = htonl(pcrinfosize);
471 	cont = 0;
472 
473 	/* encrypt data authorization key */
474 	for (i = 0; i < SHA1_DIGEST_SIZE; ++i)
475 		td->encauth[i] = td->xorhash[i] ^ blobauth[i];
476 
477 	/* calculate authorization HMAC value */
478 	if (pcrinfosize == 0) {
479 		/* no pcr info specified */
480 		ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
481 				   sess.enonce, td->nonceodd, cont,
482 				   sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
483 				   td->encauth, sizeof(uint32_t), &pcrsize,
484 				   sizeof(uint32_t), &datsize, datalen, data, 0,
485 				   0);
486 	} else {
487 		/* pcr info specified */
488 		ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
489 				   sess.enonce, td->nonceodd, cont,
490 				   sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
491 				   td->encauth, sizeof(uint32_t), &pcrsize,
492 				   pcrinfosize, pcrinfo, sizeof(uint32_t),
493 				   &datsize, datalen, data, 0, 0);
494 	}
495 	if (ret < 0)
496 		goto out;
497 
498 	/* build and send the TPM request packet */
499 	tpm_buf_reset(tb, TPM_TAG_RQU_AUTH1_COMMAND, TPM_ORD_SEAL);
500 	tpm_buf_append_u32(tb, keyhandle);
501 	tpm_buf_append(tb, td->encauth, SHA1_DIGEST_SIZE);
502 	tpm_buf_append_u32(tb, pcrinfosize);
503 	tpm_buf_append(tb, pcrinfo, pcrinfosize);
504 	tpm_buf_append_u32(tb, datalen);
505 	tpm_buf_append(tb, data, datalen);
506 	tpm_buf_append_u32(tb, sess.handle);
507 	tpm_buf_append(tb, td->nonceodd, TPM_NONCE_SIZE);
508 	tpm_buf_append_u8(tb, cont);
509 	tpm_buf_append(tb, td->pubauth, SHA1_DIGEST_SIZE);
510 
511 	ret = trusted_tpm_send(tb);
512 	if (ret < 0)
513 		goto out;
514 
515 	/* calculate the size of the returned Blob */
516 	sealinfosize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t));
517 	encdatasize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t) +
518 			     sizeof(uint32_t) + sealinfosize);
519 	storedsize = sizeof(uint32_t) + sizeof(uint32_t) + sealinfosize +
520 	    sizeof(uint32_t) + encdatasize;
521 
522 	/* check the HMAC in the response */
523 	ret = TSS_checkhmac1(tb->data, ordinal, td->nonceodd, sess.secret,
524 			     SHA1_DIGEST_SIZE, storedsize, TPM_DATA_OFFSET, 0,
525 			     0);
526 
527 	/* copy the returned blob to caller */
528 	if (!ret) {
529 		memcpy(blob, tb->data + TPM_DATA_OFFSET, storedsize);
530 		*bloblen = storedsize;
531 	}
532 out:
533 	kfree_sensitive(td);
534 	return ret;
535 }
536 
537 /*
538  * use the AUTH2_COMMAND form of unseal, to authorize both key and blob
539  */
540 static int tpm_unseal(struct tpm_buf *tb,
541 		      uint32_t keyhandle, const unsigned char *keyauth,
542 		      const unsigned char *blob, int bloblen,
543 		      const unsigned char *blobauth,
544 		      unsigned char *data, unsigned int *datalen)
545 {
546 	unsigned char nonceodd[TPM_NONCE_SIZE];
547 	unsigned char enonce1[TPM_NONCE_SIZE];
548 	unsigned char enonce2[TPM_NONCE_SIZE];
549 	unsigned char authdata1[SHA1_DIGEST_SIZE];
550 	unsigned char authdata2[SHA1_DIGEST_SIZE];
551 	uint32_t authhandle1 = 0;
552 	uint32_t authhandle2 = 0;
553 	unsigned char cont = 0;
554 	uint32_t ordinal;
555 	int ret;
556 
557 	/* sessions for unsealing key and data */
558 	ret = oiap(tb, &authhandle1, enonce1);
559 	if (ret < 0) {
560 		pr_info("oiap failed (%d)\n", ret);
561 		return ret;
562 	}
563 	ret = oiap(tb, &authhandle2, enonce2);
564 	if (ret < 0) {
565 		pr_info("oiap failed (%d)\n", ret);
566 		return ret;
567 	}
568 
569 	ordinal = htonl(TPM_ORD_UNSEAL);
570 	ret = tpm_get_random(chip, nonceodd, TPM_NONCE_SIZE);
571 	if (ret < 0)
572 		return ret;
573 
574 	if (ret != TPM_NONCE_SIZE) {
575 		pr_info("tpm_get_random failed (%d)\n", ret);
576 		return -EIO;
577 	}
578 	ret = TSS_authhmac(authdata1, keyauth, TPM_NONCE_SIZE,
579 			   enonce1, nonceodd, cont, sizeof(uint32_t),
580 			   &ordinal, bloblen, blob, 0, 0);
581 	if (ret < 0)
582 		return ret;
583 	ret = TSS_authhmac(authdata2, blobauth, TPM_NONCE_SIZE,
584 			   enonce2, nonceodd, cont, sizeof(uint32_t),
585 			   &ordinal, bloblen, blob, 0, 0);
586 	if (ret < 0)
587 		return ret;
588 
589 	/* build and send TPM request packet */
590 	tpm_buf_reset(tb, TPM_TAG_RQU_AUTH2_COMMAND, TPM_ORD_UNSEAL);
591 	tpm_buf_append_u32(tb, keyhandle);
592 	tpm_buf_append(tb, blob, bloblen);
593 	tpm_buf_append_u32(tb, authhandle1);
594 	tpm_buf_append(tb, nonceodd, TPM_NONCE_SIZE);
595 	tpm_buf_append_u8(tb, cont);
596 	tpm_buf_append(tb, authdata1, SHA1_DIGEST_SIZE);
597 	tpm_buf_append_u32(tb, authhandle2);
598 	tpm_buf_append(tb, nonceodd, TPM_NONCE_SIZE);
599 	tpm_buf_append_u8(tb, cont);
600 	tpm_buf_append(tb, authdata2, SHA1_DIGEST_SIZE);
601 
602 	ret = trusted_tpm_send(tb);
603 	if (ret < 0) {
604 		pr_info("authhmac failed (%d)\n", ret);
605 		return ret;
606 	}
607 
608 	*datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
609 	ret = TSS_checkhmac2(tb->data, ordinal, nonceodd,
610 			     keyauth, SHA1_DIGEST_SIZE,
611 			     blobauth, SHA1_DIGEST_SIZE,
612 			     sizeof(uint32_t), TPM_DATA_OFFSET,
613 			     *datalen, TPM_DATA_OFFSET + sizeof(uint32_t), 0,
614 			     0);
615 	if (ret < 0) {
616 		pr_info("TSS_checkhmac2 failed (%d)\n", ret);
617 		return ret;
618 	}
619 	memcpy(data, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t), *datalen);
620 	return 0;
621 }
622 
623 /*
624  * Have the TPM seal(encrypt) the symmetric key
625  */
626 static int key_seal(struct trusted_key_payload *p,
627 		    struct trusted_key_options *o)
628 {
629 	int ret;
630 
631 	struct tpm_buf *tb __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
632 	if (!tb)
633 		return -ENOMEM;
634 
635 	tpm_buf_init(tb, TPM_BUFSIZE);
636 
637 	/* include migratable flag at end of sealed key */
638 	p->key[p->key_len] = p->migratable;
639 
640 	ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
641 		       p->key, p->key_len + 1, p->blob, &p->blob_len,
642 		       o->blobauth, o->pcrinfo, o->pcrinfo_len);
643 	if (ret < 0)
644 		pr_info("srkseal failed (%d)\n", ret);
645 
646 	return ret;
647 }
648 
649 /*
650  * Have the TPM unseal(decrypt) the symmetric key
651  */
652 static int key_unseal(struct trusted_key_payload *p,
653 		      struct trusted_key_options *o)
654 {
655 	int ret;
656 
657 	struct tpm_buf *tb __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
658 	if (!tb)
659 		return -ENOMEM;
660 
661 	tpm_buf_init(tb, TPM_BUFSIZE);
662 
663 	ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
664 			 o->blobauth, p->key, &p->key_len);
665 	if (ret < 0)
666 		pr_info("srkunseal failed (%d)\n", ret);
667 	else
668 		/* pull migratable flag out of sealed key */
669 		p->migratable = p->key[--p->key_len];
670 
671 	return ret;
672 }
673 
674 enum {
675 	Opt_err,
676 	Opt_keyhandle, Opt_keyauth, Opt_blobauth,
677 	Opt_pcrinfo, Opt_pcrlock, Opt_migratable,
678 	Opt_hash,
679 	Opt_policydigest,
680 	Opt_policyhandle,
681 };
682 
683 static const match_table_t key_tokens = {
684 	{Opt_keyhandle, "keyhandle=%s"},
685 	{Opt_keyauth, "keyauth=%s"},
686 	{Opt_blobauth, "blobauth=%s"},
687 	{Opt_pcrinfo, "pcrinfo=%s"},
688 	{Opt_pcrlock, "pcrlock=%s"},
689 	{Opt_migratable, "migratable=%s"},
690 	{Opt_hash, "hash=%s"},
691 	{Opt_policydigest, "policydigest=%s"},
692 	{Opt_policyhandle, "policyhandle=%s"},
693 	{Opt_err, NULL}
694 };
695 
696 /* can have zero or more token= options */
697 static int getoptions(char *c, struct trusted_key_payload *pay,
698 		      struct trusted_key_options *opt)
699 {
700 	substring_t args[MAX_OPT_ARGS];
701 	char *p = c;
702 	int token;
703 	int res;
704 	unsigned long handle;
705 	unsigned long lock;
706 	unsigned long token_mask = 0;
707 	unsigned int digest_len;
708 	int i;
709 	int tpm2;
710 
711 	tpm2 = tpm_is_tpm2(chip);
712 	if (tpm2 < 0)
713 		return tpm2;
714 
715 	opt->hash = tpm2 ? HASH_ALGO_SHA256 : HASH_ALGO_SHA1;
716 
717 	if (!c)
718 		return 0;
719 
720 	while ((p = strsep(&c, " \t"))) {
721 		if (*p == '\0' || *p == ' ' || *p == '\t')
722 			continue;
723 		token = match_token(p, key_tokens, args);
724 		if (test_and_set_bit(token, &token_mask))
725 			return -EINVAL;
726 
727 		switch (token) {
728 		case Opt_pcrinfo:
729 			opt->pcrinfo_len = strlen(args[0].from) / 2;
730 			if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
731 				return -EINVAL;
732 			res = hex2bin(opt->pcrinfo, args[0].from,
733 				      opt->pcrinfo_len);
734 			if (res < 0)
735 				return -EINVAL;
736 			break;
737 		case Opt_keyhandle:
738 			res = kstrtoul(args[0].from, 16, &handle);
739 			if (res < 0)
740 				return -EINVAL;
741 			opt->keytype = SEAL_keytype;
742 			opt->keyhandle = handle;
743 			break;
744 		case Opt_keyauth:
745 			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
746 				return -EINVAL;
747 			res = hex2bin(opt->keyauth, args[0].from,
748 				      SHA1_DIGEST_SIZE);
749 			if (res < 0)
750 				return -EINVAL;
751 			break;
752 		case Opt_blobauth:
753 			/*
754 			 * TPM 1.2 authorizations are sha1 hashes passed in as
755 			 * hex strings.  TPM 2.0 authorizations are simple
756 			 * passwords (although it can take a hash as well)
757 			 */
758 			opt->blobauth_len = strlen(args[0].from);
759 
760 			if (opt->blobauth_len == 2 * TPM_DIGEST_SIZE) {
761 				res = hex2bin(opt->blobauth, args[0].from,
762 					      TPM_DIGEST_SIZE);
763 				if (res < 0)
764 					return -EINVAL;
765 
766 				opt->blobauth_len = TPM_DIGEST_SIZE;
767 				break;
768 			}
769 
770 			if (tpm2 && opt->blobauth_len <= sizeof(opt->blobauth)) {
771 				memcpy(opt->blobauth, args[0].from,
772 				       opt->blobauth_len);
773 				break;
774 			}
775 
776 			return -EINVAL;
777 
778 			break;
779 
780 		case Opt_migratable:
781 			if (*args[0].from == '0')
782 				pay->migratable = 0;
783 			else if (*args[0].from != '1')
784 				return -EINVAL;
785 			break;
786 		case Opt_pcrlock:
787 			res = kstrtoul(args[0].from, 10, &lock);
788 			if (res < 0)
789 				return -EINVAL;
790 			opt->pcrlock = lock;
791 			break;
792 		case Opt_hash:
793 			if (test_bit(Opt_policydigest, &token_mask))
794 				return -EINVAL;
795 			for (i = 0; i < HASH_ALGO__LAST; i++) {
796 				if (!strcmp(args[0].from, hash_algo_name[i])) {
797 					opt->hash = i;
798 					break;
799 				}
800 			}
801 			if (i == HASH_ALGO__LAST)
802 				return -EINVAL;
803 			if  (!tpm2 && i != HASH_ALGO_SHA1) {
804 				pr_info("TPM 1.x only supports SHA-1.\n");
805 				return -EINVAL;
806 			}
807 			break;
808 		case Opt_policydigest:
809 			digest_len = hash_digest_size[opt->hash];
810 			if (!tpm2 || strlen(args[0].from) != (2 * digest_len))
811 				return -EINVAL;
812 			res = hex2bin(opt->policydigest, args[0].from,
813 				      digest_len);
814 			if (res < 0)
815 				return -EINVAL;
816 			opt->policydigest_len = digest_len;
817 			break;
818 		case Opt_policyhandle:
819 			if (!tpm2)
820 				return -EINVAL;
821 			res = kstrtoul(args[0].from, 16, &handle);
822 			if (res < 0)
823 				return -EINVAL;
824 			opt->policyhandle = handle;
825 			break;
826 		default:
827 			return -EINVAL;
828 		}
829 	}
830 	return 0;
831 }
832 
833 static struct trusted_key_options *trusted_options_alloc(void)
834 {
835 	struct trusted_key_options *options;
836 	int tpm2;
837 
838 	tpm2 = tpm_is_tpm2(chip);
839 	if (tpm2 < 0)
840 		return NULL;
841 
842 	options = kzalloc_obj(*options);
843 	if (options) {
844 		/* set any non-zero defaults */
845 		options->keytype = SRK_keytype;
846 
847 		if (!tpm2)
848 			options->keyhandle = SRKHANDLE;
849 	}
850 	return options;
851 }
852 
853 static int trusted_tpm_seal(struct trusted_key_payload *p, char *datablob)
854 {
855 	struct trusted_key_options *options = NULL;
856 	int ret = 0;
857 	int tpm2;
858 
859 	tpm2 = tpm_is_tpm2(chip);
860 	if (tpm2 < 0)
861 		return tpm2;
862 
863 	options = trusted_options_alloc();
864 	if (!options)
865 		return -ENOMEM;
866 
867 	ret = getoptions(datablob, p, options);
868 	if (ret < 0)
869 		goto out;
870 	dump_options(options);
871 
872 	if (!options->keyhandle && !tpm2) {
873 		ret = -EINVAL;
874 		goto out;
875 	}
876 
877 	if (tpm2)
878 		ret = tpm2_seal_trusted(chip, p, options);
879 	else
880 		ret = key_seal(p, options);
881 	if (ret < 0) {
882 		pr_info("key_seal failed (%d)\n", ret);
883 		goto out;
884 	}
885 
886 	if (options->pcrlock) {
887 		ret = pcrlock(options->pcrlock);
888 		if (ret < 0) {
889 			pr_info("pcrlock failed (%d)\n", ret);
890 			goto out;
891 		}
892 	}
893 out:
894 	kfree_sensitive(options);
895 	return ret;
896 }
897 
898 static int trusted_tpm_unseal(struct trusted_key_payload *p, char *datablob)
899 {
900 	struct trusted_key_options *options = NULL;
901 	int ret = 0;
902 	int tpm2;
903 
904 	tpm2 = tpm_is_tpm2(chip);
905 	if (tpm2 < 0)
906 		return tpm2;
907 
908 	options = trusted_options_alloc();
909 	if (!options)
910 		return -ENOMEM;
911 
912 	ret = getoptions(datablob, p, options);
913 	if (ret < 0)
914 		goto out;
915 	dump_options(options);
916 
917 	if (!options->keyhandle && !tpm2) {
918 		ret = -EINVAL;
919 		goto out;
920 	}
921 
922 	if (tpm2)
923 		ret = tpm2_unseal_trusted(chip, p, options);
924 	else
925 		ret = key_unseal(p, options);
926 	if (ret < 0)
927 		pr_info("key_unseal failed (%d)\n", ret);
928 
929 	if (options->pcrlock) {
930 		ret = pcrlock(options->pcrlock);
931 		if (ret < 0) {
932 			pr_info("pcrlock failed (%d)\n", ret);
933 			goto out;
934 		}
935 	}
936 out:
937 	kfree_sensitive(options);
938 	return ret;
939 }
940 
941 static int trusted_tpm_get_random(unsigned char *key, size_t key_len)
942 {
943 	return tpm_get_random(chip, key, key_len);
944 }
945 
946 static int __init init_digests(void)
947 {
948 	int i;
949 
950 	digests = kzalloc_objs(*digests, chip->nr_allocated_banks);
951 	if (!digests)
952 		return -ENOMEM;
953 
954 	for (i = 0; i < chip->nr_allocated_banks; i++)
955 		digests[i].alg_id = chip->allocated_banks[i].alg_id;
956 
957 	return 0;
958 }
959 
960 static int __init trusted_tpm_init(void)
961 {
962 	int ret;
963 
964 	chip = tpm_default_chip();
965 	if (!chip)
966 		return -ENODEV;
967 
968 	ret = init_digests();
969 	if (ret < 0)
970 		goto err_put;
971 	ret = register_key_type(&key_type_trusted);
972 	if (ret < 0)
973 		goto err_free;
974 	return 0;
975 err_free:
976 	kfree(digests);
977 err_put:
978 	put_device(&chip->dev);
979 	return ret;
980 }
981 
982 static void trusted_tpm_exit(void)
983 {
984 	if (chip) {
985 		unregister_key_type(&key_type_trusted);
986 		put_device(&chip->dev);
987 		kfree(digests);
988 	}
989 }
990 
991 struct trusted_key_ops trusted_key_tpm_ops = {
992 	.migratable = 1, /* migratable by default */
993 	.init = trusted_tpm_init,
994 	.seal = trusted_tpm_seal,
995 	.unseal = trusted_tpm_unseal,
996 	.get_random = trusted_tpm_get_random,
997 	.exit = trusted_tpm_exit,
998 };
999