// 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/hash.h>72#include <crypto/hmac.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 crypto_aes_ctx aes_ctx;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 u8 name_size(const u8 *name)147{148static u8 size_map[] = {149[TPM_ALG_SHA1] = SHA1_DIGEST_SIZE,150[TPM_ALG_SHA256] = SHA256_DIGEST_SIZE,151[TPM_ALG_SHA384] = SHA384_DIGEST_SIZE,152[TPM_ALG_SHA512] = SHA512_DIGEST_SIZE,153};154u16 alg = get_unaligned_be16(name);155return size_map[alg] + 2;156}157158static int tpm2_parse_read_public(char *name, struct tpm_buf *buf)159{160struct tpm_header *head = (struct tpm_header *)buf->data;161off_t offset = TPM_HEADER_SIZE;162u32 tot_len = be32_to_cpu(head->length);163u32 val;164165/* we're starting after the header so adjust the length */166tot_len -= TPM_HEADER_SIZE;167168/* skip public */169val = tpm_buf_read_u16(buf, &offset);170if (val > tot_len)171return -EINVAL;172offset += val;173/* name */174val = tpm_buf_read_u16(buf, &offset);175if (val != name_size(&buf->data[offset]))176return -EINVAL;177memcpy(name, &buf->data[offset], val);178/* forget the rest */179return 0;180}181182static int tpm2_read_public(struct tpm_chip *chip, u32 handle, char *name)183{184struct tpm_buf buf;185int rc;186187rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);188if (rc)189return rc;190191tpm_buf_append_u32(&buf, handle);192rc = tpm_transmit_cmd(chip, &buf, 0, "read public");193if (rc == TPM2_RC_SUCCESS)194rc = tpm2_parse_read_public(name, &buf);195196tpm_buf_destroy(&buf);197198return rc;199}200#endif /* CONFIG_TCG_TPM2_HMAC */201202/**203* tpm_buf_append_name() - add a handle area to the buffer204* @chip: the TPM chip structure205* @buf: The buffer to be appended206* @handle: The handle to be appended207* @name: The name of the handle (may be NULL)208*209* In order to compute session HMACs, we need to know the names of the210* objects pointed to by the handles. For most objects, this is simply211* the actual 4 byte handle or an empty buf (in these cases @name212* should be NULL) but for volatile objects, permanent objects and NV213* areas, the name is defined as the hash (according to the name214* algorithm which should be set to sha256) of the public area to215* which the two byte algorithm id has been appended. For these216* objects, the @name pointer should point to this. If a name is217* required but @name is NULL, then TPM2_ReadPublic() will be called218* on the handle to obtain the name.219*220* As with most tpm_buf operations, success is assumed because failure221* will be caused by an incorrect programming model and indicated by a222* kernel message.223*/224void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,225u32 handle, u8 *name)226{227#ifdef CONFIG_TCG_TPM2_HMAC228enum tpm2_mso_type mso = tpm2_handle_mso(handle);229struct tpm2_auth *auth;230int slot;231#endif232233if (!tpm2_chip_auth(chip)) {234tpm_buf_append_handle(chip, buf, handle);235return;236}237238#ifdef CONFIG_TCG_TPM2_HMAC239slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE) / 4;240if (slot >= AUTH_MAX_NAMES) {241dev_err(&chip->dev, "TPM: too many handles\n");242return;243}244auth = chip->auth;245WARN(auth->session != tpm_buf_length(buf),246"name added in wrong place\n");247tpm_buf_append_u32(buf, handle);248auth->session += 4;249250if (mso == TPM2_MSO_PERSISTENT ||251mso == TPM2_MSO_VOLATILE ||252mso == TPM2_MSO_NVRAM) {253if (!name)254tpm2_read_public(chip, handle, auth->name[slot]);255} else {256if (name)257dev_err(&chip->dev, "TPM: Handle does not require name but one is specified\n");258}259260auth->name_h[slot] = handle;261if (name)262memcpy(auth->name[slot], name, name_size(name));263#endif264}265EXPORT_SYMBOL_GPL(tpm_buf_append_name);266267void tpm_buf_append_auth(struct tpm_chip *chip, struct tpm_buf *buf,268u8 attributes, u8 *passphrase, int passphrase_len)269{270/* offset tells us where the sessions area begins */271int offset = buf->handles * 4 + TPM_HEADER_SIZE;272u32 len = 9 + passphrase_len;273274if (tpm_buf_length(buf) != offset) {275/* not the first session so update the existing length */276len += get_unaligned_be32(&buf->data[offset]);277put_unaligned_be32(len, &buf->data[offset]);278} else {279tpm_buf_append_u32(buf, len);280}281/* auth handle */282tpm_buf_append_u32(buf, TPM2_RS_PW);283/* nonce */284tpm_buf_append_u16(buf, 0);285/* attributes */286tpm_buf_append_u8(buf, 0);287/* passphrase */288tpm_buf_append_u16(buf, passphrase_len);289tpm_buf_append(buf, passphrase, passphrase_len);290}291292/**293* tpm_buf_append_hmac_session() - Append a TPM session element294* @chip: the TPM chip structure295* @buf: The buffer to be appended296* @attributes: The session attributes297* @passphrase: The session authority (NULL if none)298* @passphrase_len: The length of the session authority (0 if none)299*300* This fills in a session structure in the TPM command buffer, except301* for the HMAC which cannot be computed until the command buffer is302* complete. The type of session is controlled by the @attributes,303* the main ones of which are TPM2_SA_CONTINUE_SESSION which means the304* session won't terminate after tpm_buf_check_hmac_response(),305* TPM2_SA_DECRYPT which means this buffers first parameter should be306* encrypted with a session key and TPM2_SA_ENCRYPT, which means the307* response buffer's first parameter needs to be decrypted (confusing,308* but the defines are written from the point of view of the TPM).309*310* Any session appended by this command must be finalized by calling311* tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect312* and the TPM will reject the command.313*314* As with most tpm_buf operations, success is assumed because failure315* will be caused by an incorrect programming model and indicated by a316* kernel message.317*/318void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,319u8 attributes, u8 *passphrase,320int passphrase_len)321{322#ifdef CONFIG_TCG_TPM2_HMAC323u8 nonce[SHA256_DIGEST_SIZE];324struct tpm2_auth *auth;325u32 len;326#endif327328if (!tpm2_chip_auth(chip)) {329tpm_buf_append_auth(chip, buf, attributes, passphrase,330passphrase_len);331return;332}333334#ifdef CONFIG_TCG_TPM2_HMAC335/* The first write to /dev/tpm{rm0} will flush the session. */336attributes |= TPM2_SA_CONTINUE_SESSION;337338/*339* The Architecture Guide requires us to strip trailing zeros340* before computing the HMAC341*/342while (passphrase && passphrase_len > 0 && passphrase[passphrase_len - 1] == '\0')343passphrase_len--;344345auth = chip->auth;346auth->attrs = attributes;347auth->passphrase_len = passphrase_len;348if (passphrase_len)349memcpy(auth->passphrase, passphrase, passphrase_len);350351if (auth->session != tpm_buf_length(buf)) {352/* we're not the first session */353len = get_unaligned_be32(&buf->data[auth->session]);354if (4 + len + auth->session != tpm_buf_length(buf)) {355WARN(1, "session length mismatch, cannot append");356return;357}358359/* add our new session */360len += 9 + 2 * SHA256_DIGEST_SIZE;361put_unaligned_be32(len, &buf->data[auth->session]);362} else {363tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);364}365366/* random number for our nonce */367get_random_bytes(nonce, sizeof(nonce));368memcpy(auth->our_nonce, nonce, sizeof(nonce));369tpm_buf_append_u32(buf, auth->handle);370/* our new nonce */371tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);372tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);373tpm_buf_append_u8(buf, auth->attrs);374/* and put a placeholder for the hmac */375tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);376tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);377#endif378}379EXPORT_SYMBOL_GPL(tpm_buf_append_hmac_session);380381#ifdef CONFIG_TCG_TPM2_HMAC382383static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,384u32 *handle, u8 *name);385386/*387* It turns out the crypto hmac(sha256) is hard for us to consume388* because it assumes a fixed key and the TPM seems to change the key389* on every operation, so we weld the hmac init and final functions in390* here to give it the same usage characteristics as a regular hash391*/392static void tpm2_hmac_init(struct sha256_ctx *sctx, u8 *key, u32 key_len)393{394u8 pad[SHA256_BLOCK_SIZE];395int i;396397sha256_init(sctx);398for (i = 0; i < sizeof(pad); i++) {399if (i < key_len)400pad[i] = key[i];401else402pad[i] = 0;403pad[i] ^= HMAC_IPAD_VALUE;404}405sha256_update(sctx, pad, sizeof(pad));406}407408static void tpm2_hmac_final(struct sha256_ctx *sctx, u8 *key, u32 key_len,409u8 *out)410{411u8 pad[SHA256_BLOCK_SIZE];412int i;413414for (i = 0; i < sizeof(pad); i++) {415if (i < key_len)416pad[i] = key[i];417else418pad[i] = 0;419pad[i] ^= HMAC_OPAD_VALUE;420}421422/* collect the final hash; use out as temporary storage */423sha256_final(sctx, out);424425sha256_init(sctx);426sha256_update(sctx, pad, sizeof(pad));427sha256_update(sctx, out, SHA256_DIGEST_SIZE);428sha256_final(sctx, out);429}430431/*432* assume hash sha256 and nonces u, v of size SHA256_DIGEST_SIZE but433* otherwise standard tpm2_KDFa. Note output is in bytes not bits.434*/435static void tpm2_KDFa(u8 *key, u32 key_len, const char *label, u8 *u,436u8 *v, u32 bytes, u8 *out)437{438u32 counter = 1;439const __be32 bits = cpu_to_be32(bytes * 8);440441while (bytes > 0) {442struct sha256_ctx sctx;443__be32 c = cpu_to_be32(counter);444445tpm2_hmac_init(&sctx, key, key_len);446sha256_update(&sctx, (u8 *)&c, sizeof(c));447sha256_update(&sctx, label, strlen(label)+1);448sha256_update(&sctx, u, SHA256_DIGEST_SIZE);449sha256_update(&sctx, v, SHA256_DIGEST_SIZE);450sha256_update(&sctx, (u8 *)&bits, sizeof(bits));451tpm2_hmac_final(&sctx, key, key_len, out);452453bytes -= SHA256_DIGEST_SIZE;454counter++;455out += SHA256_DIGEST_SIZE;456}457}458459/*460* Somewhat of a bastardization of the real KDFe. We're assuming461* we're working with known point sizes for the input parameters and462* the hash algorithm is fixed at sha256. Because we know that the463* point size is 32 bytes like the hash size, there's no need to loop464* in this KDF.465*/466static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,467u8 *out)468{469struct sha256_ctx sctx;470/*471* this should be an iterative counter, but because we know472* we're only taking 32 bytes for the point using a sha256473* hash which is also 32 bytes, there's only one loop474*/475__be32 c = cpu_to_be32(1);476477sha256_init(&sctx);478/* counter (BE) */479sha256_update(&sctx, (u8 *)&c, sizeof(c));480/* secret value */481sha256_update(&sctx, z, EC_PT_SZ);482/* string including trailing zero */483sha256_update(&sctx, str, strlen(str)+1);484sha256_update(&sctx, pt_u, EC_PT_SZ);485sha256_update(&sctx, pt_v, EC_PT_SZ);486sha256_final(&sctx, out);487}488489static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip,490struct tpm2_auth *auth)491{492struct crypto_kpp *kpp;493struct kpp_request *req;494struct scatterlist s[2], d[1];495struct ecdh p = {0};496u8 encoded_key[EC_PT_SZ], *x, *y;497unsigned int buf_len;498499/* secret is two sized points */500tpm_buf_append_u16(buf, (EC_PT_SZ + 2)*2);501/*502* we cheat here and append uninitialized data to form503* the points. All we care about is getting the two504* co-ordinate pointers, which will be used to overwrite505* the uninitialized data506*/507tpm_buf_append_u16(buf, EC_PT_SZ);508x = &buf->data[tpm_buf_length(buf)];509tpm_buf_append(buf, encoded_key, EC_PT_SZ);510tpm_buf_append_u16(buf, EC_PT_SZ);511y = &buf->data[tpm_buf_length(buf)];512tpm_buf_append(buf, encoded_key, EC_PT_SZ);513sg_init_table(s, 2);514sg_set_buf(&s[0], x, EC_PT_SZ);515sg_set_buf(&s[1], y, EC_PT_SZ);516517kpp = crypto_alloc_kpp("ecdh-nist-p256", CRYPTO_ALG_INTERNAL, 0);518if (IS_ERR(kpp)) {519dev_err(&chip->dev, "crypto ecdh allocation failed\n");520return;521}522523buf_len = crypto_ecdh_key_len(&p);524if (sizeof(encoded_key) < buf_len) {525dev_err(&chip->dev, "salt buffer too small needs %d\n",526buf_len);527goto out;528}529crypto_ecdh_encode_key(encoded_key, buf_len, &p);530/* this generates a random private key */531crypto_kpp_set_secret(kpp, encoded_key, buf_len);532533/* salt is now the public point of this private key */534req = kpp_request_alloc(kpp, GFP_KERNEL);535if (!req)536goto out;537kpp_request_set_input(req, NULL, 0);538kpp_request_set_output(req, s, EC_PT_SZ*2);539crypto_kpp_generate_public_key(req);540/*541* we're not done: now we have to compute the shared secret542* which is our private key multiplied by the tpm_key public543* point, we actually only take the x point and discard the y544* point and feed it through KDFe to get the final secret salt545*/546sg_set_buf(&s[0], chip->null_ec_key_x, EC_PT_SZ);547sg_set_buf(&s[1], chip->null_ec_key_y, EC_PT_SZ);548kpp_request_set_input(req, s, EC_PT_SZ*2);549sg_init_one(d, auth->salt, EC_PT_SZ);550kpp_request_set_output(req, d, EC_PT_SZ);551crypto_kpp_compute_shared_secret(req);552kpp_request_free(req);553554/*555* pass the shared secret through KDFe for salt. Note salt556* area is used both for input shared secret and output salt.557* This works because KDFe fully consumes the secret before it558* writes the salt559*/560tpm2_KDFe(auth->salt, "SECRET", x, chip->null_ec_key_x, auth->salt);561562out:563crypto_free_kpp(kpp);564}565566/**567* tpm_buf_fill_hmac_session() - finalize the session HMAC568* @chip: the TPM chip structure569* @buf: The buffer to be appended570*571* This command must not be called until all of the parameters have572* been appended to @buf otherwise the computed HMAC will be573* incorrect.574*575* This function computes and fills in the session HMAC using the576* session key and, if TPM2_SA_DECRYPT was specified, computes the577* encryption key and encrypts the first parameter of the command578* buffer with it.579*580* As with most tpm_buf operations, success is assumed because failure581* will be caused by an incorrect programming model and indicated by a582* kernel message.583*/584void tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)585{586u32 cc, handles, val;587struct tpm2_auth *auth = chip->auth;588int i;589struct tpm_header *head = (struct tpm_header *)buf->data;590off_t offset_s = TPM_HEADER_SIZE, offset_p;591u8 *hmac = NULL;592u32 attrs;593u8 cphash[SHA256_DIGEST_SIZE];594struct sha256_ctx sctx;595596if (!auth)597return;598599/* save the command code in BE format */600auth->ordinal = head->ordinal;601602cc = be32_to_cpu(head->ordinal);603604i = tpm2_find_cc(chip, cc);605if (i < 0) {606dev_err(&chip->dev, "Command 0x%x not found in TPM\n", cc);607return;608}609attrs = chip->cc_attrs_tbl[i];610611handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0);612613/*614* just check the names, it's easy to make mistakes. This615* would happen if someone added a handle via616* tpm_buf_append_u32() instead of tpm_buf_append_name()617*/618for (i = 0; i < handles; i++) {619u32 handle = tpm_buf_read_u32(buf, &offset_s);620621if (auth->name_h[i] != handle) {622dev_err(&chip->dev, "TPM: handle %d wrong for name\n",623i);624return;625}626}627/* point offset_s to the start of the sessions */628val = tpm_buf_read_u32(buf, &offset_s);629/* point offset_p to the start of the parameters */630offset_p = offset_s + val;631for (i = 1; offset_s < offset_p; i++) {632u32 handle = tpm_buf_read_u32(buf, &offset_s);633u16 len;634u8 a;635636/* nonce (already in auth) */637len = tpm_buf_read_u16(buf, &offset_s);638offset_s += len;639640a = tpm_buf_read_u8(buf, &offset_s);641642len = tpm_buf_read_u16(buf, &offset_s);643if (handle == auth->handle && auth->attrs == a) {644hmac = &buf->data[offset_s];645/*646* save our session number so we know which647* session in the response belongs to us648*/649auth->session = i;650}651652offset_s += len;653}654if (offset_s != offset_p) {655dev_err(&chip->dev, "TPM session length is incorrect\n");656return;657}658if (!hmac) {659dev_err(&chip->dev, "TPM could not find HMAC session\n");660return;661}662663/* encrypt before HMAC */664if (auth->attrs & TPM2_SA_DECRYPT) {665u16 len;666667/* need key and IV */668tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE669+ auth->passphrase_len, "CFB", auth->our_nonce,670auth->tpm_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,671auth->scratch);672673len = tpm_buf_read_u16(buf, &offset_p);674aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);675aescfb_encrypt(&auth->aes_ctx, &buf->data[offset_p],676&buf->data[offset_p], len,677auth->scratch + AES_KEY_BYTES);678/* reset p to beginning of parameters for HMAC */679offset_p -= 2;680}681682sha256_init(&sctx);683/* ordinal is already BE */684sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));685/* add the handle names */686for (i = 0; i < handles; i++) {687enum tpm2_mso_type mso = tpm2_handle_mso(auth->name_h[i]);688689if (mso == TPM2_MSO_PERSISTENT ||690mso == TPM2_MSO_VOLATILE ||691mso == TPM2_MSO_NVRAM) {692sha256_update(&sctx, auth->name[i],693name_size(auth->name[i]));694} else {695__be32 h = cpu_to_be32(auth->name_h[i]);696697sha256_update(&sctx, (u8 *)&h, 4);698}699}700if (offset_s != tpm_buf_length(buf))701sha256_update(&sctx, &buf->data[offset_s],702tpm_buf_length(buf) - offset_s);703sha256_final(&sctx, cphash);704705/* now calculate the hmac */706tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)707+ auth->passphrase_len);708sha256_update(&sctx, cphash, sizeof(cphash));709sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));710sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));711sha256_update(&sctx, &auth->attrs, 1);712tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)713+ auth->passphrase_len, hmac);714}715EXPORT_SYMBOL(tpm_buf_fill_hmac_session);716717/**718* tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness719* @chip: the TPM chip structure720* @buf: the original command buffer (which now contains the response)721* @rc: the return code from tpm_transmit_cmd722*723* If @rc is non zero, @buf may not contain an actual return, so @rc724* is passed through as the return and the session cleaned up and725* de-allocated if required (this is required if726* TPM2_SA_CONTINUE_SESSION was not specified as a session flag).727*728* If @rc is zero, the response HMAC is computed against the returned729* @buf and matched to the TPM one in the session area. If there is a730* mismatch, an error is logged and -EINVAL returned.731*732* The reason for this is that the command issue and HMAC check733* sequence should look like:734*735* rc = tpm_transmit_cmd(...);736* rc = tpm_buf_check_hmac_response(&buf, auth, rc);737* if (rc)738* ...739*740* Which is easily layered into the current contrl flow.741*742* Returns: 0 on success or an error.743*/744int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,745int rc)746{747struct tpm_header *head = (struct tpm_header *)buf->data;748struct tpm2_auth *auth = chip->auth;749off_t offset_s, offset_p;750u8 rphash[SHA256_DIGEST_SIZE];751u32 attrs, cc;752struct sha256_ctx sctx;753u16 tag = be16_to_cpu(head->tag);754int parm_len, len, i, handles;755756if (!auth)757return rc;758759cc = be32_to_cpu(auth->ordinal);760761if (auth->session >= TPM_HEADER_SIZE) {762WARN(1, "tpm session not filled correctly\n");763goto out;764}765766if (rc != 0)767/* pass non success rc through and close the session */768goto out;769770rc = -EINVAL;771if (tag != TPM2_ST_SESSIONS) {772dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");773goto out;774}775776i = tpm2_find_cc(chip, cc);777if (i < 0)778goto out;779attrs = chip->cc_attrs_tbl[i];780handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;781782/* point to area beyond handles */783offset_s = TPM_HEADER_SIZE + handles * 4;784parm_len = tpm_buf_read_u32(buf, &offset_s);785offset_p = offset_s;786offset_s += parm_len;787/* skip over any sessions before ours */788for (i = 0; i < auth->session - 1; i++) {789len = tpm_buf_read_u16(buf, &offset_s);790offset_s += len + 1;791len = tpm_buf_read_u16(buf, &offset_s);792offset_s += len;793}794/* TPM nonce */795len = tpm_buf_read_u16(buf, &offset_s);796if (offset_s + len > tpm_buf_length(buf))797goto out;798if (len != SHA256_DIGEST_SIZE)799goto out;800memcpy(auth->tpm_nonce, &buf->data[offset_s], len);801offset_s += len;802attrs = tpm_buf_read_u8(buf, &offset_s);803len = tpm_buf_read_u16(buf, &offset_s);804if (offset_s + len != tpm_buf_length(buf))805goto out;806if (len != SHA256_DIGEST_SIZE)807goto out;808/*809* offset_s points to the HMAC. now calculate comparison, beginning810* with rphash811*/812sha256_init(&sctx);813/* yes, I know this is now zero, but it's what the standard says */814sha256_update(&sctx, (u8 *)&head->return_code,815sizeof(head->return_code));816/* ordinal is already BE */817sha256_update(&sctx, (u8 *)&auth->ordinal, sizeof(auth->ordinal));818sha256_update(&sctx, &buf->data[offset_p], parm_len);819sha256_final(&sctx, rphash);820821/* now calculate the hmac */822tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)823+ auth->passphrase_len);824sha256_update(&sctx, rphash, sizeof(rphash));825sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));826sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));827sha256_update(&sctx, &auth->attrs, 1);828/* we're done with the rphash, so put our idea of the hmac there */829tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)830+ auth->passphrase_len, rphash);831if (memcmp(rphash, &buf->data[offset_s], SHA256_DIGEST_SIZE) == 0) {832rc = 0;833} else {834dev_err(&chip->dev, "TPM: HMAC check failed\n");835goto out;836}837838/* now do response decryption */839if (auth->attrs & TPM2_SA_ENCRYPT) {840/* need key and IV */841tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE842+ auth->passphrase_len, "CFB", auth->tpm_nonce,843auth->our_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,844auth->scratch);845846len = tpm_buf_read_u16(buf, &offset_p);847aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);848aescfb_decrypt(&auth->aes_ctx, &buf->data[offset_p],849&buf->data[offset_p], len,850auth->scratch + AES_KEY_BYTES);851}852853out:854if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {855if (rc)856/* manually close the session if it wasn't consumed */857tpm2_flush_context(chip, auth->handle);858859kfree_sensitive(auth);860chip->auth = NULL;861} else {862/* reset for next use */863auth->session = TPM_HEADER_SIZE;864}865866return rc;867}868EXPORT_SYMBOL(tpm_buf_check_hmac_response);869870/**871* tpm2_end_auth_session() - kill the allocated auth session872* @chip: the TPM chip structure873*874* ends the session started by tpm2_start_auth_session and frees all875* the resources. Under normal conditions,876* tpm_buf_check_hmac_response() will correctly end the session if877* required, so this function is only for use in error legs that will878* bypass the normal invocation of tpm_buf_check_hmac_response().879*/880void tpm2_end_auth_session(struct tpm_chip *chip)881{882struct tpm2_auth *auth = chip->auth;883884if (!auth)885return;886887tpm2_flush_context(chip, auth->handle);888kfree_sensitive(auth);889chip->auth = NULL;890}891EXPORT_SYMBOL(tpm2_end_auth_session);892893static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,894struct tpm_buf *buf)895{896struct tpm_header *head = (struct tpm_header *)buf->data;897u32 tot_len = be32_to_cpu(head->length);898off_t offset = TPM_HEADER_SIZE;899u32 val;900901/* we're starting after the header so adjust the length */902tot_len -= TPM_HEADER_SIZE;903904/* should have handle plus nonce */905if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))906return -EINVAL;907908auth->handle = tpm_buf_read_u32(buf, &offset);909val = tpm_buf_read_u16(buf, &offset);910if (val != sizeof(auth->tpm_nonce))911return -EINVAL;912memcpy(auth->tpm_nonce, &buf->data[offset], sizeof(auth->tpm_nonce));913/* now compute the session key from the nonces */914tpm2_KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,915auth->our_nonce, sizeof(auth->session_key),916auth->session_key);917918return 0;919}920921static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)922{923unsigned int offset = 0; /* dummy offset for null seed context */924u8 name[SHA256_DIGEST_SIZE + 2];925u32 tmp_null_key;926int rc;927928rc = tpm2_load_context(chip, chip->null_key_context, &offset,929&tmp_null_key);930if (rc != -EINVAL) {931if (!rc)932*null_key = tmp_null_key;933goto err;934}935936/* Try to re-create null key, given the integrity failure: */937rc = tpm2_create_primary(chip, TPM2_RH_NULL, &tmp_null_key, name);938if (rc)939goto err;940941/* Return null key if the name has not been changed: */942if (!memcmp(name, chip->null_key_name, sizeof(name))) {943*null_key = tmp_null_key;944return 0;945}946947/* Deduce from the name change TPM interference: */948dev_err(&chip->dev, "null key integrity check failed\n");949tpm2_flush_context(chip, tmp_null_key);950951err:952if (rc) {953chip->flags |= TPM_CHIP_FLAG_DISABLE;954rc = -ENODEV;955}956return rc;957}958959/**960* tpm2_start_auth_session() - Create an a HMAC authentication session961* @chip: A TPM chip962*963* Loads the ephemeral key (null seed), and starts an HMAC authenticated964* session. The null seed is flushed before the return.965*966* Returns zero on success, or a POSIX error code.967*/968int tpm2_start_auth_session(struct tpm_chip *chip)969{970struct tpm2_auth *auth;971struct tpm_buf buf;972u32 null_key;973int rc;974975if (chip->auth) {976dev_dbg_once(&chip->dev, "auth session is active\n");977return 0;978}979980auth = kzalloc(sizeof(*auth), GFP_KERNEL);981if (!auth)982return -ENOMEM;983984rc = tpm2_load_null(chip, &null_key);985if (rc)986goto out;987988auth->session = TPM_HEADER_SIZE;989990rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);991if (rc)992goto out;993994/* salt key handle */995tpm_buf_append_u32(&buf, null_key);996/* bind key handle */997tpm_buf_append_u32(&buf, TPM2_RH_NULL);998/* nonce caller */999get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce));1000tpm_buf_append_u16(&buf, sizeof(auth->our_nonce));1001tpm_buf_append(&buf, auth->our_nonce, sizeof(auth->our_nonce));10021003/* append encrypted salt and squirrel away unencrypted in auth */1004tpm_buf_append_salt(&buf, chip, auth);1005/* session type (HMAC, audit or policy) */1006tpm_buf_append_u8(&buf, TPM2_SE_HMAC);10071008/* symmetric encryption parameters */1009/* symmetric algorithm */1010tpm_buf_append_u16(&buf, TPM_ALG_AES);1011/* bits for symmetric algorithm */1012tpm_buf_append_u16(&buf, AES_KEY_BITS);1013/* symmetric algorithm mode (must be CFB) */1014tpm_buf_append_u16(&buf, TPM_ALG_CFB);1015/* hash algorithm for session */1016tpm_buf_append_u16(&buf, TPM_ALG_SHA256);10171018rc = tpm_ret_to_err(tpm_transmit_cmd(chip, &buf, 0, "StartAuthSession"));1019tpm2_flush_context(chip, null_key);10201021if (rc == TPM2_RC_SUCCESS)1022rc = tpm2_parse_start_auth_session(auth, &buf);10231024tpm_buf_destroy(&buf);10251026if (rc == TPM2_RC_SUCCESS) {1027chip->auth = auth;1028return 0;1029}10301031out:1032kfree_sensitive(auth);1033return rc;1034}1035EXPORT_SYMBOL(tpm2_start_auth_session);10361037/*1038* A mask containing the object attributes for the kernel held null primary key1039* used in HMAC encryption. For more information on specific attributes look up1040* to "8.3 TPMA_OBJECT (Object Attributes)".1041*/1042#define TPM2_OA_NULL_KEY ( \1043TPM2_OA_NO_DA | \1044TPM2_OA_FIXED_TPM | \1045TPM2_OA_FIXED_PARENT | \1046TPM2_OA_SENSITIVE_DATA_ORIGIN | \1047TPM2_OA_USER_WITH_AUTH | \1048TPM2_OA_DECRYPT | \1049TPM2_OA_RESTRICTED)10501051/**1052* tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY1053*1054* @chip: The TPM the primary was created under1055* @buf: The response buffer from the chip1056* @handle: pointer to be filled in with the return handle of the primary1057* @hierarchy: The hierarchy the primary was created for1058* @name: pointer to be filled in with the primary key name1059*1060* Return:1061* * 0 - OK1062* * -errno - A system error1063* * TPM_RC - A TPM error1064*/1065static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,1066u32 *handle, u32 hierarchy, u8 *name)1067{1068struct tpm_header *head = (struct tpm_header *)buf->data;1069off_t offset_r = TPM_HEADER_SIZE, offset_t;1070u16 len = TPM_HEADER_SIZE;1071u32 total_len = be32_to_cpu(head->length);1072u32 val, param_len, keyhandle;10731074keyhandle = tpm_buf_read_u32(buf, &offset_r);1075if (handle)1076*handle = keyhandle;1077else1078tpm2_flush_context(chip, keyhandle);10791080param_len = tpm_buf_read_u32(buf, &offset_r);1081/*1082* param_len doesn't include the header, but all the other1083* lengths and offsets do, so add it to parm len to make1084* the comparisons easier1085*/1086param_len += TPM_HEADER_SIZE;10871088if (param_len + 8 > total_len)1089return -EINVAL;1090len = tpm_buf_read_u16(buf, &offset_r);1091offset_t = offset_r;1092if (name) {1093/*1094* now we have the public area, compute the name of1095* the object1096*/1097put_unaligned_be16(TPM_ALG_SHA256, name);1098sha256(&buf->data[offset_r], len, name + 2);1099}11001101/* validate the public key */1102val = tpm_buf_read_u16(buf, &offset_t);11031104/* key type (must be what we asked for) */1105if (val != TPM_ALG_ECC)1106return -EINVAL;1107val = tpm_buf_read_u16(buf, &offset_t);11081109/* name algorithm */1110if (val != TPM_ALG_SHA256)1111return -EINVAL;1112val = tpm_buf_read_u32(buf, &offset_t);11131114/* object properties */1115if (val != TPM2_OA_NULL_KEY)1116return -EINVAL;11171118/* auth policy (empty) */1119val = tpm_buf_read_u16(buf, &offset_t);1120if (val != 0)1121return -EINVAL;11221123/* symmetric key parameters */1124val = tpm_buf_read_u16(buf, &offset_t);1125if (val != TPM_ALG_AES)1126return -EINVAL;11271128/* symmetric key length */1129val = tpm_buf_read_u16(buf, &offset_t);1130if (val != AES_KEY_BITS)1131return -EINVAL;11321133/* symmetric encryption scheme */1134val = tpm_buf_read_u16(buf, &offset_t);1135if (val != TPM_ALG_CFB)1136return -EINVAL;11371138/* signing scheme */1139val = tpm_buf_read_u16(buf, &offset_t);1140if (val != TPM_ALG_NULL)1141return -EINVAL;11421143/* ECC Curve */1144val = tpm_buf_read_u16(buf, &offset_t);1145if (val != TPM2_ECC_NIST_P256)1146return -EINVAL;11471148/* KDF Scheme */1149val = tpm_buf_read_u16(buf, &offset_t);1150if (val != TPM_ALG_NULL)1151return -EINVAL;11521153/* extract public key (x and y points) */1154val = tpm_buf_read_u16(buf, &offset_t);1155if (val != EC_PT_SZ)1156return -EINVAL;1157memcpy(chip->null_ec_key_x, &buf->data[offset_t], val);1158offset_t += val;1159val = tpm_buf_read_u16(buf, &offset_t);1160if (val != EC_PT_SZ)1161return -EINVAL;1162memcpy(chip->null_ec_key_y, &buf->data[offset_t], val);1163offset_t += val;11641165/* original length of the whole TPM2B */1166offset_r += len;11671168/* should have exactly consumed the TPM2B public structure */1169if (offset_t != offset_r)1170return -EINVAL;1171if (offset_r > param_len)1172return -EINVAL;11731174/* creation data (skip) */1175len = tpm_buf_read_u16(buf, &offset_r);1176offset_r += len;1177if (offset_r > param_len)1178return -EINVAL;11791180/* creation digest (must be sha256) */1181len = tpm_buf_read_u16(buf, &offset_r);1182offset_r += len;1183if (len != SHA256_DIGEST_SIZE || offset_r > param_len)1184return -EINVAL;11851186/* TPMT_TK_CREATION follows */1187/* tag, must be TPM_ST_CREATION (0x8021) */1188val = tpm_buf_read_u16(buf, &offset_r);1189if (val != TPM2_ST_CREATION || offset_r > param_len)1190return -EINVAL;11911192/* hierarchy */1193val = tpm_buf_read_u32(buf, &offset_r);1194if (val != hierarchy || offset_r > param_len)1195return -EINVAL;11961197/* the ticket digest HMAC (might not be sha256) */1198len = tpm_buf_read_u16(buf, &offset_r);1199offset_r += len;1200if (offset_r > param_len)1201return -EINVAL;12021203/*1204* finally we have the name, which is a sha256 digest plus a 21205* byte algorithm type1206*/1207len = tpm_buf_read_u16(buf, &offset_r);1208if (offset_r + len != param_len + 8)1209return -EINVAL;1210if (len != SHA256_DIGEST_SIZE + 2)1211return -EINVAL;12121213if (memcmp(chip->null_key_name, &buf->data[offset_r],1214SHA256_DIGEST_SIZE + 2) != 0) {1215dev_err(&chip->dev, "NULL Seed name comparison failed\n");1216return -EINVAL;1217}12181219return 0;1220}12211222/**1223* tpm2_create_primary() - create a primary key using a fixed P-256 template1224*1225* @chip: the TPM chip to create under1226* @hierarchy: The hierarchy handle to create under1227* @handle: The returned volatile handle on success1228* @name: The name of the returned key1229*1230* For platforms that might not have a persistent primary, this can be1231* used to create one quickly on the fly (it uses Elliptic Curve not1232* RSA, so even slow TPMs can create one fast). The template uses the1233* TCG mandated H one for non-endorsement ECC primaries, i.e. P-2561234* elliptic curve (the only current one all TPM2s are required to1235* have) a sha256 name hash and no policy.1236*1237* Return:1238* * 0 - OK1239* * -errno - A system error1240* * TPM_RC - A TPM error1241*/1242static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,1243u32 *handle, u8 *name)1244{1245int rc;1246struct tpm_buf buf;1247struct tpm_buf template;12481249rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);1250if (rc)1251return rc;12521253rc = tpm_buf_init_sized(&template);1254if (rc) {1255tpm_buf_destroy(&buf);1256return rc;1257}12581259/*1260* create the template. Note: in order for userspace to1261* verify the security of the system, it will have to create1262* and certify this NULL primary, meaning all the template1263* parameters will have to be identical, so conform exactly to1264* the TCG TPM v2.0 Provisioning Guidance for the SRK ECC1265* key H template (H has zero size unique points)1266*/12671268/* key type */1269tpm_buf_append_u16(&template, TPM_ALG_ECC);12701271/* name algorithm */1272tpm_buf_append_u16(&template, TPM_ALG_SHA256);12731274/* object properties */1275tpm_buf_append_u32(&template, TPM2_OA_NULL_KEY);12761277/* sauth policy (empty) */1278tpm_buf_append_u16(&template, 0);12791280/* BEGIN parameters: key specific; for ECC*/12811282/* symmetric algorithm */1283tpm_buf_append_u16(&template, TPM_ALG_AES);12841285/* bits for symmetric algorithm */1286tpm_buf_append_u16(&template, AES_KEY_BITS);12871288/* algorithm mode (must be CFB) */1289tpm_buf_append_u16(&template, TPM_ALG_CFB);12901291/* scheme (NULL means any scheme) */1292tpm_buf_append_u16(&template, TPM_ALG_NULL);12931294/* ECC Curve ID */1295tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);12961297/* KDF Scheme */1298tpm_buf_append_u16(&template, TPM_ALG_NULL);12991300/* unique: key specific; for ECC it is two zero size points */1301tpm_buf_append_u16(&template, 0);1302tpm_buf_append_u16(&template, 0);13031304/* END parameters */13051306/* primary handle */1307tpm_buf_append_u32(&buf, hierarchy);1308tpm_buf_append_empty_auth(&buf, TPM2_RS_PW);13091310/* sensitive create size is 4 for two empty buffers */1311tpm_buf_append_u16(&buf, 4);13121313/* sensitive create auth data (empty) */1314tpm_buf_append_u16(&buf, 0);13151316/* sensitive create sensitive data (empty) */1317tpm_buf_append_u16(&buf, 0);13181319/* the public template */1320tpm_buf_append(&buf, template.data, template.length);1321tpm_buf_destroy(&template);13221323/* outside info (empty) */1324tpm_buf_append_u16(&buf, 0);13251326/* creation PCR (none) */1327tpm_buf_append_u32(&buf, 0);13281329rc = tpm_transmit_cmd(chip, &buf, 0,1330"attempting to create NULL primary");13311332if (rc == TPM2_RC_SUCCESS)1333rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy,1334name);13351336tpm_buf_destroy(&buf);13371338return rc;1339}13401341static int tpm2_create_null_primary(struct tpm_chip *chip)1342{1343u32 null_key;1344int rc;13451346rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key,1347chip->null_key_name);13481349if (rc == TPM2_RC_SUCCESS) {1350unsigned int offset = 0; /* dummy offset for null key context */13511352rc = tpm2_save_context(chip, null_key, chip->null_key_context,1353sizeof(chip->null_key_context), &offset);1354tpm2_flush_context(chip, null_key);1355}13561357return rc;1358}13591360/**1361* tpm2_sessions_init() - start of day initialization for the sessions code1362* @chip: TPM chip1363*1364* Derive and context save the null primary and allocate memory in the1365* struct tpm_chip for the authorizations.1366*1367* Return:1368* * 0 - OK1369* * -errno - A system error1370* * TPM_RC - A TPM error1371*/1372int tpm2_sessions_init(struct tpm_chip *chip)1373{1374int rc;13751376rc = tpm2_create_null_primary(chip);1377if (rc) {1378dev_err(&chip->dev, "null key creation failed with %d\n", rc);1379return rc;1380}13811382return rc;1383}1384#endif /* CONFIG_TCG_TPM2_HMAC */138513861387