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