Linux Audio

Check our new training course

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