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