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