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