xref: /linux/drivers/char/tpm/tpm2-sessions.c (revision 148ab873d8194cb44f29474da3b4428fa2e100d1)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
5  *
6  * Cryptographic helper routines for handling TPM2 sessions for
7  * authorization HMAC and request response encryption.
8  *
9  * The idea is to ensure that every TPM command is HMAC protected by a
10  * session, meaning in-flight tampering would be detected and in
11  * addition all sensitive inputs and responses should be encrypted.
12  *
13  * The basic way this works is to use a TPM feature called salted
14  * sessions where a random secret used in session construction is
15  * encrypted to the public part of a known TPM key.  The problem is we
16  * have no known keys, so initially a primary Elliptic Curve key is
17  * derived from the NULL seed (we use EC because most TPMs generate
18  * these keys much faster than RSA ones).  The curve used is NIST_P256
19  * because that's now mandated to be present in 'TCG TPM v2.0
20  * Provisioning Guidance'
21  *
22  * Threat problems: the initial TPM2_CreatePrimary is not (and cannot
23  * be) session protected, so a clever Man in the Middle could return a
24  * public key they control to this command and from there intercept
25  * and decode all subsequent session based transactions.  The kernel
26  * cannot mitigate this threat but, after boot, userspace can get
27  * proof this has not happened by asking the TPM to certify the NULL
28  * key.  This certification would chain back to the TPM Endorsement
29  * Certificate and prove the NULL seed primary had not been tampered
30  * with and thus all sessions must have been cryptographically secure.
31  * To assist with this, the initial NULL seed public key name is made
32  * available in a sysfs file.
33  *
34  * Use of these functions:
35  *
36  * The design is all the crypto, hash and hmac gunk is confined in this
37  * file and never needs to be seen even by the kernel internal user.  To
38  * the user there's an init function tpm2_sessions_init() that needs to
39  * be called once per TPM which generates the NULL seed primary key.
40  *
41  * These are the usage functions:
42  *
43  * tpm2_end_auth_session() kills the session and frees the resources.
44  *	Under normal operation this function is done by
45  *	tpm_buf_check_hmac_response(), so this is only to be used on
46  *	error legs where the latter is not executed.
47  * tpm_buf_append_name() to add a handle to the buffer.  This must be
48  *	used in place of the usual tpm_buf_append_u32() for adding
49  *	handles because handles have to be processed specially when
50  *	calculating the HMAC.  In particular, for NV, volatile and
51  *	permanent objects you now need to provide the name.
52  * tpm_buf_append_hmac_session() which appends the hmac session to the
53  *	buf in the same way tpm_buf_append_auth does().
54  * tpm_buf_fill_hmac_session() This calculates the correct hash and
55  *	places it in the buffer.  It must be called after the complete
56  *	command buffer is finalized so it can fill in the correct HMAC
57  *	based on the parameters.
58  * tpm_buf_check_hmac_response() which checks the session response in
59  *	the buffer and calculates what it should be.  If there's a
60  *	mismatch it will log a warning and return an error.  If
61  *	tpm_buf_append_hmac_session() did not specify
62  *	TPM_SA_CONTINUE_SESSION then the session will be closed (if it
63  *	hasn't been consumed) and the auth structure freed.
64  */
65 
66 #include "tpm.h"
67 #include <linux/random.h>
68 #include <linux/scatterlist.h>
69 #include <linux/unaligned.h>
70 #include <crypto/kpp.h>
71 #include <crypto/ecdh.h>
72 #include <crypto/sha2.h>
73 #include <crypto/utils.h>
74 
75 /* maximum number of names the TPM must remember for authorization */
76 #define AUTH_MAX_NAMES	3
77 
78 #define AES_KEY_BYTES	AES_KEYSIZE_128
79 #define AES_KEY_BITS	(AES_KEY_BYTES*8)
80 
81 /*
82  * This is the structure that carries all the auth information (like
83  * session handle, nonces, session key and auth) from use to use it is
84  * designed to be opaque to anything outside.
85  */
86 struct tpm2_auth {
87 	u32 handle;
88 	/*
89 	 * This has two meanings: before tpm_buf_fill_hmac_session()
90 	 * it marks the offset in the buffer of the start of the
91 	 * sessions (i.e. after all the handles).  Once the buffer has
92 	 * been filled it markes the session number of our auth
93 	 * session so we can find it again in the response buffer.
94 	 *
95 	 * The two cases are distinguished because the first offset
96 	 * must always be greater than TPM_HEADER_SIZE and the second
97 	 * must be less than or equal to 5.
98 	 */
99 	u32 session;
100 	/*
101 	 * the size here is variable and set by the size of our_nonce
102 	 * which must be between 16 and the name hash length. we set
103 	 * the maximum sha256 size for the greatest protection
104 	 */
105 	u8 our_nonce[SHA256_DIGEST_SIZE];
106 	u8 tpm_nonce[SHA256_DIGEST_SIZE];
107 	/*
108 	 * the salt is only used across the session command/response
109 	 * after that it can be used as a scratch area
110 	 */
111 	union {
112 		u8 salt[EC_PT_SZ];
113 		/* scratch for key + IV */
114 		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
115 	};
116 	/*
117 	 * the session key and passphrase are the same size as the
118 	 * name digest (sha256 again).  The session key is constant
119 	 * for the use of the session and the passphrase can change
120 	 * with every invocation.
121 	 *
122 	 * Note: these fields must be adjacent and in this order
123 	 * because several HMAC/KDF schemes use the combination of the
124 	 * session_key and passphrase.
125 	 */
126 	u8 session_key[SHA256_DIGEST_SIZE];
127 	u8 passphrase[SHA256_DIGEST_SIZE];
128 	int passphrase_len;
129 	struct aes_enckey aes_key;
130 	/* saved session attributes: */
131 	u8 attrs;
132 	__be32 ordinal;
133 
134 	/*
135 	 * memory for three authorization handles.  We know them by
136 	 * handle, but they are part of the session by name, which
137 	 * we must compute and remember
138 	 */
139 	u32 name_h[AUTH_MAX_NAMES];
140 	u8 name[AUTH_MAX_NAMES][2 + SHA512_DIGEST_SIZE];
141 };
142 
143 #ifdef CONFIG_TCG_TPM2_HMAC
144 /*
145  * Name Size based on TPM algorithm (assumes no hash bigger than 255)
146  */
147 static int name_size(const u8 *name)
148 {
149 	u16 hash_alg = get_unaligned_be16(name);
150 
151 	switch (hash_alg) {
152 	case TPM_ALG_SHA1:
153 		return SHA1_DIGEST_SIZE + 2;
154 	case TPM_ALG_SHA256:
155 		return SHA256_DIGEST_SIZE + 2;
156 	case TPM_ALG_SHA384:
157 		return SHA384_DIGEST_SIZE + 2;
158 	case TPM_ALG_SHA512:
159 		return SHA512_DIGEST_SIZE + 2;
160 	default:
161 		pr_warn("tpm: unsupported name algorithm: 0x%04x\n", hash_alg);
162 		return -EINVAL;
163 	}
164 }
165 
166 static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
167 {
168 	u32 mso = tpm2_handle_mso(handle);
169 	off_t offset = TPM_HEADER_SIZE;
170 	struct tpm_buf *buf __free(kfree) = NULL;
171 	int rc, name_size_alg;
172 
173 	if (mso != TPM2_MSO_PERSISTENT && mso != TPM2_MSO_VOLATILE &&
174 	    mso != TPM2_MSO_NVRAM) {
175 		memcpy(name, &handle, sizeof(u32));
176 		return sizeof(u32);
177 	}
178 
179 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
180 	if (!buf)
181 		return -ENOMEM;
182 
183 	tpm_buf_init(buf, TPM_BUFSIZE);
184 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
185 	tpm_buf_append_u32(buf, handle);
186 
187 	rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_ReadPublic");
188 	if (rc)
189 		return tpm_ret_to_err(rc);
190 
191 	/* Skip TPMT_PUBLIC: */
192 	offset += tpm_buf_read_u16(buf, &offset);
193 
194 	/*
195 	 * Ensure space for the length field of TPM2B_NAME and hashAlg field of
196 	 * TPMT_HA (the extra four bytes).
197 	 */
198 	if (offset + 4 > tpm_buf_length(buf))
199 		return -EIO;
200 
201 	rc = tpm_buf_read_u16(buf, &offset);
202 	name_size_alg = name_size(&buf->data[offset]);
203 	if (name_size_alg < 0)
204 		return name_size_alg;
205 
206 	if (rc != name_size_alg)
207 		return -EIO;
208 
209 	if (offset + rc > tpm_buf_length(buf))
210 		return -EIO;
211 
212 	memcpy(name, &buf->data[offset], rc);
213 	return name_size_alg;
214 }
215 #endif /* CONFIG_TCG_TPM2_HMAC */
216 
217 /**
218  * tpm_buf_append_name() - add a handle area to the buffer
219  * @chip: the TPM chip structure
220  * @buf: The buffer to be appended
221  * @handle: The handle to be appended
222  * @name: The name of the handle (may be NULL)
223  *
224  * In order to compute session HMACs, we need to know the names of the
225  * objects pointed to by the handles.  For most objects, this is simply
226  * the actual 4 byte handle or an empty buf (in these cases @name
227  * should be NULL) but for volatile objects, permanent objects and NV
228  * areas, the name is defined as the hash (according to the name
229  * algorithm which should be set to sha256) of the public area to
230  * which the two byte algorithm id has been appended.  For these
231  * objects, the @name pointer should point to this.  If a name is
232  * required but @name is NULL, then TPM2_ReadPublic() will be called
233  * on the handle to obtain the name.
234  *
235  * As with most tpm_buf operations, success is assumed because failure
236  * will be caused by an incorrect programming model and indicated by a
237  * kernel message.
238  *
239  * Ends the authorization session on failure.
240  */
241 int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
242 			u32 handle, u8 *name)
243 {
244 #ifdef CONFIG_TCG_TPM2_HMAC
245 	enum tpm2_mso_type mso = tpm2_handle_mso(handle);
246 	struct tpm2_auth *auth;
247 	u16 name_size_alg;
248 	int slot;
249 	int ret;
250 #endif
251 
252 	if (!tpm2_chip_auth(chip)) {
253 		tpm_buf_append_handle(buf, handle);
254 		return 0;
255 	}
256 
257 #ifdef CONFIG_TCG_TPM2_HMAC
258 	slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE) / 4;
259 	if (slot >= AUTH_MAX_NAMES) {
260 		dev_err(&chip->dev, "too many handles\n");
261 		ret = -EIO;
262 		goto err;
263 	}
264 	auth = chip->auth;
265 	if (auth->session != tpm_buf_length(buf)) {
266 		dev_err(&chip->dev, "session state malformed");
267 		ret = -EIO;
268 		goto err;
269 	}
270 	tpm_buf_append_u32(buf, handle);
271 	auth->session += 4;
272 
273 	if (mso == TPM2_MSO_PERSISTENT ||
274 	    mso == TPM2_MSO_VOLATILE ||
275 	    mso == TPM2_MSO_NVRAM) {
276 		if (!name) {
277 			ret = tpm2_read_public(chip, handle, auth->name[slot]);
278 		} else {
279 			ret = name_size(name);
280 		}
281 
282 		if (ret < 0)
283 			goto err;
284 
285 		name_size_alg = ret;
286 	} else {
287 		if (name) {
288 			dev_err(&chip->dev, "handle 0x%08x does not use a name\n",
289 				handle);
290 			ret = -EIO;
291 			goto err;
292 		}
293 	}
294 
295 	auth->name_h[slot] = handle;
296 	if (name)
297 		memcpy(auth->name[slot], name, name_size_alg);
298 #endif
299 	return 0;
300 
301 #ifdef CONFIG_TCG_TPM2_HMAC
302 err:
303 	tpm2_end_auth_session(chip);
304 	return tpm_ret_to_err(ret);
305 #endif
306 }
307 EXPORT_SYMBOL_GPL(tpm_buf_append_name);
308 
309 void tpm_buf_append_auth(struct tpm_chip *chip, struct tpm_buf *buf,
310 			 u8 *passphrase, int passphrase_len)
311 {
312 	/* offset tells us where the sessions area begins */
313 	int offset = buf->handles * 4 + TPM_HEADER_SIZE;
314 	u32 len = 9 + passphrase_len;
315 
316 	if (tpm_buf_length(buf) != offset) {
317 		/* not the first session so update the existing length */
318 		len += get_unaligned_be32(&buf->data[offset]);
319 		put_unaligned_be32(len, &buf->data[offset]);
320 	} else {
321 		tpm_buf_append_u32(buf, len);
322 	}
323 	/* auth handle */
324 	tpm_buf_append_u32(buf, TPM2_RS_PW);
325 	/* nonce */
326 	tpm_buf_append_u16(buf, 0);
327 	/* attributes */
328 	tpm_buf_append_u8(buf, 0);
329 	/* passphrase */
330 	tpm_buf_append_u16(buf, passphrase_len);
331 	tpm_buf_append(buf, passphrase, passphrase_len);
332 }
333 
334 /**
335  * tpm_buf_append_hmac_session() - Append a TPM session element
336  * @chip: the TPM chip structure
337  * @buf: The buffer to be appended
338  * @attributes: The session attributes
339  * @passphrase: The session authority (NULL if none)
340  * @passphrase_len: The length of the session authority (0 if none)
341  *
342  * This fills in a session structure in the TPM command buffer, except
343  * for the HMAC which cannot be computed until the command buffer is
344  * complete.  The type of session is controlled by the @attributes,
345  * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
346  * session won't terminate after tpm_buf_check_hmac_response(),
347  * TPM2_SA_DECRYPT which means this buffers first parameter should be
348  * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
349  * response buffer's first parameter needs to be decrypted (confusing,
350  * but the defines are written from the point of view of the TPM).
351  *
352  * Any session appended by this command must be finalized by calling
353  * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
354  * and the TPM will reject the command.
355  *
356  * As with most tpm_buf operations, success is assumed because failure
357  * will be caused by an incorrect programming model and indicated by a
358  * kernel message.
359  */
360 void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
361 				 u8 attributes, u8 *passphrase,
362 				 int passphrase_len)
363 {
364 #ifdef CONFIG_TCG_TPM2_HMAC
365 	u8 nonce[SHA256_DIGEST_SIZE];
366 	struct tpm2_auth *auth;
367 	u32 len;
368 #endif
369 
370 	if (!tpm2_chip_auth(chip)) {
371 		tpm_buf_append_auth(chip, buf, passphrase, passphrase_len);
372 		return;
373 	}
374 
375 #ifdef CONFIG_TCG_TPM2_HMAC
376 	/* The first write to /dev/tpm{rm0} will flush the session. */
377 	attributes |= TPM2_SA_CONTINUE_SESSION;
378 
379 	/*
380 	 * The Architecture Guide requires us to strip trailing zeros
381 	 * before computing the HMAC
382 	 */
383 	while (passphrase && passphrase_len > 0 && passphrase[passphrase_len - 1] == '\0')
384 		passphrase_len--;
385 
386 	auth = chip->auth;
387 	auth->attrs = attributes;
388 	auth->passphrase_len = passphrase_len;
389 	if (passphrase_len)
390 		memcpy(auth->passphrase, passphrase, passphrase_len);
391 
392 	if (auth->session != tpm_buf_length(buf)) {
393 		/* we're not the first session */
394 		len = get_unaligned_be32(&buf->data[auth->session]);
395 		if (4 + len + auth->session != tpm_buf_length(buf)) {
396 			WARN(1, "session length mismatch, cannot append");
397 			return;
398 		}
399 
400 		/* add our new session */
401 		len += 9 + 2 * SHA256_DIGEST_SIZE;
402 		put_unaligned_be32(len, &buf->data[auth->session]);
403 	} else {
404 		tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
405 	}
406 
407 	/* random number for our nonce */
408 	get_random_bytes(nonce, sizeof(nonce));
409 	memcpy(auth->our_nonce, nonce, sizeof(nonce));
410 	tpm_buf_append_u32(buf, auth->handle);
411 	/* our new nonce */
412 	tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
413 	tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
414 	tpm_buf_append_u8(buf, auth->attrs);
415 	/* and put a placeholder for the hmac */
416 	tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
417 	tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
418 #endif
419 }
420 EXPORT_SYMBOL_GPL(tpm_buf_append_hmac_session);
421 
422 #ifdef CONFIG_TCG_TPM2_HMAC
423 
424 static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
425 			       u32 *handle, u8 *name);
426 
427 /*
428  * assume hash sha256 and nonces u, v of size SHA256_DIGEST_SIZE but
429  * otherwise standard tpm2_KDFa.  Note output is in bytes not bits.
430  */
431 static void tpm2_KDFa(u8 *key, u32 key_len, const char *label, u8 *u,
432 		      u8 *v, u32 bytes, u8 *out)
433 {
434 	u32 counter = 1;
435 	const __be32 bits = cpu_to_be32(bytes * 8);
436 
437 	while (bytes > 0) {
438 		struct hmac_sha256_ctx hctx;
439 		__be32 c = cpu_to_be32(counter);
440 
441 		hmac_sha256_init_usingrawkey(&hctx, key, key_len);
442 		hmac_sha256_update(&hctx, (u8 *)&c, sizeof(c));
443 		hmac_sha256_update(&hctx, label, strlen(label) + 1);
444 		hmac_sha256_update(&hctx, u, SHA256_DIGEST_SIZE);
445 		hmac_sha256_update(&hctx, v, SHA256_DIGEST_SIZE);
446 		hmac_sha256_update(&hctx, (u8 *)&bits, sizeof(bits));
447 		hmac_sha256_final(&hctx, out);
448 
449 		bytes -= SHA256_DIGEST_SIZE;
450 		counter++;
451 		out += SHA256_DIGEST_SIZE;
452 	}
453 }
454 
455 /*
456  * Somewhat of a bastardization of the real KDFe.  We're assuming
457  * we're working with known point sizes for the input parameters and
458  * the hash algorithm is fixed at sha256.  Because we know that the
459  * point size is 32 bytes like the hash size, there's no need to loop
460  * in this KDF.
461  */
462 static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
463 		      u8 *out)
464 {
465 	struct sha256_ctx sctx;
466 	/*
467 	 * this should be an iterative counter, but because we know
468 	 *  we're only taking 32 bytes for the point using a sha256
469 	 *  hash which is also 32 bytes, there's only one loop
470 	 */
471 	__be32 c = cpu_to_be32(1);
472 
473 	sha256_init(&sctx);
474 	/* counter (BE) */
475 	sha256_update(&sctx, (u8 *)&c, sizeof(c));
476 	/* secret value */
477 	sha256_update(&sctx, z, EC_PT_SZ);
478 	/* string including trailing zero */
479 	sha256_update(&sctx, str, strlen(str)+1);
480 	sha256_update(&sctx, pt_u, EC_PT_SZ);
481 	sha256_update(&sctx, pt_v, EC_PT_SZ);
482 	sha256_final(&sctx, out);
483 }
484 
485 static int tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip,
486 			       struct tpm2_auth *auth)
487 {
488 	struct crypto_kpp *kpp;
489 	struct kpp_request *req;
490 	DECLARE_CRYPTO_WAIT(wait);
491 	struct scatterlist s[2], d[1];
492 	struct ecdh p = {0};
493 	u8 encoded_key[EC_PT_SZ], *x, *y;
494 	unsigned int buf_len;
495 	int rc;
496 
497 	/* secret is two sized points */
498 	tpm_buf_append_u16(buf, (EC_PT_SZ + 2)*2);
499 	/*
500 	 * we cheat here and append uninitialized data to form
501 	 * the points.  All we care about is getting the two
502 	 * co-ordinate pointers, which will be used to overwrite
503 	 * the uninitialized data
504 	 */
505 	tpm_buf_append_u16(buf, EC_PT_SZ);
506 	x = &buf->data[tpm_buf_length(buf)];
507 	tpm_buf_append(buf, encoded_key, EC_PT_SZ);
508 	tpm_buf_append_u16(buf, EC_PT_SZ);
509 	y = &buf->data[tpm_buf_length(buf)];
510 	tpm_buf_append(buf, encoded_key, EC_PT_SZ);
511 	sg_init_table(s, 2);
512 	sg_set_buf(&s[0], x, EC_PT_SZ);
513 	sg_set_buf(&s[1], y, EC_PT_SZ);
514 
515 	kpp = crypto_alloc_kpp("ecdh-nist-p256", CRYPTO_ALG_INTERNAL, 0);
516 	if (IS_ERR(kpp)) {
517 		dev_err(&chip->dev, "crypto ecdh allocation failed\n");
518 		return PTR_ERR(kpp);
519 	}
520 
521 	buf_len = crypto_ecdh_key_len(&p);
522 	if (sizeof(encoded_key) < buf_len) {
523 		dev_err(&chip->dev, "salt buffer too small needs %d\n",
524 			buf_len);
525 		rc = -EINVAL;
526 		goto err_free_kpp;
527 	}
528 	crypto_ecdh_encode_key(encoded_key, buf_len, &p);
529 	/* this generates a random private key */
530 	crypto_kpp_set_secret(kpp, encoded_key, buf_len);
531 
532 	/* salt is now the public point of this private key */
533 	req = kpp_request_alloc(kpp, GFP_KERNEL);
534 	if (!req) {
535 		rc = -ENOMEM;
536 		goto err_free_kpp;
537 	}
538 	kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
539 				 crypto_req_done, &wait);
540 	kpp_request_set_input(req, NULL, 0);
541 	kpp_request_set_output(req, s, EC_PT_SZ*2);
542 	rc = crypto_wait_req(crypto_kpp_generate_public_key(req), &wait);
543 	if (rc)
544 		goto err_free_req;
545 	/*
546 	 * we're not done: now we have to compute the shared secret
547 	 * which is our private key multiplied by the tpm_key public
548 	 * point, we actually only take the x point and discard the y
549 	 * point and feed it through KDFe to get the final secret salt
550 	 */
551 	sg_set_buf(&s[0], chip->null_ec_key_x, EC_PT_SZ);
552 	sg_set_buf(&s[1], chip->null_ec_key_y, EC_PT_SZ);
553 	kpp_request_set_input(req, s, EC_PT_SZ*2);
554 	sg_init_one(d, auth->salt, EC_PT_SZ);
555 	kpp_request_set_output(req, d, EC_PT_SZ);
556 	rc = crypto_wait_req(crypto_kpp_compute_shared_secret(req), &wait);
557 	if (rc)
558 		goto err_free_req;
559 
560 	/*
561 	 * pass the shared secret through KDFe for salt. Note salt
562 	 * area is used both for input shared secret and output salt.
563 	 * This works because KDFe fully consumes the secret before it
564 	 * writes the salt
565 	 */
566 	tpm2_KDFe(auth->salt, "SECRET", x, chip->null_ec_key_x, auth->salt);
567 
568 	kpp_request_free(req);
569 	crypto_free_kpp(kpp);
570 	return 0;
571 
572 err_free_req:
573 	kpp_request_free(req);
574 
575 err_free_kpp:
576 	crypto_free_kpp(kpp);
577 	return rc;
578 }
579 
580 /**
581  * tpm_buf_fill_hmac_session() - finalize the session HMAC
582  * @chip: the TPM chip structure
583  * @buf: The buffer to be appended
584  *
585  * This command must not be called until all of the parameters have
586  * been appended to @buf otherwise the computed HMAC will be
587  * incorrect.
588  *
589  * This function computes and fills in the session HMAC using the
590  * session key and, if TPM2_SA_DECRYPT was specified, computes the
591  * encryption key and encrypts the first parameter of the command
592  * buffer with it.
593  *
594  * Ends the authorization session on failure.
595  */
596 int tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)
597 {
598 	u32 cc, handles, val;
599 	struct tpm2_auth *auth = chip->auth;
600 	int i;
601 	struct tpm_header *head = (struct tpm_header *)buf->data;
602 	off_t offset_s = TPM_HEADER_SIZE, offset_p;
603 	u8 *hmac = NULL;
604 	u32 attrs;
605 	u8 cphash[SHA256_DIGEST_SIZE];
606 	struct sha256_ctx sctx;
607 	struct hmac_sha256_ctx hctx;
608 	int ret;
609 
610 	if (!auth) {
611 		ret = -EIO;
612 		goto err;
613 	}
614 
615 	/* save the command code in BE format */
616 	auth->ordinal = head->ordinal;
617 
618 	cc = be32_to_cpu(head->ordinal);
619 
620 	i = tpm2_find_cc(chip, cc);
621 	if (i < 0) {
622 		dev_err(&chip->dev, "command 0x%08x not found\n", cc);
623 		ret = -EIO;
624 		goto err;
625 	}
626 
627 	attrs = chip->cc_attrs_tbl[i];
628 
629 	handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0);
630 
631 	/*
632 	 * just check the names, it's easy to make mistakes.  This
633 	 * would happen if someone added a handle via
634 	 * tpm_buf_append_u32() instead of tpm_buf_append_name()
635 	 */
636 	for (i = 0; i < handles; i++) {
637 		u32 handle = tpm_buf_read_u32(buf, &offset_s);
638 
639 		if (auth->name_h[i] != handle) {
640 			dev_err(&chip->dev, "invalid handle 0x%08x\n", handle);
641 			ret = -EIO;
642 			goto err;
643 		}
644 	}
645 	/* point offset_s to the start of the sessions */
646 	val = tpm_buf_read_u32(buf, &offset_s);
647 	/* point offset_p to the start of the parameters */
648 	offset_p = offset_s + val;
649 	for (i = 1; offset_s < offset_p; i++) {
650 		u32 handle = tpm_buf_read_u32(buf, &offset_s);
651 		u16 len;
652 		u8 a;
653 
654 		/* nonce (already in auth) */
655 		len = tpm_buf_read_u16(buf, &offset_s);
656 		offset_s += len;
657 
658 		a = tpm_buf_read_u8(buf, &offset_s);
659 
660 		len = tpm_buf_read_u16(buf, &offset_s);
661 		if (handle == auth->handle && auth->attrs == a) {
662 			hmac = &buf->data[offset_s];
663 			/*
664 			 * save our session number so we know which
665 			 * session in the response belongs to us
666 			 */
667 			auth->session = i;
668 		}
669 
670 		offset_s += len;
671 	}
672 	if (offset_s != offset_p) {
673 		dev_err(&chip->dev, "session length is incorrect\n");
674 		ret = -EIO;
675 		goto err;
676 	}
677 	if (!hmac) {
678 		dev_err(&chip->dev, "could not find HMAC session\n");
679 		ret = -EIO;
680 		goto err;
681 	}
682 
683 	/* encrypt before HMAC */
684 	if (auth->attrs & TPM2_SA_DECRYPT) {
685 		u16 len;
686 
687 		/* need key and IV */
688 		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
689 			  + auth->passphrase_len, "CFB", auth->our_nonce,
690 			  auth->tpm_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
691 			  auth->scratch);
692 
693 		len = tpm_buf_read_u16(buf, &offset_p);
694 		aes_prepareenckey(&auth->aes_key, auth->scratch, AES_KEY_BYTES);
695 		aescfb_encrypt(&auth->aes_key, &buf->data[offset_p],
696 			       &buf->data[offset_p], len,
697 			       auth->scratch + AES_KEY_BYTES);
698 		/* reset p to beginning of parameters for HMAC */
699 		offset_p -= 2;
700 	}
701 
702 	sha256_init(&sctx);
703 	/* ordinal is already BE */
704 	sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));
705 	/* add the handle names */
706 	for (i = 0; i < handles; i++) {
707 		enum tpm2_mso_type mso = tpm2_handle_mso(auth->name_h[i]);
708 
709 		if (mso == TPM2_MSO_PERSISTENT ||
710 		    mso == TPM2_MSO_VOLATILE ||
711 		    mso == TPM2_MSO_NVRAM) {
712 			ret = name_size(auth->name[i]);
713 			if (ret < 0)
714 				goto err;
715 
716 			sha256_update(&sctx, auth->name[i], ret);
717 		} else {
718 			__be32 h = cpu_to_be32(auth->name_h[i]);
719 
720 			sha256_update(&sctx, (u8 *)&h, 4);
721 		}
722 	}
723 	if (offset_s != tpm_buf_length(buf))
724 		sha256_update(&sctx, &buf->data[offset_s],
725 			      tpm_buf_length(buf) - offset_s);
726 	sha256_final(&sctx, cphash);
727 
728 	/* now calculate the hmac */
729 	hmac_sha256_init_usingrawkey(&hctx, auth->session_key,
730 				     sizeof(auth->session_key) +
731 					     auth->passphrase_len);
732 	hmac_sha256_update(&hctx, cphash, sizeof(cphash));
733 	hmac_sha256_update(&hctx, auth->our_nonce, sizeof(auth->our_nonce));
734 	hmac_sha256_update(&hctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
735 	hmac_sha256_update(&hctx, &auth->attrs, 1);
736 	hmac_sha256_final(&hctx, hmac);
737 	return 0;
738 
739 err:
740 	tpm2_end_auth_session(chip);
741 	return ret;
742 }
743 EXPORT_SYMBOL(tpm_buf_fill_hmac_session);
744 
745 /**
746  * tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness
747  * @chip: the TPM chip structure
748  * @buf: the original command buffer (which now contains the response)
749  * @rc: the return code from tpm_transmit_cmd
750  *
751  * If @rc is non zero, @buf may not contain an actual return, so @rc
752  * is passed through as the return and the session cleaned up and
753  * de-allocated if required (this is required if
754  * TPM2_SA_CONTINUE_SESSION was not specified as a session flag).
755  *
756  * If @rc is zero, the response HMAC is computed against the returned
757  * @buf and matched to the TPM one in the session area.  If there is a
758  * mismatch, an error is logged and -EINVAL returned.
759  *
760  * The reason for this is that the command issue and HMAC check
761  * sequence should look like:
762  *
763  *	rc = tpm_transmit_cmd(...);
764  *	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
765  *	if (rc)
766  *		...
767  *
768  * Which is easily layered into the current contrl flow.
769  *
770  * Returns: 0 on success or an error.
771  */
772 int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,
773 				int rc)
774 {
775 	struct tpm_header *head = (struct tpm_header *)buf->data;
776 	struct tpm2_auth *auth = chip->auth;
777 	off_t offset_s, offset_p;
778 	u8 rphash[SHA256_DIGEST_SIZE];
779 	u32 attrs, cc;
780 	struct sha256_ctx sctx;
781 	struct hmac_sha256_ctx hctx;
782 	u16 tag = be16_to_cpu(head->tag);
783 	int parm_len, len, i, handles;
784 
785 	if (!auth)
786 		return rc;
787 
788 	cc = be32_to_cpu(auth->ordinal);
789 
790 	if (auth->session >= TPM_HEADER_SIZE) {
791 		WARN(1, "tpm session not filled correctly\n");
792 		goto out;
793 	}
794 
795 	if (rc != 0)
796 		/* pass non success rc through and close the session */
797 		goto out;
798 
799 	rc = -EINVAL;
800 	if (tag != TPM2_ST_SESSIONS) {
801 		dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");
802 		goto out;
803 	}
804 
805 	i = tpm2_find_cc(chip, cc);
806 	if (i < 0)
807 		goto out;
808 	attrs = chip->cc_attrs_tbl[i];
809 	handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;
810 
811 	/* point to area beyond handles */
812 	offset_s = TPM_HEADER_SIZE + handles * 4;
813 	parm_len = tpm_buf_read_u32(buf, &offset_s);
814 	offset_p = offset_s;
815 	offset_s += parm_len;
816 	/* skip over any sessions before ours */
817 	for (i = 0; i < auth->session - 1; i++) {
818 		len = tpm_buf_read_u16(buf, &offset_s);
819 		offset_s += len + 1;
820 		len = tpm_buf_read_u16(buf, &offset_s);
821 		offset_s += len;
822 	}
823 	/* TPM nonce */
824 	len = tpm_buf_read_u16(buf, &offset_s);
825 	if (offset_s + len > tpm_buf_length(buf))
826 		goto out;
827 	if (len != SHA256_DIGEST_SIZE)
828 		goto out;
829 	memcpy(auth->tpm_nonce, &buf->data[offset_s], len);
830 	offset_s += len;
831 	attrs = tpm_buf_read_u8(buf, &offset_s);
832 	len = tpm_buf_read_u16(buf, &offset_s);
833 	if (offset_s + len != tpm_buf_length(buf))
834 		goto out;
835 	if (len != SHA256_DIGEST_SIZE)
836 		goto out;
837 	/*
838 	 * offset_s points to the HMAC. now calculate comparison, beginning
839 	 * with rphash
840 	 */
841 	sha256_init(&sctx);
842 	/* yes, I know this is now zero, but it's what the standard says */
843 	sha256_update(&sctx, (u8 *)&head->return_code,
844 		      sizeof(head->return_code));
845 	/* ordinal is already BE */
846 	sha256_update(&sctx, (u8 *)&auth->ordinal, sizeof(auth->ordinal));
847 	sha256_update(&sctx, &buf->data[offset_p], parm_len);
848 	sha256_final(&sctx, rphash);
849 
850 	/* now calculate the hmac */
851 	hmac_sha256_init_usingrawkey(&hctx, auth->session_key,
852 				     sizeof(auth->session_key) +
853 					     auth->passphrase_len);
854 	hmac_sha256_update(&hctx, rphash, sizeof(rphash));
855 	hmac_sha256_update(&hctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
856 	hmac_sha256_update(&hctx, auth->our_nonce, sizeof(auth->our_nonce));
857 	hmac_sha256_update(&hctx, &auth->attrs, 1);
858 	/* we're done with the rphash, so put our idea of the hmac there */
859 	hmac_sha256_final(&hctx, rphash);
860 	if (crypto_memneq(rphash, &buf->data[offset_s], SHA256_DIGEST_SIZE)) {
861 		dev_err(&chip->dev, "TPM: HMAC check failed\n");
862 		goto out;
863 	}
864 	rc = 0;
865 
866 	/* now do response decryption */
867 	if (auth->attrs & TPM2_SA_ENCRYPT) {
868 		/* need key and IV */
869 		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
870 			  + auth->passphrase_len, "CFB", auth->tpm_nonce,
871 			  auth->our_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
872 			  auth->scratch);
873 
874 		len = tpm_buf_read_u16(buf, &offset_p);
875 		aes_prepareenckey(&auth->aes_key, auth->scratch, AES_KEY_BYTES);
876 		aescfb_decrypt(&auth->aes_key, &buf->data[offset_p],
877 			       &buf->data[offset_p], len,
878 			       auth->scratch + AES_KEY_BYTES);
879 	}
880 
881  out:
882 	if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {
883 		if (rc)
884 			/* manually close the session if it wasn't consumed */
885 			tpm2_flush_context(chip, auth->handle);
886 
887 		kfree_sensitive(auth);
888 		chip->auth = NULL;
889 	} else {
890 		/* reset for next use  */
891 		auth->session = TPM_HEADER_SIZE;
892 	}
893 
894 	return rc;
895 }
896 EXPORT_SYMBOL(tpm_buf_check_hmac_response);
897 
898 /**
899  * tpm2_end_auth_session() - kill the allocated auth session
900  * @chip: the TPM chip structure
901  *
902  * ends the session started by tpm2_start_auth_session and frees all
903  * the resources.  Under normal conditions,
904  * tpm_buf_check_hmac_response() will correctly end the session if
905  * required, so this function is only for use in error legs that will
906  * bypass the normal invocation of tpm_buf_check_hmac_response().
907  */
908 void tpm2_end_auth_session(struct tpm_chip *chip)
909 {
910 	struct tpm2_auth *auth = chip->auth;
911 
912 	if (!auth)
913 		return;
914 
915 	tpm2_flush_context(chip, auth->handle);
916 	kfree_sensitive(auth);
917 	chip->auth = NULL;
918 }
919 EXPORT_SYMBOL(tpm2_end_auth_session);
920 
921 static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,
922 					 struct tpm_buf *buf)
923 {
924 	struct tpm_header *head = (struct tpm_header *)buf->data;
925 	u32 tot_len = be32_to_cpu(head->length);
926 	off_t offset = TPM_HEADER_SIZE;
927 	u32 val;
928 
929 	/* we're starting after the header so adjust the length */
930 	tot_len -= TPM_HEADER_SIZE;
931 
932 	/* should have handle plus nonce */
933 	if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
934 		return -EINVAL;
935 
936 	auth->handle = tpm_buf_read_u32(buf, &offset);
937 	val = tpm_buf_read_u16(buf, &offset);
938 	if (val != sizeof(auth->tpm_nonce))
939 		return -EINVAL;
940 	memcpy(auth->tpm_nonce, &buf->data[offset], sizeof(auth->tpm_nonce));
941 	/* now compute the session key from the nonces */
942 	tpm2_KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
943 		  auth->our_nonce, sizeof(auth->session_key),
944 		  auth->session_key);
945 
946 	return 0;
947 }
948 
949 static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)
950 {
951 	unsigned int offset = 0; /* dummy offset for null seed context */
952 	u8 name[SHA256_DIGEST_SIZE + 2];
953 	u32 tmp_null_key;
954 	int rc;
955 
956 	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
957 			       &tmp_null_key);
958 	if (rc != -EINVAL) {
959 		if (!rc)
960 			*null_key = tmp_null_key;
961 		goto err;
962 	}
963 
964 	/* Try to re-create null key, given the integrity failure: */
965 	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &tmp_null_key, name);
966 	if (rc)
967 		goto err;
968 
969 	/* Return null key if the name has not been changed: */
970 	if (!memcmp(name, chip->null_key_name, sizeof(name))) {
971 		*null_key = tmp_null_key;
972 		return 0;
973 	}
974 
975 	/* Deduce from the name change TPM interference: */
976 	dev_err(&chip->dev, "null key integrity check failed\n");
977 	tpm2_flush_context(chip, tmp_null_key);
978 	rc = -ENODEV;
979 
980 err:
981 	if (rc) {
982 		chip->flags |= TPM_CHIP_FLAG_DISABLE;
983 		rc = -ENODEV;
984 	}
985 	return rc;
986 }
987 
988 /**
989  * tpm2_start_auth_session() - Create an a HMAC authentication session
990  * @chip:	A TPM chip
991  *
992  * Loads the ephemeral key (null seed), and starts an HMAC authenticated
993  * session. The null seed is flushed before the return.
994  *
995  * Returns zero on success, or a POSIX error code.
996  */
997 int tpm2_start_auth_session(struct tpm_chip *chip)
998 {
999 	struct tpm_buf *buf __free(kfree) = NULL;
1000 	struct tpm2_auth *auth;
1001 	u32 null_key;
1002 	int rc;
1003 
1004 	if (chip->auth) {
1005 		dev_dbg_once(&chip->dev, "auth session is active\n");
1006 		return 0;
1007 	}
1008 
1009 	auth = kzalloc_obj(*auth);
1010 	if (!auth)
1011 		return -ENOMEM;
1012 
1013 	rc = tpm2_load_null(chip, &null_key);
1014 	if (rc) {
1015 		kfree_sensitive(auth);
1016 		return rc;
1017 	}
1018 
1019 	auth->session = TPM_HEADER_SIZE;
1020 
1021 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
1022 	if (!buf) {
1023 		kfree_sensitive(auth);
1024 		return -ENOMEM;
1025 	}
1026 
1027 	tpm_buf_init(buf, TPM_BUFSIZE);
1028 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
1029 	/* salt key handle */
1030 	tpm_buf_append_u32(buf, null_key);
1031 	/* bind key handle */
1032 	tpm_buf_append_u32(buf, TPM2_RH_NULL);
1033 	/* nonce caller */
1034 	get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce));
1035 	tpm_buf_append_u16(buf, sizeof(auth->our_nonce));
1036 	tpm_buf_append(buf, auth->our_nonce, sizeof(auth->our_nonce));
1037 
1038 	/* append encrypted salt and squirrel away unencrypted in auth */
1039 	rc = tpm_buf_append_salt(buf, chip, auth);
1040 	if (rc) {
1041 		tpm2_flush_context(chip, null_key);
1042 		kfree_sensitive(auth);
1043 		return rc;
1044 	}
1045 	/* session type (HMAC, audit or policy) */
1046 	tpm_buf_append_u8(buf, TPM2_SE_HMAC);
1047 
1048 	/* symmetric encryption parameters */
1049 	/* symmetric algorithm */
1050 	tpm_buf_append_u16(buf, TPM_ALG_AES);
1051 	/* bits for symmetric algorithm */
1052 	tpm_buf_append_u16(buf, AES_KEY_BITS);
1053 	/* symmetric algorithm mode (must be CFB) */
1054 	tpm_buf_append_u16(buf, TPM_ALG_CFB);
1055 	/* hash algorithm for session */
1056 	tpm_buf_append_u16(buf, TPM_ALG_SHA256);
1057 
1058 	rc = tpm_ret_to_err(tpm_transmit_cmd(chip, buf, 0, "StartAuthSession"));
1059 	tpm2_flush_context(chip, null_key);
1060 
1061 	if (rc == TPM2_RC_SUCCESS)
1062 		rc = tpm2_parse_start_auth_session(auth, buf);
1063 
1064 	if (rc == TPM2_RC_SUCCESS) {
1065 		chip->auth = auth;
1066 		return 0;
1067 	}
1068 
1069 	kfree_sensitive(auth);
1070 	return rc;
1071 }
1072 EXPORT_SYMBOL(tpm2_start_auth_session);
1073 
1074 /*
1075  * A mask containing the object attributes for the kernel held null primary key
1076  * used in HMAC encryption. For more information on specific attributes look up
1077  * to "8.3 TPMA_OBJECT (Object Attributes)".
1078  */
1079 #define TPM2_OA_NULL_KEY ( \
1080 	TPM2_OA_NO_DA | \
1081 	TPM2_OA_FIXED_TPM | \
1082 	TPM2_OA_FIXED_PARENT | \
1083 	TPM2_OA_SENSITIVE_DATA_ORIGIN |	\
1084 	TPM2_OA_USER_WITH_AUTH | \
1085 	TPM2_OA_DECRYPT | \
1086 	TPM2_OA_RESTRICTED)
1087 
1088 /**
1089  * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
1090  *
1091  * @chip:	The TPM the primary was created under
1092  * @buf:	The response buffer from the chip
1093  * @handle:	pointer to be filled in with the return handle of the primary
1094  * @hierarchy:	The hierarchy the primary was created for
1095  * @name:	pointer to be filled in with the primary key name
1096  *
1097  * Return:
1098  * * 0		- OK
1099  * * -errno	- A system error
1100  * * TPM_RC	- A TPM error
1101  */
1102 static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
1103 				     u32 *handle, u32 hierarchy, u8 *name)
1104 {
1105 	struct tpm_header *head = (struct tpm_header *)buf->data;
1106 	off_t offset_r = TPM_HEADER_SIZE, offset_t;
1107 	u16 len = TPM_HEADER_SIZE;
1108 	u32 total_len = be32_to_cpu(head->length);
1109 	u32 val, param_len, keyhandle;
1110 
1111 	keyhandle = tpm_buf_read_u32(buf, &offset_r);
1112 	if (handle)
1113 		*handle = keyhandle;
1114 	else
1115 		tpm2_flush_context(chip, keyhandle);
1116 
1117 	param_len = tpm_buf_read_u32(buf, &offset_r);
1118 	/*
1119 	 * param_len doesn't include the header, but all the other
1120 	 * lengths and offsets do, so add it to parm len to make
1121 	 * the comparisons easier
1122 	 */
1123 	param_len += TPM_HEADER_SIZE;
1124 
1125 	if (param_len + 8 > total_len)
1126 		return -EINVAL;
1127 	len = tpm_buf_read_u16(buf, &offset_r);
1128 	offset_t = offset_r;
1129 	if (name) {
1130 		/*
1131 		 * now we have the public area, compute the name of
1132 		 * the object
1133 		 */
1134 		put_unaligned_be16(TPM_ALG_SHA256, name);
1135 		sha256(&buf->data[offset_r], len, name + 2);
1136 	}
1137 
1138 	/* validate the public key */
1139 	val = tpm_buf_read_u16(buf, &offset_t);
1140 
1141 	/* key type (must be what we asked for) */
1142 	if (val != TPM_ALG_ECC)
1143 		return -EINVAL;
1144 	val = tpm_buf_read_u16(buf, &offset_t);
1145 
1146 	/* name algorithm */
1147 	if (val != TPM_ALG_SHA256)
1148 		return -EINVAL;
1149 	val = tpm_buf_read_u32(buf, &offset_t);
1150 
1151 	/* object properties */
1152 	if (val != TPM2_OA_NULL_KEY)
1153 		return -EINVAL;
1154 
1155 	/* auth policy (empty) */
1156 	val = tpm_buf_read_u16(buf, &offset_t);
1157 	if (val != 0)
1158 		return -EINVAL;
1159 
1160 	/* symmetric key parameters */
1161 	val = tpm_buf_read_u16(buf, &offset_t);
1162 	if (val != TPM_ALG_AES)
1163 		return -EINVAL;
1164 
1165 	/* symmetric key length */
1166 	val = tpm_buf_read_u16(buf, &offset_t);
1167 	if (val != AES_KEY_BITS)
1168 		return -EINVAL;
1169 
1170 	/* symmetric encryption scheme */
1171 	val = tpm_buf_read_u16(buf, &offset_t);
1172 	if (val != TPM_ALG_CFB)
1173 		return -EINVAL;
1174 
1175 	/* signing scheme */
1176 	val = tpm_buf_read_u16(buf, &offset_t);
1177 	if (val != TPM_ALG_NULL)
1178 		return -EINVAL;
1179 
1180 	/* ECC Curve */
1181 	val = tpm_buf_read_u16(buf, &offset_t);
1182 	if (val != TPM2_ECC_NIST_P256)
1183 		return -EINVAL;
1184 
1185 	/* KDF Scheme */
1186 	val = tpm_buf_read_u16(buf, &offset_t);
1187 	if (val != TPM_ALG_NULL)
1188 		return -EINVAL;
1189 
1190 	/* extract public key (x and y points) */
1191 	val = tpm_buf_read_u16(buf, &offset_t);
1192 	if (val != EC_PT_SZ)
1193 		return -EINVAL;
1194 	memcpy(chip->null_ec_key_x, &buf->data[offset_t], val);
1195 	offset_t += val;
1196 	val = tpm_buf_read_u16(buf, &offset_t);
1197 	if (val != EC_PT_SZ)
1198 		return -EINVAL;
1199 	memcpy(chip->null_ec_key_y, &buf->data[offset_t], val);
1200 	offset_t += val;
1201 
1202 	/* original length of the whole TPM2B */
1203 	offset_r += len;
1204 
1205 	/* should have exactly consumed the TPM2B public structure */
1206 	if (offset_t != offset_r)
1207 		return -EINVAL;
1208 	if (offset_r > param_len)
1209 		return -EINVAL;
1210 
1211 	/* creation data (skip) */
1212 	len = tpm_buf_read_u16(buf, &offset_r);
1213 	offset_r += len;
1214 	if (offset_r > param_len)
1215 		return -EINVAL;
1216 
1217 	/* creation digest (must be sha256) */
1218 	len = tpm_buf_read_u16(buf, &offset_r);
1219 	offset_r += len;
1220 	if (len != SHA256_DIGEST_SIZE || offset_r > param_len)
1221 		return -EINVAL;
1222 
1223 	/* TPMT_TK_CREATION follows */
1224 	/* tag, must be TPM_ST_CREATION (0x8021) */
1225 	val = tpm_buf_read_u16(buf, &offset_r);
1226 	if (val != TPM2_ST_CREATION || offset_r > param_len)
1227 		return -EINVAL;
1228 
1229 	/* hierarchy */
1230 	val = tpm_buf_read_u32(buf, &offset_r);
1231 	if (val != hierarchy || offset_r > param_len)
1232 		return -EINVAL;
1233 
1234 	/* the ticket digest HMAC (might not be sha256) */
1235 	len = tpm_buf_read_u16(buf, &offset_r);
1236 	offset_r += len;
1237 	if (offset_r > param_len)
1238 		return -EINVAL;
1239 
1240 	/*
1241 	 * finally we have the name, which is a sha256 digest plus a 2
1242 	 * byte algorithm type
1243 	 */
1244 	len = tpm_buf_read_u16(buf, &offset_r);
1245 	if (offset_r + len != param_len + 8)
1246 		return -EINVAL;
1247 	if (len != SHA256_DIGEST_SIZE + 2)
1248 		return -EINVAL;
1249 
1250 	if (memcmp(chip->null_key_name, &buf->data[offset_r],
1251 		   SHA256_DIGEST_SIZE + 2) != 0) {
1252 		dev_err(&chip->dev, "NULL Seed name comparison failed\n");
1253 		return -EINVAL;
1254 	}
1255 
1256 	return 0;
1257 }
1258 
1259 /**
1260  * tpm2_create_primary() - create a primary key using a fixed P-256 template
1261  *
1262  * @chip:      the TPM chip to create under
1263  * @hierarchy: The hierarchy handle to create under
1264  * @handle:    The returned volatile handle on success
1265  * @name:      The name of the returned key
1266  *
1267  * For platforms that might not have a persistent primary, this can be
1268  * used to create one quickly on the fly (it uses Elliptic Curve not
1269  * RSA, so even slow TPMs can create one fast).  The template uses the
1270  * TCG mandated H one for non-endorsement ECC primaries, i.e. P-256
1271  * elliptic curve (the only current one all TPM2s are required to
1272  * have) a sha256 name hash and no policy.
1273  *
1274  * Return:
1275  * * 0		- OK
1276  * * -errno	- A system error
1277  * * TPM_RC	- A TPM error
1278  */
1279 static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
1280 			       u32 *handle, u8 *name)
1281 {
1282 	struct tpm_buf *template __free(kfree) = NULL;
1283 	struct tpm_buf *buf __free(kfree) = NULL;
1284 	int rc;
1285 
1286 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
1287 	if (!buf)
1288 		return -ENOMEM;
1289 
1290 	template = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
1291 	if (!template)
1292 		return -ENOMEM;
1293 
1294 	tpm_buf_init(buf, TPM_BUFSIZE);
1295 	tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
1296 	tpm_buf_init_sized(template, TPM_BUFSIZE);
1297 
1298 	/*
1299 	 * create the template.  Note: in order for userspace to
1300 	 * verify the security of the system, it will have to create
1301 	 * and certify this NULL primary, meaning all the template
1302 	 * parameters will have to be identical, so conform exactly to
1303 	 * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
1304 	 * key H template (H has zero size unique points)
1305 	 */
1306 
1307 	/* key type */
1308 	tpm_buf_append_u16(template, TPM_ALG_ECC);
1309 
1310 	/* name algorithm */
1311 	tpm_buf_append_u16(template, TPM_ALG_SHA256);
1312 
1313 	/* object properties */
1314 	tpm_buf_append_u32(template, TPM2_OA_NULL_KEY);
1315 
1316 	/* sauth policy (empty) */
1317 	tpm_buf_append_u16(template, 0);
1318 
1319 	/* BEGIN parameters: key specific; for ECC*/
1320 
1321 	/* symmetric algorithm */
1322 	tpm_buf_append_u16(template, TPM_ALG_AES);
1323 
1324 	/* bits for symmetric algorithm */
1325 	tpm_buf_append_u16(template, AES_KEY_BITS);
1326 
1327 	/* algorithm mode (must be CFB) */
1328 	tpm_buf_append_u16(template, TPM_ALG_CFB);
1329 
1330 	/* scheme (NULL means any scheme) */
1331 	tpm_buf_append_u16(template, TPM_ALG_NULL);
1332 
1333 	/* ECC Curve ID */
1334 	tpm_buf_append_u16(template, TPM2_ECC_NIST_P256);
1335 
1336 	/* KDF Scheme */
1337 	tpm_buf_append_u16(template, TPM_ALG_NULL);
1338 
1339 	/* unique: key specific; for ECC it is two zero size points */
1340 	tpm_buf_append_u16(template, 0);
1341 	tpm_buf_append_u16(template, 0);
1342 
1343 	/* END parameters */
1344 
1345 	/* primary handle */
1346 	tpm_buf_append_u32(buf, hierarchy);
1347 	tpm_buf_append_empty_auth(buf, TPM2_RS_PW);
1348 
1349 	/* sensitive create size is 4 for two empty buffers */
1350 	tpm_buf_append_u16(buf, 4);
1351 
1352 	/* sensitive create auth data (empty) */
1353 	tpm_buf_append_u16(buf, 0);
1354 
1355 	/* sensitive create sensitive data (empty) */
1356 	tpm_buf_append_u16(buf, 0);
1357 
1358 	/* the public template */
1359 	tpm_buf_append(buf, template->data, template->length);
1360 
1361 	/* outside info (empty) */
1362 	tpm_buf_append_u16(buf, 0);
1363 
1364 	/* creation PCR (none) */
1365 	tpm_buf_append_u32(buf, 0);
1366 
1367 	rc = tpm_transmit_cmd(chip, buf, 0,
1368 			      "attempting to create NULL primary");
1369 
1370 	if (rc == TPM2_RC_SUCCESS)
1371 		rc = tpm2_parse_create_primary(chip, buf, handle, hierarchy,
1372 					       name);
1373 
1374 	return rc;
1375 }
1376 
1377 static int tpm2_create_null_primary(struct tpm_chip *chip)
1378 {
1379 	u32 null_key;
1380 	int rc;
1381 
1382 	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key,
1383 				 chip->null_key_name);
1384 
1385 	if (rc == TPM2_RC_SUCCESS) {
1386 		unsigned int offset = 0; /* dummy offset for null key context */
1387 
1388 		rc = tpm2_save_context(chip, null_key, chip->null_key_context,
1389 				       sizeof(chip->null_key_context), &offset);
1390 		tpm2_flush_context(chip, null_key);
1391 	}
1392 
1393 	return rc;
1394 }
1395 
1396 /**
1397  * tpm2_sessions_init() - start of day initialization for the sessions code
1398  * @chip: TPM chip
1399  *
1400  * Derive and context save the null primary and allocate memory in the
1401  * struct tpm_chip for the authorizations.
1402  *
1403  * Return:
1404  * * 0		- OK
1405  * * -errno	- A system error
1406  * * TPM_RC	- A TPM error
1407  */
1408 int tpm2_sessions_init(struct tpm_chip *chip)
1409 {
1410 	int rc;
1411 
1412 	rc = tpm2_create_null_primary(chip);
1413 	if (rc) {
1414 		dev_err(&chip->dev, "null key creation failed with %d\n", rc);
1415 		return rc;
1416 	}
1417 
1418 	return rc;
1419 }
1420 #endif /* CONFIG_TCG_TPM2_HMAC */
1421