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