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