1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2010 IBM Corporation
4  *
5  * Author:
6  * David Safford <safford@us.ibm.com>
7  *
8  * See Documentation/security/keys/trusted-encrypted.rst
9  */
10 
11 #include <crypto/hash_info.h>
12 #include <linux/uaccess.h>
13 #include <linux/module.h>
14 #include <linux/init.h>
15 #include <linux/slab.h>
16 #include <linux/parser.h>
17 #include <linux/string.h>
18 #include <linux/err.h>
19 #include <keys/user-type.h>
20 #include <keys/trusted-type.h>
21 #include <linux/key-type.h>
22 #include <linux/rcupdate.h>
23 #include <linux/crypto.h>
24 #include <crypto/hash.h>
25 #include <crypto/sha1.h>
26 #include <linux/capability.h>
27 #include <linux/tpm.h>
28 #include <linux/tpm_command.h>
29 
30 #include <keys/trusted_tpm.h>
31 
32 static const char hmac_alg[] = "hmac(sha1)";
33 static const char hash_alg[] = "sha1";
34 static struct tpm_chip *chip;
35 static struct tpm_digest *digests;
36 
37 struct sdesc {
38 	struct shash_desc shash;
39 	char ctx[];
40 };
41 
42 static struct crypto_shash *hashalg;
43 static struct crypto_shash *hmacalg;
44 
45 static struct sdesc *init_sdesc(struct crypto_shash *alg)
46 {
47 	struct sdesc *sdesc;
48 	int size;
49 
50 	size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
51 	sdesc = kmalloc(size, GFP_KERNEL);
52 	if (!sdesc)
53 		return ERR_PTR(-ENOMEM);
54 	sdesc->shash.tfm = alg;
55 	return sdesc;
56 }
57 
58 static int TSS_sha1(const unsigned char *data, unsigned int datalen,
59 		    unsigned char *digest)
60 {
61 	struct sdesc *sdesc;
62 	int ret;
63 
64 	sdesc = init_sdesc(hashalg);
65 	if (IS_ERR(sdesc)) {
66 		pr_info("trusted_key: can't alloc %s\n", hash_alg);
67 		return PTR_ERR(sdesc);
68 	}
69 
70 	ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
71 	kfree_sensitive(sdesc);
72 	return ret;
73 }
74 
75 static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
76 		       unsigned int keylen, ...)
77 {
78 	struct sdesc *sdesc;
79 	va_list argp;
80 	unsigned int dlen;
81 	unsigned char *data;
82 	int ret;
83 
84 	sdesc = init_sdesc(hmacalg);
85 	if (IS_ERR(sdesc)) {
86 		pr_info("trusted_key: can't alloc %s\n", hmac_alg);
87 		return PTR_ERR(sdesc);
88 	}
89 
90 	ret = crypto_shash_setkey(hmacalg, key, keylen);
91 	if (ret < 0)
92 		goto out;
93 	ret = crypto_shash_init(&sdesc->shash);
94 	if (ret < 0)
95 		goto out;
96 
97 	va_start(argp, keylen);
98 	for (;;) {
99 		dlen = va_arg(argp, unsigned int);
100 		if (dlen == 0)
101 			break;
102 		data = va_arg(argp, unsigned char *);
103 		if (data == NULL) {
104 			ret = -EINVAL;
105 			break;
106 		}
107 		ret = crypto_shash_update(&sdesc->shash, data, dlen);
108 		if (ret < 0)
109 			break;
110 	}
111 	va_end(argp);
112 	if (!ret)
113 		ret = crypto_shash_final(&sdesc->shash, digest);
114 out:
115 	kfree_sensitive(sdesc);
116 	return ret;
117 }
118 
119 /*
120  * calculate authorization info fields to send to TPM
121  */
122 int TSS_authhmac(unsigned char *digest, const unsigned char *key,
123 			unsigned int keylen, unsigned char *h1,
124 			unsigned char *h2, unsigned int h3, ...)
125 {
126 	unsigned char paramdigest[SHA1_DIGEST_SIZE];
127 	struct sdesc *sdesc;
128 	unsigned int dlen;
129 	unsigned char *data;
130 	unsigned char c;
131 	int ret;
132 	va_list argp;
133 
134 	if (!chip)
135 		return -ENODEV;
136 
137 	sdesc = init_sdesc(hashalg);
138 	if (IS_ERR(sdesc)) {
139 		pr_info("trusted_key: can't alloc %s\n", hash_alg);
140 		return PTR_ERR(sdesc);
141 	}
142 
143 	c = !!h3;
144 	ret = crypto_shash_init(&sdesc->shash);
145 	if (ret < 0)
146 		goto out;
147 	va_start(argp, h3);
148 	for (;;) {
149 		dlen = va_arg(argp, unsigned int);
150 		if (dlen == 0)
151 			break;
152 		data = va_arg(argp, unsigned char *);
153 		if (!data) {
154 			ret = -EINVAL;
155 			break;
156 		}
157 		ret = crypto_shash_update(&sdesc->shash, data, dlen);
158 		if (ret < 0)
159 			break;
160 	}
161 	va_end(argp);
162 	if (!ret)
163 		ret = crypto_shash_final(&sdesc->shash, paramdigest);
164 	if (!ret)
165 		ret = TSS_rawhmac(digest, key, keylen, SHA1_DIGEST_SIZE,
166 				  paramdigest, TPM_NONCE_SIZE, h1,
167 				  TPM_NONCE_SIZE, h2, 1, &c, 0, 0);
168 out:
169 	kfree_sensitive(sdesc);
170 	return ret;
171 }
172 EXPORT_SYMBOL_GPL(TSS_authhmac);
173 
174 /*
175  * verify the AUTH1_COMMAND (Seal) result from TPM
176  */
177 int TSS_checkhmac1(unsigned char *buffer,
178 			  const uint32_t command,
179 			  const unsigned char *ononce,
180 			  const unsigned char *key,
181 			  unsigned int keylen, ...)
182 {
183 	uint32_t bufsize;
184 	uint16_t tag;
185 	uint32_t ordinal;
186 	uint32_t result;
187 	unsigned char *enonce;
188 	unsigned char *continueflag;
189 	unsigned char *authdata;
190 	unsigned char testhmac[SHA1_DIGEST_SIZE];
191 	unsigned char paramdigest[SHA1_DIGEST_SIZE];
192 	struct sdesc *sdesc;
193 	unsigned int dlen;
194 	unsigned int dpos;
195 	va_list argp;
196 	int ret;
197 
198 	if (!chip)
199 		return -ENODEV;
200 
201 	bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
202 	tag = LOAD16(buffer, 0);
203 	ordinal = command;
204 	result = LOAD32N(buffer, TPM_RETURN_OFFSET);
205 	if (tag == TPM_TAG_RSP_COMMAND)
206 		return 0;
207 	if (tag != TPM_TAG_RSP_AUTH1_COMMAND)
208 		return -EINVAL;
209 	authdata = buffer + bufsize - SHA1_DIGEST_SIZE;
210 	continueflag = authdata - 1;
211 	enonce = continueflag - TPM_NONCE_SIZE;
212 
213 	sdesc = init_sdesc(hashalg);
214 	if (IS_ERR(sdesc)) {
215 		pr_info("trusted_key: can't alloc %s\n", hash_alg);
216 		return PTR_ERR(sdesc);
217 	}
218 	ret = crypto_shash_init(&sdesc->shash);
219 	if (ret < 0)
220 		goto out;
221 	ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
222 				  sizeof result);
223 	if (ret < 0)
224 		goto out;
225 	ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
226 				  sizeof ordinal);
227 	if (ret < 0)
228 		goto out;
229 	va_start(argp, keylen);
230 	for (;;) {
231 		dlen = va_arg(argp, unsigned int);
232 		if (dlen == 0)
233 			break;
234 		dpos = va_arg(argp, unsigned int);
235 		ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
236 		if (ret < 0)
237 			break;
238 	}
239 	va_end(argp);
240 	if (!ret)
241 		ret = crypto_shash_final(&sdesc->shash, paramdigest);
242 	if (ret < 0)
243 		goto out;
244 
245 	ret = TSS_rawhmac(testhmac, key, keylen, SHA1_DIGEST_SIZE, paramdigest,
246 			  TPM_NONCE_SIZE, enonce, TPM_NONCE_SIZE, ononce,
247 			  1, continueflag, 0, 0);
248 	if (ret < 0)
249 		goto out;
250 
251 	if (memcmp(testhmac, authdata, SHA1_DIGEST_SIZE))
252 		ret = -EINVAL;
253 out:
254 	kfree_sensitive(sdesc);
255 	return ret;
256 }
257 EXPORT_SYMBOL_GPL(TSS_checkhmac1);
258 
259 /*
260  * verify the AUTH2_COMMAND (unseal) result from TPM
261  */
262 static int TSS_checkhmac2(unsigned char *buffer,
263 			  const uint32_t command,
264 			  const unsigned char *ononce,
265 			  const unsigned char *key1,
266 			  unsigned int keylen1,
267 			  const unsigned char *key2,
268 			  unsigned int keylen2, ...)
269 {
270 	uint32_t bufsize;
271 	uint16_t tag;
272 	uint32_t ordinal;
273 	uint32_t result;
274 	unsigned char *enonce1;
275 	unsigned char *continueflag1;
276 	unsigned char *authdata1;
277 	unsigned char *enonce2;
278 	unsigned char *continueflag2;
279 	unsigned char *authdata2;
280 	unsigned char testhmac1[SHA1_DIGEST_SIZE];
281 	unsigned char testhmac2[SHA1_DIGEST_SIZE];
282 	unsigned char paramdigest[SHA1_DIGEST_SIZE];
283 	struct sdesc *sdesc;
284 	unsigned int dlen;
285 	unsigned int dpos;
286 	va_list argp;
287 	int ret;
288 
289 	bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
290 	tag = LOAD16(buffer, 0);
291 	ordinal = command;
292 	result = LOAD32N(buffer, TPM_RETURN_OFFSET);
293 
294 	if (tag == TPM_TAG_RSP_COMMAND)
295 		return 0;
296 	if (tag != TPM_TAG_RSP_AUTH2_COMMAND)
297 		return -EINVAL;
298 	authdata1 = buffer + bufsize - (SHA1_DIGEST_SIZE + 1
299 			+ SHA1_DIGEST_SIZE + SHA1_DIGEST_SIZE);
300 	authdata2 = buffer + bufsize - (SHA1_DIGEST_SIZE);
301 	continueflag1 = authdata1 - 1;
302 	continueflag2 = authdata2 - 1;
303 	enonce1 = continueflag1 - TPM_NONCE_SIZE;
304 	enonce2 = continueflag2 - TPM_NONCE_SIZE;
305 
306 	sdesc = init_sdesc(hashalg);
307 	if (IS_ERR(sdesc)) {
308 		pr_info("trusted_key: can't alloc %s\n", hash_alg);
309 		return PTR_ERR(sdesc);
310 	}
311 	ret = crypto_shash_init(&sdesc->shash);
312 	if (ret < 0)
313 		goto out;
314 	ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
315 				  sizeof result);
316 	if (ret < 0)
317 		goto out;
318 	ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
319 				  sizeof ordinal);
320 	if (ret < 0)
321 		goto out;
322 
323 	va_start(argp, keylen2);
324 	for (;;) {
325 		dlen = va_arg(argp, unsigned int);
326 		if (dlen == 0)
327 			break;
328 		dpos = va_arg(argp, unsigned int);
329 		ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
330 		if (ret < 0)
331 			break;
332 	}
333 	va_end(argp);
334 	if (!ret)
335 		ret = crypto_shash_final(&sdesc->shash, paramdigest);
336 	if (ret < 0)
337 		goto out;
338 
339 	ret = TSS_rawhmac(testhmac1, key1, keylen1, SHA1_DIGEST_SIZE,
340 			  paramdigest, TPM_NONCE_SIZE, enonce1,
341 			  TPM_NONCE_SIZE, ononce, 1, continueflag1, 0, 0);
342 	if (ret < 0)
343 		goto out;
344 	if (memcmp(testhmac1, authdata1, SHA1_DIGEST_SIZE)) {
345 		ret = -EINVAL;
346 		goto out;
347 	}
348 	ret = TSS_rawhmac(testhmac2, key2, keylen2, SHA1_DIGEST_SIZE,
349 			  paramdigest, TPM_NONCE_SIZE, enonce2,
350 			  TPM_NONCE_SIZE, ononce, 1, continueflag2, 0, 0);
351 	if (ret < 0)
352 		goto out;
353 	if (memcmp(testhmac2, authdata2, SHA1_DIGEST_SIZE))
354 		ret = -EINVAL;
355 out:
356 	kfree_sensitive(sdesc);
357 	return ret;
358 }
359 
360 /*
361  * For key specific tpm requests, we will generate and send our
362  * own TPM command packets using the drivers send function.
363  */
364 int trusted_tpm_send(unsigned char *cmd, size_t buflen)
365 {
366 	int rc;
367 
368 	if (!chip)
369 		return -ENODEV;
370 
371 	dump_tpm_buf(cmd);
372 	rc = tpm_send(chip, cmd, buflen);
373 	dump_tpm_buf(cmd);
374 	if (rc > 0)
375 		/* Can't return positive return codes values to keyctl */
376 		rc = -EPERM;
377 	return rc;
378 }
379 EXPORT_SYMBOL_GPL(trusted_tpm_send);
380 
381 /*
382  * Lock a trusted key, by extending a selected PCR.
383  *
384  * Prevents a trusted key that is sealed to PCRs from being accessed.
385  * This uses the tpm driver's extend function.
386  */
387 static int pcrlock(const int pcrnum)
388 {
389 	if (!capable(CAP_SYS_ADMIN))
390 		return -EPERM;
391 
392 	return tpm_pcr_extend(chip, pcrnum, digests) ? -EINVAL : 0;
393 }
394 
395 /*
396  * Create an object specific authorisation protocol (OSAP) session
397  */
398 static int osap(struct tpm_buf *tb, struct osapsess *s,
399 		const unsigned char *key, uint16_t type, uint32_t handle)
400 {
401 	unsigned char enonce[TPM_NONCE_SIZE];
402 	unsigned char ononce[TPM_NONCE_SIZE];
403 	int ret;
404 
405 	ret = tpm_get_random(chip, ononce, TPM_NONCE_SIZE);
406 	if (ret < 0)
407 		return ret;
408 
409 	if (ret != TPM_NONCE_SIZE)
410 		return -EIO;
411 
412 	tpm_buf_reset(tb, TPM_TAG_RQU_COMMAND, TPM_ORD_OSAP);
413 	tpm_buf_append_u16(tb, type);
414 	tpm_buf_append_u32(tb, handle);
415 	tpm_buf_append(tb, ononce, TPM_NONCE_SIZE);
416 
417 	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
418 	if (ret < 0)
419 		return ret;
420 
421 	s->handle = LOAD32(tb->data, TPM_DATA_OFFSET);
422 	memcpy(s->enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)]),
423 	       TPM_NONCE_SIZE);
424 	memcpy(enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t) +
425 				  TPM_NONCE_SIZE]), TPM_NONCE_SIZE);
426 	return TSS_rawhmac(s->secret, key, SHA1_DIGEST_SIZE, TPM_NONCE_SIZE,
427 			   enonce, TPM_NONCE_SIZE, ononce, 0, 0);
428 }
429 
430 /*
431  * Create an object independent authorisation protocol (oiap) session
432  */
433 int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
434 {
435 	int ret;
436 
437 	if (!chip)
438 		return -ENODEV;
439 
440 	tpm_buf_reset(tb, TPM_TAG_RQU_COMMAND, TPM_ORD_OIAP);
441 	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
442 	if (ret < 0)
443 		return ret;
444 
445 	*handle = LOAD32(tb->data, TPM_DATA_OFFSET);
446 	memcpy(nonce, &tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)],
447 	       TPM_NONCE_SIZE);
448 	return 0;
449 }
450 EXPORT_SYMBOL_GPL(oiap);
451 
452 struct tpm_digests {
453 	unsigned char encauth[SHA1_DIGEST_SIZE];
454 	unsigned char pubauth[SHA1_DIGEST_SIZE];
455 	unsigned char xorwork[SHA1_DIGEST_SIZE * 2];
456 	unsigned char xorhash[SHA1_DIGEST_SIZE];
457 	unsigned char nonceodd[TPM_NONCE_SIZE];
458 };
459 
460 /*
461  * Have the TPM seal(encrypt) the trusted key, possibly based on
462  * Platform Configuration Registers (PCRs). AUTH1 for sealing key.
463  */
464 static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
465 		    uint32_t keyhandle, const unsigned char *keyauth,
466 		    const unsigned char *data, uint32_t datalen,
467 		    unsigned char *blob, uint32_t *bloblen,
468 		    const unsigned char *blobauth,
469 		    const unsigned char *pcrinfo, uint32_t pcrinfosize)
470 {
471 	struct osapsess sess;
472 	struct tpm_digests *td;
473 	unsigned char cont;
474 	uint32_t ordinal;
475 	uint32_t pcrsize;
476 	uint32_t datsize;
477 	int sealinfosize;
478 	int encdatasize;
479 	int storedsize;
480 	int ret;
481 	int i;
482 
483 	/* alloc some work space for all the hashes */
484 	td = kmalloc(sizeof *td, GFP_KERNEL);
485 	if (!td)
486 		return -ENOMEM;
487 
488 	/* get session for sealing key */
489 	ret = osap(tb, &sess, keyauth, keytype, keyhandle);
490 	if (ret < 0)
491 		goto out;
492 	dump_sess(&sess);
493 
494 	/* calculate encrypted authorization value */
495 	memcpy(td->xorwork, sess.secret, SHA1_DIGEST_SIZE);
496 	memcpy(td->xorwork + SHA1_DIGEST_SIZE, sess.enonce, SHA1_DIGEST_SIZE);
497 	ret = TSS_sha1(td->xorwork, SHA1_DIGEST_SIZE * 2, td->xorhash);
498 	if (ret < 0)
499 		goto out;
500 
501 	ret = tpm_get_random(chip, td->nonceodd, TPM_NONCE_SIZE);
502 	if (ret < 0)
503 		return ret;
504 
505 	if (ret != TPM_NONCE_SIZE)
506 		return -EIO;
507 
508 	ordinal = htonl(TPM_ORD_SEAL);
509 	datsize = htonl(datalen);
510 	pcrsize = htonl(pcrinfosize);
511 	cont = 0;
512 
513 	/* encrypt data authorization key */
514 	for (i = 0; i < SHA1_DIGEST_SIZE; ++i)
515 		td->encauth[i] = td->xorhash[i] ^ blobauth[i];
516 
517 	/* calculate authorization HMAC value */
518 	if (pcrinfosize == 0) {
519 		/* no pcr info specified */
520 		ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
521 				   sess.enonce, td->nonceodd, cont,
522 				   sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
523 				   td->encauth, sizeof(uint32_t), &pcrsize,
524 				   sizeof(uint32_t), &datsize, datalen, data, 0,
525 				   0);
526 	} else {
527 		/* pcr info specified */
528 		ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
529 				   sess.enonce, td->nonceodd, cont,
530 				   sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
531 				   td->encauth, sizeof(uint32_t), &pcrsize,
532 				   pcrinfosize, pcrinfo, sizeof(uint32_t),
533 				   &datsize, datalen, data, 0, 0);
534 	}
535 	if (ret < 0)
536 		goto out;
537 
538 	/* build and send the TPM request packet */
539 	tpm_buf_reset(tb, TPM_TAG_RQU_AUTH1_COMMAND, TPM_ORD_SEAL);
540 	tpm_buf_append_u32(tb, keyhandle);
541 	tpm_buf_append(tb, td->encauth, SHA1_DIGEST_SIZE);
542 	tpm_buf_append_u32(tb, pcrinfosize);
543 	tpm_buf_append(tb, pcrinfo, pcrinfosize);
544 	tpm_buf_append_u32(tb, datalen);
545 	tpm_buf_append(tb, data, datalen);
546 	tpm_buf_append_u32(tb, sess.handle);
547 	tpm_buf_append(tb, td->nonceodd, TPM_NONCE_SIZE);
548 	tpm_buf_append_u8(tb, cont);
549 	tpm_buf_append(tb, td->pubauth, SHA1_DIGEST_SIZE);
550 
551 	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
552 	if (ret < 0)
553 		goto out;
554 
555 	/* calculate the size of the returned Blob */
556 	sealinfosize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t));
557 	encdatasize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t) +
558 			     sizeof(uint32_t) + sealinfosize);
559 	storedsize = sizeof(uint32_t) + sizeof(uint32_t) + sealinfosize +
560 	    sizeof(uint32_t) + encdatasize;
561 
562 	/* check the HMAC in the response */
563 	ret = TSS_checkhmac1(tb->data, ordinal, td->nonceodd, sess.secret,
564 			     SHA1_DIGEST_SIZE, storedsize, TPM_DATA_OFFSET, 0,
565 			     0);
566 
567 	/* copy the returned blob to caller */
568 	if (!ret) {
569 		memcpy(blob, tb->data + TPM_DATA_OFFSET, storedsize);
570 		*bloblen = storedsize;
571 	}
572 out:
573 	kfree_sensitive(td);
574 	return ret;
575 }
576 
577 /*
578  * use the AUTH2_COMMAND form of unseal, to authorize both key and blob
579  */
580 static int tpm_unseal(struct tpm_buf *tb,
581 		      uint32_t keyhandle, const unsigned char *keyauth,
582 		      const unsigned char *blob, int bloblen,
583 		      const unsigned char *blobauth,
584 		      unsigned char *data, unsigned int *datalen)
585 {
586 	unsigned char nonceodd[TPM_NONCE_SIZE];
587 	unsigned char enonce1[TPM_NONCE_SIZE];
588 	unsigned char enonce2[TPM_NONCE_SIZE];
589 	unsigned char authdata1[SHA1_DIGEST_SIZE];
590 	unsigned char authdata2[SHA1_DIGEST_SIZE];
591 	uint32_t authhandle1 = 0;
592 	uint32_t authhandle2 = 0;
593 	unsigned char cont = 0;
594 	uint32_t ordinal;
595 	int ret;
596 
597 	/* sessions for unsealing key and data */
598 	ret = oiap(tb, &authhandle1, enonce1);
599 	if (ret < 0) {
600 		pr_info("trusted_key: oiap failed (%d)\n", ret);
601 		return ret;
602 	}
603 	ret = oiap(tb, &authhandle2, enonce2);
604 	if (ret < 0) {
605 		pr_info("trusted_key: oiap failed (%d)\n", ret);
606 		return ret;
607 	}
608 
609 	ordinal = htonl(TPM_ORD_UNSEAL);
610 	ret = tpm_get_random(chip, nonceodd, TPM_NONCE_SIZE);
611 	if (ret < 0)
612 		return ret;
613 
614 	if (ret != TPM_NONCE_SIZE) {
615 		pr_info("trusted_key: tpm_get_random failed (%d)\n", ret);
616 		return -EIO;
617 	}
618 	ret = TSS_authhmac(authdata1, keyauth, TPM_NONCE_SIZE,
619 			   enonce1, nonceodd, cont, sizeof(uint32_t),
620 			   &ordinal, bloblen, blob, 0, 0);
621 	if (ret < 0)
622 		return ret;
623 	ret = TSS_authhmac(authdata2, blobauth, TPM_NONCE_SIZE,
624 			   enonce2, nonceodd, cont, sizeof(uint32_t),
625 			   &ordinal, bloblen, blob, 0, 0);
626 	if (ret < 0)
627 		return ret;
628 
629 	/* build and send TPM request packet */
630 	tpm_buf_reset(tb, TPM_TAG_RQU_AUTH2_COMMAND, TPM_ORD_UNSEAL);
631 	tpm_buf_append_u32(tb, keyhandle);
632 	tpm_buf_append(tb, blob, bloblen);
633 	tpm_buf_append_u32(tb, authhandle1);
634 	tpm_buf_append(tb, nonceodd, TPM_NONCE_SIZE);
635 	tpm_buf_append_u8(tb, cont);
636 	tpm_buf_append(tb, authdata1, SHA1_DIGEST_SIZE);
637 	tpm_buf_append_u32(tb, authhandle2);
638 	tpm_buf_append(tb, nonceodd, TPM_NONCE_SIZE);
639 	tpm_buf_append_u8(tb, cont);
640 	tpm_buf_append(tb, authdata2, SHA1_DIGEST_SIZE);
641 
642 	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
643 	if (ret < 0) {
644 		pr_info("trusted_key: authhmac failed (%d)\n", ret);
645 		return ret;
646 	}
647 
648 	*datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
649 	ret = TSS_checkhmac2(tb->data, ordinal, nonceodd,
650 			     keyauth, SHA1_DIGEST_SIZE,
651 			     blobauth, SHA1_DIGEST_SIZE,
652 			     sizeof(uint32_t), TPM_DATA_OFFSET,
653 			     *datalen, TPM_DATA_OFFSET + sizeof(uint32_t), 0,
654 			     0);
655 	if (ret < 0) {
656 		pr_info("trusted_key: TSS_checkhmac2 failed (%d)\n", ret);
657 		return ret;
658 	}
659 	memcpy(data, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t), *datalen);
660 	return 0;
661 }
662 
663 /*
664  * Have the TPM seal(encrypt) the symmetric key
665  */
666 static int key_seal(struct trusted_key_payload *p,
667 		    struct trusted_key_options *o)
668 {
669 	struct tpm_buf tb;
670 	int ret;
671 
672 	ret = tpm_buf_init(&tb, 0, 0);
673 	if (ret)
674 		return ret;
675 
676 	/* include migratable flag at end of sealed key */
677 	p->key[p->key_len] = p->migratable;
678 
679 	ret = tpm_seal(&tb, o->keytype, o->keyhandle, o->keyauth,
680 		       p->key, p->key_len + 1, p->blob, &p->blob_len,
681 		       o->blobauth, o->pcrinfo, o->pcrinfo_len);
682 	if (ret < 0)
683 		pr_info("trusted_key: srkseal failed (%d)\n", ret);
684 
685 	tpm_buf_destroy(&tb);
686 	return ret;
687 }
688 
689 /*
690  * Have the TPM unseal(decrypt) the symmetric key
691  */
692 static int key_unseal(struct trusted_key_payload *p,
693 		      struct trusted_key_options *o)
694 {
695 	struct tpm_buf tb;
696 	int ret;
697 
698 	ret = tpm_buf_init(&tb, 0, 0);
699 	if (ret)
700 		return ret;
701 
702 	ret = tpm_unseal(&tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
703 			 o->blobauth, p->key, &p->key_len);
704 	if (ret < 0)
705 		pr_info("trusted_key: srkunseal failed (%d)\n", ret);
706 	else
707 		/* pull migratable flag out of sealed key */
708 		p->migratable = p->key[--p->key_len];
709 
710 	tpm_buf_destroy(&tb);
711 	return ret;
712 }
713 
714 enum {
715 	Opt_err,
716 	Opt_new, Opt_load, Opt_update,
717 	Opt_keyhandle, Opt_keyauth, Opt_blobauth,
718 	Opt_pcrinfo, Opt_pcrlock, Opt_migratable,
719 	Opt_hash,
720 	Opt_policydigest,
721 	Opt_policyhandle,
722 };
723 
724 static const match_table_t key_tokens = {
725 	{Opt_new, "new"},
726 	{Opt_load, "load"},
727 	{Opt_update, "update"},
728 	{Opt_keyhandle, "keyhandle=%s"},
729 	{Opt_keyauth, "keyauth=%s"},
730 	{Opt_blobauth, "blobauth=%s"},
731 	{Opt_pcrinfo, "pcrinfo=%s"},
732 	{Opt_pcrlock, "pcrlock=%s"},
733 	{Opt_migratable, "migratable=%s"},
734 	{Opt_hash, "hash=%s"},
735 	{Opt_policydigest, "policydigest=%s"},
736 	{Opt_policyhandle, "policyhandle=%s"},
737 	{Opt_err, NULL}
738 };
739 
740 /* can have zero or more token= options */
741 static int getoptions(char *c, struct trusted_key_payload *pay,
742 		      struct trusted_key_options *opt)
743 {
744 	substring_t args[MAX_OPT_ARGS];
745 	char *p = c;
746 	int token;
747 	int res;
748 	unsigned long handle;
749 	unsigned long lock;
750 	unsigned long token_mask = 0;
751 	unsigned int digest_len;
752 	int i;
753 	int tpm2;
754 
755 	tpm2 = tpm_is_tpm2(chip);
756 	if (tpm2 < 0)
757 		return tpm2;
758 
759 	opt->hash = tpm2 ? HASH_ALGO_SHA256 : HASH_ALGO_SHA1;
760 
761 	while ((p = strsep(&c, " \t"))) {
762 		if (*p == '\0' || *p == ' ' || *p == '\t')
763 			continue;
764 		token = match_token(p, key_tokens, args);
765 		if (test_and_set_bit(token, &token_mask))
766 			return -EINVAL;
767 
768 		switch (token) {
769 		case Opt_pcrinfo:
770 			opt->pcrinfo_len = strlen(args[0].from) / 2;
771 			if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
772 				return -EINVAL;
773 			res = hex2bin(opt->pcrinfo, args[0].from,
774 				      opt->pcrinfo_len);
775 			if (res < 0)
776 				return -EINVAL;
777 			break;
778 		case Opt_keyhandle:
779 			res = kstrtoul(args[0].from, 16, &handle);
780 			if (res < 0)
781 				return -EINVAL;
782 			opt->keytype = SEAL_keytype;
783 			opt->keyhandle = handle;
784 			break;
785 		case Opt_keyauth:
786 			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
787 				return -EINVAL;
788 			res = hex2bin(opt->keyauth, args[0].from,
789 				      SHA1_DIGEST_SIZE);
790 			if (res < 0)
791 				return -EINVAL;
792 			break;
793 		case Opt_blobauth:
794 			if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
795 				return -EINVAL;
796 			res = hex2bin(opt->blobauth, args[0].from,
797 				      SHA1_DIGEST_SIZE);
798 			if (res < 0)
799 				return -EINVAL;
800 			break;
801 		case Opt_migratable:
802 			if (*args[0].from == '0')
803 				pay->migratable = 0;
804 			else if (*args[0].from != '1')
805 				return -EINVAL;
806 			break;
807 		case Opt_pcrlock:
808 			res = kstrtoul(args[0].from, 10, &lock);
809 			if (res < 0)
810 				return -EINVAL;
811 			opt->pcrlock = lock;
812 			break;
813 		case Opt_hash:
814 			if (test_bit(Opt_policydigest, &token_mask))
815 				return -EINVAL;
816 			for (i = 0; i < HASH_ALGO__LAST; i++) {
817 				if (!strcmp(args[0].from, hash_algo_name[i])) {
818 					opt->hash = i;
819 					break;
820 				}
821 			}
822 			if (i == HASH_ALGO__LAST)
823 				return -EINVAL;
824 			if  (!tpm2 && i != HASH_ALGO_SHA1) {
825 				pr_info("trusted_key: TPM 1.x only supports SHA-1.\n");
826 				return -EINVAL;
827 			}
828 			break;
829 		case Opt_policydigest:
830 			digest_len = hash_digest_size[opt->hash];
831 			if (!tpm2 || strlen(args[0].from) != (2 * digest_len))
832 				return -EINVAL;
833 			res = hex2bin(opt->policydigest, args[0].from,
834 				      digest_len);
835 			if (res < 0)
836 				return -EINVAL;
837 			opt->policydigest_len = digest_len;
838 			break;
839 		case Opt_policyhandle:
840 			if (!tpm2)
841 				return -EINVAL;
842 			res = kstrtoul(args[0].from, 16, &handle);
843 			if (res < 0)
844 				return -EINVAL;
845 			opt->policyhandle = handle;
846 			break;
847 		default:
848 			return -EINVAL;
849 		}
850 	}
851 	return 0;
852 }
853 
854 /*
855  * datablob_parse - parse the keyctl data and fill in the
856  * 		    payload and options structures
857  *
858  * On success returns 0, otherwise -EINVAL.
859  */
860 static int datablob_parse(char *datablob, struct trusted_key_payload *p,
861 			  struct trusted_key_options *o)
862 {
863 	substring_t args[MAX_OPT_ARGS];
864 	long keylen;
865 	int ret = -EINVAL;
866 	int key_cmd;
867 	char *c;
868 
869 	/* main command */
870 	c = strsep(&datablob, " \t");
871 	if (!c)
872 		return -EINVAL;
873 	key_cmd = match_token(c, key_tokens, args);
874 	switch (key_cmd) {
875 	case Opt_new:
876 		/* first argument is key size */
877 		c = strsep(&datablob, " \t");
878 		if (!c)
879 			return -EINVAL;
880 		ret = kstrtol(c, 10, &keylen);
881 		if (ret < 0 || keylen < MIN_KEY_SIZE || keylen > MAX_KEY_SIZE)
882 			return -EINVAL;
883 		p->key_len = keylen;
884 		ret = getoptions(datablob, p, o);
885 		if (ret < 0)
886 			return ret;
887 		ret = Opt_new;
888 		break;
889 	case Opt_load:
890 		/* first argument is sealed blob */
891 		c = strsep(&datablob, " \t");
892 		if (!c)
893 			return -EINVAL;
894 		p->blob_len = strlen(c) / 2;
895 		if (p->blob_len > MAX_BLOB_SIZE)
896 			return -EINVAL;
897 		ret = hex2bin(p->blob, c, p->blob_len);
898 		if (ret < 0)
899 			return -EINVAL;
900 		ret = getoptions(datablob, p, o);
901 		if (ret < 0)
902 			return ret;
903 		ret = Opt_load;
904 		break;
905 	case Opt_update:
906 		/* all arguments are options */
907 		ret = getoptions(datablob, p, o);
908 		if (ret < 0)
909 			return ret;
910 		ret = Opt_update;
911 		break;
912 	case Opt_err:
913 		return -EINVAL;
914 		break;
915 	}
916 	return ret;
917 }
918 
919 static struct trusted_key_options *trusted_options_alloc(void)
920 {
921 	struct trusted_key_options *options;
922 	int tpm2;
923 
924 	tpm2 = tpm_is_tpm2(chip);
925 	if (tpm2 < 0)
926 		return NULL;
927 
928 	options = kzalloc(sizeof *options, GFP_KERNEL);
929 	if (options) {
930 		/* set any non-zero defaults */
931 		options->keytype = SRK_keytype;
932 
933 		if (!tpm2)
934 			options->keyhandle = SRKHANDLE;
935 	}
936 	return options;
937 }
938 
939 static struct trusted_key_payload *trusted_payload_alloc(struct key *key)
940 {
941 	struct trusted_key_payload *p = NULL;
942 	int ret;
943 
944 	ret = key_payload_reserve(key, sizeof *p);
945 	if (ret < 0)
946 		return p;
947 	p = kzalloc(sizeof *p, GFP_KERNEL);
948 	if (p)
949 		p->migratable = 1; /* migratable by default */
950 	return p;
951 }
952 
953 /*
954  * trusted_instantiate - create a new trusted key
955  *
956  * Unseal an existing trusted blob or, for a new key, get a
957  * random key, then seal and create a trusted key-type key,
958  * adding it to the specified keyring.
959  *
960  * On success, return 0. Otherwise return errno.
961  */
962 static int trusted_instantiate(struct key *key,
963 			       struct key_preparsed_payload *prep)
964 {
965 	struct trusted_key_payload *payload = NULL;
966 	struct trusted_key_options *options = NULL;
967 	size_t datalen = prep->datalen;
968 	char *datablob;
969 	int ret = 0;
970 	int key_cmd;
971 	size_t key_len;
972 	int tpm2;
973 
974 	tpm2 = tpm_is_tpm2(chip);
975 	if (tpm2 < 0)
976 		return tpm2;
977 
978 	if (datalen <= 0 || datalen > 32767 || !prep->data)
979 		return -EINVAL;
980 
981 	datablob = kmalloc(datalen + 1, GFP_KERNEL);
982 	if (!datablob)
983 		return -ENOMEM;
984 	memcpy(datablob, prep->data, datalen);
985 	datablob[datalen] = '\0';
986 
987 	options = trusted_options_alloc();
988 	if (!options) {
989 		ret = -ENOMEM;
990 		goto out;
991 	}
992 	payload = trusted_payload_alloc(key);
993 	if (!payload) {
994 		ret = -ENOMEM;
995 		goto out;
996 	}
997 
998 	key_cmd = datablob_parse(datablob, payload, options);
999 	if (key_cmd < 0) {
1000 		ret = key_cmd;
1001 		goto out;
1002 	}
1003 
1004 	if (!options->keyhandle) {
1005 		ret = -EINVAL;
1006 		goto out;
1007 	}
1008 
1009 	dump_payload(payload);
1010 	dump_options(options);
1011 
1012 	switch (key_cmd) {
1013 	case Opt_load:
1014 		if (tpm2)
1015 			ret = tpm2_unseal_trusted(chip, payload, options);
1016 		else
1017 			ret = key_unseal(payload, options);
1018 		dump_payload(payload);
1019 		dump_options(options);
1020 		if (ret < 0)
1021 			pr_info("trusted_key: key_unseal failed (%d)\n", ret);
1022 		break;
1023 	case Opt_new:
1024 		key_len = payload->key_len;
1025 		ret = tpm_get_random(chip, payload->key, key_len);
1026 		if (ret < 0)
1027 			goto out;
1028 
1029 		if (ret != key_len) {
1030 			pr_info("trusted_key: key_create failed (%d)\n", ret);
1031 			ret = -EIO;
1032 			goto out;
1033 		}
1034 		if (tpm2)
1035 			ret = tpm2_seal_trusted(chip, payload, options);
1036 		else
1037 			ret = key_seal(payload, options);
1038 		if (ret < 0)
1039 			pr_info("trusted_key: key_seal failed (%d)\n", ret);
1040 		break;
1041 	default:
1042 		ret = -EINVAL;
1043 		goto out;
1044 	}
1045 	if (!ret && options->pcrlock)
1046 		ret = pcrlock(options->pcrlock);
1047 out:
1048 	kfree_sensitive(datablob);
1049 	kfree_sensitive(options);
1050 	if (!ret)
1051 		rcu_assign_keypointer(key, payload);
1052 	else
1053 		kfree_sensitive(payload);
1054 	return ret;
1055 }
1056 
1057 static void trusted_rcu_free(struct rcu_head *rcu)
1058 {
1059 	struct trusted_key_payload *p;
1060 
1061 	p = container_of(rcu, struct trusted_key_payload, rcu);
1062 	kfree_sensitive(p);
1063 }
1064 
1065 /*
1066  * trusted_update - reseal an existing key with new PCR values
1067  */
1068 static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
1069 {
1070 	struct trusted_key_payload *p;
1071 	struct trusted_key_payload *new_p;
1072 	struct trusted_key_options *new_o;
1073 	size_t datalen = prep->datalen;
1074 	char *datablob;
1075 	int ret = 0;
1076 
1077 	if (key_is_negative(key))
1078 		return -ENOKEY;
1079 	p = key->payload.data[0];
1080 	if (!p->migratable)
1081 		return -EPERM;
1082 	if (datalen <= 0 || datalen > 32767 || !prep->data)
1083 		return -EINVAL;
1084 
1085 	datablob = kmalloc(datalen + 1, GFP_KERNEL);
1086 	if (!datablob)
1087 		return -ENOMEM;
1088 	new_o = trusted_options_alloc();
1089 	if (!new_o) {
1090 		ret = -ENOMEM;
1091 		goto out;
1092 	}
1093 	new_p = trusted_payload_alloc(key);
1094 	if (!new_p) {
1095 		ret = -ENOMEM;
1096 		goto out;
1097 	}
1098 
1099 	memcpy(datablob, prep->data, datalen);
1100 	datablob[datalen] = '\0';
1101 	ret = datablob_parse(datablob, new_p, new_o);
1102 	if (ret != Opt_update) {
1103 		ret = -EINVAL;
1104 		kfree_sensitive(new_p);
1105 		goto out;
1106 	}
1107 
1108 	if (!new_o->keyhandle) {
1109 		ret = -EINVAL;
1110 		kfree_sensitive(new_p);
1111 		goto out;
1112 	}
1113 
1114 	/* copy old key values, and reseal with new pcrs */
1115 	new_p->migratable = p->migratable;
1116 	new_p->key_len = p->key_len;
1117 	memcpy(new_p->key, p->key, p->key_len);
1118 	dump_payload(p);
1119 	dump_payload(new_p);
1120 
1121 	ret = key_seal(new_p, new_o);
1122 	if (ret < 0) {
1123 		pr_info("trusted_key: key_seal failed (%d)\n", ret);
1124 		kfree_sensitive(new_p);
1125 		goto out;
1126 	}
1127 	if (new_o->pcrlock) {
1128 		ret = pcrlock(new_o->pcrlock);
1129 		if (ret < 0) {
1130 			pr_info("trusted_key: pcrlock failed (%d)\n", ret);
1131 			kfree_sensitive(new_p);
1132 			goto out;
1133 		}
1134 	}
1135 	rcu_assign_keypointer(key, new_p);
1136 	call_rcu(&p->rcu, trusted_rcu_free);
1137 out:
1138 	kfree_sensitive(datablob);
1139 	kfree_sensitive(new_o);
1140 	return ret;
1141 }
1142 
1143 /*
1144  * trusted_read - copy the sealed blob data to userspace in hex.
1145  * On success, return to userspace the trusted key datablob size.
1146  */
1147 static long trusted_read(const struct key *key, char *buffer,
1148 			 size_t buflen)
1149 {
1150 	const struct trusted_key_payload *p;
1151 	char *bufp;
1152 	int i;
1153 
1154 	p = dereference_key_locked(key);
1155 	if (!p)
1156 		return -EINVAL;
1157 
1158 	if (buffer && buflen >= 2 * p->blob_len) {
1159 		bufp = buffer;
1160 		for (i = 0; i < p->blob_len; i++)
1161 			bufp = hex_byte_pack(bufp, p->blob[i]);
1162 	}
1163 	return 2 * p->blob_len;
1164 }
1165 
1166 /*
1167  * trusted_destroy - clear and free the key's payload
1168  */
1169 static void trusted_destroy(struct key *key)
1170 {
1171 	kfree_sensitive(key->payload.data[0]);
1172 }
1173 
1174 struct key_type key_type_trusted = {
1175 	.name = "trusted",
1176 	.instantiate = trusted_instantiate,
1177 	.update = trusted_update,
1178 	.destroy = trusted_destroy,
1179 	.describe = user_describe,
1180 	.read = trusted_read,
1181 };
1182 
1183 EXPORT_SYMBOL_GPL(key_type_trusted);
1184 
1185 static void trusted_shash_release(void)
1186 {
1187 	if (hashalg)
1188 		crypto_free_shash(hashalg);
1189 	if (hmacalg)
1190 		crypto_free_shash(hmacalg);
1191 }
1192 
1193 static int __init trusted_shash_alloc(void)
1194 {
1195 	int ret;
1196 
1197 	hmacalg = crypto_alloc_shash(hmac_alg, 0, 0);
1198 	if (IS_ERR(hmacalg)) {
1199 		pr_info("trusted_key: could not allocate crypto %s\n",
1200 			hmac_alg);
1201 		return PTR_ERR(hmacalg);
1202 	}
1203 
1204 	hashalg = crypto_alloc_shash(hash_alg, 0, 0);
1205 	if (IS_ERR(hashalg)) {
1206 		pr_info("trusted_key: could not allocate crypto %s\n",
1207 			hash_alg);
1208 		ret = PTR_ERR(hashalg);
1209 		goto hashalg_fail;
1210 	}
1211 
1212 	return 0;
1213 
1214 hashalg_fail:
1215 	crypto_free_shash(hmacalg);
1216 	return ret;
1217 }
1218 
1219 static int __init init_digests(void)
1220 {
1221 	int i;
1222 
1223 	digests = kcalloc(chip->nr_allocated_banks, sizeof(*digests),
1224 			  GFP_KERNEL);
1225 	if (!digests)
1226 		return -ENOMEM;
1227 
1228 	for (i = 0; i < chip->nr_allocated_banks; i++)
1229 		digests[i].alg_id = chip->allocated_banks[i].alg_id;
1230 
1231 	return 0;
1232 }
1233 
1234 static int __init init_trusted(void)
1235 {
1236 	int ret;
1237 
1238 	/* encrypted_keys.ko depends on successful load of this module even if
1239 	 * TPM is not used.
1240 	 */
1241 	chip = tpm_default_chip();
1242 	if (!chip)
1243 		return 0;
1244 
1245 	ret = init_digests();
1246 	if (ret < 0)
1247 		goto err_put;
1248 	ret = trusted_shash_alloc();
1249 	if (ret < 0)
1250 		goto err_free;
1251 	ret = register_key_type(&key_type_trusted);
1252 	if (ret < 0)
1253 		goto err_release;
1254 	return 0;
1255 err_release:
1256 	trusted_shash_release();
1257 err_free:
1258 	kfree(digests);
1259 err_put:
1260 	put_device(&chip->dev);
1261 	return ret;
1262 }
1263 
1264 static void __exit cleanup_trusted(void)
1265 {
1266 	if (chip) {
1267 		put_device(&chip->dev);
1268 		kfree(digests);
1269 		trusted_shash_release();
1270 		unregister_key_type(&key_type_trusted);
1271 	}
1272 }
1273 
1274 late_initcall(init_trusted);
1275 module_exit(cleanup_trusted);
1276 
1277 MODULE_LICENSE("GPL");
1278