From patchwork Tue May 28 03:51:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Jarkko Sakkinen X-Patchwork-Id: 13676071 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E80201B969; Tue, 28 May 2024 03:51:51 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868312; cv=none; b=QhE2k6s7I2c1q248CC1XbbuzayK7fuRrI7fAYRuJnUK+cMteqzSFg7/4HvbZ7YkLfZGSKpJ1EqouZeXqWF2SvyJzsqhKSgWeorysIafO6GnyjnxpRAxZCfVlCZs0+cC7d3oJBZocbzaB4wLFkCZMUVRxdKSH1xcFNsRBC+g7wJw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868312; c=relaxed/simple; bh=ZgvWBP6tE4s9/snimxcOGEFivWgLx0Ri9cZOylfpUtU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=PwVoLlUxz1PTFbgsNPxOJ78WoXpL8QuK77UmIzV7ZIHxRIhnXYWRnHNYnV7ARMOfdy+z1k3stZAJbPrWE6Ot65SZysmd72oBoWmNWuk1SNbnsyVUo2WOFPNreq726B8wE8NgrR6wOJ1MAyGMVfB8L04ueZbyFhYvMIMbBmhU3n8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=EWz2qLEs; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="EWz2qLEs" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 18704C32782; Tue, 28 May 2024 03:51:50 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1716868311; bh=ZgvWBP6tE4s9/snimxcOGEFivWgLx0Ri9cZOylfpUtU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=EWz2qLEsuPGoqRilvjGGhFYLpoa49Vdz9h5ql48FBVCCK1E2lO2ZWnYMTOxZjNeMj WqbZUful+bX0pH00nrSNekDdxmdvjDfL3j/AAXP09tL3krHhUkesz2/eve6LtOFsCz pdzwOUB3pMN+3XNn6WUm1wZ9HhIUpQJMtNpMdLWmaAOmNlreq40dgF3z0xO3KKsUI6 rPbrOSFHVrT/lXkWJUFT3a3ej3CS5nx7rOeC0XOvpb0mx/r6hktfk+DtS8VrxudufD 0o/5j126Kcyg2X5KQhESSjN9ZDUvNKrYzgiSH1ivPnRwKDx+VV979sZp1Xiq06fEN3 hdRmRedKZufRQ== From: Jarkko Sakkinen To: Herbert Xu Cc: linux-integrity@vger.kernel.org, keyrings@vger.kernel.org, Andreas.Fuchs@infineon.com, James Prestwood , David Woodhouse , Eric Biggers , James Bottomley , linux-crypto@vger.kernel.org, Stefan Berger , Jarkko Sakkinen , "David S. Miller" , linux-kernel@vger.kernel.org (open list), Peter Huewe , Jason Gunthorpe , James Bottomley , Ard Biesheuvel , Mario Limonciello Subject: [PATCH v6 1/6] tpm: Open code tpm_buf_parameters() Date: Tue, 28 May 2024 06:51:16 +0300 Message-ID: <20240528035136.11464-2-jarkko@kernel.org> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240528035136.11464-1-jarkko@kernel.org> References: <20240528035136.11464-1-jarkko@kernel.org> Precedence: bulk X-Mailing-List: keyrings@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 With only single call site, this makes zero sense (slipped out of the radar during the review). Open code and document the action directly to the site, to make it more readable. Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()") Signed-off-by: Jarkko Sakkinen --- drivers/char/tpm/tpm-buf.c | 26 -------------------------- drivers/char/tpm/tpm2-cmd.c | 10 +++++++++- include/linux/tpm.h | 2 -- 3 files changed, 9 insertions(+), 29 deletions(-) diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c index 647c6ca92ac3..cad0048bcc3c 100644 --- a/drivers/char/tpm/tpm-buf.c +++ b/drivers/char/tpm/tpm-buf.c @@ -223,30 +223,4 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset) } EXPORT_SYMBOL_GPL(tpm_buf_read_u32); -static u16 tpm_buf_tag(struct tpm_buf *buf) -{ - struct tpm_header *head = (struct tpm_header *)buf->data; - - return be16_to_cpu(head->tag); -} - -/** - * tpm_buf_parameters - return the TPM response parameters area of the tpm_buf - * @buf: tpm_buf to use - * - * Where the parameters are located depends on the tag of a TPM - * command (it's immediately after the header for TPM_ST_NO_SESSIONS - * or 4 bytes after for TPM_ST_SESSIONS). Evaluate this and return a - * pointer to the first byte of the parameters area. - * - * @return: pointer to parameters area - */ -u8 *tpm_buf_parameters(struct tpm_buf *buf) -{ - int offset = TPM_HEADER_SIZE; - - if (tpm_buf_tag(buf) == TPM2_ST_SESSIONS) - offset += 4; - return &buf->data[offset]; -} diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c index 0cdf892ec2a7..1e856259219e 100644 --- a/drivers/char/tpm/tpm2-cmd.c +++ b/drivers/char/tpm/tpm2-cmd.c @@ -281,6 +281,7 @@ struct tpm2_get_random_out { int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max) { struct tpm2_get_random_out *out; + struct tpm_header *head; struct tpm_buf buf; u32 recd; u32 num_bytes = max; @@ -288,6 +289,7 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max) int total = 0; int retries = 5; u8 *dest_ptr = dest; + off_t offset; if (!num_bytes || max > TPM_MAX_RNG_DATA) return -EINVAL; @@ -320,7 +322,13 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max) goto out; } - out = (struct tpm2_get_random_out *)tpm_buf_parameters(&buf); + head = (struct tpm_header *)buf.data; + offset = TPM_HEADER_SIZE; + /* Skip the parameter size field: */ + if (be16_to_cpu(head->tag) == TPM2_ST_SESSIONS) + offset += 4; + + out = (struct tpm2_get_random_out *)&buf.data[offset]; recd = min_t(u32, be16_to_cpu(out->size), num_bytes); if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + diff --git a/include/linux/tpm.h b/include/linux/tpm.h index c17e4efbb2e5..b3217200df28 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -437,8 +437,6 @@ u8 tpm_buf_read_u8(struct tpm_buf *buf, off_t *offset); u16 tpm_buf_read_u16(struct tpm_buf *buf, off_t *offset); u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset); -u8 *tpm_buf_parameters(struct tpm_buf *buf); - /* * Check if TPM device is in the firmware upgrade mode. */ From patchwork Tue May 28 03:51:17 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Jarkko Sakkinen X-Patchwork-Id: 13676072 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AB904241E7; Tue, 28 May 2024 03:51:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868317; cv=none; b=UpBGA6iST6LV9a7BARR/cc4JFJJDJ2BQHL8Oiu3iSjGfFdbhVO4YJzXL3xcZu5EsVIVkotx/MmaM1715lklAyJ0r8dt3Y4uQ6Wt7Z4VYK7xZpEtCtRmqZaPg3KsxM4HAf+E0/usEsgyre3PJMZG7GVTKkTofEdYUBWAlkbkZrP8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868317; c=relaxed/simple; bh=rQTPLrmfpCPpQ7Zz53PlLkcw1m7mUahOVVqZUGpxmKU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=pXRcuhK4RkPvNrurY6LIWnuqENuAeRxK6PyNxC/m58bkJOOVeUK140igZWEeX9cYNDEayLtILFhl17LM6U5zGEYrWlxwEEMoh5FgoAZ0mnBJ+9FkW0Y/m7TjzaKh51gFNlK7aCNqrH04+9002XNFkHCsBr7QaJ0bWOJptA6TI4g= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=mFJGocpV; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="mFJGocpV" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EB1A0C3277B; Tue, 28 May 2024 03:51:56 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1716868317; bh=rQTPLrmfpCPpQ7Zz53PlLkcw1m7mUahOVVqZUGpxmKU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mFJGocpV6xt6VzaDwEswX4GBU1Uo5NqO2zz6v9xQkJ0Hm+AGkuL/h65yRlRVkxQ5A Ykzd7tkUMMlUbyIiyAgF+TuoctQpMaIW7+Q9fUOrB/1gWl5cWBPoXHe3S9i7RV6hPU 6oTNd3b7GkG5n1vwHLjZJvfnk6cImEd7uvuEnCTQcTCub/dfsxWkhDBNv5EprmoE6G N9WP17eZoWZmlmBy4QecAjM2QK+VBEGVrAe1c/DV0t3JPGSEbwmSwIdAcZNgs6KAv8 hBv3SMTMzW6t1IDR42bR42If+YfLqCdcuSdlS4ljvWehBmYXNkOJridfL8YOmZZ2nF p3oKyNm8QJpSQ== From: Jarkko Sakkinen To: Herbert Xu Cc: linux-integrity@vger.kernel.org, keyrings@vger.kernel.org, Andreas.Fuchs@infineon.com, James Prestwood , David Woodhouse , Eric Biggers , James Bottomley , linux-crypto@vger.kernel.org, Stefan Berger , Jarkko Sakkinen , "David S. Miller" , linux-kernel@vger.kernel.org (open list) Subject: [PATCH v6 2/6] crypto: rsa-pkcs1pad: export rsa1_asn_lookup() Date: Tue, 28 May 2024 06:51:17 +0300 Message-ID: <20240528035136.11464-3-jarkko@kernel.org> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240528035136.11464-1-jarkko@kernel.org> References: <20240528035136.11464-1-jarkko@kernel.org> Precedence: bulk X-Mailing-List: keyrings@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 ASN.1 template is required for TPM2 asymmetric keys, as it needs to be piggy-packed with the input data before applying TPM2_RSA_Decrypt. This patch prepares crypto subsystem for the addition of those keys. Signed-off-by: Jarkko Sakkinen --- crypto/rsa-pkcs1pad.c | 16 ++++++++++------ include/crypto/rsa-pkcs1pad.h | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) create mode 100644 include/crypto/rsa-pkcs1pad.h diff --git a/crypto/rsa-pkcs1pad.c b/crypto/rsa-pkcs1pad.c index cd501195f34a..00b6c14f861c 100644 --- a/crypto/rsa-pkcs1pad.c +++ b/crypto/rsa-pkcs1pad.c @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -79,11 +80,7 @@ static const u8 rsa_digest_info_sha3_512[] = { 0x05, 0x00, 0x04, 0x40 }; -static const struct rsa_asn1_template { - const char *name; - const u8 *data; - size_t size; -} rsa_asn1_templates[] = { +static const struct rsa_asn1_template rsa_asn1_templates[] = { #define _(X) { #X, rsa_digest_info_##X, sizeof(rsa_digest_info_##X) } _(md5), _(sha1), @@ -101,7 +98,13 @@ static const struct rsa_asn1_template { { NULL } }; -static const struct rsa_asn1_template *rsa_lookup_asn1(const char *name) +/** + * rsa_lookup_asn1() - Lookup the ASN.1 digest info given the hash + * name: hash algorithm name + * + * Returns the ASN.1 digest info on success, and NULL on failure. + */ +const struct rsa_asn1_template *rsa_lookup_asn1(const char *name) { const struct rsa_asn1_template *p; @@ -110,6 +113,7 @@ static const struct rsa_asn1_template *rsa_lookup_asn1(const char *name) return p; return NULL; } +EXPORT_SYMBOL_GPL(rsa_lookup_asn1); struct pkcs1pad_ctx { struct crypto_akcipher *child; diff --git a/include/crypto/rsa-pkcs1pad.h b/include/crypto/rsa-pkcs1pad.h new file mode 100644 index 000000000000..32c7453ff644 --- /dev/null +++ b/include/crypto/rsa-pkcs1pad.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * RSA padding templates. + */ + +#ifndef _CRYPTO_RSA_PKCS1PAD_H +#define _CRYPTO_RSA_PKCS1PAD_H + +/* + * Hash algorithm name to ASN.1 template mapping. + */ +struct rsa_asn1_template { + const char *name; + const u8 *data; + size_t size; +}; + +const struct rsa_asn1_template *rsa_lookup_asn1(const char *name); + +#endif /* _CRYPTO_RSA_PKCS1PAD_H */ From patchwork Tue May 28 03:51:18 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Jarkko Sakkinen X-Patchwork-Id: 13676073 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4EC7538DD4; Tue, 28 May 2024 03:52:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868322; cv=none; b=J5YaxeMKl7kTIHTsy2P8y86NtcyMo6ituUweT8T6CXAHosh2ps7U1RnGmbTn2JrFI6gAfwVnivTmnjJ+5h6OrRec1UFuSUVD4MHRa0HnvPMr7jG9FwICg3o9KaKVkNnhVh6TxOZNQLpmaLdsMKu4UOHrHi1TCfGAsiJLjtA2AL8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868322; c=relaxed/simple; bh=h8orBF4zzRfW1mNSKt+5IoMKfbFfiHan4PWjJTDQxIE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Xu7IlmlXWVRv+pswWsSzGcTg9UQef/En/4OLQpyiTR9IKtLguaAXDJ4TNMTRBKa7YjjDvQDO2YsI6IrbSgx9iGJdfJuMvQp0JlNV6U1fw/6+cjHsniD60KDZib1mdZWHay6evkZR1ya+ZeDSUMoLMVIWsIwayBFRNZ2WPaXv4gM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=DMR4uXbx; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="DMR4uXbx" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3DE52C3277B; Tue, 28 May 2024 03:52:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1716868321; bh=h8orBF4zzRfW1mNSKt+5IoMKfbFfiHan4PWjJTDQxIE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DMR4uXbxPtMAAUSDyjM0JaGvYfg95UpO8ERhJg1kuQ1NZQlv5asuLufFPLmH8X1/i JO1mODpqnsFGWlgfYu7IyKMRNDDqTowWakrJ2j7doKBVAYJgucOebgf7t4TDu1+gwo ZrLeTqIFxuOLt+Xn6CAhe/g2CvM/5ohEIyeCYHioYRRSWEEQyAaU32MemP3t2nN6qe mbAsY4Qf82aMGXMjGf/lAXSvKKNJTT9UHHEzigP5wzd2irOP9aJFXHVlNOfYqC7mt4 mwVU2SdFbSs4EUZwh5vox+vpasfqjVm6UGq3BKsm4si84c/QPk/zdE3evigcnw8TKc K7zW1IEcnu2Nw== From: Jarkko Sakkinen To: Herbert Xu Cc: linux-integrity@vger.kernel.org, keyrings@vger.kernel.org, Andreas.Fuchs@infineon.com, James Prestwood , David Woodhouse , Eric Biggers , James Bottomley , linux-crypto@vger.kernel.org, Stefan Berger , Jarkko Sakkinen , "David S. Miller" , linux-kernel@vger.kernel.org (open list), James Bottomley , Mimi Zohar , David Howells , Paul Moore , James Morris , "Serge E. Hallyn" , linux-security-module@vger.kernel.org (open list:SECURITY SUBSYSTEM) Subject: [PATCH v6 3/6] KEYS: trusted: Change -EINVAL to -E2BIG Date: Tue, 28 May 2024 06:51:18 +0300 Message-ID: <20240528035136.11464-4-jarkko@kernel.org> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240528035136.11464-1-jarkko@kernel.org> References: <20240528035136.11464-1-jarkko@kernel.org> Precedence: bulk X-Mailing-List: keyrings@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Report -E2BIG instead of -EINVAL when too large size for the key blob is requested. Signed-off-by: Jarkko Sakkinen --- security/keys/trusted-keys/trusted_tpm2.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c index 8b7dd73d94c1..06c8fa7b21ae 100644 --- a/security/keys/trusted-keys/trusted_tpm2.c +++ b/security/keys/trusted-keys/trusted_tpm2.c @@ -122,7 +122,7 @@ static int tpm2_key_decode(struct trusted_key_payload *payload, return ret; if (ctx.priv_len + ctx.pub_len > MAX_BLOB_SIZE) - return -EINVAL; + return -E2BIG; blob = kmalloc(ctx.priv_len + ctx.pub_len + 4, GFP_KERNEL); if (!blob) From patchwork Tue May 28 03:51:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Jarkko Sakkinen X-Patchwork-Id: 13676074 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0F3D338DD4; Tue, 28 May 2024 03:52:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868328; cv=none; b=T5cZL3FSNx+3QeC1cGZbI5/LwlU46rLclUTCxaSyUhH87Oyul27MXNISZg+abF0fB5JZDh+hBnmUQMZLaUUphro7y1RL/wxoU/Ipr5GwlUwPaHlRRfDBQbEKoCNivACydhJbyU2c5T/aOPauCGGppy1ib29RwX6aSfPgP3v5QmM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868328; c=relaxed/simple; bh=HjejRQyXQOkUessmoO6+Yc8j3jipeT/V6wTG5u+1Yho=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=HDtYYvb1BNafXf3W5rQ2nlpkwsASK7ixqIoACbjWHRCp7rgVhZEsI9ujHUIEl2xXUuGz6kEeoBzN0rLOmcvSjMlJJLWWbyR7dwA2zme7yck+2fucSHVV/I8dbm+TODrGkZBapAT6beO1b5CsDxEuKrkw+/ap4L5ReYfLzJYKJ6g= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=u2yGrxG/; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="u2yGrxG/" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 544FDC3277B; Tue, 28 May 2024 03:52:07 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1716868327; bh=HjejRQyXQOkUessmoO6+Yc8j3jipeT/V6wTG5u+1Yho=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=u2yGrxG/8Y4Ah2lara5ZhVKlPsHwiDZl+NQdJjnO0zCQPiVaevURbfUpyCbzLbhpN RblQPpyZrrZiQFB2LZz4GaWhLvQoPaAS+pPPXGMxxHTk24eJJt26iaZNtXRqo28xY2 Mxi2QjFX9bSaUlzJ0OCHEpMhrN2p5d/XWIWYlVsRMMS5lE5ajrDXH7T5EOSQM7/ui3 enJ+umiDIyy9yUdI5PuxaVtjqiO/oUdBBQ6712CV7JyrJ7eQ5SmwQu3fXfVwktX83Z qLRQ6mo2mY2X3hTvvhMkpYqekROdA8fGi4kPZLQc/vv7M6Iz/EBWwZFTxtGcJxVCQj SPn6sE6O1WaZg== From: Jarkko Sakkinen To: Herbert Xu Cc: linux-integrity@vger.kernel.org, keyrings@vger.kernel.org, Andreas.Fuchs@infineon.com, James Prestwood , David Woodhouse , Eric Biggers , James Bottomley , linux-crypto@vger.kernel.org, Stefan Berger , Jarkko Sakkinen , "David S. Miller" , linux-kernel@vger.kernel.org (open list), James Bottomley , Mimi Zohar , David Howells , Paul Moore , James Morris , "Serge E. Hallyn" , linux-security-module@vger.kernel.org (open list:SECURITY SUBSYSTEM) Subject: [PATCH v6 4/6] crypto: tpm2_key: Introduce a TPM2 key type Date: Tue, 28 May 2024 06:51:19 +0300 Message-ID: <20240528035136.11464-5-jarkko@kernel.org> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240528035136.11464-1-jarkko@kernel.org> References: <20240528035136.11464-1-jarkko@kernel.org> Precedence: bulk X-Mailing-List: keyrings@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 TPM2 ASN.1 format is required for trusted keys and asymmetric keys. Move it to crypto in order to make it available for both. Implement validation with coverage of all TPMT_PUBLIC shared fields. Key type specific fields must be covered by the different subsystems using this. A Kconfig option CRYPTO_TPM2_KEY can be used to select the feature, which depends only crypto subsystem itself and ASN.1 parser. Signed-off-by: Jarkko Sakkinen --- v6: * Relocate to crypto. Validate the shared part and provide accessor functions. Use a fixed buffer size. v2: * Do not allocate blob twice. Use the one inside struct tpm2_key. --- crypto/Kconfig | 7 ++ crypto/Makefile | 6 + crypto/tpm2_key.asn1 | 11 ++ crypto/tpm2_key.c | 134 ++++++++++++++++++++ include/crypto/tpm2_key.h | 46 +++++++ security/keys/trusted-keys/Kconfig | 2 +- security/keys/trusted-keys/Makefile | 2 - security/keys/trusted-keys/tpm2key.asn1 | 11 -- security/keys/trusted-keys/trusted_tpm2.c | 141 +++++----------------- 9 files changed, 235 insertions(+), 125 deletions(-) create mode 100644 crypto/tpm2_key.asn1 create mode 100644 crypto/tpm2_key.c create mode 100644 include/crypto/tpm2_key.h delete mode 100644 security/keys/trusted-keys/tpm2key.asn1 diff --git a/crypto/Kconfig b/crypto/Kconfig index 5688d42a59c2..c8989bc71f57 100644 --- a/crypto/Kconfig +++ b/crypto/Kconfig @@ -5,6 +5,13 @@ config XOR_BLOCKS tristate +config CRYPTO_TPM2_KEY + bool + depends on CRYPTO + select ASN1 + select OID_REGISTRY + default n + # # async_tx api: hardware offloaded memory transfer/transform support # diff --git a/crypto/Makefile b/crypto/Makefile index edbbaa3ffef5..d932fdb72319 100644 --- a/crypto/Makefile +++ b/crypto/Makefile @@ -216,3 +216,9 @@ obj-$(CONFIG_CRYPTO_SIMD) += crypto_simd.o # Key derivation function # obj-$(CONFIG_CRYPTO_KDF800108_CTR) += kdf_sp800108.o + +ifdef CONFIG_CRYPTO_TPM2_KEY +$(obj)/tpm2_key.asn1.o: $(obj)/tpm2_key.asn1.h $(obj)/tpm2_key.asn1.c +$(obj)/tpm2_key.o: $(obj)/tpm2_key.asn1.h +obj-y += tpm2_key.o tpm2_key.asn1.o +endif diff --git a/crypto/tpm2_key.asn1 b/crypto/tpm2_key.asn1 new file mode 100644 index 000000000000..b235d02ab78e --- /dev/null +++ b/crypto/tpm2_key.asn1 @@ -0,0 +1,11 @@ +--- +--- ASN.1 for TPM 2.0 keys +--- + +TPMKey ::= SEQUENCE { + type OBJECT IDENTIFIER ({tpm2_key_get_type}), + emptyAuth [0] EXPLICIT BOOLEAN OPTIONAL, + parent INTEGER ({tpm2_key_get_parent}), + pubkey OCTET STRING ({tpm2_get_public}), + privkey OCTET STRING ({tpm2_get_private}) + } diff --git a/crypto/tpm2_key.c b/crypto/tpm2_key.c new file mode 100644 index 000000000000..78f55478d046 --- /dev/null +++ b/crypto/tpm2_key.c @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-2.0-only + +#include +#include +#include +#include +#include +#include "tpm2_key.asn1.h" + +#undef pr_fmt +#define pr_fmt(fmt) "tpm2_key: "fmt + +struct tpm2_key_decoder_context { + u32 parent; + const u8 *pub; + u32 pub_len; + const u8 *priv; + u32 priv_len; + enum OID oid; +}; + +int tpm2_key_get_parent(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_key_decoder_context *decoder = context; + const u8 *v = value; + int i; + + decoder->parent = 0; + for (i = 0; i < vlen; i++) { + decoder->parent <<= 8; + decoder->parent |= v[i]; + } + + return 0; +} + +int tpm2_key_get_type(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_key_decoder_context *decoder = context; + + decoder->oid = look_up_OID(value, vlen); + return 0; +} + +static inline bool tpm2_key_is_valid(const void *value, size_t vlen) +{ + if (vlen < 2 || vlen > TPM2_KEY_BYTES_MAX) + return false; + + if (get_unaligned_be16(value) != vlen - 2) + return false; + + return true; +} + +int tpm2_get_public(void *context, size_t hdrlen, unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_key_decoder_context *decoder = context; + + if (!tpm2_key_is_valid(value, vlen)) + return -EBADMSG; + + if (sizeof(struct tpm2_key_desc) > vlen - 2) + return -EBADMSG; + + decoder->pub = value; + decoder->pub_len = vlen; + return 0; +} + +int tpm2_get_private(void *context, size_t hdrlen, unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_key_decoder_context *decoder = context; + + if (!tpm2_key_is_valid(value, vlen)) + return -EBADMSG; + + decoder->priv = value; + decoder->priv_len = vlen; + return 0; +} + +/** + * tpm_key_decode() - Decode TPM2 ASN.1 key + * @src: ASN.1 source. + * @src_len: ASN.1 source length. + * + * Decodes the TPM2 ASN.1 key and validates that the public key data has all + * the shared fields of TPMT_PUBLIC. This is full coverage of the memory that + * can be validated before doing any key type specific validation. + * + * Return: + * - TPM2 ASN.1 key on success. + * - -EBADMSG when decoding fails. + * - -ENOMEM when OOM while allocating struct tpm2_key. + */ +struct tpm2_key *tpm2_key_decode(const u8 *src, u32 src_len) +{ + struct tpm2_key_decoder_context decoder; + struct tpm2_key *key; + u8 *data; + int ret; + + memset(&decoder, 0, sizeof(decoder)); + ret = asn1_ber_decoder(&tpm2_key_decoder, &decoder, src, src_len); + if (ret < 0) { + if (ret != -EBADMSG) + pr_info("Decoder error %d\n", ret); + + return ERR_PTR(-EBADMSG); + } + + key = kzalloc(sizeof(*key), GFP_KERNEL); + if (!key) + return ERR_PTR(-ENOMEM); + + data = &key->data[0]; + memcpy(&data[0], decoder.priv, decoder.priv_len); + memcpy(&data[decoder.priv_len], decoder.pub, decoder.pub_len); + + key->oid = decoder.oid; + key->priv_len = decoder.priv_len; + key->pub_len = decoder.pub_len; + key->parent = decoder.parent; + key->desc = (struct tpm2_key_desc *)&data[decoder.priv_len + 2]; + return key; +} +EXPORT_SYMBOL_GPL(tpm2_key_decode); diff --git a/include/crypto/tpm2_key.h b/include/crypto/tpm2_key.h new file mode 100644 index 000000000000..74debaf707bf --- /dev/null +++ b/include/crypto/tpm2_key.h @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __LINUX_TPM2_KEY_H__ +#define __LINUX_TPM2_KEY_H__ + +#include +#include + +#define TPM2_KEY_BYTES_MAX 1024 + +/* TPM2 Structures 12.2.4: TPMT_PUBLIC */ +struct tpm2_key_desc { + __be16 type; + __be16 name_alg; + __be32 object_attributes; + __be16 policy_size; +} __packed; + +/* Decoded TPM2 ASN.1 key. */ +struct tpm2_key { + u8 data[2 * TPM2_KEY_BYTES_MAX]; + struct tpm2_key_desc *desc; + u16 priv_len; + u16 pub_len; + u32 parent; + enum OID oid; + char oid_str[64]; +}; + +struct tpm2_key *tpm2_key_decode(const u8 *src, u32 src_len); + +static inline const void *tpm2_key_data(const struct tpm2_key *key) +{ + return &key->data[0]; +} + +static inline u16 tpm2_key_type(const struct tpm2_key *key) +{ + return be16_to_cpu(key->desc->type); +} + +static inline int tpm2_key_policy_size(const struct tpm2_key *key) +{ + return be16_to_cpu(key->desc->policy_size); +} + +#endif /* __LINUX_TPM2_KEY_H__ */ diff --git a/security/keys/trusted-keys/Kconfig b/security/keys/trusted-keys/Kconfig index 1fb8aa001995..00d9489384ac 100644 --- a/security/keys/trusted-keys/Kconfig +++ b/security/keys/trusted-keys/Kconfig @@ -9,9 +9,9 @@ config TRUSTED_KEYS_TPM select CRYPTO_HMAC select CRYPTO_SHA1 select CRYPTO_HASH_INFO + select CRYPTO_TPM2_KEY select ASN1_ENCODER select OID_REGISTRY - select ASN1 select HAVE_TRUSTED_KEYS help Enable use of the Trusted Platform Module (TPM) as trusted key diff --git a/security/keys/trusted-keys/Makefile b/security/keys/trusted-keys/Makefile index f0f3b27f688b..2674d5c10fc9 100644 --- a/security/keys/trusted-keys/Makefile +++ b/security/keys/trusted-keys/Makefile @@ -7,9 +7,7 @@ obj-$(CONFIG_TRUSTED_KEYS) += trusted.o trusted-y += trusted_core.o trusted-$(CONFIG_TRUSTED_KEYS_TPM) += trusted_tpm1.o -$(obj)/trusted_tpm2.o: $(obj)/tpm2key.asn1.h trusted-$(CONFIG_TRUSTED_KEYS_TPM) += trusted_tpm2.o -trusted-$(CONFIG_TRUSTED_KEYS_TPM) += tpm2key.asn1.o trusted-$(CONFIG_TRUSTED_KEYS_TEE) += trusted_tee.o diff --git a/security/keys/trusted-keys/tpm2key.asn1 b/security/keys/trusted-keys/tpm2key.asn1 deleted file mode 100644 index f57f869ad600..000000000000 --- a/security/keys/trusted-keys/tpm2key.asn1 +++ /dev/null @@ -1,11 +0,0 @@ ---- ---- ASN.1 for TPM 2.0 keys ---- - -TPMKey ::= SEQUENCE { - type OBJECT IDENTIFIER ({tpm2_key_type}), - emptyAuth [0] EXPLICIT BOOLEAN OPTIONAL, - parent INTEGER ({tpm2_key_parent}), - pubkey OCTET STRING ({tpm2_key_pub}), - privkey OCTET STRING ({tpm2_key_priv}) - } diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c index 06c8fa7b21ae..b9e505e99e8c 100644 --- a/security/keys/trusted-keys/trusted_tpm2.c +++ b/security/keys/trusted-keys/trusted_tpm2.c @@ -13,11 +13,10 @@ #include #include +#include #include -#include "tpm2key.asn1.h" - static struct tpm2_hash tpm2_hash_map[] = { {HASH_ALGO_SHA1, TPM_ALG_SHA1}, {HASH_ALGO_SHA256, TPM_ALG_SHA256}, @@ -98,106 +97,6 @@ static int tpm2_key_encode(struct trusted_key_payload *payload, return ret; } -struct tpm2_key_context { - u32 parent; - const u8 *pub; - u32 pub_len; - const u8 *priv; - u32 priv_len; -}; - -static int tpm2_key_decode(struct trusted_key_payload *payload, - struct trusted_key_options *options, - u8 **buf) -{ - int ret; - struct tpm2_key_context ctx; - u8 *blob; - - memset(&ctx, 0, sizeof(ctx)); - - ret = asn1_ber_decoder(&tpm2key_decoder, &ctx, payload->blob, - payload->blob_len); - if (ret < 0) - return ret; - - if (ctx.priv_len + ctx.pub_len > MAX_BLOB_SIZE) - return -E2BIG; - - blob = kmalloc(ctx.priv_len + ctx.pub_len + 4, GFP_KERNEL); - if (!blob) - return -ENOMEM; - - *buf = blob; - options->keyhandle = ctx.parent; - - memcpy(blob, ctx.priv, ctx.priv_len); - blob += ctx.priv_len; - - memcpy(blob, ctx.pub, ctx.pub_len); - - return 0; -} - -int tpm2_key_parent(void *context, size_t hdrlen, - unsigned char tag, - const void *value, size_t vlen) -{ - struct tpm2_key_context *ctx = context; - const u8 *v = value; - int i; - - ctx->parent = 0; - for (i = 0; i < vlen; i++) { - ctx->parent <<= 8; - ctx->parent |= v[i]; - } - - return 0; -} - -int tpm2_key_type(void *context, size_t hdrlen, - unsigned char tag, - const void *value, size_t vlen) -{ - enum OID oid = look_up_OID(value, vlen); - - if (oid != OID_TPMSealedData) { - char buffer[50]; - - sprint_oid(value, vlen, buffer, sizeof(buffer)); - pr_debug("OID is \"%s\" which is not TPMSealedData\n", - buffer); - return -EINVAL; - } - - return 0; -} - -int tpm2_key_pub(void *context, size_t hdrlen, - unsigned char tag, - const void *value, size_t vlen) -{ - struct tpm2_key_context *ctx = context; - - ctx->pub = value; - ctx->pub_len = vlen; - - return 0; -} - -int tpm2_key_priv(void *context, size_t hdrlen, - unsigned char tag, - const void *value, size_t vlen) -{ - struct tpm2_key_context *ctx = context; - - ctx->priv = value; - ctx->priv_len = vlen; - - return 0; -} - /** * tpm2_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer. * @@ -387,22 +286,43 @@ static int tpm2_load_cmd(struct tpm_chip *chip, struct trusted_key_options *options, u32 *blob_handle) { - struct tpm_buf buf; unsigned int private_len; unsigned int public_len; unsigned int blob_len; - u8 *blob, *pub; - int rc; + struct tpm2_key *key; + const u8 *blob, *pub; + struct tpm_buf buf; u32 attrs; + int rc; - rc = tpm2_key_decode(payload, options, &blob); - if (rc) { - /* old form */ + key = tpm2_key_decode(payload->blob, payload->blob_len); + if (IS_ERR(key)) { + /* Get the error code and reset the pointer to the key: */ + rc = PTR_ERR(key); + key = NULL; + + if (rc == -ENOMEM) + return -ENOMEM; + + /* A sanity check, as only -EBADMSG or -ENOMEM are expected: */ + if (rc != -EBADMSG) + pr_err("tpm2_key_decode(): spurious error code %d\n", rc); + + /* Fallback to the legacy format: */ blob = payload->blob; payload->old_format = 1; + } else { + blob = tpm2_key_data(key); + if (key->oid != OID_TPMSealedData) { + kfree(key); + return -EBADMSG; + } } - /* new format carries keyhandle but old format doesn't */ + /* + * Must be non-zero here, either extracted from the ASN.1 for the new + * format or specified on the command line for the old. + */ if (!options->keyhandle) return -EINVAL; @@ -464,8 +384,7 @@ static int tpm2_load_cmd(struct tpm_chip *chip, (__be32 *) &buf.data[TPM_HEADER_SIZE]); out: - if (blob != payload->blob) - kfree(blob); + kfree(key); tpm_buf_destroy(&buf); if (rc > 0) From patchwork Tue May 28 03:51:20 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Jarkko Sakkinen X-Patchwork-Id: 13676075 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1E8413F9CC; Tue, 28 May 2024 03:52:16 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868336; cv=none; b=ADXHeHWKuoc/lDuS/JjPnc6It7BDgTB4v9sVA0pFlwm8xl/Rgjwcfnn2YmGtPKY/MWj/m2ERR5I2/dYv4Cb5esCiGsUoIDs6qV924Nbf4pf4pJhz8gKTlfTIv6ScSX1VMX2dEw1NlX0h/enRLyN1OIo0emLu+ikr0XcmHBQdCXM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868336; c=relaxed/simple; bh=rPWLmQY2zzug7xultvNTKxKIqKu9pOMzbL8ZxMT08mQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=aarEU5M2Po61iX9ECM1+6ivah9kKfag//W2cP5Lvg0CqqARyOYK2dm7nXJ1CjFh9IA+DPlVuxoPSn+Jb8EftMB4J+Knb732zKYRwQnAbHqgAfg8abKYjTo/2sqJIcN0Sc2RKMPgboIYYJkWKOBcjETJ8zFXCgOlpSUApSldGUdA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=UHVAUBg9; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="UHVAUBg9" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 931D8C3277B; Tue, 28 May 2024 03:52:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1716868336; bh=rPWLmQY2zzug7xultvNTKxKIqKu9pOMzbL8ZxMT08mQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=UHVAUBg9nXMbwDPxq5yoFzCfyj5GyITMqEvzvJ2IaLpGvDxga6Nj6Bot46rJcrqlB uW449D89Bn1QG7mTU6MquAK3C9X9GQt+Ovof/TkZkhAFm5Y3SBK5sL9SajQvKpCMAF xkjuRM4JfFG4jQ1VoJ3R3KFeD8LFy8AoBhYlGXvSQRAuF3ywHOSkE+bPyIE04EV80l f3M+Pq8T38yhj/jaqqoTzQSvvowwmwQIjchD/aPywOXxYrV1TB8M3Yr92nHGAXe7rQ w/FzdHY0kRIB6ip0Fq94KDOyrk/lpYXaRbKJmnFG4TjSlkjX2irZgwMmlHkK7mQ5wA zOqIyfOA8fFpA== From: Jarkko Sakkinen To: Herbert Xu Cc: linux-integrity@vger.kernel.org, keyrings@vger.kernel.org, Andreas.Fuchs@infineon.com, James Prestwood , David Woodhouse , Eric Biggers , James Bottomley , linux-crypto@vger.kernel.org, Stefan Berger , Jarkko Sakkinen , "David S. Miller" , linux-kernel@vger.kernel.org (open list), David Howells , James Bottomley , Ard Biesheuvel , Mario Limonciello Subject: [PATCH v6 5/6] keys: asymmetric: Add tpm2_key_rsa Date: Tue, 28 May 2024 06:51:20 +0300 Message-ID: <20240528035136.11464-6-jarkko@kernel.org> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240528035136.11464-1-jarkko@kernel.org> References: <20240528035136.11464-1-jarkko@kernel.org> Precedence: bulk X-Mailing-List: keyrings@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 * Asymmetric TPM2 RSA key with signing and verification. * Encryption and decryption when pcks1 encoding is used. * Enabled with CONFIG_ASYMMETRIC_TPM2_KEY_ECDSA_SUBTYPE. Signed-off-by: James Prestwood Co-developed-by: Jarkko Sakkinen Signed-off-by: Jarkko Sakkinen --- v6: * Validate RSA parameters, and also that the blob has space for them. * Fix tpm2_key_rsa_destroy() memory corruption: cast to tpm2_key_rsa * Allocate temporary buffers from heap. * Rename tpm2_key_rsa_extract_pub to tpm2_key_rsa_probe. * While pre-parsing, return -EBADMSG when the probing fails. This translates to "not detected" for the framework, i.e. should not be considered as an error but instead "move on". E.g. TPM_ALG_RSA is checked and if it is instead TPM_ALG_ECDSA, then it is passed to that module. v5: * akcipher has two *undocumented* parameters. Document this clearly. * Remove unused variable. v4: * Just put the values to the buffer instead of encoding them. * Adjust buffer sizes. * Make tpm2_rsa_key_encode() not to allocate from heap and simplify the serialization. v3: * Drop the special case for null handle i.e. do not define policy. * Remove extra empty line. v2: * Remove two spurios pr_info() messsages that I forgot to remove. * Clean up padding functions and add additional checks for length also in tpm2_unpad_pcks1(). * Add the missing success check kzalloc() in tpm2_key_rsa_decrypt(). * Check that params->out_len for capacity before copying the result. --- crypto/asymmetric_keys/Kconfig | 15 + crypto/asymmetric_keys/Makefile | 1 + crypto/asymmetric_keys/tpm2_key_rsa.c | 678 ++++++++++++++++++++++++++ include/linux/tpm.h | 2 + 4 files changed, 696 insertions(+) create mode 100644 crypto/asymmetric_keys/tpm2_key_rsa.c diff --git a/crypto/asymmetric_keys/Kconfig b/crypto/asymmetric_keys/Kconfig index e1345b8f39f1..9d88c1190621 100644 --- a/crypto/asymmetric_keys/Kconfig +++ b/crypto/asymmetric_keys/Kconfig @@ -15,6 +15,7 @@ config ASYMMETRIC_PUBLIC_KEY_SUBTYPE select MPILIB select CRYPTO_HASH_INFO select CRYPTO_AKCIPHER + select CRYPTO_RSA select CRYPTO_SIG select CRYPTO_HASH help @@ -23,6 +24,20 @@ config ASYMMETRIC_PUBLIC_KEY_SUBTYPE appropriate hash algorithms (such as SHA-1) must be available. ENOPKG will be reported if the requisite algorithm is unavailable. +config ASYMMETRIC_TPM2_KEY_RSA_SUBTYPE + tristate "Asymmetric TPM2 RSA crypto algorithm subtype" + depends on TCG_TPM + select CRYPTO_RSA + select CRYPTO_SHA256 + select CRYPTO_HASH_INFO + select CRYPTO_TPM2_KEY + select ASN1 + help + This option provides support for asymmetric TPM2 key type handling. + If signature generation and/or verification are to be used, + appropriate hash algorithms (such as SHA-256) must be available. + ENOPKG will be reported if the requisite algorithm is unavailable. + config X509_CERTIFICATE_PARSER tristate "X.509 certificate parser" depends on ASYMMETRIC_PUBLIC_KEY_SUBTYPE diff --git a/crypto/asymmetric_keys/Makefile b/crypto/asymmetric_keys/Makefile index bc65d3b98dcb..c6da84607824 100644 --- a/crypto/asymmetric_keys/Makefile +++ b/crypto/asymmetric_keys/Makefile @@ -11,6 +11,7 @@ asymmetric_keys-y := \ signature.o obj-$(CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key.o +obj-$(CONFIG_ASYMMETRIC_TPM2_KEY_RSA_SUBTYPE) += tpm2_key_rsa.o # # X.509 Certificate handling diff --git a/crypto/asymmetric_keys/tpm2_key_rsa.c b/crypto/asymmetric_keys/tpm2_key_rsa.c new file mode 100644 index 000000000000..4bc322580037 --- /dev/null +++ b/crypto/asymmetric_keys/tpm2_key_rsa.c @@ -0,0 +1,678 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* TPM2 asymmetric public-key crypto subtype + * + * Asymmetric TPM2 RSA key: + * - Decrypts RSA with TPM2_RSA_Decrypt. + * - Signs with PKCS#1 1.5 padding. Signing is implemented with + * TPM2_RSA_Decrypt operation. + * - Encrypts with the akcipher rsa-pcks1pad. + * + * See Documentation/crypto/asymmetric-keys.rst + * + * Copyright (c) 2020 Intel Corporation + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#undef pr_fmt +#define pr_fmt(fmt) "tpm2_key_rsa: "fmt + +#define PKCS1_PAD_MIN_SIZE 11 + +/* TPM2 Structures 12.2.3.5: TPMS_RSA_PARMS */ +struct tpm2_rsa_parms { + __be16 symmetric; + __be16 scheme; + __be16 key_bits; + __be32 exponent; + __be16 modulus_size; +} __packed; + +/* + * Fill the data with PKCS#1 v1.5 padding. + */ +static int tpm2_pad_pkcs1(const u8 *in, int in_len, u8 *out, int out_len) +{ + unsigned int prefix_len = out_len - in_len - 3; + + if (in_len > out_len - PKCS1_PAD_MIN_SIZE) + return -EBADMSG; + + /* prefix */ + out[0] = 0; + out[1] = 1; + memset(&out[2], 0xff, prefix_len); + out[2 + prefix_len] = 0; + /* payload */ + memcpy(&out[2 + prefix_len + 1], in, in_len); + + return 0; +} + +/* + * RFC 3447 - Section 7.2.2 + * Size of the input data should be checked against public key size by + * the caller. + */ +static const u8 *tpm2_unpad_pkcs1(const u8 *in, int in_len, int *out_len) +{ + int i; + + if (in[0] != 0 || in[1] != 2) + return NULL; + + i = 2; + while (in[i] != 0 && i < in_len) + i++; + + if (i == in_len || i < (PKCS1_PAD_MIN_SIZE - 1)) + return NULL; + + *out_len = in_len - i - 1; + return in + i + 1; +} + +/* + * Outputs the cipher algorithm name on success, and retuns -ENOPKG + * on failure. + */ +static int tpm2_key_get_akcipher(const char *encoding, const char *hash_algo, + char *cipher) +{ + ssize_t ret; + + if (strcmp(encoding, "pkcs1") == 0) { + if (!hash_algo) { + strcpy(cipher, "pkcs1pad(rsa)"); + return 0; + } + + ret = snprintf(cipher, CRYPTO_MAX_ALG_NAME, + "pkcs1pad(rsa,%s)", + hash_algo); + if (ret >= CRYPTO_MAX_ALG_NAME) + return -ENOPKG; + + return 0; + } + + if (strcmp(encoding, "raw") == 0) { + strcpy(cipher, "rsa"); + return 0; + } + + return -ENOPKG; +} + +static int tpm2_key_rsa_encode(const struct tpm2_key *key, u8 *buf) +{ + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + const struct tpm2_rsa_parms *p = + (const struct tpm2_rsa_parms *)&key->data[o]; + const u16 mod_size = be16_to_cpu(p->modulus_size); + const void *mod = &key->data[o + sizeof(*p)]; + + u8 *start = &buf[4]; + u8 *work = &buf[4]; + u32 seq_len; + + work[0] = 0x02; /* INTEGER */ + work[1] = 0x82; /* u16 */ + work[2] = mod_size >> 8; + work[3] = mod_size & 0xff; + work = &work[4]; + memcpy(work, mod, mod_size); + work = &work[mod_size]; + work[0] = 0x02; /* INTEGER */ + work[1] = 3; /* < 128 */ + work[2] = 1; /* 65537 */ + work[3] = 0; + work[4] = 1; + work = &work[5]; + seq_len = work - start; + buf[0] = 0x30; /* SEQUENCE */ + buf[1] = 0x82; /* u16 */ + buf[2] = seq_len >> 8; + buf[3] = seq_len & 0xff; + + /* + * ABI requires this according include/crypto/akcipher.h, which says + * that there is epilogue with algorithm OID and parameters length. + * Neither size nor semantics is documented *anywhere*, and there's no + * struct to hold them. + * + * So zeroing out the last eight bytes after the key blob seems like the + * best bet, given no better (or any) information. The size of the + * parameters (two u32's) was found from crypto/asymmetric/public_key.c. + */ + memset(work, 0, 8); + + return seq_len + 4; +} + +/* + * Encryption operation is performed with the public key. Hence it is done + * in software + */ +static int tpm2_key_rsa_encrypt(struct tpm2_key *key, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + char cipher[CRYPTO_MAX_ALG_NAME]; + struct scatterlist in_sg, out_sg; + struct akcipher_request *req; + struct crypto_akcipher *tfm; + struct crypto_wait cwait; + u8 *buf; + int ret; + + buf = kzalloc(TPM2_KEY_BYTES_MAX, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + ret = tpm2_key_get_akcipher(params->encoding, params->hash_algo, cipher); + if (ret < 0) + goto err_buf; + + tfm = crypto_alloc_akcipher(cipher, 0, 0); + if (IS_ERR(tfm)) { + ret = PTR_ERR(tfm); + goto err_buf; + } + + ret = tpm2_key_rsa_encode(key, buf); + if (ret < 0) + goto err_tfm; + + ret = crypto_akcipher_set_pub_key(tfm, buf, ret); + if (ret < 0) + goto err_tfm; + + req = akcipher_request_alloc(tfm, GFP_KERNEL); + if (!req) { + ret = -ENOMEM; + goto err_tfm; + } + + sg_init_one(&in_sg, in, params->in_len); + sg_init_one(&out_sg, out, params->out_len); + akcipher_request_set_crypt(req, &in_sg, &out_sg, params->in_len, + params->out_len); + + crypto_init_wait(&cwait); + akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | + CRYPTO_TFM_REQ_MAY_SLEEP, + crypto_req_done, &cwait); + + ret = crypto_akcipher_encrypt(req); + if (ret) + goto err_tfm; + + ret = crypto_wait_req(ret, &cwait); + if (!ret) + ret = req->dst_len; + + akcipher_request_free(req); + +err_tfm: + crypto_free_akcipher(tfm); + +err_buf: + kfree(buf); + return ret; +} + +static int __tpm2_key_rsa_decrypt(struct tpm_chip *chip, + struct tpm2_key *key, + struct kernel_pkey_params *params, + const void *in, int in_len, void *out) +{ + u32 key_handle = 0; + struct tpm_buf buf; + u16 decrypted_len; + u8 *pos; + int ret; + + ret = tpm_try_get_ops(chip); + if (ret) + return ret; + + ret = tpm2_start_auth_session(chip); + if (ret) + goto err_ops; + + ret = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD); + if (ret < 0) + goto err_auth; + + tpm_buf_append_name(chip, &buf, key->parent, NULL); + tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_CONTINUE_SESSION | + TPM2_SA_ENCRYPT, NULL, 0); + tpm_buf_append(&buf, &key->data[0], key->priv_len + key->pub_len); + if (buf.flags & TPM_BUF_OVERFLOW) { + ret = -E2BIG; + goto err_buf; + } + tpm_buf_fill_hmac_session(chip, &buf); + ret = tpm_transmit_cmd(chip, &buf, 4, "TPM2_CC_LOAD"); + ret = tpm_buf_check_hmac_response(chip, &buf, ret); + if (ret) { + ret = -EIO; + goto err_buf; + } + key_handle = be32_to_cpup((__be32 *)&buf.data[TPM_HEADER_SIZE]); + + tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_RSA_DECRYPT); + tpm_buf_append_name(chip, &buf, key_handle, NULL); + tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_DECRYPT, NULL, 0); + tpm_buf_append_u16(&buf, in_len); + tpm_buf_append(&buf, in, in_len); + tpm_buf_append_u16(&buf, TPM_ALG_NULL); + tpm_buf_append_u16(&buf, 0); + tpm_buf_fill_hmac_session(chip, &buf); + ret = tpm_transmit_cmd(chip, &buf, 4, "TPM2_RSA_DECRYPT"); + ret = tpm_buf_check_hmac_response(chip, &buf, ret); + if (ret) { + ret = -EIO; + goto err_blob; + } + + pos = buf.data + TPM_HEADER_SIZE + 4; + decrypted_len = be16_to_cpup((__be16 *)pos); + pos += 2; + + if (params->out_len < decrypted_len) { + ret = -EMSGSIZE; + goto err_blob; + } + + memcpy(out, pos, decrypted_len); + ret = decrypted_len; + +err_blob: + tpm2_flush_context(chip, key_handle); + +err_buf: + tpm_buf_destroy(&buf); + +err_auth: + if (ret < 0) + tpm2_end_auth_session(chip); + +err_ops: + tpm_put_ops(chip); + return ret; +} + +static int tpm2_key_rsa_decrypt(struct tpm_chip *chip, struct tpm2_key *key, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + const u8 *ptr; + int out_len; + u8 *work; + int ret; + + work = kzalloc(TPM2_KEY_BYTES_MAX, GFP_KERNEL); + if (!work) + return -ENOMEM; + + ret = __tpm2_key_rsa_decrypt(chip, key, params, in, params->in_len, + work); + if (ret < 0) + goto err; + + ptr = tpm2_unpad_pkcs1(work, ret, &out_len); + if (!ptr) { + ret = -EINVAL; + goto err; + } + + if (out_len > params->out_len) { + ret = -EMSGSIZE; + goto err; + } + + memcpy(out, ptr, out_len); + kfree(work); + return out_len; + +err: + kfree(work); + return ret; +} + +/* + * Sign operation is an encryption using the TPM's private key. With RSA the + * only difference between encryption and decryption is where the padding goes. + * Since own padding can be used, TPM2_RSA_Decrypt can be repurposed to do + * encryption. + */ +static int tpm2_key_rsa_sign(struct tpm_chip *chip, struct tpm2_key *key, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + const struct tpm2_rsa_parms *p = + (const struct tpm2_rsa_parms *)&key->data[o]; + const u16 mod_size = be16_to_cpu(p->modulus_size); + const struct rsa_asn1_template *asn1; + u32 in_len = params->in_len; + void *asn1_wrapped = NULL; + u8 *padded; + int ret; + + if (strcmp(params->encoding, "pkcs1") != 0) { + ret = -ENOPKG; + goto err; + } + + if (params->hash_algo) { + asn1 = rsa_lookup_asn1(params->hash_algo); + if (!asn1) { + ret = -ENOPKG; + goto err; + } + + /* Request enough space for the ASN.1 template + input hash */ + asn1_wrapped = kzalloc(in_len + asn1->size, GFP_KERNEL); + if (!asn1_wrapped) { + ret = -ENOMEM; + goto err; + } + + /* Copy ASN.1 template, then the input */ + memcpy(asn1_wrapped, asn1->data, asn1->size); + memcpy(asn1_wrapped + asn1->size, in, in_len); + + in = asn1_wrapped; + in_len += asn1->size; + } + + /* with padding: */ + padded = kmalloc(mod_size, GFP_KERNEL); + tpm2_pad_pkcs1(in, in_len, padded, mod_size); + ret = __tpm2_key_rsa_decrypt(chip, key, params, padded, mod_size, out); + kfree(padded); + +err: + kfree(asn1_wrapped); + return ret; +} + +static void tpm2_key_rsa_describe(const struct key *asymmetric_key, + struct seq_file *m) +{ + struct tpm2_key *key = asymmetric_key->payload.data[asym_crypto]; + + if (!key) { + pr_err("key blob missing"); + return; + } + + seq_puts(m, "TPM2/RSA"); +} + +static void tpm2_key_rsa_destroy(void *payload0, void *payload3) +{ + struct tpm2_key *key = payload0; + + if (!key) + return; + + kfree(key); +} + +static int tpm2_key_rsa_eds_op(struct kernel_pkey_params *params, + const void *in, void *out) +{ + struct tpm2_key *key = params->key->payload.data[asym_crypto]; + struct tpm_chip *chip = tpm_default_chip(); + + if (!chip) + return -ENODEV; + + switch (params->op) { + case kernel_pkey_encrypt: + return tpm2_key_rsa_encrypt(key, params, in, out); + case kernel_pkey_decrypt: + return tpm2_key_rsa_decrypt(chip, key, params, in, out); + case kernel_pkey_sign: + return tpm2_key_rsa_sign(chip, key, params, in, out); + default: + return -EOPNOTSUPP; + } +} + +static int tpm2_key_rsa_verify(const struct key *key, + const struct public_key_signature *sig) +{ + const struct tpm2_key *tpm2_key = key->payload.data[asym_crypto]; + char alg_name[CRYPTO_MAX_ALG_NAME]; + struct akcipher_request *req; + struct scatterlist src_sg[2]; + struct crypto_akcipher *tfm; + struct crypto_wait cwait; + u8 *buf; + int ret; + + if (!sig->digest) + return -ENOPKG; + + ret = tpm2_key_get_akcipher(sig->encoding, sig->hash_algo, alg_name); + if (ret < 0) + return ret; + + buf = kzalloc(TPM2_KEY_BYTES_MAX, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + tfm = crypto_alloc_akcipher(alg_name, 0, 0); + if (IS_ERR(tfm)) { + ret = PTR_ERR(tfm); + goto err_buf; + } + + ret = tpm2_key_rsa_encode(tpm2_key, buf); + if (ret < 0) + goto err_tfm; + + ret = crypto_akcipher_set_pub_key(tfm, buf, ret); + if (ret < 0) + goto err_tfm; + + ret = -ENOMEM; + req = akcipher_request_alloc(tfm, GFP_KERNEL); + if (!req) + goto err_tfm; + + sg_init_table(src_sg, 2); + sg_set_buf(&src_sg[0], sig->s, sig->s_size); + sg_set_buf(&src_sg[1], sig->digest, sig->digest_size); + akcipher_request_set_crypt(req, src_sg, NULL, sig->s_size, + sig->digest_size); + crypto_init_wait(&cwait); + akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | + CRYPTO_TFM_REQ_MAY_SLEEP, + crypto_req_done, &cwait); + ret = crypto_wait_req(crypto_akcipher_verify(req), &cwait); + + akcipher_request_free(req); + +err_tfm: + crypto_free_akcipher(tfm); + +err_buf: + kfree(buf); + return ret; +} + +static int tpm2_key_rsa_query(const struct kernel_pkey_params *params, + struct kernel_pkey_query *info) +{ + const struct tpm2_key *key = params->key->payload.data[asym_crypto]; + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + const struct tpm2_rsa_parms *p = + (const struct tpm2_rsa_parms *)&key->data[o]; + const u16 mod_size = be16_to_cpu(p->modulus_size); + char alg_name[CRYPTO_MAX_ALG_NAME]; + struct crypto_akcipher *tfm; + unsigned int len; + u8 *buf; + int ret; + + ret = tpm2_key_get_akcipher(params->encoding, params->hash_algo, alg_name); + if (ret < 0) + return ret; + + buf = kzalloc(TPM2_KEY_BYTES_MAX, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + tfm = crypto_alloc_akcipher(alg_name, 0, 0); + if (IS_ERR(tfm)) { + ret = PTR_ERR(tfm); + goto err_buf; + } + + ret = tpm2_key_rsa_encode(key, buf); + if (ret < 0) + goto err_tfm; + + ret = crypto_akcipher_set_pub_key(tfm, buf, ret); + if (ret < 0) + goto err_tfm; + + len = crypto_akcipher_maxsize(tfm); + + info->key_size = mod_size * 8; + info->max_data_size = mod_size; + info->max_sig_size = len; + info->max_enc_size = len; + info->max_dec_size = mod_size; + + info->supported_ops = KEYCTL_SUPPORTS_SIGN | KEYCTL_SUPPORTS_VERIFY; + + if (!strcmp(params->encoding, "pkcs1")) { + pr_info("pkcs1\n"); + info->supported_ops = + KEYCTL_SUPPORTS_ENCRYPT | KEYCTL_SUPPORTS_DECRYPT; + } + +err_tfm: + crypto_free_akcipher(tfm); + return ret; + +err_buf: + kfree(buf); + return ret; +} + +struct asymmetric_key_subtype tpm2_key_rsa_subtype = { + .owner = THIS_MODULE, + .name = "tpm2_key_rsa", + .name_len = sizeof("tpm2_key_rsa") - 1, + .describe = tpm2_key_rsa_describe, + .destroy = tpm2_key_rsa_destroy, + .query = tpm2_key_rsa_query, + .eds_op = tpm2_key_rsa_eds_op, + .verify_signature = tpm2_key_rsa_verify, +}; +EXPORT_SYMBOL_GPL(tpm2_key_rsa_subtype); + +static int __tpm2_key_rsa_preparse(struct tpm2_key *key) +{ + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + const struct tpm2_rsa_parms *p = + (const struct tpm2_rsa_parms *)&key->data[o]; + + if (tpm2_key_type(key) != TPM_ALG_RSA) + return -EBADMSG; + + if (tpm2_key_policy_size(key) != 0) + return -EBADMSG; + + if (be16_to_cpu(p->symmetric) != TPM_ALG_NULL) + return -EBADMSG; + + if (be16_to_cpu(p->scheme) != TPM_ALG_NULL) + return -EBADMSG; + + if (be16_to_cpu(p->key_bits) != 2048 && + be16_to_cpu(p->key_bits) != 3072 && + be16_to_cpu(p->key_bits) != 4096) + return -EBADMSG; + + if (be32_to_cpu(p->exponent) != 0x00000000 && + be32_to_cpu(p->exponent) != 0x00010001) + return -EBADMSG; + + pr_debug("modulus_size=%u\n", be16_to_cpu(p->modulus_size)); + return 0; +} + +/* + * Attempt to parse a data blob for a key as a TPM private key blob. + */ +static int tpm2_key_rsa_preparse(struct key_preparsed_payload *prep) +{ + struct tpm2_key *key; + int ret; + + key = tpm2_key_decode(prep->data, prep->datalen); + if (IS_ERR(key)) + return ret; + + if (key->oid != OID_TPMLoadableKey) { + kfree(key); + return -EBADMSG; + } + + ret = __tpm2_key_rsa_preparse(key); + if (ret < 0) { + kfree(key); + return ret; + } + + prep->payload.data[asym_subtype] = &tpm2_key_rsa_subtype; + prep->payload.data[asym_key_ids] = NULL; + prep->payload.data[asym_crypto] = key; + prep->payload.data[asym_auth] = NULL; + prep->quotalen = 100; + + return 0; +} + +static struct asymmetric_key_parser tpm2_key_rsa_parser = { + .owner = THIS_MODULE, + .name = "tpm2_key_rsa_parser", + .parse = tpm2_key_rsa_preparse, +}; + +static int __init tpm2_key_rsa_init(void) +{ + return register_asymmetric_key_parser(&tpm2_key_rsa_parser); +} + +static void __exit tpm2_key_rsa_exit(void) +{ + unregister_asymmetric_key_parser(&tpm2_key_rsa_parser); +} + +module_init(tpm2_key_rsa_init); +module_exit(tpm2_key_rsa_exit); + +MODULE_DESCRIPTION("Asymmetric TPM2 RSA key"); +MODULE_LICENSE("GPL"); diff --git a/include/linux/tpm.h b/include/linux/tpm.h index b3217200df28..a4be7a852bde 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -43,6 +43,7 @@ enum tpm2_session_types { /* if you add a new hash to this, increment TPM_MAX_HASHES below */ enum tpm_algorithms { TPM_ALG_ERROR = 0x0000, + TPM_ALG_RSA = 0x0001, TPM_ALG_SHA1 = 0x0004, TPM_ALG_AES = 0x0006, TPM_ALG_KEYEDHASH = 0x0008, @@ -271,6 +272,7 @@ enum tpm2_command_codes { TPM2_CC_NV_READ = 0x014E, TPM2_CC_CREATE = 0x0153, TPM2_CC_LOAD = 0x0157, + TPM2_CC_RSA_DECRYPT = 0x0159, TPM2_CC_SEQUENCE_UPDATE = 0x015C, TPM2_CC_UNSEAL = 0x015E, TPM2_CC_CONTEXT_LOAD = 0x0161, From patchwork Tue May 28 03:51:21 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Jarkko Sakkinen X-Patchwork-Id: 13676076 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8140D481A3; Tue, 28 May 2024 03:52:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868344; cv=none; b=l59n6fYe8CzYmye3AavbTAiCe0Kzw8kohU/g1/SliTTSW1NHKc122PgfJtPHufsQJLZcSH1DBvzSYzpXN/Khn2wW/cg6QqNWQmPMkLdEX92fFWeeCFksGQSUzmdM4lNYu8o/ZDNYkPsqwBBIqfDWVFPv4cRiWRv9AoeK8+tT/D8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716868344; c=relaxed/simple; bh=v9MeUiUS8Q/VuRxCC2YKx8zhemgKA48t6o1IF1bDbl0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=bOSsW6s4t/p/i0JsRQKJrJAY5JIKOC7JtwsXPfUy4RtRxiEZfbtCbEopDEGUNdT3hI5HETXZArp8CmEaBQxfb9Kkdg/MFbZTUEk2LWHK/L+yJxttHFbU/H8w5pjld6Icrgaq529uQmnJiOyM+IarxYsCrRy/4rCkKN0ndWfOvVU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=kB20Hgfq; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="kB20Hgfq" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A42D4C3277B; Tue, 28 May 2024 03:52:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1716868344; bh=v9MeUiUS8Q/VuRxCC2YKx8zhemgKA48t6o1IF1bDbl0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=kB20HgfqIdxr8FnPHpdOq7kp5ptxOQks+jQLKLVV4HQuLseViQGgK+5uI0XP2l1DC uPkWS1AEzhNcQ6cCbeRMICjk1Jtxv6W5jhsoZSC9FZv2UILW0KscsyJ9avpVovWhJN 4Hiki8Qb8jyo8B+bY8FsdNfSKe3xMDejnpWyRhJ30wS4M49bpfTms5Kh3ZrvFT0iss LQgMQZH9jxA255/p+svA8VxjMndHlk6Usf0r48dRJYkRFyuwoJf+6LvNjD9bYjNQ2w pr4Arjdd4dz4roiVu+311c/eaogmfMkx+7h6o+N1N9tBr1IZDF1WCHPo7RCT553aF1 yxfyQ1pAhRljQ== From: Jarkko Sakkinen To: Herbert Xu Cc: linux-integrity@vger.kernel.org, keyrings@vger.kernel.org, Andreas.Fuchs@infineon.com, James Prestwood , David Woodhouse , Eric Biggers , James Bottomley , linux-crypto@vger.kernel.org, Stefan Berger , Jarkko Sakkinen , "David S. Miller" , linux-kernel@vger.kernel.org (open list), David Howells , James Bottomley , Ard Biesheuvel , Mario Limonciello Subject: [PATCH v6 6/6] keys: asymmetric: Add tpm2_key_ecdsa Date: Tue, 28 May 2024 06:51:21 +0300 Message-ID: <20240528035136.11464-7-jarkko@kernel.org> X-Mailer: git-send-email 2.45.1 In-Reply-To: <20240528035136.11464-1-jarkko@kernel.org> References: <20240528035136.11464-1-jarkko@kernel.org> Precedence: bulk X-Mailing-List: keyrings@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 * Asymmetric TPM2 ECDSA key with signing and verification. * Enabled with CONFIG_ASYMMETRIC_TPM2_KEY_ECDSA_SUBTYPE. Cc: Stefan Berger Signed-off-by: Jarkko Sakkinen --- v6: * Very first version. * Stefan: any idea why the signature give -EKEYREJECTED? --- crypto/asymmetric_keys/Kconfig | 15 + crypto/asymmetric_keys/Makefile | 1 + crypto/asymmetric_keys/tpm2_key_ecdsa.c | 441 ++++++++++++++++++++++++ crypto/ecdsa.c | 1 - include/linux/tpm.h | 6 + 5 files changed, 463 insertions(+), 1 deletion(-) create mode 100644 crypto/asymmetric_keys/tpm2_key_ecdsa.c diff --git a/crypto/asymmetric_keys/Kconfig b/crypto/asymmetric_keys/Kconfig index 9d88c1190621..c97f11e0340c 100644 --- a/crypto/asymmetric_keys/Kconfig +++ b/crypto/asymmetric_keys/Kconfig @@ -24,6 +24,21 @@ config ASYMMETRIC_PUBLIC_KEY_SUBTYPE appropriate hash algorithms (such as SHA-1) must be available. ENOPKG will be reported if the requisite algorithm is unavailable. +config ASYMMETRIC_TPM2_KEY_ECDSA_SUBTYPE + tristate "Asymmetric TPM2 ECDSA crypto algorithm subtype" + depends on TCG_TPM + select CRYPTO_ECDSA + select CRYPTO_SHA256 + select CRYPTO_HASH_INFO + select CRYPTO_TPM2_KEY + select ASN1 + select ASN1_ENCODER + help + This option provides support for asymmetric TPM2 key type handling. + If signature generation and/or verification are to be used, + appropriate hash algorithms (such as SHA-256) must be available. + ENOPKG will be reported if the requisite algorithm is unavailable. + config ASYMMETRIC_TPM2_KEY_RSA_SUBTYPE tristate "Asymmetric TPM2 RSA crypto algorithm subtype" depends on TCG_TPM diff --git a/crypto/asymmetric_keys/Makefile b/crypto/asymmetric_keys/Makefile index c6da84607824..0843d2268a69 100644 --- a/crypto/asymmetric_keys/Makefile +++ b/crypto/asymmetric_keys/Makefile @@ -11,6 +11,7 @@ asymmetric_keys-y := \ signature.o obj-$(CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key.o +obj-$(CONFIG_ASYMMETRIC_TPM2_KEY_ECDSA_SUBTYPE) += tpm2_key_ecdsa.o obj-$(CONFIG_ASYMMETRIC_TPM2_KEY_RSA_SUBTYPE) += tpm2_key_rsa.o # diff --git a/crypto/asymmetric_keys/tpm2_key_ecdsa.c b/crypto/asymmetric_keys/tpm2_key_ecdsa.c new file mode 100644 index 000000000000..ad99984440fd --- /dev/null +++ b/crypto/asymmetric_keys/tpm2_key_ecdsa.c @@ -0,0 +1,441 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* Asymmetric TPM2 ECDSA key subtype. + * + * See Documentation/crypto/asymmetric-keys.rst + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#undef pr_fmt +#define pr_fmt(fmt) "tpm2_key_ecdsa: "fmt + +struct tpm2_ecc_parms { + __be16 symmetric; + __be16 scheme; + __be16 ecc; + __be16 kdf; +}; + +static const u8 *tpm2_key_ecdsa_ecc_x(const struct tpm2_key *key) +{ + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + + return &key->data[o + sizeof(struct tpm2_ecc_parms)]; +} + +static const u8 *tpm2_key_ecdsa_ecc_y(const struct tpm2_key *key) +{ + const u8 *x = tpm2_key_ecdsa_ecc_x(key); + u16 x_size = get_unaligned_be16(&x[0]); + + /* +2 from the size field: */ + return &x[2 + x_size]; +} + +static void tpm2_key_ecdsa_describe(const struct key *asymmetric_key, + struct seq_file *m) +{ + struct tpm2_key *key = asymmetric_key->payload.data[asym_crypto]; + + if (!key) { + pr_err("key missing"); + return; + } + + seq_puts(m, "TPM2/ECDSA"); +} + +static void tpm2_key_ecdsa_destroy(void *payload0, void *payload3) +{ + struct tpm2_key *key = payload0; + + if (!key) + return; + + kfree(key); +} + +static const char *tpm2_ecc_name(u16 ecc) +{ + const char *name; + + switch (ecc) { + case TPM2_ECC_NIST_P521: + name = "ecdsa-nist-p521"; + break; + case TPM2_ECC_NIST_P384: + name = "ecdsa-nist-p384"; + break; + default: + name = "ecdsa-nist-p256"; + break; + } + + return name; +} + +static int tpm2_key_ecdsa_query(const struct kernel_pkey_params *params, + struct kernel_pkey_query *info) +{ + const struct tpm2_key *key = params->key->payload.data[asym_crypto]; + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + const struct tpm2_ecc_parms *p = + (const struct tpm2_ecc_parms *)&key->data[o]; + u16 ecc = be16_to_cpu(p->ecc); + const char *ecc_name = tpm2_ecc_name(ecc); + const u8 *x = tpm2_key_ecdsa_ecc_x(key); + u16 x_size = get_unaligned_be16(&x[0]); + struct crypto_akcipher *tfm; + char data[256]; + u8 *ptr; + int ret; + + memset(data, 0, sizeof(data)); + + tfm = crypto_alloc_akcipher(ecc_name, 0, 0); + if (IS_ERR(tfm)) + return PTR_ERR(tfm); + + /* Probe for ecdsa_set_pub_key(): */ + ptr = &data[0]; + *ptr++ = 0x04; /* uncompressed */ + memcpy(&ptr[0], &x[2], x_size); + memcpy(&ptr[x_size], &x[2 + x_size + 2], x_size); + ret = crypto_akcipher_set_pub_key(tfm, data, 2 * x_size + 1); + crypto_free_akcipher(tfm); + if (ret < 0) + return ret; + + info->max_sig_size = 256; + info->key_size = 256; + info->max_data_size = 256; + info->supported_ops = KEYCTL_SUPPORTS_SIGN | KEYCTL_SUPPORTS_VERIFY; + return ret; +} + +static int tpm2_key_ecdsa_sign(struct tpm_chip *chip, struct tpm2_key *key, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + off_t offset = sizeof(struct tpm_header) + 4; + u16 hash_algo = TPM_ALG_SHA256; + u8 digest[SHA256_DIGEST_SIZE]; + u32 in_len = params->in_len; + struct tpm_buf buf; + u16 digest_size; + u32 key_handle; + u8 *ptr = out; + u16 sig_algo; + int ret; + + /* Require explicit hash algorithm: */ + if (!params->hash_algo) + return -EINVAL; + + /* Currently only support SHA256: */ + if (!!strcmp(params->hash_algo, "sha256")) + return -EINVAL; + + ret = tpm_try_get_ops(chip); + if (ret) + return ret; + + ret = tpm2_start_auth_session(chip); + if (ret) + goto err_ops; + + ret = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD); + if (ret < 0) { + tpm2_end_auth_session(chip); + goto err_ops; + } + + tpm_buf_append_name(chip, &buf, key->parent, NULL); + tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_CONTINUE_SESSION | + TPM2_SA_ENCRYPT, NULL, 0); + tpm_buf_append(&buf, &key->data[0], key->priv_len + key->pub_len); + if (buf.flags & TPM_BUF_OVERFLOW) { + tpm2_end_auth_session(chip); + ret = -E2BIG; + goto err_buf; + } + tpm_buf_fill_hmac_session(chip, &buf); + ret = tpm_transmit_cmd(chip, &buf, 4, "ECDSA loading"); + ret = tpm_buf_check_hmac_response(chip, &buf, ret); + if (ret) { + tpm2_end_auth_session(chip); + ret = -EIO; + goto err_buf; + } + + key_handle = be32_to_cpup((__be32 *)&buf.data[TPM_HEADER_SIZE]); + + tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_SIGN); + tpm_buf_append_name(chip, &buf, key_handle, NULL); + tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_DECRYPT, NULL, 0); + + sha256(in, in_len, digest); + tpm_buf_append_u16(&buf, SHA256_DIGEST_SIZE); + tpm_buf_append(&buf, digest, SHA256_DIGEST_SIZE); + tpm_buf_append_u16(&buf, TPM_ALG_ECDSA); + tpm_buf_append_u16(&buf, TPM_ALG_SHA256); + + /* 10.7.2 A NULL Ticket */ + tpm_buf_append_u16(&buf, TPM2_ST_HASHCHECK); + tpm_buf_append_u32(&buf, TPM2_RH_NULL); + tpm_buf_append_u16(&buf, 0); + + tpm_buf_fill_hmac_session(chip, &buf); + ret = tpm_transmit_cmd(chip, &buf, 4, "ECDSA signing"); + ret = tpm_buf_check_hmac_response(chip, &buf, ret); + if (ret) { + tpm2_end_auth_session(chip); + ret = -EIO; + goto err_blob; + } + + ret = -EIO; + sig_algo = tpm_buf_read_u16(&buf, &offset); + if (sig_algo != TPM_ALG_ECDSA) + goto err_blob; + + hash_algo = tpm_buf_read_u16(&buf, &offset); + if (hash_algo != TPM_ALG_SHA256) + goto err_blob; + + digest_size = tpm_buf_read_u16(&buf, &offset); + if (digest_size != SHA256_DIGEST_SIZE) + goto err_blob; + + /* SEQUENCE */ + *ptr++ = 0x30; + *ptr++ = 2 * (2 + SHA256_DIGEST_SIZE); + /* INTEGER */ + *ptr++ = 0x02; + *ptr++ = SHA256_DIGEST_SIZE; + memcpy(ptr, &buf.data[offset], SHA256_DIGEST_SIZE); + offset += SHA256_DIGEST_SIZE; + ptr += SHA256_DIGEST_SIZE; + + digest_size = tpm_buf_read_u16(&buf, &offset); + if (digest_size != SHA256_DIGEST_SIZE) + goto err_blob; + + /* INTEGER */ + *ptr++ = 0x02; + *ptr++ = SHA256_DIGEST_SIZE; + memcpy(ptr, &buf.data[offset], SHA256_DIGEST_SIZE); + offset += SHA256_DIGEST_SIZE; + ptr += SHA256_DIGEST_SIZE; + + ret = (void *)ptr - out; + pr_info("ret=%d\n", ret); + +err_blob: + tpm2_flush_context(chip, key_handle); + +err_buf: + tpm_buf_destroy(&buf); + +err_ops: + tpm_put_ops(chip); + return ret; +} + +static int tpm2_key_ecdsa_eds_op(struct kernel_pkey_params *params, + const void *in, void *out) +{ + struct tpm2_key *key = params->key->payload.data[asym_crypto]; + struct tpm_chip *chip = tpm_default_chip(); + + if (!chip) + return -ENODEV; + + switch (params->op) { + case kernel_pkey_sign: + return tpm2_key_ecdsa_sign(chip, key, params, in, out); + default: + return -EOPNOTSUPP; + } +} + +static int tpm2_key_ecdsa_verify_signature(const struct key *key, + const struct public_key_signature *sig) +{ + const struct tpm2_key *tpm2_key = key->payload.data[asym_crypto]; + const off_t o = tpm2_key->priv_len + 2 + sizeof(*tpm2_key->desc); + const struct tpm2_ecc_parms *p = + (const struct tpm2_ecc_parms *)&tpm2_key->data[o]; + u16 ecc = be16_to_cpu(p->ecc); + const char *ecc_name = tpm2_ecc_name(ecc); + const u8 *x = tpm2_key_ecdsa_ecc_x(tpm2_key); + u16 x_size = get_unaligned_be16(&x[0]); + struct akcipher_request *req; + struct scatterlist src_sg[2]; + struct crypto_akcipher *tfm; + struct crypto_wait cwait; + char data[256]; + u8 *ptr; + int ret; + + memset(data, 0, sizeof(data)); + + tfm = crypto_alloc_akcipher(ecc_name, 0, 0); + if (IS_ERR(tfm)) + return PTR_ERR(tfm); + + /* Probe for ecdsa_set_pub_key(): */ + ptr = &data[0]; + *ptr++ = 0x04; /* uncompressed */ + memcpy(&ptr[0], &x[2], x_size); + memcpy(&ptr[x_size], &x[2 + x_size + 2], x_size); + ret = crypto_akcipher_set_pub_key(tfm, data, 2 * x_size + 1); + if (ret) + goto err_tfm; + + ret = -ENOMEM; + req = akcipher_request_alloc(tfm, GFP_KERNEL); + if (!req) + goto err_tfm; + + sg_init_table(src_sg, 2); + sg_set_buf(&src_sg[0], sig->s, sig->s_size); + sg_set_buf(&src_sg[1], sig->digest, sig->digest_size); + akcipher_request_set_crypt(req, src_sg, NULL, sig->s_size, + sig->digest_size); + crypto_init_wait(&cwait); + akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | + CRYPTO_TFM_REQ_MAY_SLEEP, + crypto_req_done, &cwait); + ret = crypto_wait_req(crypto_akcipher_verify(req), &cwait); + akcipher_request_free(req); + +err_tfm: + crypto_free_akcipher(tfm); + return ret; +} + +/* + * Asymmetric TPM2 ECDSA key. Signs and decrypts with TPM. + */ +struct asymmetric_key_subtype tpm2_key_ecdsa_subtype = { + .owner = THIS_MODULE, + .name = "tpm2_key_ecdsa", + .name_len = sizeof("tpm2_key_ecdsa") - 1, + .describe = tpm2_key_ecdsa_describe, + .destroy = tpm2_key_ecdsa_destroy, + .query = tpm2_key_ecdsa_query, + .eds_op = tpm2_key_ecdsa_eds_op, + .verify_signature = tpm2_key_ecdsa_verify_signature, +}; +EXPORT_SYMBOL_GPL(tpm2_key_ecdsa_subtype); + +static int __tpm2_key_ecdsa_preparse(struct tpm2_key *key) +{ + const off_t o = key->priv_len + 2 + sizeof(*key->desc); + const struct tpm2_ecc_parms *p = + (const struct tpm2_ecc_parms *)&key->data[o]; + u16 x_size, y_size; + const u8 *x, *y; + + if (tpm2_key_type(key) != TPM_ALG_ECC) + return -EBADMSG; + + if (tpm2_key_policy_size(key) != 0) + return -EBADMSG; + + if (be16_to_cpu(p->symmetric) != TPM_ALG_NULL) + return -EBADMSG; + + if (be16_to_cpu(p->scheme) != TPM_ALG_NULL) + return -EBADMSG; + + if (be16_to_cpu(p->ecc) != TPM2_ECC_NIST_P256 && + be16_to_cpu(p->ecc) != TPM2_ECC_NIST_P384 && + be16_to_cpu(p->ecc) != TPM2_ECC_NIST_P521) + return -EBADMSG; + + if (be16_to_cpu(p->kdf) != TPM_ALG_NULL) + return -EBADMSG; + + x = tpm2_key_ecdsa_ecc_x(key); + x_size = get_unaligned_be16(&x[0]); + if (x_size > ECC_MAX_BYTES) + return -EBADMSG; + + y = tpm2_key_ecdsa_ecc_y(key); + y_size = get_unaligned_be16(&y[0]); + if (y_size > ECC_MAX_BYTES) + return -EBADMSG; + + if (x_size != y_size) + return -EBADMSG; + + return 0; +} + +/* + * Attempt to parse a data blob for a key as a TPM private key blob. + */ +static int tpm2_key_ecdsa_preparse(struct key_preparsed_payload *prep) +{ + struct tpm2_key *key; + int ret; + + key = tpm2_key_decode(prep->data, prep->datalen); + if (IS_ERR(key)) + return ret; + + if (key->oid != OID_TPMLoadableKey) { + kfree(key); + return -EBADMSG; + } + + ret = __tpm2_key_ecdsa_preparse(key); + if (ret < 0) { + kfree(key); + return ret; + } + + prep->payload.data[asym_subtype] = &tpm2_key_ecdsa_subtype; + prep->payload.data[asym_key_ids] = NULL; + prep->payload.data[asym_crypto] = key; + prep->payload.data[asym_auth] = NULL; + prep->quotalen = 100; + return 0; +} + +static struct asymmetric_key_parser tpm2_key_ecdsa_parser = { + .owner = THIS_MODULE, + .name = "tpm2_key_ecdsa_parser", + .parse = tpm2_key_ecdsa_preparse, +}; + +static int __init tpm2_key_ecdsa_init(void) +{ + return register_asymmetric_key_parser(&tpm2_key_ecdsa_parser); +} + +static void __exit tpm2_key_ecdsa_exit(void) +{ + unregister_asymmetric_key_parser(&tpm2_key_ecdsa_parser); +} + +module_init(tpm2_key_ecdsa_init); +module_exit(tpm2_key_ecdsa_exit); + +MODULE_DESCRIPTION("Asymmetric TPM2 ECDSA key"); +MODULE_LICENSE("GPL"); diff --git a/crypto/ecdsa.c b/crypto/ecdsa.c index 258fffbf623d..cf7d630c6593 100644 --- a/crypto/ecdsa.c +++ b/crypto/ecdsa.c @@ -236,7 +236,6 @@ static int ecdsa_set_pub_key(struct crypto_akcipher *tfm, const void *key, unsig if (d[0] != 4) return -EINVAL; - keylen--; digitlen = keylen >> 1; ndigits = DIV_ROUND_UP(digitlen, sizeof(u64)); diff --git a/include/linux/tpm.h b/include/linux/tpm.h index a4be7a852bde..b70ba5962102 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -45,6 +45,7 @@ enum tpm_algorithms { TPM_ALG_ERROR = 0x0000, TPM_ALG_RSA = 0x0001, TPM_ALG_SHA1 = 0x0004, + TPM_ALG_HMAC = 0x0004, TPM_ALG_AES = 0x0006, TPM_ALG_KEYEDHASH = 0x0008, TPM_ALG_SHA256 = 0x000B, @@ -52,6 +53,7 @@ enum tpm_algorithms { TPM_ALG_SHA512 = 0x000D, TPM_ALG_NULL = 0x0010, TPM_ALG_SM3_256 = 0x0012, + TPM_ALG_ECDSA = 0x0018, TPM_ALG_ECC = 0x0023, TPM_ALG_CFB = 0x0043, }; @@ -65,6 +67,8 @@ enum tpm_algorithms { enum tpm2_curves { TPM2_ECC_NONE = 0x0000, TPM2_ECC_NIST_P256 = 0x0003, + TPM2_ECC_NIST_P384 = 0x0004, + TPM2_ECC_NIST_P521 = 0x0005, }; struct tpm_digest { @@ -239,6 +243,7 @@ enum tpm2_structures { TPM2_ST_NO_SESSIONS = 0x8001, TPM2_ST_SESSIONS = 0x8002, TPM2_ST_CREATION = 0x8021, + TPM2_ST_HASHCHECK = 0x8024, }; /* Indicates from what layer of the software stack the error comes from */ @@ -274,6 +279,7 @@ enum tpm2_command_codes { TPM2_CC_LOAD = 0x0157, TPM2_CC_RSA_DECRYPT = 0x0159, TPM2_CC_SEQUENCE_UPDATE = 0x015C, + TPM2_CC_SIGN = 0x015D, TPM2_CC_UNSEAL = 0x015E, TPM2_CC_CONTEXT_LOAD = 0x0161, TPM2_CC_CONTEXT_SAVE = 0x0162,