// SPDX-License-Identifier: GPL-2.012/*3* Copyright (C) 2018 [email protected]4*5* Cryptographic helper routines for handling TPM2 sessions for6* authorization HMAC and request response encryption.7*8* The idea is to ensure that every TPM command is HMAC protected by a9* session, meaning in-flight tampering would be detected and in10* addition all sensitive inputs and responses should be encrypted.11*12* The basic way this works is to use a TPM feature called salted13* sessions where a random secret used in session construction is14* encrypted to the public part of a known TPM key. The problem is we15* have no known keys, so initially a primary Elliptic Curve key is16* derived from the NULL seed (we use EC because most TPMs generate17* these keys much faster than RSA ones). The curve used is NIST_P25618* because that's now mandated to be present in 'TCG TPM v2.019* Provisioning Guidance'20*21* Threat problems: the initial TPM2_CreatePrimary is not (and cannot22* be) session protected, so a clever Man in the Middle could return a23* public key they control to this command and from there intercept24* and decode all subsequent session based transactions. The kernel25* cannot mitigate this threat but, after boot, userspace can get26* proof this has not happened by asking the TPM to certify the NULL27* key. This certification would chain back to the TPM Endorsement28* Certificate and prove the NULL seed primary had not been tampered29* with and thus all sessions must have been cryptographically secure.30* To assist with this, the initial NULL seed public key name is made31* available in a sysfs file.32*33* Use of these functions:34*35* The design is all the crypto, hash and hmac gunk is confined in this36* file and never needs to be seen even by the kernel internal user. To37* the user there's an init function tpm2_sessions_init() that needs to38* be called once per TPM which generates the NULL seed primary key.39*40* These are the usage functions:41*42* tpm2_end_auth_session() kills the session and frees the resources.43* Under normal operation this function is done by44* tpm_buf_check_hmac_response(), so this is only to be used on45* error legs where the latter is not executed.46* tpm_buf_append_name() to add a handle to the buffer. This must be47* used in place of the usual tpm_buf_append_u32() for adding48* handles because handles have to be processed specially when49* calculating the HMAC. In particular, for NV, volatile and50* permanent objects you now need to provide the name.51* tpm_buf_append_hmac_session() which appends the hmac session to the52* buf in the same way tpm_buf_append_auth does().53* tpm_buf_fill_hmac_session() This calculates the correct hash and54* places it in the buffer. It must be called after the complete55* command buffer is finalized so it can fill in the correct HMAC56* based on the parameters.57* tpm_buf_check_hmac_response() which checks the session response in58* the buffer and calculates what it should be. If there's a59* mismatch it will log a warning and return an error. If60* tpm_buf_append_hmac_session() did not specify61* TPM_SA_CONTINUE_SESSION then the session will be closed (if it62* hasn't been consumed) and the auth structure freed.63*/6465#include "tpm.h"66#include <linux/random.h>67#include <linux/scatterlist.h>68#include <linux/unaligned.h>69#include <crypto/kpp.h>70#include <crypto/ecdh.h>71#include <crypto/sha2.h>72#include <crypto/utils.h>7374/* maximum number of names the TPM must remember for authorization */75#define AUTH_MAX_NAMES 37677#define AES_KEY_BYTES AES_KEYSIZE_12878#define AES_KEY_BITS (AES_KEY_BYTES*8)7980/*81* This is the structure that carries all the auth information (like82* session handle, nonces, session key and auth) from use to use it is83* designed to be opaque to anything outside.84*/85struct tpm2_auth {86u32 handle;87/*88* This has two meanings: before tpm_buf_fill_hmac_session()89* it marks the offset in the buffer of the start of the90* sessions (i.e. after all the handles). Once the buffer has91* been filled it markes the session number of our auth92* session so we can find it again in the response buffer.93*94* The two cases are distinguished because the first offset95* must always be greater than TPM_HEADER_SIZE and the second96* must be less than or equal to 5.97*/98u32 session;99/*100* the size here is variable and set by the size of our_nonce101* which must be between 16 and the name hash length. we set102* the maximum sha256 size for the greatest protection103*/104u8 our_nonce[SHA256_DIGEST_SIZE];105u8 tpm_nonce[SHA256_DIGEST_SIZE];106/*107* the salt is only used across the session command/response108* after that it can be used as a scratch area109*/110union {111u8 salt[EC_PT_SZ];112/* scratch for key + IV */113u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];114};115/*116* the session key and passphrase are the same size as the117* name digest (sha256 again). The session key is constant118* for the use of the session and the passphrase can change119* with every invocation.120*121* Note: these fields must be adjacent and in this order122* because several HMAC/KDF schemes use the combination of the123* session_key and passphrase.124*/125u8 session_key[SHA256_DIGEST_SIZE];126u8 passphrase[SHA256_DIGEST_SIZE];127int passphrase_len;128struct aes_enckey aes_key;129/* saved session attributes: */130u8 attrs;131__be32 ordinal;132133/*134* memory for three authorization handles. We know them by135* handle, but they are part of the session by name, which136* we must compute and remember137*/138u32 name_h[AUTH_MAX_NAMES];139u8 name[AUTH_MAX_NAMES][2 + SHA512_DIGEST_SIZE];140};141142#ifdef CONFIG_TCG_TPM2_HMAC143/*144* Name Size based on TPM algorithm (assumes no hash bigger than 255)145*/146static int name_size(const u8 *name)147{148u16 hash_alg = get_unaligned_be16(name);149150switch (hash_alg) {151case TPM_ALG_SHA1:152return SHA1_DIGEST_SIZE + 2;153case TPM_ALG_SHA256:154return SHA256_DIGEST_SIZE + 2;155case TPM_ALG_SHA384:156return SHA384_DIGEST_SIZE + 2;157case TPM_ALG_SHA512:158return SHA512_DIGEST_SIZE + 2;159default:160pr_warn("tpm: unsupported name algorithm: 0x%04x\n", hash_alg);161return -EINVAL;162}163}164165static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)166{167u32 mso = tpm2_handle_mso(handle);168off_t offset = TPM_HEADER_SIZE;169int rc, name_size_alg;170struct tpm_buf buf;171172if (mso != TPM2_MSO_PERSISTENT && mso != TPM2_MSO_VOLATILE &&173mso != TPM2_MSO_NVRAM) {174memcpy(name, &handle, sizeof(u32));175return sizeof(u32);176}177178rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);179if (rc)180return rc;181182tpm_buf_append_u32(&buf, handle);183184rc = tpm_transmit_cmd(chip, &buf, 0, "TPM2_ReadPublic");185if (rc) {186tpm_buf_destroy(&buf);187return tpm_ret_to_err(rc);188}189190/* Skip TPMT_PUBLIC: */191offset += tpm_buf_read_u16(&buf, &offset);192193/*194* Ensure space for the length field of TPM2B_NAME and hashAlg field of195* TPMT_HA (the extra four bytes).196*/197if (offset + 4 > tpm_buf_length(&buf)) {198tpm_buf_destroy(&buf);199return -EIO;200}201202rc = tpm_buf_read_u16(&buf, &offset);203name_size_alg = name_size(&buf.data[offset]);204205if (name_size_alg < 0)206return name_size_alg;207208if (rc != name_size_alg) {209tpm_buf_destroy(&buf);210return -EIO;211}212213if (offset + rc > tpm_buf_length(&buf)) {214tpm_buf_destroy(&buf);215return -EIO;216}217218memcpy(name, &buf.data[offset], rc);219return name_size_alg;220}221#endif /* CONFIG_TCG_TPM2_HMAC */222223/**224* tpm_buf_append_name() - add a handle area to the buffer225* @chip: the TPM chip structure226* @buf: The buffer to be appended227* @handle: The handle to be appended228* @name: The name of the handle (may be NULL)229*230* In order to compute session HMACs, we need to know the names of the231* objects pointed to by the handles. For most objects, this is simply232* the actual 4 byte handle or an empty buf (in these cases @name233* should be NULL) but for volatile objects, permanent objects and NV234* areas, the name is defined as the hash (according to the name235* algorithm which should be set to sha256) of the public area to236* which the two byte algorithm id has been appended. For these237* objects, the @name pointer should point to this. If a name is238* required but @name is NULL, then TPM2_ReadPublic() will be called239* on the handle to obtain the name.240*241* As with most tpm_buf operations, success is assumed because failure242* will be caused by an incorrect programming model and indicated by a243* kernel message.244*245* Ends the authorization session on failure.246*/247int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,248u32 handle, u8 *name)249{250#ifdef CONFIG_TCG_TPM2_HMAC251enum tpm2_mso_type mso = tpm2_handle_mso(handle);252struct tpm2_auth *auth;253u16 name_size_alg;254int slot;255int ret;256#endif257258if (!tpm2_chip_auth(chip)) {259tpm_buf_append_handle(chip, buf, handle);260return 0;261}262263#ifdef CONFIG_TCG_TPM2_HMAC264slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE) / 4;265if (slot >= AUTH_MAX_NAMES) {266dev_err(&chip->dev, "too many handles\n");267ret = -EIO;268goto err;269}270auth = chip->auth;271if (auth->session != tpm_buf_length(buf)) {272dev_err(&chip->dev, "session state malformed");273ret = -EIO;274goto err;275}276tpm_buf_append_u32(buf, handle);277auth->session += 4;278279if (mso == TPM2_MSO_PERSISTENT ||280mso == TPM2_MSO_VOLATILE ||281mso == TPM2_MSO_NVRAM) {282if (!name) {283ret = tpm2_read_public(chip, handle, auth->name[slot]);284if (ret < 0)285goto err;286287name_size_alg = ret;288}289} else {290if (name) {291dev_err(&chip->dev, "handle 0x%08x does not use a name\n",292handle);293ret = -EIO;294goto err;295}296}297298auth->name_h[slot] = handle;299if (name)300memcpy(auth->name[slot], name, name_size_alg);301#endif302return 0;303304#ifdef CONFIG_TCG_TPM2_HMAC305err:306tpm2_end_auth_session(chip);307return tpm_ret_to_err(ret);308#endif309}310EXPORT_SYMBOL_GPL(tpm_buf_append_name);311312void tpm_buf_append_auth(struct tpm_chip *chip, struct tpm_buf *buf,313u8 *passphrase, int passphrase_len)314{315/* offset tells us where the sessions area begins */316int offset = buf->handles * 4 + TPM_HEADER_SIZE;317u32 len = 9 + passphrase_len;318319if (tpm_buf_length(buf) != offset) {320/* not the first session so update the existing length */321len += get_unaligned_be32(&buf->data[offset]);322put_unaligned_be32(len, &buf->data[offset]);323} else {324tpm_buf_append_u32(buf, len);325}326/* auth handle */327tpm_buf_append_u32(buf, TPM2_RS_PW);328/* nonce */329tpm_buf_append_u16(buf, 0);330/* attributes */331tpm_buf_append_u8(buf, 0);332/* passphrase */333tpm_buf_append_u16(buf, passphrase_len);334tpm_buf_append(buf, passphrase, passphrase_len);335}336337/**338* tpm_buf_append_hmac_session() - Append a TPM session element339* @chip: the TPM chip structure340* @buf: The buffer to be appended341* @attributes: The session attributes342* @passphrase: The session authority (NULL if none)343* @passphrase_len: The length of the session authority (0 if none)344*345* This fills in a session structure in the TPM command buffer, except346* for the HMAC which cannot be computed until the command buffer is347* complete. The type of session is controlled by the @attributes,348* the main ones of which are TPM2_SA_CONTINUE_SESSION which means the349* session won't terminate after tpm_buf_check_hmac_response(),350* TPM2_SA_DECRYPT which means this buffers first parameter should be351* encrypted with a session key and TPM2_SA_ENCRYPT, which means the352* response buffer's first parameter needs to be decrypted (confusing,353* but the defines are written from the point of view of the TPM).354*355* Any session appended by this command must be finalized by calling356* tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect357* and the TPM will reject the command.358*359* As with most tpm_buf operations, success is assumed because failure360* will be caused by an incorrect programming model and indicated by a361* kernel message.362*/363void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,364u8 attributes, u8 *passphrase,365int passphrase_len)366{367#ifdef CONFIG_TCG_TPM2_HMAC368u8 nonce[SHA256_DIGEST_SIZE];369struct tpm2_auth *auth;370u32 len;371#endif372373if (!tpm2_chip_auth(chip)) {374tpm_buf_append_auth(chip, buf, passphrase, passphrase_len);375return;376}377378#ifdef CONFIG_TCG_TPM2_HMAC379/* The first write to /dev/tpm{rm0} will flush the session. */380attributes |= TPM2_SA_CONTINUE_SESSION;381382/*383* The Architecture Guide requires us to strip trailing zeros384* before computing the HMAC385*/386while (passphrase && passphrase_len > 0 && passphrase[passphrase_len - 1] == '\0')387passphrase_len--;388389auth = chip->auth;390auth->attrs = attributes;391auth->passphrase_len = passphrase_len;392if (passphrase_len)393memcpy(auth->passphrase, passphrase, passphrase_len);394395if (auth->session != tpm_buf_length(buf)) {396/* we're not the first session */397len = get_unaligned_be32(&buf->data[auth->session]);398if (4 + len + auth->session != tpm_buf_length(buf)) {399WARN(1, "session length mismatch, cannot append");400return;401}402403/* add our new session */404len += 9 + 2 * SHA256_DIGEST_SIZE;405put_unaligned_be32(len, &buf->data[auth->session]);406} else {407tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);408}409410/* random number for our nonce */411get_random_bytes(nonce, sizeof(nonce));412memcpy(auth->our_nonce, nonce, sizeof(nonce));413tpm_buf_append_u32(buf, auth->handle);414/* our new nonce */415tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);416tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);417tpm_buf_append_u8(buf, auth->attrs);418/* and put a placeholder for the hmac */419tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);420tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);421#endif422}423EXPORT_SYMBOL_GPL(tpm_buf_append_hmac_session);424425#ifdef CONFIG_TCG_TPM2_HMAC426427static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,428u32 *handle, u8 *name);429430/*431* assume hash sha256 and nonces u, v of size SHA256_DIGEST_SIZE but432* otherwise standard tpm2_KDFa. Note output is in bytes not bits.433*/434static void tpm2_KDFa(u8 *key, u32 key_len, const char *label, u8 *u,435u8 *v, u32 bytes, u8 *out)436{437u32 counter = 1;438const __be32 bits = cpu_to_be32(bytes * 8);439440while (bytes > 0) {441struct hmac_sha256_ctx hctx;442__be32 c = cpu_to_be32(counter);443444hmac_sha256_init_usingrawkey(&hctx, key, key_len);445hmac_sha256_update(&hctx, (u8 *)&c, sizeof(c));446hmac_sha256_update(&hctx, label, strlen(label) + 1);447hmac_sha256_update(&hctx, u, SHA256_DIGEST_SIZE);448hmac_sha256_update(&hctx, v, SHA256_DIGEST_SIZE);449hmac_sha256_update(&hctx, (u8 *)&bits, sizeof(bits));450hmac_sha256_final(&hctx, out);451452bytes -= SHA256_DIGEST_SIZE;453counter++;454out += SHA256_DIGEST_SIZE;455}456}457458/*459* Somewhat of a bastardization of the real KDFe. We're assuming460* we're working with known point sizes for the input parameters and461* the hash algorithm is fixed at sha256. Because we know that the462* point size is 32 bytes like the hash size, there's no need to loop463* in this KDF.464*/465static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,466u8 *out)467{468struct sha256_ctx sctx;469/*470* this should be an iterative counter, but because we know471* we're only taking 32 bytes for the point using a sha256472* hash which is also 32 bytes, there's only one loop473*/474__be32 c = cpu_to_be32(1);475476sha256_init(&sctx);477/* counter (BE) */478sha256_update(&sctx, (u8 *)&c, sizeof(c));479/* secret value */480sha256_update(&sctx, z, EC_PT_SZ);481/* string including trailing zero */482sha256_update(&sctx, str, strlen(str)+1);483sha256_update(&sctx, pt_u, EC_PT_SZ);484sha256_update(&sctx, pt_v, EC_PT_SZ);485sha256_final(&sctx, out);486}487488static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip,489struct tpm2_auth *auth)490{491struct crypto_kpp *kpp;492struct kpp_request *req;493struct scatterlist s[2], d[1];494struct ecdh p = {0};495u8 encoded_key[EC_PT_SZ], *x, *y;496unsigned int buf_len;497498/* secret is two sized points */499tpm_buf_append_u16(buf, (EC_PT_SZ + 2)*2);500/*501* we cheat here and append uninitialized data to form502* the points. All we care about is getting the two503* co-ordinate pointers, which will be used to overwrite504* the uninitialized data505*/506tpm_buf_append_u16(buf, EC_PT_SZ);507x = &buf->data[tpm_buf_length(buf)];508tpm_buf_append(buf, encoded_key, EC_PT_SZ);509tpm_buf_append_u16(buf, EC_PT_SZ);510y = &buf->data[tpm_buf_length(buf)];511tpm_buf_append(buf, encoded_key, EC_PT_SZ);512sg_init_table(s, 2);513sg_set_buf(&s[0], x, EC_PT_SZ);514sg_set_buf(&s[1], y, EC_PT_SZ);515516kpp = crypto_alloc_kpp("ecdh-nist-p256", CRYPTO_ALG_INTERNAL, 0);517if (IS_ERR(kpp)) {518dev_err(&chip->dev, "crypto ecdh allocation failed\n");519return;520}521522buf_len = crypto_ecdh_key_len(&p);523if (sizeof(encoded_key) < buf_len) {524dev_err(&chip->dev, "salt buffer too small needs %d\n",525buf_len);526goto out;527}528crypto_ecdh_encode_key(encoded_key, buf_len, &p);529/* this generates a random private key */530crypto_kpp_set_secret(kpp, encoded_key, buf_len);531532/* salt is now the public point of this private key */533req = kpp_request_alloc(kpp, GFP_KERNEL);534if (!req)535goto out;536kpp_request_set_input(req, NULL, 0);537kpp_request_set_output(req, s, EC_PT_SZ*2);538crypto_kpp_generate_public_key(req);539/*540* we're not done: now we have to compute the shared secret541* which is our private key multiplied by the tpm_key public542* point, we actually only take the x point and discard the y543* point and feed it through KDFe to get the final secret salt544*/545sg_set_buf(&s[0], chip->null_ec_key_x, EC_PT_SZ);546sg_set_buf(&s[1], chip->null_ec_key_y, EC_PT_SZ);547kpp_request_set_input(req, s, EC_PT_SZ*2);548sg_init_one(d, auth->salt, EC_PT_SZ);549kpp_request_set_output(req, d, EC_PT_SZ);550crypto_kpp_compute_shared_secret(req);551kpp_request_free(req);552553/*554* pass the shared secret through KDFe for salt. Note salt555* area is used both for input shared secret and output salt.556* This works because KDFe fully consumes the secret before it557* writes the salt558*/559tpm2_KDFe(auth->salt, "SECRET", x, chip->null_ec_key_x, auth->salt);560561out:562crypto_free_kpp(kpp);563}564565/**566* tpm_buf_fill_hmac_session() - finalize the session HMAC567* @chip: the TPM chip structure568* @buf: The buffer to be appended569*570* This command must not be called until all of the parameters have571* been appended to @buf otherwise the computed HMAC will be572* incorrect.573*574* This function computes and fills in the session HMAC using the575* session key and, if TPM2_SA_DECRYPT was specified, computes the576* encryption key and encrypts the first parameter of the command577* buffer with it.578*579* Ends the authorization session on failure.580*/581int tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)582{583u32 cc, handles, val;584struct tpm2_auth *auth = chip->auth;585int i;586struct tpm_header *head = (struct tpm_header *)buf->data;587off_t offset_s = TPM_HEADER_SIZE, offset_p;588u8 *hmac = NULL;589u32 attrs;590u8 cphash[SHA256_DIGEST_SIZE];591struct sha256_ctx sctx;592struct hmac_sha256_ctx hctx;593int ret;594595if (!auth) {596ret = -EIO;597goto err;598}599600/* save the command code in BE format */601auth->ordinal = head->ordinal;602603cc = be32_to_cpu(head->ordinal);604605i = tpm2_find_cc(chip, cc);606if (i < 0) {607dev_err(&chip->dev, "command 0x%08x not found\n", cc);608ret = -EIO;609goto err;610}611612attrs = chip->cc_attrs_tbl[i];613614handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0);615616/*617* just check the names, it's easy to make mistakes. This618* would happen if someone added a handle via619* tpm_buf_append_u32() instead of tpm_buf_append_name()620*/621for (i = 0; i < handles; i++) {622u32 handle = tpm_buf_read_u32(buf, &offset_s);623624if (auth->name_h[i] != handle) {625dev_err(&chip->dev, "invalid handle 0x%08x\n", handle);626ret = -EIO;627goto err;628}629}630/* point offset_s to the start of the sessions */631val = tpm_buf_read_u32(buf, &offset_s);632/* point offset_p to the start of the parameters */633offset_p = offset_s + val;634for (i = 1; offset_s < offset_p; i++) {635u32 handle = tpm_buf_read_u32(buf, &offset_s);636u16 len;637u8 a;638639/* nonce (already in auth) */640len = tpm_buf_read_u16(buf, &offset_s);641offset_s += len;642643a = tpm_buf_read_u8(buf, &offset_s);644645len = tpm_buf_read_u16(buf, &offset_s);646if (handle == auth->handle && auth->attrs == a) {647hmac = &buf->data[offset_s];648/*649* save our session number so we know which650* session in the response belongs to us651*/652auth->session = i;653}654655offset_s += len;656}657if (offset_s != offset_p) {658dev_err(&chip->dev, "session length is incorrect\n");659ret = -EIO;660goto err;661}662if (!hmac) {663dev_err(&chip->dev, "could not find HMAC session\n");664ret = -EIO;665goto err;666}667668/* encrypt before HMAC */669if (auth->attrs & TPM2_SA_DECRYPT) {670u16 len;671672/* need key and IV */673tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE674+ auth->passphrase_len, "CFB", auth->our_nonce,675auth->tpm_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,676auth->scratch);677678len = tpm_buf_read_u16(buf, &offset_p);679aes_prepareenckey(&auth->aes_key, auth->scratch, AES_KEY_BYTES);680aescfb_encrypt(&auth->aes_key, &buf->data[offset_p],681&buf->data[offset_p], len,682auth->scratch + AES_KEY_BYTES);683/* reset p to beginning of parameters for HMAC */684offset_p -= 2;685}686687sha256_init(&sctx);688/* ordinal is already BE */689sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));690/* add the handle names */691for (i = 0; i < handles; i++) {692enum tpm2_mso_type mso = tpm2_handle_mso(auth->name_h[i]);693694if (mso == TPM2_MSO_PERSISTENT ||695mso == TPM2_MSO_VOLATILE ||696mso == TPM2_MSO_NVRAM) {697ret = name_size(auth->name[i]);698if (ret < 0)699goto err;700701sha256_update(&sctx, auth->name[i], ret);702} else {703__be32 h = cpu_to_be32(auth->name_h[i]);704705sha256_update(&sctx, (u8 *)&h, 4);706}707}708if (offset_s != tpm_buf_length(buf))709sha256_update(&sctx, &buf->data[offset_s],710tpm_buf_length(buf) - offset_s);711sha256_final(&sctx, cphash);712713/* now calculate the hmac */714hmac_sha256_init_usingrawkey(&hctx, auth->session_key,715sizeof(auth->session_key) +716auth->passphrase_len);717hmac_sha256_update(&hctx, cphash, sizeof(cphash));718hmac_sha256_update(&hctx, auth->our_nonce, sizeof(auth->our_nonce));719hmac_sha256_update(&hctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));720hmac_sha256_update(&hctx, &auth->attrs, 1);721hmac_sha256_final(&hctx, hmac);722return 0;723724err:725tpm2_end_auth_session(chip);726return ret;727}728EXPORT_SYMBOL(tpm_buf_fill_hmac_session);729730/**731* tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness732* @chip: the TPM chip structure733* @buf: the original command buffer (which now contains the response)734* @rc: the return code from tpm_transmit_cmd735*736* If @rc is non zero, @buf may not contain an actual return, so @rc737* is passed through as the return and the session cleaned up and738* de-allocated if required (this is required if739* TPM2_SA_CONTINUE_SESSION was not specified as a session flag).740*741* If @rc is zero, the response HMAC is computed against the returned742* @buf and matched to the TPM one in the session area. If there is a743* mismatch, an error is logged and -EINVAL returned.744*745* The reason for this is that the command issue and HMAC check746* sequence should look like:747*748* rc = tpm_transmit_cmd(...);749* rc = tpm_buf_check_hmac_response(&buf, auth, rc);750* if (rc)751* ...752*753* Which is easily layered into the current contrl flow.754*755* Returns: 0 on success or an error.756*/757int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,758int rc)759{760struct tpm_header *head = (struct tpm_header *)buf->data;761struct tpm2_auth *auth = chip->auth;762off_t offset_s, offset_p;763u8 rphash[SHA256_DIGEST_SIZE];764u32 attrs, cc;765struct sha256_ctx sctx;766struct hmac_sha256_ctx hctx;767u16 tag = be16_to_cpu(head->tag);768int parm_len, len, i, handles;769770if (!auth)771return rc;772773cc = be32_to_cpu(auth->ordinal);774775if (auth->session >= TPM_HEADER_SIZE) {776WARN(1, "tpm session not filled correctly\n");777goto out;778}779780if (rc != 0)781/* pass non success rc through and close the session */782goto out;783784rc = -EINVAL;785if (tag != TPM2_ST_SESSIONS) {786dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");787goto out;788}789790i = tpm2_find_cc(chip, cc);791if (i < 0)792goto out;793attrs = chip->cc_attrs_tbl[i];794handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;795796/* point to area beyond handles */797offset_s = TPM_HEADER_SIZE + handles * 4;798parm_len = tpm_buf_read_u32(buf, &offset_s);799offset_p = offset_s;800offset_s += parm_len;801/* skip over any sessions before ours */802for (i = 0; i < auth->session - 1; i++) {803len = tpm_buf_read_u16(buf, &offset_s);804offset_s += len + 1;805len = tpm_buf_read_u16(buf, &offset_s);806offset_s += len;807}808/* TPM nonce */809len = tpm_buf_read_u16(buf, &offset_s);810if (offset_s + len > tpm_buf_length(buf))811goto out;812if (len != SHA256_DIGEST_SIZE)813goto out;814memcpy(auth->tpm_nonce, &buf->data[offset_s], len);815offset_s += len;816attrs = tpm_buf_read_u8(buf, &offset_s);817len = tpm_buf_read_u16(buf, &offset_s);818if (offset_s + len != tpm_buf_length(buf))819goto out;820if (len != SHA256_DIGEST_SIZE)821goto out;822/*823* offset_s points to the HMAC. now calculate comparison, beginning824* with rphash825*/826sha256_init(&sctx);827/* yes, I know this is now zero, but it's what the standard says */828sha256_update(&sctx, (u8 *)&head->return_code,829sizeof(head->return_code));830/* ordinal is already BE */831sha256_update(&sctx, (u8 *)&auth->ordinal, sizeof(auth->ordinal));832sha256_update(&sctx, &buf->data[offset_p], parm_len);833sha256_final(&sctx, rphash);834835/* now calculate the hmac */836hmac_sha256_init_usingrawkey(&hctx, auth->session_key,837sizeof(auth->session_key) +838auth->passphrase_len);839hmac_sha256_update(&hctx, rphash, sizeof(rphash));840hmac_sha256_update(&hctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));841hmac_sha256_update(&hctx, auth->our_nonce, sizeof(auth->our_nonce));842hmac_sha256_update(&hctx, &auth->attrs, 1);843/* we're done with the rphash, so put our idea of the hmac there */844hmac_sha256_final(&hctx, rphash);845if (crypto_memneq(rphash, &buf->data[offset_s], SHA256_DIGEST_SIZE)) {846dev_err(&chip->dev, "TPM: HMAC check failed\n");847goto out;848}849rc = 0;850851/* now do response decryption */852if (auth->attrs & TPM2_SA_ENCRYPT) {853/* need key and IV */854tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE855+ auth->passphrase_len, "CFB", auth->tpm_nonce,856auth->our_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,857auth->scratch);858859len = tpm_buf_read_u16(buf, &offset_p);860aes_prepareenckey(&auth->aes_key, auth->scratch, AES_KEY_BYTES);861aescfb_decrypt(&auth->aes_key, &buf->data[offset_p],862&buf->data[offset_p], len,863auth->scratch + AES_KEY_BYTES);864}865866out:867if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {868if (rc)869/* manually close the session if it wasn't consumed */870tpm2_flush_context(chip, auth->handle);871872kfree_sensitive(auth);873chip->auth = NULL;874} else {875/* reset for next use */876auth->session = TPM_HEADER_SIZE;877}878879return rc;880}881EXPORT_SYMBOL(tpm_buf_check_hmac_response);882883/**884* tpm2_end_auth_session() - kill the allocated auth session885* @chip: the TPM chip structure886*887* ends the session started by tpm2_start_auth_session and frees all888* the resources. Under normal conditions,889* tpm_buf_check_hmac_response() will correctly end the session if890* required, so this function is only for use in error legs that will891* bypass the normal invocation of tpm_buf_check_hmac_response().892*/893void tpm2_end_auth_session(struct tpm_chip *chip)894{895struct tpm2_auth *auth = chip->auth;896897if (!auth)898return;899900tpm2_flush_context(chip, auth->handle);901kfree_sensitive(auth);902chip->auth = NULL;903}904EXPORT_SYMBOL(tpm2_end_auth_session);905906static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,907struct tpm_buf *buf)908{909struct tpm_header *head = (struct tpm_header *)buf->data;910u32 tot_len = be32_to_cpu(head->length);911off_t offset = TPM_HEADER_SIZE;912u32 val;913914/* we're starting after the header so adjust the length */915tot_len -= TPM_HEADER_SIZE;916917/* should have handle plus nonce */918if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))919return -EINVAL;920921auth->handle = tpm_buf_read_u32(buf, &offset);922val = tpm_buf_read_u16(buf, &offset);923if (val != sizeof(auth->tpm_nonce))924return -EINVAL;925memcpy(auth->tpm_nonce, &buf->data[offset], sizeof(auth->tpm_nonce));926/* now compute the session key from the nonces */927tpm2_KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,928auth->our_nonce, sizeof(auth->session_key),929auth->session_key);930931return 0;932}933934static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)935{936unsigned int offset = 0; /* dummy offset for null seed context */937u8 name[SHA256_DIGEST_SIZE + 2];938u32 tmp_null_key;939int rc;940941rc = tpm2_load_context(chip, chip->null_key_context, &offset,942&tmp_null_key);943if (rc != -EINVAL) {944if (!rc)945*null_key = tmp_null_key;946goto err;947}948949/* Try to re-create null key, given the integrity failure: */950rc = tpm2_create_primary(chip, TPM2_RH_NULL, &tmp_null_key, name);951if (rc)952goto err;953954/* Return null key if the name has not been changed: */955if (!memcmp(name, chip->null_key_name, sizeof(name))) {956*null_key = tmp_null_key;957return 0;958}959960/* Deduce from the name change TPM interference: */961dev_err(&chip->dev, "null key integrity check failed\n");962tpm2_flush_context(chip, tmp_null_key);963964err:965if (rc) {966chip->flags |= TPM_CHIP_FLAG_DISABLE;967rc = -ENODEV;968}969return rc;970}971972/**973* tpm2_start_auth_session() - Create an a HMAC authentication session974* @chip: A TPM chip975*976* Loads the ephemeral key (null seed), and starts an HMAC authenticated977* session. The null seed is flushed before the return.978*979* Returns zero on success, or a POSIX error code.980*/981int tpm2_start_auth_session(struct tpm_chip *chip)982{983struct tpm2_auth *auth;984struct tpm_buf buf;985u32 null_key;986int rc;987988if (chip->auth) {989dev_dbg_once(&chip->dev, "auth session is active\n");990return 0;991}992993auth = kzalloc(sizeof(*auth), GFP_KERNEL);994if (!auth)995return -ENOMEM;996997rc = tpm2_load_null(chip, &null_key);998if (rc)999goto out;10001001auth->session = TPM_HEADER_SIZE;10021003rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);1004if (rc)1005goto out;10061007/* salt key handle */1008tpm_buf_append_u32(&buf, null_key);1009/* bind key handle */1010tpm_buf_append_u32(&buf, TPM2_RH_NULL);1011/* nonce caller */1012get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce));1013tpm_buf_append_u16(&buf, sizeof(auth->our_nonce));1014tpm_buf_append(&buf, auth->our_nonce, sizeof(auth->our_nonce));10151016/* append encrypted salt and squirrel away unencrypted in auth */1017tpm_buf_append_salt(&buf, chip, auth);1018/* session type (HMAC, audit or policy) */1019tpm_buf_append_u8(&buf, TPM2_SE_HMAC);10201021/* symmetric encryption parameters */1022/* symmetric algorithm */1023tpm_buf_append_u16(&buf, TPM_ALG_AES);1024/* bits for symmetric algorithm */1025tpm_buf_append_u16(&buf, AES_KEY_BITS);1026/* symmetric algorithm mode (must be CFB) */1027tpm_buf_append_u16(&buf, TPM_ALG_CFB);1028/* hash algorithm for session */1029tpm_buf_append_u16(&buf, TPM_ALG_SHA256);10301031rc = tpm_ret_to_err(tpm_transmit_cmd(chip, &buf, 0, "StartAuthSession"));1032tpm2_flush_context(chip, null_key);10331034if (rc == TPM2_RC_SUCCESS)1035rc = tpm2_parse_start_auth_session(auth, &buf);10361037tpm_buf_destroy(&buf);10381039if (rc == TPM2_RC_SUCCESS) {1040chip->auth = auth;1041return 0;1042}10431044out:1045kfree_sensitive(auth);1046return rc;1047}1048EXPORT_SYMBOL(tpm2_start_auth_session);10491050/*1051* A mask containing the object attributes for the kernel held null primary key1052* used in HMAC encryption. For more information on specific attributes look up1053* to "8.3 TPMA_OBJECT (Object Attributes)".1054*/1055#define TPM2_OA_NULL_KEY ( \1056TPM2_OA_NO_DA | \1057TPM2_OA_FIXED_TPM | \1058TPM2_OA_FIXED_PARENT | \1059TPM2_OA_SENSITIVE_DATA_ORIGIN | \1060TPM2_OA_USER_WITH_AUTH | \1061TPM2_OA_DECRYPT | \1062TPM2_OA_RESTRICTED)10631064/**1065* tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY1066*1067* @chip: The TPM the primary was created under1068* @buf: The response buffer from the chip1069* @handle: pointer to be filled in with the return handle of the primary1070* @hierarchy: The hierarchy the primary was created for1071* @name: pointer to be filled in with the primary key name1072*1073* Return:1074* * 0 - OK1075* * -errno - A system error1076* * TPM_RC - A TPM error1077*/1078static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,1079u32 *handle, u32 hierarchy, u8 *name)1080{1081struct tpm_header *head = (struct tpm_header *)buf->data;1082off_t offset_r = TPM_HEADER_SIZE, offset_t;1083u16 len = TPM_HEADER_SIZE;1084u32 total_len = be32_to_cpu(head->length);1085u32 val, param_len, keyhandle;10861087keyhandle = tpm_buf_read_u32(buf, &offset_r);1088if (handle)1089*handle = keyhandle;1090else1091tpm2_flush_context(chip, keyhandle);10921093param_len = tpm_buf_read_u32(buf, &offset_r);1094/*1095* param_len doesn't include the header, but all the other1096* lengths and offsets do, so add it to parm len to make1097* the comparisons easier1098*/1099param_len += TPM_HEADER_SIZE;11001101if (param_len + 8 > total_len)1102return -EINVAL;1103len = tpm_buf_read_u16(buf, &offset_r);1104offset_t = offset_r;1105if (name) {1106/*1107* now we have the public area, compute the name of1108* the object1109*/1110put_unaligned_be16(TPM_ALG_SHA256, name);1111sha256(&buf->data[offset_r], len, name + 2);1112}11131114/* validate the public key */1115val = tpm_buf_read_u16(buf, &offset_t);11161117/* key type (must be what we asked for) */1118if (val != TPM_ALG_ECC)1119return -EINVAL;1120val = tpm_buf_read_u16(buf, &offset_t);11211122/* name algorithm */1123if (val != TPM_ALG_SHA256)1124return -EINVAL;1125val = tpm_buf_read_u32(buf, &offset_t);11261127/* object properties */1128if (val != TPM2_OA_NULL_KEY)1129return -EINVAL;11301131/* auth policy (empty) */1132val = tpm_buf_read_u16(buf, &offset_t);1133if (val != 0)1134return -EINVAL;11351136/* symmetric key parameters */1137val = tpm_buf_read_u16(buf, &offset_t);1138if (val != TPM_ALG_AES)1139return -EINVAL;11401141/* symmetric key length */1142val = tpm_buf_read_u16(buf, &offset_t);1143if (val != AES_KEY_BITS)1144return -EINVAL;11451146/* symmetric encryption scheme */1147val = tpm_buf_read_u16(buf, &offset_t);1148if (val != TPM_ALG_CFB)1149return -EINVAL;11501151/* signing scheme */1152val = tpm_buf_read_u16(buf, &offset_t);1153if (val != TPM_ALG_NULL)1154return -EINVAL;11551156/* ECC Curve */1157val = tpm_buf_read_u16(buf, &offset_t);1158if (val != TPM2_ECC_NIST_P256)1159return -EINVAL;11601161/* KDF Scheme */1162val = tpm_buf_read_u16(buf, &offset_t);1163if (val != TPM_ALG_NULL)1164return -EINVAL;11651166/* extract public key (x and y points) */1167val = tpm_buf_read_u16(buf, &offset_t);1168if (val != EC_PT_SZ)1169return -EINVAL;1170memcpy(chip->null_ec_key_x, &buf->data[offset_t], val);1171offset_t += val;1172val = tpm_buf_read_u16(buf, &offset_t);1173if (val != EC_PT_SZ)1174return -EINVAL;1175memcpy(chip->null_ec_key_y, &buf->data[offset_t], val);1176offset_t += val;11771178/* original length of the whole TPM2B */1179offset_r += len;11801181/* should have exactly consumed the TPM2B public structure */1182if (offset_t != offset_r)1183return -EINVAL;1184if (offset_r > param_len)1185return -EINVAL;11861187/* creation data (skip) */1188len = tpm_buf_read_u16(buf, &offset_r);1189offset_r += len;1190if (offset_r > param_len)1191return -EINVAL;11921193/* creation digest (must be sha256) */1194len = tpm_buf_read_u16(buf, &offset_r);1195offset_r += len;1196if (len != SHA256_DIGEST_SIZE || offset_r > param_len)1197return -EINVAL;11981199/* TPMT_TK_CREATION follows */1200/* tag, must be TPM_ST_CREATION (0x8021) */1201val = tpm_buf_read_u16(buf, &offset_r);1202if (val != TPM2_ST_CREATION || offset_r > param_len)1203return -EINVAL;12041205/* hierarchy */1206val = tpm_buf_read_u32(buf, &offset_r);1207if (val != hierarchy || offset_r > param_len)1208return -EINVAL;12091210/* the ticket digest HMAC (might not be sha256) */1211len = tpm_buf_read_u16(buf, &offset_r);1212offset_r += len;1213if (offset_r > param_len)1214return -EINVAL;12151216/*1217* finally we have the name, which is a sha256 digest plus a 21218* byte algorithm type1219*/1220len = tpm_buf_read_u16(buf, &offset_r);1221if (offset_r + len != param_len + 8)1222return -EINVAL;1223if (len != SHA256_DIGEST_SIZE + 2)1224return -EINVAL;12251226if (memcmp(chip->null_key_name, &buf->data[offset_r],1227SHA256_DIGEST_SIZE + 2) != 0) {1228dev_err(&chip->dev, "NULL Seed name comparison failed\n");1229return -EINVAL;1230}12311232return 0;1233}12341235/**1236* tpm2_create_primary() - create a primary key using a fixed P-256 template1237*1238* @chip: the TPM chip to create under1239* @hierarchy: The hierarchy handle to create under1240* @handle: The returned volatile handle on success1241* @name: The name of the returned key1242*1243* For platforms that might not have a persistent primary, this can be1244* used to create one quickly on the fly (it uses Elliptic Curve not1245* RSA, so even slow TPMs can create one fast). The template uses the1246* TCG mandated H one for non-endorsement ECC primaries, i.e. P-2561247* elliptic curve (the only current one all TPM2s are required to1248* have) a sha256 name hash and no policy.1249*1250* Return:1251* * 0 - OK1252* * -errno - A system error1253* * TPM_RC - A TPM error1254*/1255static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,1256u32 *handle, u8 *name)1257{1258int rc;1259struct tpm_buf buf;1260struct tpm_buf template;12611262rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);1263if (rc)1264return rc;12651266rc = tpm_buf_init_sized(&template);1267if (rc) {1268tpm_buf_destroy(&buf);1269return rc;1270}12711272/*1273* create the template. Note: in order for userspace to1274* verify the security of the system, it will have to create1275* and certify this NULL primary, meaning all the template1276* parameters will have to be identical, so conform exactly to1277* the TCG TPM v2.0 Provisioning Guidance for the SRK ECC1278* key H template (H has zero size unique points)1279*/12801281/* key type */1282tpm_buf_append_u16(&template, TPM_ALG_ECC);12831284/* name algorithm */1285tpm_buf_append_u16(&template, TPM_ALG_SHA256);12861287/* object properties */1288tpm_buf_append_u32(&template, TPM2_OA_NULL_KEY);12891290/* sauth policy (empty) */1291tpm_buf_append_u16(&template, 0);12921293/* BEGIN parameters: key specific; for ECC*/12941295/* symmetric algorithm */1296tpm_buf_append_u16(&template, TPM_ALG_AES);12971298/* bits for symmetric algorithm */1299tpm_buf_append_u16(&template, AES_KEY_BITS);13001301/* algorithm mode (must be CFB) */1302tpm_buf_append_u16(&template, TPM_ALG_CFB);13031304/* scheme (NULL means any scheme) */1305tpm_buf_append_u16(&template, TPM_ALG_NULL);13061307/* ECC Curve ID */1308tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);13091310/* KDF Scheme */1311tpm_buf_append_u16(&template, TPM_ALG_NULL);13121313/* unique: key specific; for ECC it is two zero size points */1314tpm_buf_append_u16(&template, 0);1315tpm_buf_append_u16(&template, 0);13161317/* END parameters */13181319/* primary handle */1320tpm_buf_append_u32(&buf, hierarchy);1321tpm_buf_append_empty_auth(&buf, TPM2_RS_PW);13221323/* sensitive create size is 4 for two empty buffers */1324tpm_buf_append_u16(&buf, 4);13251326/* sensitive create auth data (empty) */1327tpm_buf_append_u16(&buf, 0);13281329/* sensitive create sensitive data (empty) */1330tpm_buf_append_u16(&buf, 0);13311332/* the public template */1333tpm_buf_append(&buf, template.data, template.length);1334tpm_buf_destroy(&template);13351336/* outside info (empty) */1337tpm_buf_append_u16(&buf, 0);13381339/* creation PCR (none) */1340tpm_buf_append_u32(&buf, 0);13411342rc = tpm_transmit_cmd(chip, &buf, 0,1343"attempting to create NULL primary");13441345if (rc == TPM2_RC_SUCCESS)1346rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy,1347name);13481349tpm_buf_destroy(&buf);13501351return rc;1352}13531354static int tpm2_create_null_primary(struct tpm_chip *chip)1355{1356u32 null_key;1357int rc;13581359rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key,1360chip->null_key_name);13611362if (rc == TPM2_RC_SUCCESS) {1363unsigned int offset = 0; /* dummy offset for null key context */13641365rc = tpm2_save_context(chip, null_key, chip->null_key_context,1366sizeof(chip->null_key_context), &offset);1367tpm2_flush_context(chip, null_key);1368}13691370return rc;1371}13721373/**1374* tpm2_sessions_init() - start of day initialization for the sessions code1375* @chip: TPM chip1376*1377* Derive and context save the null primary and allocate memory in the1378* struct tpm_chip for the authorizations.1379*1380* Return:1381* * 0 - OK1382* * -errno - A system error1383* * TPM_RC - A TPM error1384*/1385int tpm2_sessions_init(struct tpm_chip *chip)1386{1387int rc;13881389rc = tpm2_create_null_primary(chip);1390if (rc) {1391dev_err(&chip->dev, "null key creation failed with %d\n", rc);1392return rc;1393}13941395return rc;1396}1397#endif /* CONFIG_TCG_TPM2_HMAC */139813991400