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