xref: /linux/drivers/char/tpm/tpm2-sessions.c (revision 3e7819886281e077e82006fe4804b0d6b0f5643b)
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;
750 	struct sha256_state sctx;
751 	u16 tag = be16_to_cpu(head->tag);
752 	u32 cc = be32_to_cpu(auth->ordinal);
753 	int parm_len, len, i, handles;
754 
755 	if (!auth)
756 		return rc;
757 
758 	if (auth->session >= TPM_HEADER_SIZE) {
759 		WARN(1, "tpm session not filled correctly\n");
760 		goto out;
761 	}
762 
763 	if (rc != 0)
764 		/* pass non success rc through and close the session */
765 		goto out;
766 
767 	rc = -EINVAL;
768 	if (tag != TPM2_ST_SESSIONS) {
769 		dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");
770 		goto out;
771 	}
772 
773 	i = tpm2_find_cc(chip, cc);
774 	if (i < 0)
775 		goto out;
776 	attrs = chip->cc_attrs_tbl[i];
777 	handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;
778 
779 	/* point to area beyond handles */
780 	offset_s = TPM_HEADER_SIZE + handles * 4;
781 	parm_len = tpm_buf_read_u32(buf, &offset_s);
782 	offset_p = offset_s;
783 	offset_s += parm_len;
784 	/* skip over any sessions before ours */
785 	for (i = 0; i < auth->session - 1; i++) {
786 		len = tpm_buf_read_u16(buf, &offset_s);
787 		offset_s += len + 1;
788 		len = tpm_buf_read_u16(buf, &offset_s);
789 		offset_s += len;
790 	}
791 	/* TPM nonce */
792 	len = tpm_buf_read_u16(buf, &offset_s);
793 	if (offset_s + len > tpm_buf_length(buf))
794 		goto out;
795 	if (len != SHA256_DIGEST_SIZE)
796 		goto out;
797 	memcpy(auth->tpm_nonce, &buf->data[offset_s], len);
798 	offset_s += len;
799 	attrs = tpm_buf_read_u8(buf, &offset_s);
800 	len = tpm_buf_read_u16(buf, &offset_s);
801 	if (offset_s + len != tpm_buf_length(buf))
802 		goto out;
803 	if (len != SHA256_DIGEST_SIZE)
804 		goto out;
805 	/*
806 	 * offset_s points to the HMAC. now calculate comparison, beginning
807 	 * with rphash
808 	 */
809 	sha256_init(&sctx);
810 	/* yes, I know this is now zero, but it's what the standard says */
811 	sha256_update(&sctx, (u8 *)&head->return_code,
812 		      sizeof(head->return_code));
813 	/* ordinal is already BE */
814 	sha256_update(&sctx, (u8 *)&auth->ordinal, sizeof(auth->ordinal));
815 	sha256_update(&sctx, &buf->data[offset_p], parm_len);
816 	sha256_final(&sctx, rphash);
817 
818 	/* now calculate the hmac */
819 	tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
820 		       + auth->passphrase_len);
821 	sha256_update(&sctx, rphash, sizeof(rphash));
822 	sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
823 	sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));
824 	sha256_update(&sctx, &auth->attrs, 1);
825 	/* we're done with the rphash, so put our idea of the hmac there */
826 	tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
827 			+ auth->passphrase_len, rphash);
828 	if (memcmp(rphash, &buf->data[offset_s], SHA256_DIGEST_SIZE) == 0) {
829 		rc = 0;
830 	} else {
831 		dev_err(&chip->dev, "TPM: HMAC check failed\n");
832 		goto out;
833 	}
834 
835 	/* now do response decryption */
836 	if (auth->attrs & TPM2_SA_ENCRYPT) {
837 		/* need key and IV */
838 		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
839 			  + auth->passphrase_len, "CFB", auth->tpm_nonce,
840 			  auth->our_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
841 			  auth->scratch);
842 
843 		len = tpm_buf_read_u16(buf, &offset_p);
844 		aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);
845 		aescfb_decrypt(&auth->aes_ctx, &buf->data[offset_p],
846 			       &buf->data[offset_p], len,
847 			       auth->scratch + AES_KEY_BYTES);
848 	}
849 
850  out:
851 	if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {
852 		if (rc)
853 			/* manually close the session if it wasn't consumed */
854 			tpm2_flush_context(chip, auth->handle);
855 		memzero_explicit(auth, sizeof(*auth));
856 	} else {
857 		/* reset for next use  */
858 		auth->session = TPM_HEADER_SIZE;
859 	}
860 
861 	return rc;
862 }
863 EXPORT_SYMBOL(tpm_buf_check_hmac_response);
864 
865 /**
866  * tpm2_end_auth_session() - kill the allocated auth session
867  * @chip: the TPM chip structure
868  *
869  * ends the session started by tpm2_start_auth_session and frees all
870  * the resources.  Under normal conditions,
871  * tpm_buf_check_hmac_response() will correctly end the session if
872  * required, so this function is only for use in error legs that will
873  * bypass the normal invocation of tpm_buf_check_hmac_response().
874  */
875 void tpm2_end_auth_session(struct tpm_chip *chip)
876 {
877 	struct tpm2_auth *auth = chip->auth;
878 
879 	if (!auth)
880 		return;
881 
882 	tpm2_flush_context(chip, auth->handle);
883 	memzero_explicit(auth, sizeof(*auth));
884 }
885 EXPORT_SYMBOL(tpm2_end_auth_session);
886 
887 static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,
888 					 struct tpm_buf *buf)
889 {
890 	struct tpm_header *head = (struct tpm_header *)buf->data;
891 	u32 tot_len = be32_to_cpu(head->length);
892 	off_t offset = TPM_HEADER_SIZE;
893 	u32 val;
894 
895 	/* we're starting after the header so adjust the length */
896 	tot_len -= TPM_HEADER_SIZE;
897 
898 	/* should have handle plus nonce */
899 	if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
900 		return -EINVAL;
901 
902 	auth->handle = tpm_buf_read_u32(buf, &offset);
903 	val = tpm_buf_read_u16(buf, &offset);
904 	if (val != sizeof(auth->tpm_nonce))
905 		return -EINVAL;
906 	memcpy(auth->tpm_nonce, &buf->data[offset], sizeof(auth->tpm_nonce));
907 	/* now compute the session key from the nonces */
908 	tpm2_KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
909 		  auth->our_nonce, sizeof(auth->session_key),
910 		  auth->session_key);
911 
912 	return 0;
913 }
914 
915 static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)
916 {
917 	int rc;
918 	unsigned int offset = 0; /* dummy offset for null seed context */
919 	u8 name[SHA256_DIGEST_SIZE + 2];
920 
921 	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
922 			       null_key);
923 	if (rc != -EINVAL)
924 		return rc;
925 
926 	/* an integrity failure may mean the TPM has been reset */
927 	dev_err(&chip->dev, "NULL key integrity failure!\n");
928 	/* check the null name against what we know */
929 	tpm2_create_primary(chip, TPM2_RH_NULL, NULL, name);
930 	if (memcmp(name, chip->null_key_name, sizeof(name)) == 0)
931 		/* name unchanged, assume transient integrity failure */
932 		return rc;
933 	/*
934 	 * Fatal TPM failure: the NULL seed has actually changed, so
935 	 * the TPM must have been illegally reset.  All in-kernel TPM
936 	 * operations will fail because the NULL primary can't be
937 	 * loaded to salt the sessions, but disable the TPM anyway so
938 	 * userspace programmes can't be compromised by it.
939 	 */
940 	dev_err(&chip->dev, "NULL name has changed, disabling TPM due to interference\n");
941 	chip->flags |= TPM_CHIP_FLAG_DISABLE;
942 
943 	return rc;
944 }
945 
946 /**
947  * tpm2_start_auth_session() - create a HMAC authentication session with the TPM
948  * @chip: the TPM chip structure to create the session with
949  *
950  * This function loads the NULL seed from its saved context and starts
951  * an authentication session on the null seed, fills in the
952  * @chip->auth structure to contain all the session details necessary
953  * for performing the HMAC, encrypt and decrypt operations and
954  * returns.  The NULL seed is flushed before this function returns.
955  *
956  * Return: zero on success or actual error encountered.
957  */
958 int tpm2_start_auth_session(struct tpm_chip *chip)
959 {
960 	struct tpm_buf buf;
961 	struct tpm2_auth *auth = chip->auth;
962 	int rc;
963 	u32 null_key;
964 
965 	if (!auth) {
966 		dev_warn_once(&chip->dev, "auth session is not active\n");
967 		return 0;
968 	}
969 
970 	rc = tpm2_load_null(chip, &null_key);
971 	if (rc)
972 		goto out;
973 
974 	auth->session = TPM_HEADER_SIZE;
975 
976 	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
977 	if (rc)
978 		goto out;
979 
980 	/* salt key handle */
981 	tpm_buf_append_u32(&buf, null_key);
982 	/* bind key handle */
983 	tpm_buf_append_u32(&buf, TPM2_RH_NULL);
984 	/* nonce caller */
985 	get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce));
986 	tpm_buf_append_u16(&buf, sizeof(auth->our_nonce));
987 	tpm_buf_append(&buf, auth->our_nonce, sizeof(auth->our_nonce));
988 
989 	/* append encrypted salt and squirrel away unencrypted in auth */
990 	tpm_buf_append_salt(&buf, chip);
991 	/* session type (HMAC, audit or policy) */
992 	tpm_buf_append_u8(&buf, TPM2_SE_HMAC);
993 
994 	/* symmetric encryption parameters */
995 	/* symmetric algorithm */
996 	tpm_buf_append_u16(&buf, TPM_ALG_AES);
997 	/* bits for symmetric algorithm */
998 	tpm_buf_append_u16(&buf, AES_KEY_BITS);
999 	/* symmetric algorithm mode (must be CFB) */
1000 	tpm_buf_append_u16(&buf, TPM_ALG_CFB);
1001 	/* hash algorithm for session */
1002 	tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
1003 
1004 	rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
1005 	tpm2_flush_context(chip, null_key);
1006 
1007 	if (rc == TPM2_RC_SUCCESS)
1008 		rc = tpm2_parse_start_auth_session(auth, &buf);
1009 
1010 	tpm_buf_destroy(&buf);
1011 
1012 	if (rc)
1013 		goto out;
1014 
1015  out:
1016 	return rc;
1017 }
1018 EXPORT_SYMBOL(tpm2_start_auth_session);
1019 
1020 /*
1021  * A mask containing the object attributes for the kernel held null primary key
1022  * used in HMAC encryption. For more information on specific attributes look up
1023  * to "8.3 TPMA_OBJECT (Object Attributes)".
1024  */
1025 #define TPM2_OA_NULL_KEY ( \
1026 	TPM2_OA_NO_DA | \
1027 	TPM2_OA_FIXED_TPM | \
1028 	TPM2_OA_FIXED_PARENT | \
1029 	TPM2_OA_SENSITIVE_DATA_ORIGIN |	\
1030 	TPM2_OA_USER_WITH_AUTH | \
1031 	TPM2_OA_DECRYPT | \
1032 	TPM2_OA_RESTRICTED)
1033 
1034 /**
1035  * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
1036  *
1037  * @chip:	The TPM the primary was created under
1038  * @buf:	The response buffer from the chip
1039  * @handle:	pointer to be filled in with the return handle of the primary
1040  * @hierarchy:	The hierarchy the primary was created for
1041  * @name:	pointer to be filled in with the primary key name
1042  *
1043  * Return:
1044  * * 0		- OK
1045  * * -errno	- A system error
1046  * * TPM_RC	- A TPM error
1047  */
1048 static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
1049 				     u32 *handle, u32 hierarchy, u8 *name)
1050 {
1051 	struct tpm_header *head = (struct tpm_header *)buf->data;
1052 	off_t offset_r = TPM_HEADER_SIZE, offset_t;
1053 	u16 len = TPM_HEADER_SIZE;
1054 	u32 total_len = be32_to_cpu(head->length);
1055 	u32 val, param_len, keyhandle;
1056 
1057 	keyhandle = tpm_buf_read_u32(buf, &offset_r);
1058 	if (handle)
1059 		*handle = keyhandle;
1060 	else
1061 		tpm2_flush_context(chip, keyhandle);
1062 
1063 	param_len = tpm_buf_read_u32(buf, &offset_r);
1064 	/*
1065 	 * param_len doesn't include the header, but all the other
1066 	 * lengths and offsets do, so add it to parm len to make
1067 	 * the comparisons easier
1068 	 */
1069 	param_len += TPM_HEADER_SIZE;
1070 
1071 	if (param_len + 8 > total_len)
1072 		return -EINVAL;
1073 	len = tpm_buf_read_u16(buf, &offset_r);
1074 	offset_t = offset_r;
1075 	if (name) {
1076 		/*
1077 		 * now we have the public area, compute the name of
1078 		 * the object
1079 		 */
1080 		put_unaligned_be16(TPM_ALG_SHA256, name);
1081 		sha256(&buf->data[offset_r], len, name + 2);
1082 	}
1083 
1084 	/* validate the public key */
1085 	val = tpm_buf_read_u16(buf, &offset_t);
1086 
1087 	/* key type (must be what we asked for) */
1088 	if (val != TPM_ALG_ECC)
1089 		return -EINVAL;
1090 	val = tpm_buf_read_u16(buf, &offset_t);
1091 
1092 	/* name algorithm */
1093 	if (val != TPM_ALG_SHA256)
1094 		return -EINVAL;
1095 	val = tpm_buf_read_u32(buf, &offset_t);
1096 
1097 	/* object properties */
1098 	if (val != TPM2_OA_NULL_KEY)
1099 		return -EINVAL;
1100 
1101 	/* auth policy (empty) */
1102 	val = tpm_buf_read_u16(buf, &offset_t);
1103 	if (val != 0)
1104 		return -EINVAL;
1105 
1106 	/* symmetric key parameters */
1107 	val = tpm_buf_read_u16(buf, &offset_t);
1108 	if (val != TPM_ALG_AES)
1109 		return -EINVAL;
1110 
1111 	/* symmetric key length */
1112 	val = tpm_buf_read_u16(buf, &offset_t);
1113 	if (val != AES_KEY_BITS)
1114 		return -EINVAL;
1115 
1116 	/* symmetric encryption scheme */
1117 	val = tpm_buf_read_u16(buf, &offset_t);
1118 	if (val != TPM_ALG_CFB)
1119 		return -EINVAL;
1120 
1121 	/* signing scheme */
1122 	val = tpm_buf_read_u16(buf, &offset_t);
1123 	if (val != TPM_ALG_NULL)
1124 		return -EINVAL;
1125 
1126 	/* ECC Curve */
1127 	val = tpm_buf_read_u16(buf, &offset_t);
1128 	if (val != TPM2_ECC_NIST_P256)
1129 		return -EINVAL;
1130 
1131 	/* KDF Scheme */
1132 	val = tpm_buf_read_u16(buf, &offset_t);
1133 	if (val != TPM_ALG_NULL)
1134 		return -EINVAL;
1135 
1136 	/* extract public key (x and y points) */
1137 	val = tpm_buf_read_u16(buf, &offset_t);
1138 	if (val != EC_PT_SZ)
1139 		return -EINVAL;
1140 	memcpy(chip->null_ec_key_x, &buf->data[offset_t], val);
1141 	offset_t += val;
1142 	val = tpm_buf_read_u16(buf, &offset_t);
1143 	if (val != EC_PT_SZ)
1144 		return -EINVAL;
1145 	memcpy(chip->null_ec_key_y, &buf->data[offset_t], val);
1146 	offset_t += val;
1147 
1148 	/* original length of the whole TPM2B */
1149 	offset_r += len;
1150 
1151 	/* should have exactly consumed the TPM2B public structure */
1152 	if (offset_t != offset_r)
1153 		return -EINVAL;
1154 	if (offset_r > param_len)
1155 		return -EINVAL;
1156 
1157 	/* creation data (skip) */
1158 	len = tpm_buf_read_u16(buf, &offset_r);
1159 	offset_r += len;
1160 	if (offset_r > param_len)
1161 		return -EINVAL;
1162 
1163 	/* creation digest (must be sha256) */
1164 	len = tpm_buf_read_u16(buf, &offset_r);
1165 	offset_r += len;
1166 	if (len != SHA256_DIGEST_SIZE || offset_r > param_len)
1167 		return -EINVAL;
1168 
1169 	/* TPMT_TK_CREATION follows */
1170 	/* tag, must be TPM_ST_CREATION (0x8021) */
1171 	val = tpm_buf_read_u16(buf, &offset_r);
1172 	if (val != TPM2_ST_CREATION || offset_r > param_len)
1173 		return -EINVAL;
1174 
1175 	/* hierarchy */
1176 	val = tpm_buf_read_u32(buf, &offset_r);
1177 	if (val != hierarchy || offset_r > param_len)
1178 		return -EINVAL;
1179 
1180 	/* the ticket digest HMAC (might not be sha256) */
1181 	len = tpm_buf_read_u16(buf, &offset_r);
1182 	offset_r += len;
1183 	if (offset_r > param_len)
1184 		return -EINVAL;
1185 
1186 	/*
1187 	 * finally we have the name, which is a sha256 digest plus a 2
1188 	 * byte algorithm type
1189 	 */
1190 	len = tpm_buf_read_u16(buf, &offset_r);
1191 	if (offset_r + len != param_len + 8)
1192 		return -EINVAL;
1193 	if (len != SHA256_DIGEST_SIZE + 2)
1194 		return -EINVAL;
1195 
1196 	if (memcmp(chip->null_key_name, &buf->data[offset_r],
1197 		   SHA256_DIGEST_SIZE + 2) != 0) {
1198 		dev_err(&chip->dev, "NULL Seed name comparison failed\n");
1199 		return -EINVAL;
1200 	}
1201 
1202 	return 0;
1203 }
1204 
1205 /**
1206  * tpm2_create_primary() - create a primary key using a fixed P-256 template
1207  *
1208  * @chip:      the TPM chip to create under
1209  * @hierarchy: The hierarchy handle to create under
1210  * @handle:    The returned volatile handle on success
1211  * @name:      The name of the returned key
1212  *
1213  * For platforms that might not have a persistent primary, this can be
1214  * used to create one quickly on the fly (it uses Elliptic Curve not
1215  * RSA, so even slow TPMs can create one fast).  The template uses the
1216  * TCG mandated H one for non-endorsement ECC primaries, i.e. P-256
1217  * elliptic curve (the only current one all TPM2s are required to
1218  * have) a sha256 name hash and no policy.
1219  *
1220  * Return:
1221  * * 0		- OK
1222  * * -errno	- A system error
1223  * * TPM_RC	- A TPM error
1224  */
1225 static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
1226 			       u32 *handle, u8 *name)
1227 {
1228 	int rc;
1229 	struct tpm_buf buf;
1230 	struct tpm_buf template;
1231 
1232 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
1233 	if (rc)
1234 		return rc;
1235 
1236 	rc = tpm_buf_init_sized(&template);
1237 	if (rc) {
1238 		tpm_buf_destroy(&buf);
1239 		return rc;
1240 	}
1241 
1242 	/*
1243 	 * create the template.  Note: in order for userspace to
1244 	 * verify the security of the system, it will have to create
1245 	 * and certify this NULL primary, meaning all the template
1246 	 * parameters will have to be identical, so conform exactly to
1247 	 * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
1248 	 * key H template (H has zero size unique points)
1249 	 */
1250 
1251 	/* key type */
1252 	tpm_buf_append_u16(&template, TPM_ALG_ECC);
1253 
1254 	/* name algorithm */
1255 	tpm_buf_append_u16(&template, TPM_ALG_SHA256);
1256 
1257 	/* object properties */
1258 	tpm_buf_append_u32(&template, TPM2_OA_NULL_KEY);
1259 
1260 	/* sauth policy (empty) */
1261 	tpm_buf_append_u16(&template, 0);
1262 
1263 	/* BEGIN parameters: key specific; for ECC*/
1264 
1265 	/* symmetric algorithm */
1266 	tpm_buf_append_u16(&template, TPM_ALG_AES);
1267 
1268 	/* bits for symmetric algorithm */
1269 	tpm_buf_append_u16(&template, AES_KEY_BITS);
1270 
1271 	/* algorithm mode (must be CFB) */
1272 	tpm_buf_append_u16(&template, TPM_ALG_CFB);
1273 
1274 	/* scheme (NULL means any scheme) */
1275 	tpm_buf_append_u16(&template, TPM_ALG_NULL);
1276 
1277 	/* ECC Curve ID */
1278 	tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
1279 
1280 	/* KDF Scheme */
1281 	tpm_buf_append_u16(&template, TPM_ALG_NULL);
1282 
1283 	/* unique: key specific; for ECC it is two zero size points */
1284 	tpm_buf_append_u16(&template, 0);
1285 	tpm_buf_append_u16(&template, 0);
1286 
1287 	/* END parameters */
1288 
1289 	/* primary handle */
1290 	tpm_buf_append_u32(&buf, hierarchy);
1291 	tpm_buf_append_empty_auth(&buf, TPM2_RS_PW);
1292 
1293 	/* sensitive create size is 4 for two empty buffers */
1294 	tpm_buf_append_u16(&buf, 4);
1295 
1296 	/* sensitive create auth data (empty) */
1297 	tpm_buf_append_u16(&buf, 0);
1298 
1299 	/* sensitive create sensitive data (empty) */
1300 	tpm_buf_append_u16(&buf, 0);
1301 
1302 	/* the public template */
1303 	tpm_buf_append(&buf, template.data, template.length);
1304 	tpm_buf_destroy(&template);
1305 
1306 	/* outside info (empty) */
1307 	tpm_buf_append_u16(&buf, 0);
1308 
1309 	/* creation PCR (none) */
1310 	tpm_buf_append_u32(&buf, 0);
1311 
1312 	rc = tpm_transmit_cmd(chip, &buf, 0,
1313 			      "attempting to create NULL primary");
1314 
1315 	if (rc == TPM2_RC_SUCCESS)
1316 		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy,
1317 					       name);
1318 
1319 	tpm_buf_destroy(&buf);
1320 
1321 	return rc;
1322 }
1323 
1324 static int tpm2_create_null_primary(struct tpm_chip *chip)
1325 {
1326 	u32 null_key;
1327 	int rc;
1328 
1329 	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key,
1330 				 chip->null_key_name);
1331 
1332 	if (rc == TPM2_RC_SUCCESS) {
1333 		unsigned int offset = 0; /* dummy offset for null key context */
1334 
1335 		rc = tpm2_save_context(chip, null_key, chip->null_key_context,
1336 				       sizeof(chip->null_key_context), &offset);
1337 		tpm2_flush_context(chip, null_key);
1338 	}
1339 
1340 	return rc;
1341 }
1342 
1343 /**
1344  * tpm2_sessions_init() - start of day initialization for the sessions code
1345  * @chip: TPM chip
1346  *
1347  * Derive and context save the null primary and allocate memory in the
1348  * struct tpm_chip for the authorizations.
1349  */
1350 int tpm2_sessions_init(struct tpm_chip *chip)
1351 {
1352 	int rc;
1353 
1354 	rc = tpm2_create_null_primary(chip);
1355 	if (rc)
1356 		dev_err(&chip->dev, "TPM: security failed (NULL seed derivation): %d\n", rc);
1357 
1358 	chip->auth = kmalloc(sizeof(*chip->auth), GFP_KERNEL);
1359 	if (!chip->auth)
1360 		return -ENOMEM;
1361 
1362 	return rc;
1363 }
1364 #endif /* CONFIG_TCG_TPM2_HMAC */
1365