1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2004 IBM Corporation
4  * Copyright (C) 2014 Intel Corporation
5  */
6 
7 #include <linux/asn1_encoder.h>
8 #include <linux/oid_registry.h>
9 #include <linux/string.h>
10 #include <linux/err.h>
11 #include <linux/tpm.h>
12 #include <linux/tpm_command.h>
13 
14 #include <keys/trusted-type.h>
15 #include <keys/trusted_tpm.h>
16 
17 #include <asm/unaligned.h>
18 
19 #include "tpm2key.asn1.h"
20 
21 static struct tpm2_hash tpm2_hash_map[] = {
22 	{HASH_ALGO_SHA1, TPM_ALG_SHA1},
23 	{HASH_ALGO_SHA256, TPM_ALG_SHA256},
24 	{HASH_ALGO_SHA384, TPM_ALG_SHA384},
25 	{HASH_ALGO_SHA512, TPM_ALG_SHA512},
26 	{HASH_ALGO_SM3_256, TPM_ALG_SM3_256},
27 };
28 
29 static u32 tpm2key_oid[] = { 2, 23, 133, 10, 1, 5 };
30 
31 static int tpm2_key_encode(struct trusted_key_payload *payload,
32 			   struct trusted_key_options *options,
33 			   u8 *src, u32 len)
34 {
35 	const int SCRATCH_SIZE = PAGE_SIZE;
36 	u8 *scratch = kmalloc(SCRATCH_SIZE, GFP_KERNEL);
37 	u8 *work = scratch, *work1;
38 	u8 *end_work = scratch + SCRATCH_SIZE;
39 	u8 *priv, *pub;
40 	u16 priv_len, pub_len;
41 	int ret;
42 
43 	priv_len = get_unaligned_be16(src) + 2;
44 	priv = src;
45 
46 	src += priv_len;
47 
48 	pub_len = get_unaligned_be16(src) + 2;
49 	pub = src;
50 
51 	if (!scratch)
52 		return -ENOMEM;
53 
54 	work = asn1_encode_oid(work, end_work, tpm2key_oid,
55 			       asn1_oid_len(tpm2key_oid));
56 
57 	if (options->blobauth_len == 0) {
58 		unsigned char bool[3], *w = bool;
59 		/* tag 0 is emptyAuth */
60 		w = asn1_encode_boolean(w, w + sizeof(bool), true);
61 		if (WARN(IS_ERR(w), "BUG: Boolean failed to encode")) {
62 			ret = PTR_ERR(w);
63 			goto err;
64 		}
65 		work = asn1_encode_tag(work, end_work, 0, bool, w - bool);
66 	}
67 
68 	/*
69 	 * Assume both octet strings will encode to a 2 byte definite length
70 	 *
71 	 * Note: For a well behaved TPM, this warning should never
72 	 * trigger, so if it does there's something nefarious going on
73 	 */
74 	if (WARN(work - scratch + pub_len + priv_len + 14 > SCRATCH_SIZE,
75 		 "BUG: scratch buffer is too small")) {
76 		ret = -EINVAL;
77 		goto err;
78 	}
79 
80 	work = asn1_encode_integer(work, end_work, options->keyhandle);
81 	work = asn1_encode_octet_string(work, end_work, pub, pub_len);
82 	work = asn1_encode_octet_string(work, end_work, priv, priv_len);
83 
84 	work1 = payload->blob;
85 	work1 = asn1_encode_sequence(work1, work1 + sizeof(payload->blob),
86 				     scratch, work - scratch);
87 	if (IS_ERR(work1)) {
88 		ret = PTR_ERR(work1);
89 		pr_err("BUG: ASN.1 encoder failed with %d\n", ret);
90 		goto err;
91 	}
92 
93 	kfree(scratch);
94 	return work1 - payload->blob;
95 
96 err:
97 	kfree(scratch);
98 	return ret;
99 }
100 
101 struct tpm2_key_context {
102 	u32 parent;
103 	const u8 *pub;
104 	u32 pub_len;
105 	const u8 *priv;
106 	u32 priv_len;
107 };
108 
109 static int tpm2_key_decode(struct trusted_key_payload *payload,
110 			   struct trusted_key_options *options,
111 			   u8 **buf)
112 {
113 	int ret;
114 	struct tpm2_key_context ctx;
115 	u8 *blob;
116 
117 	memset(&ctx, 0, sizeof(ctx));
118 
119 	ret = asn1_ber_decoder(&tpm2key_decoder, &ctx, payload->blob,
120 			       payload->blob_len);
121 	if (ret < 0)
122 		return ret;
123 
124 	if (ctx.priv_len + ctx.pub_len > MAX_BLOB_SIZE)
125 		return -EINVAL;
126 
127 	blob = kmalloc(ctx.priv_len + ctx.pub_len + 4, GFP_KERNEL);
128 	if (!blob)
129 		return -ENOMEM;
130 
131 	*buf = blob;
132 	options->keyhandle = ctx.parent;
133 
134 	memcpy(blob, ctx.priv, ctx.priv_len);
135 	blob += ctx.priv_len;
136 
137 	memcpy(blob, ctx.pub, ctx.pub_len);
138 
139 	return 0;
140 }
141 
142 int tpm2_key_parent(void *context, size_t hdrlen,
143 		  unsigned char tag,
144 		  const void *value, size_t vlen)
145 {
146 	struct tpm2_key_context *ctx = context;
147 	const u8 *v = value;
148 	int i;
149 
150 	ctx->parent = 0;
151 	for (i = 0; i < vlen; i++) {
152 		ctx->parent <<= 8;
153 		ctx->parent |= v[i];
154 	}
155 
156 	return 0;
157 }
158 
159 int tpm2_key_type(void *context, size_t hdrlen,
160 		unsigned char tag,
161 		const void *value, size_t vlen)
162 {
163 	enum OID oid = look_up_OID(value, vlen);
164 
165 	if (oid != OID_TPMSealedData) {
166 		char buffer[50];
167 
168 		sprint_oid(value, vlen, buffer, sizeof(buffer));
169 		pr_debug("OID is \"%s\" which is not TPMSealedData\n",
170 			 buffer);
171 		return -EINVAL;
172 	}
173 
174 	return 0;
175 }
176 
177 int tpm2_key_pub(void *context, size_t hdrlen,
178 	       unsigned char tag,
179 	       const void *value, size_t vlen)
180 {
181 	struct tpm2_key_context *ctx = context;
182 
183 	ctx->pub = value;
184 	ctx->pub_len = vlen;
185 
186 	return 0;
187 }
188 
189 int tpm2_key_priv(void *context, size_t hdrlen,
190 		unsigned char tag,
191 		const void *value, size_t vlen)
192 {
193 	struct tpm2_key_context *ctx = context;
194 
195 	ctx->priv = value;
196 	ctx->priv_len = vlen;
197 
198 	return 0;
199 }
200 
201 /**
202  * tpm2_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer.
203  *
204  * @buf: an allocated tpm_buf instance
205  * @session_handle: session handle
206  * @nonce: the session nonce, may be NULL if not used
207  * @nonce_len: the session nonce length, may be 0 if not used
208  * @attributes: the session attributes
209  * @hmac: the session HMAC or password, may be NULL if not used
210  * @hmac_len: the session HMAC or password length, maybe 0 if not used
211  */
212 static void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle,
213 				 const u8 *nonce, u16 nonce_len,
214 				 u8 attributes,
215 				 const u8 *hmac, u16 hmac_len)
216 {
217 	tpm_buf_append_u32(buf, 9 + nonce_len + hmac_len);
218 	tpm_buf_append_u32(buf, session_handle);
219 	tpm_buf_append_u16(buf, nonce_len);
220 
221 	if (nonce && nonce_len)
222 		tpm_buf_append(buf, nonce, nonce_len);
223 
224 	tpm_buf_append_u8(buf, attributes);
225 	tpm_buf_append_u16(buf, hmac_len);
226 
227 	if (hmac && hmac_len)
228 		tpm_buf_append(buf, hmac, hmac_len);
229 }
230 
231 /**
232  * tpm2_seal_trusted() - seal the payload of a trusted key
233  *
234  * @chip: TPM chip to use
235  * @payload: the key data in clear and encrypted form
236  * @options: authentication values and other options
237  *
238  * Return: < 0 on error and 0 on success.
239  */
240 int tpm2_seal_trusted(struct tpm_chip *chip,
241 		      struct trusted_key_payload *payload,
242 		      struct trusted_key_options *options)
243 {
244 	int blob_len = 0;
245 	struct tpm_buf buf;
246 	u32 hash;
247 	u32 flags;
248 	int i;
249 	int rc;
250 
251 	for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) {
252 		if (options->hash == tpm2_hash_map[i].crypto_id) {
253 			hash = tpm2_hash_map[i].tpm_id;
254 			break;
255 		}
256 	}
257 
258 	if (i == ARRAY_SIZE(tpm2_hash_map))
259 		return -EINVAL;
260 
261 	if (!options->keyhandle)
262 		return -EINVAL;
263 
264 	rc = tpm_try_get_ops(chip);
265 	if (rc)
266 		return rc;
267 
268 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
269 	if (rc) {
270 		tpm_put_ops(chip);
271 		return rc;
272 	}
273 
274 	tpm_buf_append_u32(&buf, options->keyhandle);
275 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
276 			     NULL /* nonce */, 0,
277 			     0 /* session_attributes */,
278 			     options->keyauth /* hmac */,
279 			     TPM_DIGEST_SIZE);
280 
281 	/* sensitive */
282 	tpm_buf_append_u16(&buf, 4 + options->blobauth_len + payload->key_len);
283 
284 	tpm_buf_append_u16(&buf, options->blobauth_len);
285 	if (options->blobauth_len)
286 		tpm_buf_append(&buf, options->blobauth, options->blobauth_len);
287 
288 	tpm_buf_append_u16(&buf, payload->key_len);
289 	tpm_buf_append(&buf, payload->key, payload->key_len);
290 
291 	/* public */
292 	tpm_buf_append_u16(&buf, 14 + options->policydigest_len);
293 	tpm_buf_append_u16(&buf, TPM_ALG_KEYEDHASH);
294 	tpm_buf_append_u16(&buf, hash);
295 
296 	/* key properties */
297 	flags = 0;
298 	flags |= options->policydigest_len ? 0 : TPM2_OA_USER_WITH_AUTH;
299 	flags |= payload->migratable ? 0 : (TPM2_OA_FIXED_TPM |
300 					    TPM2_OA_FIXED_PARENT);
301 	tpm_buf_append_u32(&buf, flags);
302 
303 	/* policy */
304 	tpm_buf_append_u16(&buf, options->policydigest_len);
305 	if (options->policydigest_len)
306 		tpm_buf_append(&buf, options->policydigest,
307 			       options->policydigest_len);
308 
309 	/* public parameters */
310 	tpm_buf_append_u16(&buf, TPM_ALG_NULL);
311 	tpm_buf_append_u16(&buf, 0);
312 
313 	/* outside info */
314 	tpm_buf_append_u16(&buf, 0);
315 
316 	/* creation PCR */
317 	tpm_buf_append_u32(&buf, 0);
318 
319 	if (buf.flags & TPM_BUF_OVERFLOW) {
320 		rc = -E2BIG;
321 		goto out;
322 	}
323 
324 	rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data");
325 	if (rc)
326 		goto out;
327 
328 	blob_len = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]);
329 	if (blob_len > MAX_BLOB_SIZE) {
330 		rc = -E2BIG;
331 		goto out;
332 	}
333 	if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 4 + blob_len) {
334 		rc = -EFAULT;
335 		goto out;
336 	}
337 
338 	blob_len = tpm2_key_encode(payload, options,
339 				   &buf.data[TPM_HEADER_SIZE + 4],
340 				   blob_len);
341 
342 out:
343 	tpm_buf_destroy(&buf);
344 
345 	if (rc > 0) {
346 		if (tpm2_rc_value(rc) == TPM2_RC_HASH)
347 			rc = -EINVAL;
348 		else
349 			rc = -EPERM;
350 	}
351 	if (blob_len < 0)
352 		rc = blob_len;
353 	else
354 		payload->blob_len = blob_len;
355 
356 	tpm_put_ops(chip);
357 	return rc;
358 }
359 
360 /**
361  * tpm2_load_cmd() - execute a TPM2_Load command
362  *
363  * @chip: TPM chip to use
364  * @payload: the key data in clear and encrypted form
365  * @options: authentication values and other options
366  * @blob_handle: returned blob handle
367  *
368  * Return: 0 on success.
369  *        -E2BIG on wrong payload size.
370  *        -EPERM on tpm error status.
371  *        < 0 error from tpm_send.
372  */
373 static int tpm2_load_cmd(struct tpm_chip *chip,
374 			 struct trusted_key_payload *payload,
375 			 struct trusted_key_options *options,
376 			 u32 *blob_handle)
377 {
378 	struct tpm_buf buf;
379 	unsigned int private_len;
380 	unsigned int public_len;
381 	unsigned int blob_len;
382 	u8 *blob, *pub;
383 	int rc;
384 	u32 attrs;
385 
386 	rc = tpm2_key_decode(payload, options, &blob);
387 	if (rc) {
388 		/* old form */
389 		blob = payload->blob;
390 		payload->old_format = 1;
391 	}
392 
393 	/* new format carries keyhandle but old format doesn't */
394 	if (!options->keyhandle)
395 		return -EINVAL;
396 
397 	/* must be big enough for at least the two be16 size counts */
398 	if (payload->blob_len < 4)
399 		return -EINVAL;
400 
401 	private_len = get_unaligned_be16(blob);
402 
403 	/* must be big enough for following public_len */
404 	if (private_len + 2 + 2 > (payload->blob_len))
405 		return -E2BIG;
406 
407 	public_len = get_unaligned_be16(blob + 2 + private_len);
408 	if (private_len + 2 + public_len + 2 > payload->blob_len)
409 		return -E2BIG;
410 
411 	pub = blob + 2 + private_len + 2;
412 	/* key attributes are always at offset 4 */
413 	attrs = get_unaligned_be32(pub + 4);
414 
415 	if ((attrs & (TPM2_OA_FIXED_TPM | TPM2_OA_FIXED_PARENT)) ==
416 	    (TPM2_OA_FIXED_TPM | TPM2_OA_FIXED_PARENT))
417 		payload->migratable = 0;
418 	else
419 		payload->migratable = 1;
420 
421 	blob_len = private_len + public_len + 4;
422 	if (blob_len > payload->blob_len)
423 		return -E2BIG;
424 
425 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
426 	if (rc)
427 		return rc;
428 
429 	tpm_buf_append_u32(&buf, options->keyhandle);
430 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
431 			     NULL /* nonce */, 0,
432 			     0 /* session_attributes */,
433 			     options->keyauth /* hmac */,
434 			     TPM_DIGEST_SIZE);
435 
436 	tpm_buf_append(&buf, blob, blob_len);
437 
438 	if (buf.flags & TPM_BUF_OVERFLOW) {
439 		rc = -E2BIG;
440 		goto out;
441 	}
442 
443 	rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob");
444 	if (!rc)
445 		*blob_handle = be32_to_cpup(
446 			(__be32 *) &buf.data[TPM_HEADER_SIZE]);
447 
448 out:
449 	if (blob != payload->blob)
450 		kfree(blob);
451 	tpm_buf_destroy(&buf);
452 
453 	if (rc > 0)
454 		rc = -EPERM;
455 
456 	return rc;
457 }
458 
459 /**
460  * tpm2_unseal_cmd() - execute a TPM2_Unload command
461  *
462  * @chip: TPM chip to use
463  * @payload: the key data in clear and encrypted form
464  * @options: authentication values and other options
465  * @blob_handle: blob handle
466  *
467  * Return: 0 on success
468  *         -EPERM on tpm error status
469  *         < 0 error from tpm_send
470  */
471 static int tpm2_unseal_cmd(struct tpm_chip *chip,
472 			   struct trusted_key_payload *payload,
473 			   struct trusted_key_options *options,
474 			   u32 blob_handle)
475 {
476 	struct tpm_buf buf;
477 	u16 data_len;
478 	u8 *data;
479 	int rc;
480 
481 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
482 	if (rc)
483 		return rc;
484 
485 	tpm_buf_append_u32(&buf, blob_handle);
486 	tpm2_buf_append_auth(&buf,
487 			     options->policyhandle ?
488 			     options->policyhandle : TPM2_RS_PW,
489 			     NULL /* nonce */, 0,
490 			     TPM2_SA_CONTINUE_SESSION,
491 			     options->blobauth /* hmac */,
492 			     options->blobauth_len);
493 
494 	rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing");
495 	if (rc > 0)
496 		rc = -EPERM;
497 
498 	if (!rc) {
499 		data_len = be16_to_cpup(
500 			(__be16 *) &buf.data[TPM_HEADER_SIZE + 4]);
501 		if (data_len < MIN_KEY_SIZE ||  data_len > MAX_KEY_SIZE) {
502 			rc = -EFAULT;
503 			goto out;
504 		}
505 
506 		if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 6 + data_len) {
507 			rc = -EFAULT;
508 			goto out;
509 		}
510 		data = &buf.data[TPM_HEADER_SIZE + 6];
511 
512 		if (payload->old_format) {
513 			/* migratable flag is at the end of the key */
514 			memcpy(payload->key, data, data_len - 1);
515 			payload->key_len = data_len - 1;
516 			payload->migratable = data[data_len - 1];
517 		} else {
518 			/*
519 			 * migratable flag already collected from key
520 			 * attributes
521 			 */
522 			memcpy(payload->key, data, data_len);
523 			payload->key_len = data_len;
524 		}
525 	}
526 
527 out:
528 	tpm_buf_destroy(&buf);
529 	return rc;
530 }
531 
532 /**
533  * tpm2_unseal_trusted() - unseal the payload of a trusted key
534  *
535  * @chip: TPM chip to use
536  * @payload: the key data in clear and encrypted form
537  * @options: authentication values and other options
538  *
539  * Return: Same as with tpm_send.
540  */
541 int tpm2_unseal_trusted(struct tpm_chip *chip,
542 			struct trusted_key_payload *payload,
543 			struct trusted_key_options *options)
544 {
545 	u32 blob_handle;
546 	int rc;
547 
548 	rc = tpm_try_get_ops(chip);
549 	if (rc)
550 		return rc;
551 
552 	rc = tpm2_load_cmd(chip, payload, options, &blob_handle);
553 	if (rc)
554 		goto out;
555 
556 	rc = tpm2_unseal_cmd(chip, payload, options, blob_handle);
557 	tpm2_flush_context(chip, blob_handle);
558 
559 out:
560 	tpm_put_ops(chip);
561 
562 	return rc;
563 }
564