From patchwork Mon May 18 17:26:48 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555899 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id ED3CF912 for ; Mon, 18 May 2020 17:27:15 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id D1D5520715 for ; Mon, 18 May 2020 17:27:15 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="NkW7ruD6" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1726958AbgERR1P (ORCPT ); Mon, 18 May 2020 13:27:15 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57494 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1727942AbgERR1O (ORCPT ); Mon, 18 May 2020 13:27:14 -0400 Received: from mail-pf1-x441.google.com (mail-pf1-x441.google.com [IPv6:2607:f8b0:4864:20::441]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id AC70EC061A0C for ; Mon, 18 May 2020 10:27:13 -0700 (PDT) Received: by mail-pf1-x441.google.com with SMTP id y18so5253201pfl.9 for ; Mon, 18 May 2020 10:27:13 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=VU2Z9jH2tHrmIYCSZ+Qm/Bdg8LSTyT9WNzv/6AK0Y/I=; b=NkW7ruD6LOylPL/N24x8fpSfp9iM08MmlXlkq1BAue8ZV8nfEMTiQkaigqcGO47SNV GkBputvng6Blh0/hdwvlpxuRHCxqRaSyxIxqC5zgwDZewNAFeEBT6WKi8kgQdAKIQzsi NVNZBs7t6xXBztm3AlQlsfKJzfPS+1kWKY4UX1MLD3LWGvE6FkAeq+Ws3KzlKkkdT1gh pT9aFU7NFzN+AhJxBH1LqleosvclCaRJcpVifnXMQd7bjy3ZVOTE4KifgSPAU4QrI/lf IGrzK5dO9HCHpWBHK0htPFDs47Qxa4OBUUpM0+NQ17+N72CQzGA/ylP0hMjXsxilmIhg VhVw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=VU2Z9jH2tHrmIYCSZ+Qm/Bdg8LSTyT9WNzv/6AK0Y/I=; b=HTOyTHYtblkKopmu+WD1Kso6U97RWoadd/NldFwT32pkN6lTtO4J1P8AIdtZ3HbsV9 OvF+Lw6raMK4pu/RJ8Qk2Q/855e5KP7jK0a91S6W4ylAF/Iv59dsNBol4c29z3y6vEG9 /vhrQFYK15QKfc8u7r4eVVOKXCPTKoDGbDcb2tzEbZY7EcZyijiQS0U4QkjEDenFJpVM 4OvNOBjyj9W1JgPFtNFqSJz/aUvfnO/7yVTttUNUnLIhgSrKzDhi3zFBl3DVY1IzihPC evxBDC2c+wiI42HHYi4RwGqcN+nZBjf2hFny9SRjO+9UiXq2EOwrlDyw40DOGjCojEpf /AnA== X-Gm-Message-State: AOAM532ewxH9LuLXcd2Sbt7alLU8rjTRdkFhmGMKY0DfNXhKAeWWsVF5 jxfpTLfJ0R5+wGyjzBUgKLGzd4Zz5WY= X-Google-Smtp-Source: ABdhPJxTSSbiwkXqmBMzwpJ8hChY2v6VT3wUQQN1HsQi9wBwxf30odHq9JIs0r0Q7lydSFTYPUsIUw== X-Received: by 2002:a65:4489:: with SMTP id l9mr7811736pgq.223.1589822832809; Mon, 18 May 2020 10:27:12 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.11 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:12 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 01/17] tpm-buf: move from static inlines to real functions Date: Mon, 18 May 2020 10:26:48 -0700 Message-Id: <20200518172704.29608-2-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley This separates out the old tpm_buf_... handling functions from static inlines in tpm.h and makes them their own tpm-buf.c file. This is a precursor so we can add new functions for other TPM type handling Signed-off-by: James Bottomley --- drivers/char/tpm/Makefile | 1 + drivers/char/tpm/tpm-buf.c | 118 +++++++++++++++++++++++++++++++++++++ drivers/char/tpm/tpm.h | 10 ++++ include/linux/tpm.h | 101 ++++++------------------------- 4 files changed, 146 insertions(+), 84 deletions(-) create mode 100644 drivers/char/tpm/tpm-buf.c diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile index 9567e5197f74..4d5765c41972 100644 --- a/drivers/char/tpm/Makefile +++ b/drivers/char/tpm/Makefile @@ -15,6 +15,7 @@ tpm-y += tpm-sysfs.o tpm-y += eventlog/common.o tpm-y += eventlog/tpm1.o tpm-y += eventlog/tpm2.o +tpm-y += tpm-buf.o tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o tpm-$(CONFIG_EFI) += eventlog/efi.o diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c new file mode 100644 index 000000000000..9fa8a9cb0fdf --- /dev/null +++ b/drivers/char/tpm/tpm-buf.c @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Handing for tpm_buf structures to facilitate the building of commands + */ + +#include "tpm.h" + +#include + +static int __tpm_buf_init(struct tpm_buf *buf) +{ + buf->data_page = alloc_page(GFP_HIGHUSER); + if (!buf->data_page) + return -ENOMEM; + + buf->flags = 0; + buf->data = kmap(buf->data_page); + + return 0; +} + +void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal) +{ + struct tpm_header *head; + + head = (struct tpm_header *) buf->data; + + head->tag = cpu_to_be16(tag); + head->length = cpu_to_be32(sizeof(*head)); + head->ordinal = cpu_to_be32(ordinal); +} +EXPORT_SYMBOL_GPL(tpm_buf_reset); + +int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal) +{ + int rc; + + rc = __tpm_buf_init(buf); + if (rc) + return rc; + + tpm_buf_reset(buf, tag, ordinal); + + return 0; +} +EXPORT_SYMBOL_GPL(tpm_buf_init); + +void tpm_buf_destroy(struct tpm_buf *buf) +{ + kunmap(buf->data_page); + __free_page(buf->data_page); +} +EXPORT_SYMBOL_GPL(tpm_buf_destroy); + +u32 tpm_buf_length(struct tpm_buf *buf) +{ + struct tpm_header *head = (struct tpm_header *)buf->data; + u32 len; + + len = be32_to_cpu(head->length); + if (buf->flags & TPM_BUF_2B) + len -= sizeof(*head); + return len; +} +EXPORT_SYMBOL_GPL(tpm_buf_length); + +u16 tpm_buf_tag(struct tpm_buf *buf) +{ + struct tpm_header *head = (struct tpm_header *)buf->data; + + return be16_to_cpu(head->tag); +} +EXPORT_SYMBOL_GPL(tpm_buf_tag); + +void tpm_buf_append(struct tpm_buf *buf, + const unsigned char *new_data, + unsigned int new_len) +{ + struct tpm_header *head = (struct tpm_header *) buf->data; + u32 len = be32_to_cpu(head->length); + + /* Return silently if overflow has already happened. */ + if (buf->flags & TPM_BUF_OVERFLOW) + return; + + if ((len + new_len) > PAGE_SIZE) { + WARN(1, "tpm_buf: overflow\n"); + buf->flags |= TPM_BUF_OVERFLOW; + return; + } + + memcpy(&buf->data[len], new_data, new_len); + head->length = cpu_to_be32(len + new_len); +} +EXPORT_SYMBOL_GPL(tpm_buf_append); + +void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value) +{ + tpm_buf_append(buf, &value, 1); +} +EXPORT_SYMBOL_GPL(tpm_buf_append_u8); + +void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value) +{ + __be16 value2 = cpu_to_be16(value); + + tpm_buf_append(buf, (u8 *) &value2, 2); +} +EXPORT_SYMBOL_GPL(tpm_buf_append_u16); + +void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value) +{ + __be32 value2 = cpu_to_be32(value); + + tpm_buf_append(buf, (u8 *) &value2, 4); +} +EXPORT_SYMBOL_GPL(tpm_buf_append_u32); diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h index 5620747da0cf..379629704522 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -153,6 +153,16 @@ enum tpm_sub_capabilities { * compiler warnings about stack frame size. */ #define TPM_MAX_RNG_DATA 128 +int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal); +void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal); +void tpm_buf_destroy(struct tpm_buf *buf); +u32 tpm_buf_length(struct tpm_buf *buf); +void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data, + unsigned int new_len); +void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value); +void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value); +void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value); + extern struct class *tpm_class; extern struct class *tpmrm_class; extern dev_t tpm_devt; diff --git a/include/linux/tpm.h b/include/linux/tpm.h index 03e9b184411b..893aa87ea211 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -289,9 +289,11 @@ struct tpm_header { enum tpm_buf_flags { TPM_BUF_OVERFLOW = BIT(0), + TPM_BUF_2B = BIT(1), }; struct tpm_buf { + struct page *data_page; unsigned int flags; u8 *data; }; @@ -309,90 +311,6 @@ struct tpm2_hash { unsigned int tpm_id; }; -static inline void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal) -{ - struct tpm_header *head = (struct tpm_header *)buf->data; - - head->tag = cpu_to_be16(tag); - head->length = cpu_to_be32(sizeof(*head)); - head->ordinal = cpu_to_be32(ordinal); -} - -static inline int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal) -{ - buf->data = (u8 *)__get_free_page(GFP_KERNEL); - if (!buf->data) - return -ENOMEM; - - buf->flags = 0; - tpm_buf_reset(buf, tag, ordinal); - return 0; -} - -static inline void tpm_buf_destroy(struct tpm_buf *buf) -{ - free_page((unsigned long)buf->data); -} - -static inline u32 tpm_buf_length(struct tpm_buf *buf) -{ - struct tpm_header *head = (struct tpm_header *)buf->data; - - return be32_to_cpu(head->length); -} - -static inline u16 tpm_buf_tag(struct tpm_buf *buf) -{ - struct tpm_header *head = (struct tpm_header *)buf->data; - - return be16_to_cpu(head->tag); -} - -static inline void tpm_buf_append(struct tpm_buf *buf, - const unsigned char *new_data, - unsigned int new_len) -{ - struct tpm_header *head = (struct tpm_header *)buf->data; - u32 len = tpm_buf_length(buf); - - /* Return silently if overflow has already happened. */ - if (buf->flags & TPM_BUF_OVERFLOW) - return; - - if ((len + new_len) > PAGE_SIZE) { - WARN(1, "tpm_buf: overflow\n"); - buf->flags |= TPM_BUF_OVERFLOW; - return; - } - - memcpy(&buf->data[len], new_data, new_len); - head->length = cpu_to_be32(len + new_len); -} - -static inline void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value) -{ - tpm_buf_append(buf, &value, 1); -} - -static inline void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value) -{ - __be16 value2 = cpu_to_be16(value); - - tpm_buf_append(buf, (u8 *) &value2, 2); -} - -static inline void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value) -{ - __be32 value2 = cpu_to_be32(value); - - tpm_buf_append(buf, (u8 *) &value2, 4); -} - -static inline u32 tpm2_rc_value(u32 rc) -{ - return (rc & BIT(7)) ? rc & 0xff : rc; -} - #if defined(CONFIG_TCG_TPM) || defined(CONFIG_TCG_TPM_MODULE) extern int tpm_is_tpm2(struct tpm_chip *chip); @@ -404,6 +322,21 @@ extern int tpm_send(struct tpm_chip *chip, void *cmd, size_t buflen); extern int tpm_get_random(struct tpm_chip *chip, u8 *data, size_t max); extern struct tpm_chip *tpm_default_chip(void); void tpm2_flush_context(struct tpm_chip *chip, u32 handle); +extern int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal); +extern void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal); +extern void tpm_buf_destroy(struct tpm_buf *buf); +extern u32 tpm_buf_length(struct tpm_buf *buf); +extern void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data, + unsigned int new_len); +extern void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value); +extern void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value); +extern void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value); + +static inline u32 tpm2_rc_value(u32 rc) +{ + return (rc & BIT(7)) ? rc & 0xff : rc; +} + #else static inline int tpm_is_tpm2(struct tpm_chip *chip) { From patchwork Mon May 18 17:26:49 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555897 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 82C99913 for ; Mon, 18 May 2020 17:27:15 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 6BFAE20715 for ; Mon, 18 May 2020 17:27:15 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="P7kmqkQA" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728152AbgERR1P (ORCPT ); Mon, 18 May 2020 13:27:15 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57496 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1726958AbgERR1O (ORCPT ); Mon, 18 May 2020 13:27:14 -0400 Received: from mail-pg1-x544.google.com (mail-pg1-x544.google.com [IPv6:2607:f8b0:4864:20::544]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 9213BC05BD09 for ; Mon, 18 May 2020 10:27:14 -0700 (PDT) Received: by mail-pg1-x544.google.com with SMTP id t11so5146590pgg.2 for ; Mon, 18 May 2020 10:27:14 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=oHITpSRaDOxHt+OJGpz86kUPCUVylMr0qalk3pgiieM=; b=P7kmqkQAoT4XBsco7M4uM7mb2eqPZSRd+E/j87i4sM2T1s7ryg/N3/q6zUZAKvOBdg o4Cj9ZMSz0ODpBTehbYy5kpT1o6f4OdgyN7Fe77uIcGm/Dpp0pI+8sU6e284q+8MZuEf 2T3mBUXml7VQdENuZHBBO6zQ6zzRb4LB2MdfiSN8WXvXu8LHNDMNobVLgEf4lsA8CCDg kORF6W3hdatqLud3e81EwamkrqZ1Dy9raJ5ns0a8hUvc5rwroed846B2vvHMPl8B95Xz ysvHpjSaQQqtIkNj77Fn/IiQ4QgRCKp4lU/40fDrwrmGN4pxS1TXCZlBO368jv7NIJ5p M/ig== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=oHITpSRaDOxHt+OJGpz86kUPCUVylMr0qalk3pgiieM=; b=oGkHUtvrg5fJzW4guKy+5Iq62QDFzdmLjTzdK1g+mn3xgA95C2CuEhiLqI2rPUohcb CN9XGbCwOMePHqPznKzLlEUJubXessFN/hQVKtcp8AYHfoGIO8JhmcyNcSksT2howN3F z1fNpAfMeiix0rsFiXpEwPqp5xglcPLJAk4OJvFY56Ld7ohcfS3uBnOjcr9kI9FmA1Gj F/X/pW81qeZAWTe4sb8WrsWKyGINE0kcTq3LE9qCr1BmPl5Ikwc9k94sXB/qzEeivngw oex17slcuTu0zEKYYiyCfDPyocXlE2rpqT7AR9uB1I3BRn/wuf2uXiLm/xFQHqnQFzJU Y1TA== X-Gm-Message-State: AOAM530veUX+/UmTc87skDTJ1dV7hpo11bZYtmdbRoMq/9MXVbOzADGG BLhHaRTaoygzmMGNzDb1/ScWtcDBiog= X-Google-Smtp-Source: ABdhPJxbm55ZVzhAHx+XD0u5f/gmZYgsdTepmY5VGyq/JnB32ezSNpbR7mZ2xCZlzrbcy7dylfiUdA== X-Received: by 2002:a63:3c11:: with SMTP id j17mr16368542pga.70.1589822833840; Mon, 18 May 2020 10:27:13 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.13 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:13 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 02/17] tpm-buf: add handling for TPM2B types Date: Mon, 18 May 2020 10:26:49 -0700 Message-Id: <20200518172704.29608-3-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley Most complex TPM commands require appending TPM2B buffers to the command body. Since TPM2B types are essentially variable size arrays, it makes it impossible to represent these complex command arguments as structures and we simply have to build them up using append primitives like these. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm-buf.c | 47 ++++++++++++++++++++++++++++++++++++++ drivers/char/tpm/tpm.h | 2 ++ 2 files changed, 49 insertions(+) diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c index 9fa8a9cb0fdf..8c1ed8a14e01 100644 --- a/drivers/char/tpm/tpm-buf.c +++ b/drivers/char/tpm/tpm-buf.c @@ -8,6 +8,8 @@ #include +#include + static int __tpm_buf_init(struct tpm_buf *buf) { buf->data_page = alloc_page(GFP_HIGHUSER); @@ -46,6 +48,24 @@ int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal) } EXPORT_SYMBOL_GPL(tpm_buf_init); +int tpm_buf_init_2b(struct tpm_buf *buf) +{ + struct tpm_header *head; + int rc; + + rc = __tpm_buf_init(buf); + if (rc) + return rc; + + head = (struct tpm_header *) buf->data; + + head->length = cpu_to_be32(sizeof(*head)); + + buf->flags = TPM_BUF_2B; + return 0; +} +EXPORT_SYMBOL_GPL(tpm_buf_init_2b); + void tpm_buf_destroy(struct tpm_buf *buf) { kunmap(buf->data_page); @@ -53,6 +73,13 @@ void tpm_buf_destroy(struct tpm_buf *buf) } EXPORT_SYMBOL_GPL(tpm_buf_destroy); +static void *tpm_buf_data(struct tpm_buf *buf) +{ + if (buf->flags & TPM_BUF_2B) + return buf->data + TPM_HEADER_SIZE; + return buf->data; +} + u32 tpm_buf_length(struct tpm_buf *buf) { struct tpm_header *head = (struct tpm_header *)buf->data; @@ -116,3 +143,23 @@ void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value) tpm_buf_append(buf, (u8 *) &value2, 4); } EXPORT_SYMBOL_GPL(tpm_buf_append_u32); + +static void tpm_buf_reset_int(struct tpm_buf *buf) +{ + struct tpm_header *head; + + head = (struct tpm_header *)buf->data; + head->length = cpu_to_be32(sizeof(*head)); +} + +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b) +{ + u16 len = tpm_buf_length(tpm2b); + + tpm_buf_append_u16(buf, len); + tpm_buf_append(buf, tpm_buf_data(tpm2b), len); + /* clear the buf for reuse */ + tpm_buf_reset_int(tpm2b); +} +EXPORT_SYMBOL_GPL(tpm_buf_append_2b); + diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h index 379629704522..dfa03b63d8ee 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -155,6 +155,7 @@ enum tpm_sub_capabilities { int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal); void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal); +int tpm_buf_init_2b(struct tpm_buf *buf); void tpm_buf_destroy(struct tpm_buf *buf); u32 tpm_buf_length(struct tpm_buf *buf); void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data, @@ -162,6 +163,7 @@ void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data, void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value); void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value); void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value); +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b); extern struct class *tpm_class; extern struct class *tpmrm_class; From patchwork Mon May 18 17:26:50 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555901 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 440AC14C0 for ; Mon, 18 May 2020 17:27:16 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 2D71120715 for ; Mon, 18 May 2020 17:27:16 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="Vp3U5JfN" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728295AbgERR1Q (ORCPT ); Mon, 18 May 2020 13:27:16 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57498 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1727942AbgERR1P (ORCPT ); Mon, 18 May 2020 13:27:15 -0400 Received: from mail-pl1-x644.google.com (mail-pl1-x644.google.com [IPv6:2607:f8b0:4864:20::644]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 773CCC061A0C for ; Mon, 18 May 2020 10:27:15 -0700 (PDT) Received: by mail-pl1-x644.google.com with SMTP id x10so4498040plr.4 for ; Mon, 18 May 2020 10:27:15 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=IWRS7emRXYf9qWcwlkWmHmKvw+QoHIBpaRQNYzd6eIk=; b=Vp3U5JfNzQg8WqwZvczMy+zStTaDZvZz5/Nwj5rlWs0CrqzNlXKM3Ly0gX2jQbYT1u c0zIFc95MSZNjhTRikVGTu0IbdvpE7Z9bXg6TpCBIJ7oNMYqWsRODMObEEVcZdsCtCeD RDDWnCVyP3vMxjIOyJC/0UJSJzYaL05SAyV7P5zP1BeOA9YZWykTD/wPm8Q0gcfN8ii+ Ux286lHRtYwM92sjI4IuUMfNfNv5gjef6CjajI0dCvUR97fnIcRi8m3yTguVsvXp/600 KErFqgBHtVJe3up53IMLS0lFLYsGjuo152UaPPO73B096JLXvp2P87w21njsBvagp7aQ ETzw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=IWRS7emRXYf9qWcwlkWmHmKvw+QoHIBpaRQNYzd6eIk=; b=ecO9J6/kOp69qRM3CZpayCYvrRrWP7PK6/kGCnjQTAeM8NvZUFKvqT3fqLhKSK0Cn3 XpB76K4M0EkYOkkXQc0Y/591B7hn+yrNDiEGb73poZ6khQ+r40NzvYi+rqmEiEyB1ngV GLusbuH0UIUy4BY61o90OVZIZrUUR+tAvH7FUKA+5xI/XPydqen+FqfTuYqcthD8kZXB 1Ez1RFmcFxVd4/TeSLtANw/rIQPWa4KYV3bchoVfVtEG9dRsrFV8Z0gWHM7TQmBt70Of a3ChC4vFE4P7SgtWTM0eopdCGasEA8nRLDAU3bxfPax1YExW5WyW4OWoMuw/sOkuoCra ZuUA== X-Gm-Message-State: AOAM533ZFJu1I4WAjpR6BC/UnCjgXxbFQxsEfwPbenVMMcuZua0m+zQ4 vTKK2rS8obwmkUT/Nyd0BwJHhZjuLsU= X-Google-Smtp-Source: ABdhPJyIA/tYn/LrGzy6b/qFeFvGBOos+MiXyn4Rhypg4QH24kbKo5SS/L2D6wdVi3cBwPGsTYR19Q== X-Received: by 2002:a17:90b:19d2:: with SMTP id nm18mr491944pjb.71.1589822834817; Mon, 18 May 2020 10:27:14 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.13 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:14 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 03/17] tpm-buf: add cursor based functions for response parsing Date: Mon, 18 May 2020 10:26:50 -0700 Message-Id: <20200518172704.29608-4-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley It's very convenient when parsing responses to have a cursor you simply move over the response extracting the data. Add such cursor functions for the TPM unsigned integer types. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm-buf.c | 26 ++++++++++++++++++++++++++ drivers/char/tpm/tpm.h | 4 ++++ 2 files changed, 30 insertions(+) diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c index 8c1ed8a14e01..553adb84b0ac 100644 --- a/drivers/char/tpm/tpm-buf.c +++ b/drivers/char/tpm/tpm-buf.c @@ -163,3 +163,29 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b) } EXPORT_SYMBOL_GPL(tpm_buf_append_2b); +/* functions for unmarshalling data and moving the cursor */ +u8 tpm_get_inc_u8(const u8 **ptr) +{ + return *((*ptr)++); +} +EXPORT_SYMBOL_GPL(tpm_get_inc_u8); + +u16 tpm_get_inc_u16(const u8 **ptr) +{ + u16 val; + + val = get_unaligned_be16(*ptr); + *ptr += sizeof(val); + return val; +} +EXPORT_SYMBOL_GPL(tpm_get_inc_u16); + +u32 tpm_get_inc_u32(const u8 **ptr) +{ + u32 val; + + val = get_unaligned_be32(*ptr); + *ptr += sizeof(val); + return val; +} +EXPORT_SYMBOL_GPL(tpm_get_inc_u32); diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h index dfa03b63d8ee..c75340dc3bce 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -165,6 +165,10 @@ void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value); void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value); void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b); +u8 tpm_get_inc_u8(const u8 **ptr); +u16 tpm_get_inc_u16(const u8 **ptr); +u32 tpm_get_inc_u32(const u8 **ptr); + extern struct class *tpm_class; extern struct class *tpmrm_class; extern dev_t tpm_devt; From patchwork Mon May 18 17:26:51 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555903 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 34A90912 for ; Mon, 18 May 2020 17:27:18 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 1DF6220715 for ; Mon, 18 May 2020 17:27:18 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="Spz5aj7R" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728416AbgERR1S (ORCPT ); Mon, 18 May 2020 13:27:18 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57506 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1727942AbgERR1R (ORCPT ); Mon, 18 May 2020 13:27:17 -0400 Received: from mail-pj1-x1042.google.com (mail-pj1-x1042.google.com [IPv6:2607:f8b0:4864:20::1042]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 6355DC061A0C for ; Mon, 18 May 2020 10:27:16 -0700 (PDT) Received: by mail-pj1-x1042.google.com with SMTP id n15so132311pjt.4 for ; Mon, 18 May 2020 10:27:16 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=4x/3TSpmMIdn//ZEVT/ngeetbkRV8X2ObeYCcuramf8=; b=Spz5aj7RpEbHHE30eKPxdyyGUHFeDddR+lq7fw41ra9VbtmNxyPwbmquFjS7InSspl knjtxS+TDipwag/LYRdi+I271NQ17BvAjac5MZXnnA/2yWOVuEn7FE32tP1SIsA3Ijqq qAr4iQ+5YYAlCNik7VyJKZKnDkwGE7rJG0CG2+FT6DN7nWM6LxLA2ggWc3WySQs2XWgW Vt70guWqSAevXz47LHampkilgjwDT2TfD+OWsIW7M6YQHc7bl9LlzMgqRFymPffxhjXS dl0KrmCCk61W/kotSQAiHie2kN7Fsegw7dWDlB/KTchpIaoNhm6ETG9ZBr3IE4ZKodNM RrmA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=4x/3TSpmMIdn//ZEVT/ngeetbkRV8X2ObeYCcuramf8=; b=afClJOzg+nKMzdG4EybcLgkB1L/9TRh8Up5XR6j6fqHgApjAJloJTgwNbU/hLDbOPa vUZr+Jt0SmXyVUftH0bILWQe2zFNwIQPHHKgyAMkSLbMwCOrNYxvQumFdAjqABTSOl1P dKozNoCYKUeSiuTox3oi2SZdRH+ETm3/N7+rk6MQBYkfeKYKqmQMlSJHceUa2Ftls1Gd uXm96/YEGA1GHNDXVZ4JFc0dzIpmKpJWuMvEx5z95KI8uqAQOD11BY5Aqc1honhAMMv6 xVOLew06bOrGzQBgw5kUkgEokVV64xd3//v78kkgc1xkiYoCxKbvowRyzT1/Jam8n+aA Rh+Q== X-Gm-Message-State: AOAM533l1KIkossfNcfJsLTgv4XD+z6L0EZbmNb+Waj+7Tw5nzMnDjUn kDRqPG7Z71JG0XAUVyZi/o+tskD/lW0= X-Google-Smtp-Source: ABdhPJwMSYQ5JaRnZm7kGxQqyvdjcaiIQkaUpPfsp9jYe8UJq5QK+R+ROgwrJPDhokBAljf4SAW2SQ== X-Received: by 2002:a17:90b:1994:: with SMTP id mv20mr471459pjb.41.1589822835678; Mon, 18 May 2020 10:27:15 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.14 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:15 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 04/17] tpm2-space: export the context save and load commands Date: Mon, 18 May 2020 10:26:51 -0700 Message-Id: <20200518172704.29608-5-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley The TPM2 session handling code needs to save and restore a single volatile context for the elliptic curve version of the NULL seed, so export the APIs which do this for internal use. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm.h | 4 ++++ drivers/char/tpm/tpm2-space.c | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h index c75340dc3bce..ba76bec04ca4 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -250,6 +250,10 @@ int tpm2_prepare_space(struct tpm_chip *chip, struct tpm_space *space, u8 *cmd, size_t cmdsiz); int tpm2_commit_space(struct tpm_chip *chip, struct tpm_space *space, void *buf, size_t *bufsiz); +int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf, + unsigned int buf_size, unsigned int *offset); +int tpm2_load_context(struct tpm_chip *chip, u8 *buf, + unsigned int *offset, u32 *handle); int tpm_bios_log_setup(struct tpm_chip *chip); void tpm_bios_log_teardown(struct tpm_chip *chip); diff --git a/drivers/char/tpm/tpm2-space.c b/drivers/char/tpm/tpm2-space.c index 982d341d8837..ca1cb56ccc51 100644 --- a/drivers/char/tpm/tpm2-space.c +++ b/drivers/char/tpm/tpm2-space.c @@ -65,8 +65,8 @@ void tpm2_del_space(struct tpm_chip *chip, struct tpm_space *space) kfree(space->session_buf); } -static int tpm2_load_context(struct tpm_chip *chip, u8 *buf, - unsigned int *offset, u32 *handle) +int tpm2_load_context(struct tpm_chip *chip, u8 *buf, + unsigned int *offset, u32 *handle) { struct tpm_buf tbuf; struct tpm2_context *ctx; @@ -116,8 +116,8 @@ static int tpm2_load_context(struct tpm_chip *chip, u8 *buf, return 0; } -static int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf, - unsigned int buf_size, unsigned int *offset) +int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf, + unsigned int buf_size, unsigned int *offset) { struct tpm_buf tbuf; unsigned int body_size; From patchwork Mon May 18 17:26:52 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555909 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 473EE1668 for ; Mon, 18 May 2020 17:27:21 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 1CE2020715 for ; Mon, 18 May 2020 17:27:21 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="EjO9/CAL" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1727942AbgERR1V (ORCPT ); Mon, 18 May 2020 13:27:21 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57514 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728419AbgERR1U (ORCPT ); Mon, 18 May 2020 13:27:20 -0400 Received: from mail-pf1-x42d.google.com (mail-pf1-x42d.google.com [IPv6:2607:f8b0:4864:20::42d]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id CF5A8C05BD09 for ; Mon, 18 May 2020 10:27:18 -0700 (PDT) Received: by mail-pf1-x42d.google.com with SMTP id y198so3679079pfb.4 for ; Mon, 18 May 2020 10:27:18 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=dM0V4v/Xo4cfzQ6jfMWNANZQ4Q4qJ06rNCofJ0HlTGY=; b=EjO9/CALfMebI5aAeyzVXjOdGaydK7l+qkxLvPU6gpuTe63lSNn/DTnDPk1q/Wcd3r NjXAdOtotkWOXXiNUB4ch5eDVdMJDYaHUzAWkuxJ7pKlGtmCkfHbDoWxE4tW52zXpMAV vjwp1vr/sWCJeL3napWTo5yOfp9u3zycB3Mz93Anx6M8pqoBhCFgDdgiDyQgd1muhggs 0VKSgg7LnFTaLbeL9d/P6Ia4yAaWSAmtfvQHdRT7Y/IHSbTK203BEg/teZVSKcEtSI/h y7228pobgX/CBx7P54muNrjiH+FYk7ye+E3TCjRZAkAsvyv7KZR/w+b9rmYsd2tZNwlh GV6g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=dM0V4v/Xo4cfzQ6jfMWNANZQ4Q4qJ06rNCofJ0HlTGY=; b=Mrxipql0WhHdivKofopdHgEZoHL6reCTB+BsD7jtEmtRPuyOMD5DU2x33unn5JMRSA JKIHPMrvu9/0W/UzlqbWSFk5qdvOrSfY6YhgBF/usT1ED6zz4c7OxIwh+FpqHqoPBoO3 fLckuHNx0IoWj/y5n2dyFT66my7bODXa7EYxIbh3RiVzncMT2MLyWgegILaagM7AfYQ4 m2PCKc2fQnd6Oj9K8TbLEXTkY/FZDL22iDF3QjaeWFGSShEnVIndYSNRPhnXkx8oMcrT /gPZ1C8GahZfQjDJ8iHBmxwJf7+lWiqIwT5yCiji0d/kMjYL6EnXZbGsD/ak/DRCLUes EcEg== X-Gm-Message-State: AOAM532CMFz/5/HISPMoeXy4K9xFadZmXMdDGbpC3aaNf069tiI8WFTe WFceVIgPP+sln8tcjcyuphXOWQ+DIjE= X-Google-Smtp-Source: ABdhPJxeOB3Grcfq1+ZKLXXeYo3UTEV3wMULY6FdAjL+BNIBGjv9emThukY4OjQWVPsqwCKuyUjehw== X-Received: by 2002:a63:1414:: with SMTP id u20mr16132790pgl.47.1589822836841; Mon, 18 May 2020 10:27:16 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.15 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:16 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, Ard Biesheuvel Subject: [PATCH 05/17] tpm2-sessions: Add full HMAC and encrypt/decrypt session handling Date: Mon, 18 May 2020 10:26:52 -0700 Message-Id: <20200518172704.29608-6-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley This code adds true session based HMAC authentication plus parameter decryption and response encryption using AES. The basic design of this code is to segregate all the nasty crypto, hash and hmac code into tpm2-sessions.c and export a usable API. The API first of all starts off by gaining a session with tpm2_start_auth_session() Which initiates a session with the TPM and allocates an opaque tpm2_auth structure to handle the session parameters. Then the use is simply: * tpm_buf_append_name() in place of the tpm_buf_append_u32 for the handles * tpm_buf_append_hmac_session() where tpm2_append_auth() would go * tpm_buf_fill_hmac_session() called after the entire command buffer is finished but before tpm_transmit_cmd() is called which computes the correct HMAC and places it in the command at the correct location. Finally, after tpm_transmit_cmd() is called, tpm_buf_check_hmac_response() is called to check that the returned HMAC matched and collect the new state for the next use of the session, if any. The features of the session is controlled by the session attributes set in tpm_buf_append_hmac_session(). If TPM2_SA_CONTINUE_SESSION is not specified, the session will be flushed and the tpm2_auth structure freed in tpm_buf_check_hmac_response(); otherwise the session may be used again. Parameter encryption is specified by or'ing the flag TPM2_SA_DECRYPT and response encryption by or'ing the flag TPM2_SA_ENCRYPT. the various encryptions will be taken care of by tpm_buf_fill_hmac_session() and tpm_buf_check_hmac_response() respectively. To get all of this to work securely, the Kernel now needs a primary key to encrypt the session salt to, so we derive an EC key from the NULL seed and save its context in the tpm_chip structure. The context is loaded on demand into an available volatile handle when tpm_start_auth_session() is called, but is flushed before that function exits to conserve handles. Signed-off-by: James Bottomley Reviewed-by: Ard Biesheuvel # crypto API parts --- drivers/char/tpm/Kconfig | 11 + drivers/char/tpm/Makefile | 1 + drivers/char/tpm/tpm-buf.c | 1 + drivers/char/tpm/tpm.h | 13 + drivers/char/tpm/tpm2-cmd.c | 300 ++++++++ drivers/char/tpm/tpm2-sessions.c | 1203 ++++++++++++++++++++++++++++++ drivers/char/tpm/tpm2-sessions.h | 114 +++ include/linux/tpm.h | 49 ++ 8 files changed, 1692 insertions(+) create mode 100644 drivers/char/tpm/tpm2-sessions.c create mode 100644 drivers/char/tpm/tpm2-sessions.h diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig index aacdeed93320..305775975a8b 100644 --- a/drivers/char/tpm/Kconfig +++ b/drivers/char/tpm/Kconfig @@ -9,6 +9,9 @@ menuconfig TCG_TPM imply SECURITYFS select CRYPTO select CRYPTO_HASH_INFO + select CRYPTO_ECDH + select CRYPTO_AES + select CRYPTO_CFB ---help--- If you have a TPM security chip in your system, which implements the Trusted Computing Group's specification, @@ -27,6 +30,14 @@ menuconfig TCG_TPM if TCG_TPM +config TPM_BUS_SECURITY + bool "Use secure transactions on the TPM bus" + default y + ---help--- + Setting this causes us to deploy a tamper resistent scheme + for communicating with the TPM to prevent or detect bus snooping + attacks like TPM Genie. Saying Y here adds some encryption overhead + to all kernel to TPM transactions. config HW_RANDOM_TPM bool "TPM HW Random Number Generator support" depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m) diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile index 4d5765c41972..618473a9c368 100644 --- a/drivers/char/tpm/Makefile +++ b/drivers/char/tpm/Makefile @@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o tpm-y += eventlog/tpm2.o tpm-y += tpm-buf.o +tpm-$(CONFIG_TPM_BUS_SECURITY) += tpm2-sessions.o tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o tpm-$(CONFIG_EFI) += eventlog/efi.o tpm-$(CONFIG_OF) += eventlog/of.o diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c index 553adb84b0ac..f56350123a08 100644 --- a/drivers/char/tpm/tpm-buf.c +++ b/drivers/char/tpm/tpm-buf.c @@ -31,6 +31,7 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal) head->tag = cpu_to_be16(tag); head->length = cpu_to_be32(sizeof(*head)); head->ordinal = cpu_to_be32(ordinal); + buf->handles = 0; } EXPORT_SYMBOL_GPL(tpm_buf_reset); diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h index ba76bec04ca4..a1959675a889 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -169,6 +169,9 @@ u8 tpm_get_inc_u8(const u8 **ptr); u16 tpm_get_inc_u16(const u8 **ptr); u32 tpm_get_inc_u32(const u8 **ptr); +/* opaque structure, holds auth session parameters like the session key */ +struct tpm2_auth; + extern struct class *tpm_class; extern struct class *tpmrm_class; extern dev_t tpm_devt; @@ -259,4 +262,14 @@ int tpm_bios_log_setup(struct tpm_chip *chip); void tpm_bios_log_teardown(struct tpm_chip *chip); int tpm_dev_common_init(void); void tpm_dev_common_exit(void); + +#ifdef CONFIG_TPM_BUS_SECURITY +int tpm2_sessions_init(struct tpm_chip *chip); +#else +static inline int tpm2_sessions_init(struct tpm_chip *chip) +{ + return 0; +} +#endif + #endif diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c index 760329598b99..8d076c6752eb 100644 --- a/drivers/char/tpm/tpm2-cmd.c +++ b/drivers/char/tpm/tpm2-cmd.c @@ -12,7 +12,9 @@ */ #include "tpm.h" +#include "tpm2-sessions.h" #include +#include static struct tpm2_hash tpm2_hash_map[] = { {HASH_ALGO_SHA1, TPM_ALG_SHA1}, @@ -364,6 +366,299 @@ void tpm2_flush_context(struct tpm_chip *chip, u32 handle) } EXPORT_SYMBOL_GPL(tpm2_flush_context); +/** + * tpm_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer. + * + * @buf: an allocated tpm_buf instance + * @session_handle: session handle + * @nonce: the session nonce, may be NULL if not used + * @nonce_len: the session nonce length, may be 0 if not used + * @attributes: the session attributes + * @hmac: the session HMAC or password, may be NULL if not used + * @hmac_len: the session HMAC or password length, maybe 0 if not used + */ +void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle, + const u8 *nonce, u16 nonce_len, + u8 attributes, + const u8 *hmac, u16 hmac_len) +{ + tpm_buf_append_u32(buf, 9 + nonce_len + hmac_len); + tpm_buf_append_u32(buf, session_handle); + tpm_buf_append_u16(buf, nonce_len); + + if (nonce && nonce_len) + tpm_buf_append(buf, nonce, nonce_len); + + tpm_buf_append_u8(buf, attributes); + tpm_buf_append_u16(buf, hmac_len); + + if (hmac && hmac_len) + tpm_buf_append(buf, hmac, hmac_len); +} + +/** + * tpm2_seal_trusted() - seal the payload of a trusted key + * + * @chip: TPM chip to use + * @payload: the key data in clear and encrypted form + * @options: authentication values and other options + * + * Return: < 0 on error and 0 on success. + */ +int tpm2_seal_trusted(struct tpm_chip *chip, + struct trusted_key_payload *payload, + struct trusted_key_options *options) +{ + unsigned int blob_len; + struct tpm_buf buf; + u32 hash; + int i; + int rc; + + for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) { + if (options->hash == tpm2_hash_map[i].crypto_id) { + hash = tpm2_hash_map[i].tpm_id; + break; + } + } + + if (i == ARRAY_SIZE(tpm2_hash_map)) + return -EINVAL; + + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE); + if (rc) + return rc; + + tpm_buf_append_u32(&buf, options->keyhandle); + tpm2_buf_append_auth(&buf, TPM2_RS_PW, + NULL /* nonce */, 0, + 0 /* session_attributes */, + options->keyauth /* hmac */, + TPM_DIGEST_SIZE); + + /* sensitive */ + tpm_buf_append_u16(&buf, 4 + TPM_DIGEST_SIZE + payload->key_len + 1); + + tpm_buf_append_u16(&buf, TPM_DIGEST_SIZE); + tpm_buf_append(&buf, options->blobauth, TPM_DIGEST_SIZE); + tpm_buf_append_u16(&buf, payload->key_len + 1); + tpm_buf_append(&buf, payload->key, payload->key_len); + tpm_buf_append_u8(&buf, payload->migratable); + + /* public */ + tpm_buf_append_u16(&buf, 14 + options->policydigest_len); + tpm_buf_append_u16(&buf, TPM_ALG_KEYEDHASH); + tpm_buf_append_u16(&buf, hash); + + /* policy */ + if (options->policydigest_len) { + tpm_buf_append_u32(&buf, 0); + tpm_buf_append_u16(&buf, options->policydigest_len); + tpm_buf_append(&buf, options->policydigest, + options->policydigest_len); + } else { + tpm_buf_append_u32(&buf, TPM2_OA_USER_WITH_AUTH); + tpm_buf_append_u16(&buf, 0); + } + + /* public parameters */ + tpm_buf_append_u16(&buf, TPM_ALG_NULL); + tpm_buf_append_u16(&buf, 0); + + /* outside info */ + tpm_buf_append_u16(&buf, 0); + + /* creation PCR */ + tpm_buf_append_u32(&buf, 0); + + if (buf.flags & TPM_BUF_OVERFLOW) { + rc = -E2BIG; + goto out; + } + + rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data"); + if (rc) + goto out; + + blob_len = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]); + if (blob_len > MAX_BLOB_SIZE) { + rc = -E2BIG; + goto out; + } + if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 4 + blob_len) { + rc = -EFAULT; + goto out; + } + + memcpy(payload->blob, &buf.data[TPM_HEADER_SIZE + 4], blob_len); + payload->blob_len = blob_len; + +out: + tpm_buf_destroy(&buf); + + if (rc > 0) { + if (tpm2_rc_value(rc) == TPM2_RC_HASH) + rc = -EINVAL; + else + rc = -EPERM; + } + + return rc; +} + +/** + * tpm2_load_cmd() - execute a TPM2_Load command + * + * @chip: TPM chip to use + * @payload: the key data in clear and encrypted form + * @options: authentication values and other options + * @blob_handle: returned blob handle + * + * Return: 0 on success. + * -E2BIG on wrong payload size. + * -EPERM on tpm error status. + * < 0 error from tpm_transmit_cmd. + */ +static int tpm2_load_cmd(struct tpm_chip *chip, + struct trusted_key_payload *payload, + struct trusted_key_options *options, + u32 *blob_handle) +{ + struct tpm_buf buf; + unsigned int private_len; + unsigned int public_len; + unsigned int blob_len; + int rc; + + private_len = be16_to_cpup((__be16 *) &payload->blob[0]); + if (private_len > (payload->blob_len - 2)) + return -E2BIG; + + public_len = be16_to_cpup((__be16 *) &payload->blob[2 + private_len]); + blob_len = private_len + public_len + 4; + if (blob_len > payload->blob_len) + return -E2BIG; + + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD); + if (rc) + return rc; + + tpm_buf_append_u32(&buf, options->keyhandle); + tpm2_buf_append_auth(&buf, TPM2_RS_PW, + NULL /* nonce */, 0, + 0 /* session_attributes */, + options->keyauth /* hmac */, + TPM_DIGEST_SIZE); + + tpm_buf_append(&buf, payload->blob, blob_len); + + if (buf.flags & TPM_BUF_OVERFLOW) { + rc = -E2BIG; + goto out; + } + + rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob"); + if (!rc) + *blob_handle = be32_to_cpup( + (__be32 *) &buf.data[TPM_HEADER_SIZE]); + +out: + tpm_buf_destroy(&buf); + + if (rc > 0) + rc = -EPERM; + + return rc; +} + +/** + * tpm2_unseal_cmd() - execute a TPM2_Unload command + * + * @chip: TPM chip to use + * @payload: the key data in clear and encrypted form + * @options: authentication values and other options + * @blob_handle: blob handle + * + * Return: 0 on success + * -EPERM on tpm error status + * < 0 error from tpm_transmit_cmd + */ +static int tpm2_unseal_cmd(struct tpm_chip *chip, + struct trusted_key_payload *payload, + struct trusted_key_options *options, + u32 blob_handle) +{ + struct tpm_buf buf; + u16 data_len; + u8 *data; + int rc; + + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL); + if (rc) + return rc; + + tpm_buf_append_u32(&buf, blob_handle); + tpm2_buf_append_auth(&buf, + options->policyhandle ? + options->policyhandle : TPM2_RS_PW, + NULL /* nonce */, 0, + TPM2_SA_CONTINUE_SESSION, + options->blobauth /* hmac */, + TPM_DIGEST_SIZE); + + rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing"); + if (rc > 0) + rc = -EPERM; + + if (!rc) { + data_len = be16_to_cpup( + (__be16 *) &buf.data[TPM_HEADER_SIZE + 4]); + if (data_len < MIN_KEY_SIZE || data_len > MAX_KEY_SIZE + 1) { + rc = -EFAULT; + goto out; + } + + if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 6 + data_len) { + rc = -EFAULT; + goto out; + } + data = &buf.data[TPM_HEADER_SIZE + 6]; + + memcpy(payload->key, data, data_len - 1); + payload->key_len = data_len - 1; + payload->migratable = data[data_len - 1]; + } + +out: + tpm_buf_destroy(&buf); + return rc; +} + +/** + * tpm2_unseal_trusted() - unseal the payload of a trusted key + * + * @chip: TPM chip to use + * @payload: the key data in clear and encrypted form + * @options: authentication values and other options + * + * Return: Same as with tpm_transmit_cmd. + */ +int tpm2_unseal_trusted(struct tpm_chip *chip, + struct trusted_key_payload *payload, + struct trusted_key_options *options) +{ + u32 blob_handle; + int rc; + + rc = tpm2_load_cmd(chip, payload, options, &blob_handle); + if (rc) + return rc; + + rc = tpm2_unseal_cmd(chip, payload, options, blob_handle); + tpm2_flush_context(chip, blob_handle); + return rc; +} + struct tpm2_get_cap_out { u8 more_data; __be32 subcap_id; @@ -742,6 +1037,11 @@ int tpm2_auto_startup(struct tpm_chip *chip) rc = tpm2_get_cc_attrs_tbl(chip); + if (rc) + goto out; + + rc = tpm2_sessions_init(chip); + out: if (rc > 0) rc = -ENODEV; diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c new file mode 100644 index 000000000000..7307f061e5df --- /dev/null +++ b/drivers/char/tpm/tpm2-sessions.c @@ -0,0 +1,1203 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Copyright (C) 2018 James.Bottomley@HansenPartnership.com + * + * Cryptographic helper routines for handling TPM2 sessions for + * authorization HMAC and request response encryption. + * + * The idea is to ensure that every TPM command is HMAC protected by a + * session, meaning in-flight tampering would be detected and in + * addition all sensitive inputs and responses should be encrypted. + * + * The basic way this works is to use a TPM feature called salted + * sessions where a random secret used in session construction is + * encrypted to the public part of a known TPM key. The problem is we + * have no known keys, so initially a primary Elliptic Curve key is + * derived from the NULL seed (we use EC because most TPMs generate + * these keys much faster than RSA ones). The curve used is NIST_P256 + * because that's now mandated to be present in 'TCG TPM v2.0 + * Provisioning Guidance' + * + * Threat problems: the initial TPM2_CreatePrimary is not (and cannot + * be) session protected, so a clever Man in the Middle could return a + * public key they control to this command and from there intercept + * and decode all subsequent session based transactions. The kernel + * cannot mitigate this threat but, after boot, userspace can get + * proof this has not happened by asking the TPM to certify the NULL + * key. This certification would chain back to the TPM Endorsement + * Certificate and prove the NULL seed primary had not been tampered + * with and thus all sessions must have been cryptographically secure. + * To assist with this, the initial NULL seed public key name is made + * available in a sysfs file. + * + * Use of these functions: + * + * The design is all the crypto, hash and hmac gunk is confined in this + * file and never needs to be seen even by the kernel internal user. To + * the user there's an init function tpm2_sessions_init() that needs to + * be called once per TPM which generates the NULL seed primary key. + * + * Then there are six usage functions: + * + * tpm2_start_auth_session() which allocates the opaque auth structure + * and gets a session from the TPM. This must be called before + * any of the following functions. The session is protected by a + * session_key which is derived from a random salt value + * encrypted to the NULL seed. + * tpm2_end_auth_session() kills the session and frees the resources. + * Under normal operation this function is done by + * tpm_buf_check_hmac_response(), so this is only to be used on + * error legs where the latter is not executed. + * tpm_buf_append_name() to add a handle to the buffer. This must be + * used in place of the usual tpm_buf_append_u32() for adding + * handles because handles have to be processed specially when + * calculating the HMAC. In particular, for NV, volatile and + * permanent objects you now need to provide the name. + * tpm_buf_append_hmac_session() which appends the hmac session to the + * buf in the same way tpm_buf_append_auth does(). + * tpm_buf_fill_hmac_session() This calculates the correct hash and + * places it in the buffer. It must be called after the complete + * command buffer is finalized so it can fill in the correct HMAC + * based on the parameters. + * tpm_buf_check_hmac_response() which checks the session response in + * the buffer and calculates what it should be. If there's a + * mismatch it will log a warning and return an error. If + * tpm_buf_append_hmac_session() did not specify + * TPM_SA_CONTINUE_SESSION then the session will be closed (if it + * hasn't been consumed) and the auth structure freed. + */ + +#include "tpm.h" +#include "tpm2-sessions.h" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +/* if you change to AES256, you only need change this */ +#define AES_KEYBYTES AES_KEYSIZE_128 + +#define AES_KEYBITS (AES_KEYBYTES*8) +#define AUTH_MAX_NAMES 3 + +/* + * This is the structure that carries all the auth information (like + * session handle, nonces, session key and auth) from use to use it is + * designed to be opaque to anything outside. + */ +struct tpm2_auth { + u32 handle; + /* + * This has two meanings: before tpm_buf_fill_hmac_session() + * it marks the offset in the buffer of the start of the + * sessions (i.e. after all the handles). Once the buffer has + * been filled it markes the session number of our auth + * session so we can find it again in the response buffer. + * + * The two cases are distinguished because the first offset + * must always be greater than TPM_HEADER_SIZE and the second + * must be less than or equal to 5. + */ + u32 session; + /* + * the size here is variable and set by the size of our_nonce + * which must be between 16 and the name hash length. we set + * the maximum sha256 size for the greatest protection + */ + u8 our_nonce[SHA256_DIGEST_SIZE]; + u8 tpm_nonce[SHA256_DIGEST_SIZE]; + /* + * the salt is only used across the session command/response + * after that it can be used as a scratch area + */ + union { + u8 salt[EC_PT_SZ]; + /* scratch for key + IV */ + u8 scratch[AES_KEYBYTES + AES_BLOCK_SIZE]; + }; + /* + * the session key and passphrase are the same size as the + * name digest (sha256 again). The session key is constant + * for the use of the session and the passphrase can change + * with every invocation. + * + * Note: these fields must be adjacent and in this order + * because several HMAC/KDF schemes use the combination of the + * session_key and passphrase. + */ + u8 session_key[SHA256_DIGEST_SIZE]; + u8 passphrase[SHA256_DIGEST_SIZE]; + int passphraselen; + /* saved session attributes */ + u8 attrs; + __be32 ordinal; + struct crypto_sync_skcipher *aes; + struct tpm_chip *chip; + /* 3 names of handles: name_h is handle, name is name of handle */ + u32 name_h[AUTH_MAX_NAMES]; + u8 name[AUTH_MAX_NAMES][2 + SHA256_DIGEST_SIZE]; +}; + +/* + * this is our static crypto shash. This is possible because the hash + * is multi-threaded and all the state stored in the desc + */ +static struct crypto_shash *sha256_hash; + +/* + * It turns out the crypto hmac(sha256) is hard for us to consume + * because it assumes a fixed key and the TPM seems to change the key + * on every operation, so we weld the hmac init and final functions in + * here to give it the same usage characteristics as a regular hash + */ +static void hmac_init(struct shash_desc *desc, u8 *key, int keylen) +{ + u8 pad[SHA256_BLOCK_SIZE]; + int i; + + desc->tfm = sha256_hash; + crypto_shash_init(desc); + for (i = 0; i < sizeof(pad); i++) { + if (i < keylen) + pad[i] = key[i]; + else + pad[i] = 0; + pad[i] ^= HMAC_IPAD_VALUE; + } + crypto_shash_update(desc, pad, sizeof(pad)); +} + +static void hmac_final(struct shash_desc *desc, u8 *key, int keylen, u8 *out) +{ + u8 pad[SHA256_BLOCK_SIZE]; + int i; + + for (i = 0; i < sizeof(pad); i++) { + if (i < keylen) + pad[i] = key[i]; + else + pad[i] = 0; + pad[i] ^= HMAC_OPAD_VALUE; + } + + /* collect the final hash; use out as temporary storage */ + crypto_shash_final(desc, out); + + /* reuse the desc */ + crypto_shash_init(desc); + crypto_shash_update(desc, pad, sizeof(pad)); + crypto_shash_update(desc, out, SHA256_DIGEST_SIZE); + crypto_shash_final(desc, out); +} + +/* + * assume hash sha256 and nonces u, v of size SHA256_DIGEST_SIZE but + * otherwise standard KDFa. Note output is in bytes not bits. + */ +static void KDFa(u8 *key, int keylen, const char *label, u8 *u, + u8 *v, int bytes, u8 *out) +{ + u32 counter; + const __be32 bits = cpu_to_be32(bytes * 8); + + for (counter = 1; bytes > 0; bytes -= SHA256_DIGEST_SIZE, counter++, + out += SHA256_DIGEST_SIZE) { + SHASH_DESC_ON_STACK(desc, sha256_hash); + __be32 c = cpu_to_be32(counter); + + hmac_init(desc, key, keylen); + crypto_shash_update(desc, (u8 *)&c, sizeof(c)); + crypto_shash_update(desc, label, strlen(label)+1); + crypto_shash_update(desc, u, SHA256_DIGEST_SIZE); + crypto_shash_update(desc, v, SHA256_DIGEST_SIZE); + crypto_shash_update(desc, (u8 *)&bits, sizeof(bits)); + hmac_final(desc, key, keylen, out); + } +} + +/* + * Somewhat of a bastardization of the real KDFe. We're assuming + * we're working with known point sizes for the input parameters and + * the hash algorithm is fixed at sha256. Because we know that the + * point size is 32 bytes like the hash size, there's no need to loop + * in this KDF. + */ +static void KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v, + u8 *keyout) +{ + SHASH_DESC_ON_STACK(desc, sha256_hash); + /* + * this should be an iterative counter, but because we know + * we're only taking 32 bytes for the point using a sha256 + * hash which is also 32 bytes, there's only one loop + */ + __be32 c = cpu_to_be32(1); + + desc->tfm = sha256_hash; + + crypto_shash_init(desc); + /* counter (BE) */ + crypto_shash_update(desc, (u8 *)&c, sizeof(c)); + /* secret value */ + crypto_shash_update(desc, z, EC_PT_SZ); + /* string including trailing zero */ + crypto_shash_update(desc, str, strlen(str)+1); + crypto_shash_update(desc, pt_u, EC_PT_SZ); + crypto_shash_update(desc, pt_v, EC_PT_SZ); + crypto_shash_final(desc, keyout); +} + +static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip, + struct tpm2_auth *auth) +{ + struct crypto_kpp *kpp; + struct kpp_request *req; + struct scatterlist s[2], d[1]; + struct ecdh p = {0}; + u8 encoded_key[EC_PT_SZ], *x, *y; + unsigned int buf_len; + u8 *secret; + + secret = kmalloc(EC_PT_SZ, GFP_KERNEL); + if (!secret) + return; + + p.curve_id = ECC_CURVE_NIST_P256; + + /* secret is two sized points */ + tpm_buf_append_u16(buf, (EC_PT_SZ + 2)*2); + /* + * we cheat here and append uninitialized data to form + * the points. All we care about is getting the two + * co-ordinate pointers, which will be used to overwrite + * the uninitialized data + */ + tpm_buf_append_u16(buf, EC_PT_SZ); + x = &buf->data[tpm_buf_length(buf)]; + tpm_buf_append(buf, encoded_key, EC_PT_SZ); + tpm_buf_append_u16(buf, EC_PT_SZ); + y = &buf->data[tpm_buf_length(buf)]; + tpm_buf_append(buf, encoded_key, EC_PT_SZ); + sg_init_table(s, 2); + sg_set_buf(&s[0], x, EC_PT_SZ); + sg_set_buf(&s[1], y, EC_PT_SZ); + + kpp = crypto_alloc_kpp("ecdh", CRYPTO_ALG_INTERNAL, 0); + if (IS_ERR(kpp)) { + dev_err(&chip->dev, "crypto ecdh allocation failed\n"); + return; + } + + buf_len = crypto_ecdh_key_len(&p); + if (sizeof(encoded_key) < buf_len) { + dev_err(&chip->dev, "salt buffer too small needs %d\n", + buf_len); + goto out; + } + crypto_ecdh_encode_key(encoded_key, buf_len, &p); + /* this generates a random private key */ + crypto_kpp_set_secret(kpp, encoded_key, buf_len); + + /* salt is now the public point of this private key */ + req = kpp_request_alloc(kpp, GFP_KERNEL); + if (!req) + goto out; + kpp_request_set_input(req, NULL, 0); + kpp_request_set_output(req, s, EC_PT_SZ*2); + crypto_kpp_generate_public_key(req); + /* + * we're not done: now we have to compute the shared secret + * which is our private key multiplied by the tpm_key public + * point, we actually only take the x point and discard the y + * point and feed it through KDFe to get the final secret salt + */ + sg_set_buf(&s[0], chip->ec_point_x, EC_PT_SZ); + sg_set_buf(&s[1], chip->ec_point_y, EC_PT_SZ); + kpp_request_set_input(req, s, EC_PT_SZ*2); + sg_init_one(d, secret, EC_PT_SZ); + kpp_request_set_output(req, d, EC_PT_SZ); + crypto_kpp_compute_shared_secret(req); + kpp_request_free(req); + + /* pass the shared secret through KDFe for salt */ + KDFe(secret, "SECRET", x, chip->ec_point_x, auth->salt); + out: + crypto_free_kpp(kpp); +} + +/** + * tpm_buf_append_hmac_session() append a TPM session element + * @buf: The buffer to be appended + * @auth: the auth structure allocated by tpm2_start_auth_session() + * @attributes: The session attributes + * @passphrase: The session authority (NULL if none) + * @passphraselen: The length of the session authority (0 if none) + * + * This fills in a session structure in the TPM command buffer, except + * for the HMAC which cannot be computed until the command buffer is + * complete. The type of session is controlled by the @attributes, + * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the + * session won't terminate after tpm_buf_check_hmac_response(), + * TPM2_SA_DECRYPT which means this buffers first parameter should be + * encrypted with a session key and TPM2_SA_ENCRYPT, which means the + * response buffer's first parameter needs to be decrypted (confusing, + * but the defines are written from the point of view of the TPM). + * + * Any session appended by this command must be finalized by calling + * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect + * and the TPM will reject the command. + * + * As with most tpm_buf operations, success is assumed because failure + * will be caused by an incorrect programming model and indicated by a + * kernel message. + */ +void tpm_buf_append_hmac_session(struct tpm_buf *buf, struct tpm2_auth *auth, + u8 attributes, u8 *passphrase, + int passphraselen) +{ + u8 nonce[SHA256_DIGEST_SIZE]; + u32 len; + + /* + * The Architecture Guide requires us to strip trailing zeros + * before computing the HMAC + */ + while (passphrase && passphraselen > 0 + && passphrase[passphraselen - 1] == '\0') + passphraselen--; + + auth->attrs = attributes; + auth->passphraselen = passphraselen; + if (passphraselen) + memcpy(auth->passphrase, passphrase, passphraselen); + + if (auth->session != tpm_buf_length(buf)) { + /* we're not the first session */ + len = get_unaligned_be32(&buf->data[auth->session]); + if (4 + len + auth->session != tpm_buf_length(buf)) { + WARN(1, "session length mismatch, cannot append"); + return; + } + + /* add our new session */ + len += 9 + 2 * SHA256_DIGEST_SIZE; + put_unaligned_be32(len, &buf->data[auth->session]); + } else { + tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE); + } + + /* random number for our nonce */ + get_random_bytes(nonce, sizeof(nonce)); + memcpy(auth->our_nonce, nonce, sizeof(nonce)); + tpm_buf_append_u32(buf, auth->handle); + /* our new nonce */ + tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE); + tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE); + tpm_buf_append_u8(buf, auth->attrs); + /* and put a placeholder for the hmac */ + tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE); + tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE); +} +EXPORT_SYMBOL(tpm_buf_append_hmac_session); + +/** + * tpm_buf_fill_hmac_session() - finalize the session HMAC + * @buf: The buffer to be appended + * @auth: the auth structure allocated by tpm2_start_auth_session() + * + * This command must not be called until all of the parameters have + * been appended to @buf otherwise the computed HMAC will be + * incorrect. + * + * This function computes and fills in the session HMAC using the + * session key and, if TPM2_SA_DECRYPT was specified, computes the + * encryption key and encrypts the first parameter of the command + * buffer with it. + * + * As with most tpm_buf operations, success is assumed because failure + * will be caused by an incorrect programming model and indicated by a + * kernel message. + */ +void tpm_buf_fill_hmac_session(struct tpm_buf *buf, struct tpm2_auth *auth) +{ + u32 cc, handles, val; + struct tpm_chip *chip = auth->chip; + int i; + struct tpm_header *head = (struct tpm_header *)buf->data; + const u8 *s, *p; + u8 *hmac = NULL; + u32 attrs; + u8 cphash[SHA256_DIGEST_SIZE]; + SHASH_DESC_ON_STACK(desc, sha256_hash); + + /* save the command code in BE format */ + auth->ordinal = head->ordinal; + + desc->tfm = sha256_hash; + + cc = be32_to_cpu(head->ordinal); + + i = tpm2_find_cc(chip, cc); + if (i < 0) { + dev_err(&chip->dev, "Command 0x%x not found in TPM\n", cc); + return; + } + attrs = chip->cc_attrs_tbl[i]; + + handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0); + + s = &buf->data[TPM_HEADER_SIZE]; + /* + * just check the names, it's easy to make mistakes. This + * would happen if someone added a handle via + * tpm_buf_append_u32() instead of tpm_buf_append_name() + */ + for (i = 0; i < handles; i++) { + u32 handle = tpm_get_inc_u32(&s); + + if (auth->name_h[i] != handle) { + dev_err(&chip->dev, "TPM: handle %d wrong for name\n", + i); + return; + } + } + /* point s to the start of the sessions */ + val = tpm_get_inc_u32(&s); + /* point p to the start of the parameters */ + p = s + val; + for (i = 1; s < p; i++) { + u32 handle = tpm_get_inc_u32(&s); + u16 len; + u8 a; + + /* nonce (already in auth) */ + len = tpm_get_inc_u16(&s); + s += len; + + a = *s++; + + len = tpm_get_inc_u16(&s); + if (handle == auth->handle && auth->attrs == a) { + hmac = (u8 *)s; + /* + * save our session number so we know which + * session in the response belongs to us + */ + auth->session = i; + } + + s += len; + } + if (s != p) { + dev_err(&chip->dev, "TPM session length is incorrect\n"); + return; + } + if (!hmac) { + dev_err(&chip->dev, "TPM could not find HMAC session\n"); + return; + } + + /* encrypt before HMAC */ + if (auth->attrs & TPM2_SA_DECRYPT) { + struct scatterlist sg[1]; + u16 len; + SYNC_SKCIPHER_REQUEST_ON_STACK(req, auth->aes); + DECLARE_CRYPTO_WAIT(wait); + + skcipher_request_set_sync_tfm(req, auth->aes); + skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, + crypto_req_done, &wait); + + /* need key and IV */ + KDFa(auth->session_key, SHA256_DIGEST_SIZE + + auth->passphraselen, "CFB", auth->our_nonce, + auth->tpm_nonce, AES_KEYBYTES + AES_BLOCK_SIZE, + auth->scratch); + crypto_sync_skcipher_setkey(auth->aes, auth->scratch, AES_KEYBYTES); + len = tpm_get_inc_u16(&p); + sg_init_one(sg, p, len); + skcipher_request_set_crypt(req, sg, sg, len, + auth->scratch + AES_KEYBYTES); + crypto_wait_req(crypto_skcipher_encrypt(req), &wait); + /* reset p to beginning of parameters for HMAC */ + p -= 2; + } + + crypto_shash_init(desc); + /* ordinal is already BE */ + crypto_shash_update(desc, (u8 *)&head->ordinal, sizeof(head->ordinal)); + /* add the handle names */ + for (i = 0; i < handles; i++) { + u8 mso = auth->name_h[i] >> 24; + + if (mso == 0x81 || mso == 0x80 || mso == 0x01) { + crypto_shash_update(desc, auth->name[i], + SHA256_DIGEST_SIZE + 2); + } else { + __be32 h = cpu_to_be32(auth->name_h[i]); + + crypto_shash_update(desc, (u8 *)&h, 4); + } + } + if (buf->data - s != tpm_buf_length(buf)) + crypto_shash_update(desc, s, buf->data + + tpm_buf_length(buf) - s); + crypto_shash_final(desc, cphash); + + /* now calculate the hmac */ + hmac_init(desc, auth->session_key, sizeof(auth->session_key) + + auth->passphraselen); + crypto_shash_update(desc, cphash, sizeof(cphash)); + crypto_shash_update(desc, auth->our_nonce, sizeof(auth->our_nonce)); + crypto_shash_update(desc, auth->tpm_nonce, sizeof(auth->tpm_nonce)); + crypto_shash_update(desc, &auth->attrs, 1); + hmac_final(desc, auth->session_key, sizeof(auth->session_key) + + auth->passphraselen, hmac); +} +EXPORT_SYMBOL(tpm_buf_fill_hmac_session); + +static int parse_read_public(char *name, const u8 *data) +{ + struct tpm_header *head = (struct tpm_header *)data; + u32 tot_len = be32_to_cpu(head->length); + u32 val; + + data += TPM_HEADER_SIZE; + /* we're starting after the header so adjust the length */ + tot_len -= TPM_HEADER_SIZE; + + /* skip public */ + val = tpm_get_inc_u16(&data); + if (val > tot_len) + return -EINVAL; + data += val; + /* name */ + val = tpm_get_inc_u16(&data); + if (val != SHA256_DIGEST_SIZE + 2) + return -EINVAL; + memcpy(name, data, SHA256_DIGEST_SIZE + 2); + /* forget the rest */ + return 0; +} + +static int tpm2_readpublic(struct tpm_chip *chip, u32 handle, char *name) +{ + struct tpm_buf buf; + int rc; + + rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC); + if (rc) + return rc; + + tpm_buf_append_u32(&buf, handle); + rc = tpm_transmit_cmd(chip, &buf, 0, "read public"); + if (rc == TPM2_RC_SUCCESS) + rc = parse_read_public(name, buf.data); + + tpm_buf_destroy(&buf); + + return rc; +} + +/** + * tpm_buf_append_name() - add a handle area to the buffer + * @buf: The buffer to be appended + * @auth: the auth structure allocated by tpm2_start_auth_session() + * @handle: The handle to be appended + * @name: The name of the handle (may be NULL) + * + * In order to compute session HMACs, we need to know the names of the + * objects pointed to by the handles. For most objects, this is simly + * the actual 4 byte handle or an empty buf (in these cases @name + * should be NULL) but for volatile objects, permanent objects and NV + * areas, the name is defined as the hash (according to the name + * algorithm which should be set to sha256) of the public area to + * which the two byte algorithm id has been appended. For these + * objects, the @name pointer should point to this. If a name is + * required but @name is NULL, then TPM2_ReadPublic() will be called + * on the handle to obtain the name. + * + * As with most tpm_buf operations, success is assumed because failure + * will be caused by an incorrect programming model and indicated by a + * kernel message. + */ +void tpm_buf_append_name(struct tpm_buf *buf, struct tpm2_auth *auth, + u32 handle, u8 *name) +{ + int slot; + u8 mso = handle >> 24; + + slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE)/4; + if (slot >= AUTH_MAX_NAMES) { + dev_err(&auth->chip->dev, "TPM: too many handles\n"); + return; + } + WARN(auth->session != tpm_buf_length(buf), + "name added in wrong place\n"); + tpm_buf_append_u32(buf, handle); + auth->session += 4; + + if (mso == 0x81 || mso == 0x80 || mso == 0x01) { + if (!name) + tpm2_readpublic(auth->chip, handle, auth->name[slot]); + } else { + if (name) + dev_err(&auth->chip->dev, "TPM: Handle does not require name but one is specified\n"); + } + + auth->name_h[slot] = handle; + if (name) + memcpy(auth->name[slot], name, SHA256_DIGEST_SIZE + 2); +} +EXPORT_SYMBOL(tpm_buf_append_name); + +/** + * tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness + * @buf: the original command buffer (which now contains the response) + * @auth: the auth structure allocated by tpm2_start_auth_session() + * @rc: the return code from tpm_transmit_cmd + * + * If @rc is non zero, @buf may not contain an actual return, so @rc + * is passed through as the return and the session cleaned up and + * de-allocated if required (this is required if + * TPM2_SA_CONTINUE_SESSION was not specified as a session flag). + * + * If @rc is zero, the response HMAC is computed against the returned + * @buf and matched to the TPM one in the session area. If there is a + * mismatch, an error is logged and -EINVAL returned. + * + * The reason for this is that the command issue and HMAC check + * sequence should look like: + * + * rc = tpm_transmit_cmd(...); + * rc = tpm_buf_check_hmac_response(&buf, auth, rc); + * if (rc) + * ... + * + * Which is easily layered into the current contrl flow. + * + * Returns: 0 on success or an error. + */ +int tpm_buf_check_hmac_response(struct tpm_buf *buf, struct tpm2_auth *auth, + int rc) +{ + struct tpm_header *head = (struct tpm_header *)buf->data; + struct tpm_chip *chip = auth->chip; + const u8 *s, *p; + u8 rphash[SHA256_DIGEST_SIZE]; + u32 attrs; + SHASH_DESC_ON_STACK(desc, sha256_hash); + u16 tag = be16_to_cpu(head->tag); + u32 cc = be32_to_cpu(auth->ordinal); + int parm_len, len, i, handles; + + if (auth->session >= TPM_HEADER_SIZE) { + WARN(1, "tpm session not filled correctly\n"); + goto out; + } + + if (rc != 0) + /* pass non success rc through and close the session */ + goto out; + + rc = -EINVAL; + if (tag != TPM2_ST_SESSIONS) { + dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n"); + goto out; + } + + i = tpm2_find_cc(chip, cc); + if (i < 0) + goto out; + attrs = chip->cc_attrs_tbl[i]; + handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1; + + /* point to area beyond handles */ + s = &buf->data[TPM_HEADER_SIZE + handles * 4]; + parm_len = tpm_get_inc_u32(&s); + p = s; + s += parm_len; + /* skip over any sessions before ours */ + for (i = 0; i < auth->session - 1; i++) { + len = tpm_get_inc_u16(&s); + s += len + 1; + len = tpm_get_inc_u16(&s); + s += len; + } + /* TPM nonce */ + len = tpm_get_inc_u16(&s); + if (s - buf->data + len > tpm_buf_length(buf)) + goto out; + if (len != SHA256_DIGEST_SIZE) + goto out; + memcpy(auth->tpm_nonce, s, len); + s += len; + attrs = *s++; + len = tpm_get_inc_u16(&s); + if (s - buf->data + len != tpm_buf_length(buf)) + goto out; + if (len != SHA256_DIGEST_SIZE) + goto out; + /* + * s points to the HMAC. now calculate comparison, beginning + * with rphash + */ + desc->tfm = sha256_hash; + crypto_shash_init(desc); + /* yes, I know this is now zero, but it's what the standard says */ + crypto_shash_update(desc, (u8 *)&head->return_code, + sizeof(head->return_code)); + /* ordinal is already BE */ + crypto_shash_update(desc, (u8 *)&auth->ordinal, sizeof(auth->ordinal)); + crypto_shash_update(desc, p, parm_len); + crypto_shash_final(desc, rphash); + + /* now calculate the hmac */ + hmac_init(desc, auth->session_key, sizeof(auth->session_key) + + auth->passphraselen); + crypto_shash_update(desc, rphash, sizeof(rphash)); + crypto_shash_update(desc, auth->tpm_nonce, sizeof(auth->tpm_nonce)); + crypto_shash_update(desc, auth->our_nonce, sizeof(auth->our_nonce)); + crypto_shash_update(desc, &auth->attrs, 1); + /* we're done with the rphash, so put our idea of the hmac there */ + hmac_final(desc, auth->session_key, sizeof(auth->session_key) + + auth->passphraselen, rphash); + if (memcmp(rphash, s, SHA256_DIGEST_SIZE) == 0) { + rc = 0; + } else { + dev_err(&auth->chip->dev, "TPM: HMAC check failed\n"); + goto out; + } + + /* now do response decryption */ + if (auth->attrs & TPM2_SA_ENCRYPT) { + struct scatterlist sg[1]; + SYNC_SKCIPHER_REQUEST_ON_STACK(req, auth->aes); + DECLARE_CRYPTO_WAIT(wait); + + skcipher_request_set_sync_tfm(req, auth->aes); + skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, + crypto_req_done, &wait); + + /* need key and IV */ + KDFa(auth->session_key, SHA256_DIGEST_SIZE + + auth->passphraselen, "CFB", auth->tpm_nonce, + auth->our_nonce, AES_KEYBYTES + AES_BLOCK_SIZE, + auth->scratch); + crypto_sync_skcipher_setkey(auth->aes, auth->scratch, AES_KEYBYTES); + len = tpm_get_inc_u16(&p); + sg_init_one(sg, p, len); + skcipher_request_set_crypt(req, sg, sg, len, + auth->scratch + AES_KEYBYTES); + crypto_wait_req(crypto_skcipher_decrypt(req), &wait); + } + + out: + if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) { + /* manually close the session if it wasn't consumed */ + if (rc) + tpm2_flush_context(chip, auth->handle); + crypto_free_sync_skcipher(auth->aes); + kfree(auth); + } else { + /* reset for next use */ + auth->session = TPM_HEADER_SIZE; + } + + return rc; +} +EXPORT_SYMBOL(tpm_buf_check_hmac_response); + +/** + * tpm2_end_auth_session - kill the allocated auth session + * @auth: the auth structure allocated by tpm2_start_auth_session() + * + * ends the session started by tpm2_start_auth_session and frees all + * the resources. Under normal conditions, + * tpm_buf_check_hmac_response() will correctly end the session if + * required, so this function is only for use in error legs that will + * bypass the normal invocation of tpm_buf_check_hmac_respons(). + */ +void tpm2_end_auth_session(struct tpm2_auth *auth) +{ + tpm2_flush_context(auth->chip, auth->handle); + crypto_free_sync_skcipher(auth->aes); + kfree(auth); +} +EXPORT_SYMBOL(tpm2_end_auth_session); + +static int parse_start_auth_session(struct tpm2_auth *auth, const u8 *data) +{ + struct tpm_header *head = (struct tpm_header *)data; + u32 tot_len = be32_to_cpu(head->length); + u32 val; + + data += TPM_HEADER_SIZE; + /* we're starting after the header so adjust the length */ + tot_len -= TPM_HEADER_SIZE; + + /* should have handle plus nonce */ + if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce)) + return -EINVAL; + + auth->handle = tpm_get_inc_u32(&data); + val = tpm_get_inc_u16(&data); + if (val != sizeof(auth->tpm_nonce)) + return -EINVAL; + memcpy(auth->tpm_nonce, data, sizeof(auth->tpm_nonce)); + /* now compute the session key from the nonces */ + KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce, + auth->our_nonce, sizeof(auth->session_key), auth->session_key); + + return 0; +} + +/** + * tpm2_start_auth_session - create a HMAC authentication session with the TPM + * @chip: the TPM chip structure to create the session with + * @authp: A pointer to an opaque tpm2_auth structure to be allocated + * + * This function loads the NULL seed from its saved context and starts + * an authentication session on the null seed, allocates a tpm2_auth + * structure to contain all the session details necessary for + * performing the HMAC, encrypt and decrypt operations, fills it in + * and returns. The NULL seed is flushed before this function returns. + * + * Return: zero on success or actual error encountered. If return is + * zero, @authp will be allocated. + */ +int tpm2_start_auth_session(struct tpm_chip *chip, struct tpm2_auth **authp) +{ + struct tpm_buf buf; + struct tpm2_auth *auth; + int rc; + unsigned int offset = 0; /* dummy offset for null seed context */ + u32 nullkey; + + auth = kmalloc(sizeof(**authp), GFP_KERNEL); + if (!auth) + return -ENOMEM; + + rc = tpm2_load_context(chip, chip->tpmkeycontext, &offset, + &nullkey); + if (rc) + return rc; + + auth->chip = chip; + auth->session = TPM_HEADER_SIZE; + + rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS); + if (rc) + goto out; + + /* salt key handle */ + tpm_buf_append_u32(&buf, nullkey); + /* bind key handle */ + tpm_buf_append_u32(&buf, TPM2_RH_NULL); + /* nonce caller */ + get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce)); + tpm_buf_append_u16(&buf, sizeof(auth->our_nonce)); + tpm_buf_append(&buf, auth->our_nonce, sizeof(auth->our_nonce)); + + /* append encrypted salt and squirrel away unencrypted in auth */ + tpm_buf_append_salt(&buf, chip, auth); + /* session type (HMAC, audit or policy) */ + tpm_buf_append_u8(&buf, TPM2_SE_HMAC); + + /* symmetric encryption parameters */ + /* symmetric algorithm */ + tpm_buf_append_u16(&buf, TPM_ALG_AES); + /* bits for symmetric algorithm */ + tpm_buf_append_u16(&buf, AES_KEYBITS); + /* symmetric algorithm mode (must be CFB) */ + tpm_buf_append_u16(&buf, TPM_ALG_CFB); + /* hash algorithm for session */ + tpm_buf_append_u16(&buf, TPM_ALG_SHA256); + + rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session"); + tpm2_flush_context(chip, nullkey); + + if (rc == TPM2_RC_SUCCESS) + rc = parse_start_auth_session(auth, buf.data); + + tpm_buf_destroy(&buf); + + if (rc) + goto out; + + auth->aes = crypto_alloc_sync_skcipher("cfb(aes)", 0, 0); + if (IS_ERR(auth->aes)) { + rc = PTR_ERR(auth->aes); + dev_err(&chip->dev, "TPM: error getting cfb(aes): %d\n", rc); + } + out: + if (rc) + kfree(auth); + else + *authp = auth; + + return rc; +} +EXPORT_SYMBOL(tpm2_start_auth_session); + +static int parse_create_primary(struct tpm_chip *chip, u8 *data, u32 *nullkey) +{ + struct tpm_header *head = (struct tpm_header *)data; + u16 len; + u32 tot_len = be32_to_cpu(head->length); + u32 val, parm_len; + const u8 *resp, *tmp; + SHASH_DESC_ON_STACK(desc, sha256_hash); + + data += TPM_HEADER_SIZE; + /* we're starting after the header so adjust the length */ + tot_len -= TPM_HEADER_SIZE; + + resp = data; + *nullkey = tpm_get_inc_u32(&resp); + parm_len = tpm_get_inc_u32(&resp); + if (parm_len + 8 > tot_len) + return -EINVAL; + len = tpm_get_inc_u16(&resp); + tmp = resp; + /* now we have the public area, compute the name of the object */ + desc->tfm = sha256_hash; + put_unaligned_be16(TPM_ALG_SHA256, chip->tpmkeyname); + crypto_shash_init(desc); + crypto_shash_update(desc, resp, len); + crypto_shash_final(desc, chip->tpmkeyname + 2); + /* validate the public key */ + val = tpm_get_inc_u16(&tmp); + /* key type (must be what we asked for) */ + if (val != TPM_ALG_ECC) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* name algorithm */ + if (val != TPM_ALG_SHA256) + return -EINVAL; + val = tpm_get_inc_u32(&tmp); + /* object properties */ + if (val != (TPM2_OA_NO_DA | + TPM2_OA_FIXED_TPM | + TPM2_OA_FIXED_PARENT | + TPM2_OA_SENSITIVE_DATA_ORIGIN | + TPM2_OA_USER_WITH_AUTH | + TPM2_OA_DECRYPT | + TPM2_OA_RESTRICTED)) + return -EINVAL; + /* auth policy (empty) */ + val = tpm_get_inc_u16(&tmp); + if (val != 0) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* symmetric key parameters */ + if (val != TPM_ALG_AES) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* symmetric key length */ + if (val != AES_KEYBITS) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* symmetric encryption scheme */ + if (val != TPM_ALG_CFB) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* signing scheme */ + if (val != TPM_ALG_NULL) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* ECC Curve */ + if (val != TPM2_ECC_NIST_P256) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* KDF Scheme */ + if (val != TPM_ALG_NULL) + return -EINVAL; + val = tpm_get_inc_u16(&tmp); + /* x point */ + if (val != 32) + return -EINVAL; + memcpy(chip->ec_point_x, tmp, val); + tmp += val; + val = tpm_get_inc_u16(&tmp); + if (val != 32) + return -EINVAL; + memcpy(chip->ec_point_y, tmp, val); + tmp += val; + resp += len; + /* should have exactly consumed the tpm2b public structure */ + if (tmp != resp) + return -EINVAL; + if (resp - data > parm_len) + return -EINVAL; + /* creation data (skip) */ + len = tpm_get_inc_u16(&resp); + resp += len; + if (resp - data > parm_len) + return -EINVAL; + /* creation digest (must be sha256) */ + len = tpm_get_inc_u16(&resp); + resp += len; + if (len != SHA256_DIGEST_SIZE || resp - data > parm_len) + return -EINVAL; + /* TPMT_TK_CREATION follows */ + /* tag, must be TPM_ST_CREATION (0x8021) */ + val = tpm_get_inc_u16(&resp); + if (val != TPM2_ST_CREATION || resp - data > parm_len) + return -EINVAL; + /* hierarchy (must be NULL) */ + val = tpm_get_inc_u32(&resp); + if (val != TPM2_RH_NULL || resp - data > parm_len) + return -EINVAL; + /* the ticket digest HMAC (might not be sha256) */ + len = tpm_get_inc_u16(&resp); + resp += len; + if (resp - data > parm_len) + return -EINVAL; + /* + * finally we have the name, which is a sha256 digest plus a 2 + * byte algorithm type + */ + len = tpm_get_inc_u16(&resp); + if (resp + len - data != parm_len + 8) + return -EINVAL; + if (len != SHA256_DIGEST_SIZE + 2) + return -EINVAL; + + if (memcmp(chip->tpmkeyname, resp, SHA256_DIGEST_SIZE + 2) != 0) { + printk("TPM NULL Seed name comparison failed\n"); + return -EINVAL; + } + + return 0; +} + +static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy, u32 *handle) +{ + int rc; + struct tpm_buf buf; + struct tpm_buf template; + + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY); + if (rc) + return rc; + + rc = tpm_buf_init_2b(&template); + if (rc) { + tpm_buf_destroy(&buf); + return rc; + } + + /* + * create the template. Note: in order for userspace to + * verify the security of the system, it will have to create + * and certify this NULL primary, meaning all the template + * parameters will have to be identical, so conform exactly to + * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC + * key + */ + + /* key type */ + tpm_buf_append_u16(&template, TPM_ALG_ECC); + /* name algorithm */ + tpm_buf_append_u16(&template, TPM_ALG_SHA256); + /* object properties */ + tpm_buf_append_u32(&template, TPM2_OA_NO_DA | + TPM2_OA_FIXED_TPM | + TPM2_OA_FIXED_PARENT | + TPM2_OA_SENSITIVE_DATA_ORIGIN | + TPM2_OA_USER_WITH_AUTH | + TPM2_OA_DECRYPT | + TPM2_OA_RESTRICTED); + /* sauth policy (empty) */ + tpm_buf_append_u16(&template, 0); + + /* BEGIN parameters: key specific; for ECC*/ + /* symmetric algorithm */ + tpm_buf_append_u16(&template, TPM_ALG_AES); + /* bits for symmetric algorithm */ + tpm_buf_append_u16(&template, 128); + /* algorithm mode (must be CFB) */ + tpm_buf_append_u16(&template, TPM_ALG_CFB); + /* scheme (NULL means any scheme) */ + tpm_buf_append_u16(&template, TPM_ALG_NULL); + /* ECC Curve ID */ + tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256); + /* KDF Scheme */ + tpm_buf_append_u16(&template, TPM_ALG_NULL); + /* unique: key specific; for ECC it is two points */ + tpm_buf_append_u16(&template, 0); + tpm_buf_append_u16(&template, 0); + /* END parameters */ + + /* primary handle */ + tpm_buf_append_u32(&buf, hierarchy); + /* simple authorization for empty auth */ + tpm2_buf_append_auth(&buf, TPM2_RS_PW, NULL, 0, 0, NULL, 0); + /* sensitive create size is 4 for two empty buffers */ + tpm_buf_append_u16(&buf, 4); + /* sensitive create auth data (empty) */ + tpm_buf_append_u16(&buf, 0); + /* sensitive create sensitive data (empty) */ + tpm_buf_append_u16(&buf, 0); + /* the public template */ + tpm_buf_append_2b(&buf, &template); + tpm_buf_destroy(&template); + /* outside info (empty) */ + tpm_buf_append_u16(&buf, 0); + /* creation PCR (none) */ + tpm_buf_append_u32(&buf, 0); + + rc = tpm_transmit_cmd(chip, &buf, 0, + "attempting to create NULL primary"); + + if (rc == TPM2_RC_SUCCESS) + rc = parse_create_primary(chip, buf.data, handle); + + tpm_buf_destroy(&buf); + + return rc; +} + +int tpm2_create_null_primary(struct tpm_chip *chip) { + u32 nullkey; + int rc; + + rc = tpm2_create_primary(chip, TPM2_RH_NULL, &nullkey); + + if (rc == TPM2_RC_SUCCESS) { + unsigned int offset = 0; /* dummy offset for tpmkeycontext */ + + rc = tpm2_save_context(chip, nullkey, chip->tpmkeycontext, + sizeof(chip->tpmkeycontext), &offset); + tpm2_flush_context(chip, nullkey); + } + + return rc; +} + +int tpm2_sessions_init(struct tpm_chip *chip) +{ + int rc; + + sha256_hash = crypto_alloc_shash("sha256", 0, 0); + if (!sha256_hash) { + dev_err(&chip->dev, "TPM: failed to allocate hash\n"); + return -ENOMEM; + } + + rc = tpm2_create_null_primary(chip); + if (rc) + dev_err(&chip->dev, "TPM: security failed (NULL seed derivation): %d\n", rc); + return rc; +} +EXPORT_SYMBOL(tpm2_sessions_init); diff --git a/drivers/char/tpm/tpm2-sessions.h b/drivers/char/tpm/tpm2-sessions.h new file mode 100644 index 000000000000..5b5ce07c0346 --- /dev/null +++ b/drivers/char/tpm/tpm2-sessions.h @@ -0,0 +1,114 @@ +/* + * Defines for TPM2 authentications + */ + +#ifndef _TPM2_SESSIONS_H +#define _TPM2_SESSIONS_H + +#include "tpm.h" + +enum tpm2_session_types { + TPM2_SE_HMAC = 0x00, + TPM2_SE_POLICY = 0x01, + TPM2_SE_TRIAL = 0x02, +}; + +struct tpm2_auth; + +void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle, + const u8 *nonce, u16 nonce_len, + u8 attributes, + const u8 *hmac, u16 hmac_len); + +#ifdef CONFIG_TPM_BUS_SECURITY + +int tpm2_start_auth_session(struct tpm_chip *chip, struct tpm2_auth **authp); +void tpm_buf_append_name(struct tpm_buf *buf, struct tpm2_auth *auth, + u32 handle, u8 *name); +void tpm_buf_append_hmac_session(struct tpm_buf *buf, struct tpm2_auth *auth, + u8 attributes, u8 *passphrase, + int passphraselen); +static inline void tpm_buf_append_hmac_session_opt(struct tpm_buf *buf, + struct tpm2_auth *auth, + u8 attributes, + u8 *passphrase, + int passphraselen) +{ + tpm_buf_append_hmac_session(buf, auth, attributes, passphrase, + passphraselen); +} +void tpm_buf_fill_hmac_session(struct tpm_buf *buf, struct tpm2_auth *auth); +int tpm_buf_check_hmac_response(struct tpm_buf *buf, struct tpm2_auth *auth, + int rc); +void tpm2_end_auth_session(struct tpm2_auth *auth); +#else +#include + +static inline int tpm2_start_auth_session(struct tpm_chip *chip, + struct tpm2_auth **authp) +{ + return 0; +} +static inline void tpm2_end_auth_session(struct tpm2_auth *auth) +{ +} +static inline void tpm_buf_append_name(struct tpm_buf *buf, + struct tpm2_auth *auth, + u32 handle, u8 *name) +{ + tpm_buf_append_u32(buf, handle); + /* count the number of handles in the upper bits of flags */ + buf->handles++; +} +static inline void tpm_buf_append_hmac_session(struct tpm_buf *buf, + struct tpm2_auth *auth, + u8 attributes, u8 *passphrase, + int passphraselen) +{ + /* offset tells us where the sessions area begins */ + int offset = buf->handles * 4 + TPM_HEADER_SIZE; + u32 len = 9 + passphraselen; + if (tpm_buf_length(buf) != offset) { + /* not the first session so update the existing length */ + len += get_unaligned_be32(&buf->data[offset]); + put_unaligned_be32(len, &buf->data[offset]); + } else { + tpm_buf_append_u32(buf, len); + } + /* auth handle */ + tpm_buf_append_u32(buf, TPM2_RS_PW); + /* nonce */ + tpm_buf_append_u16(buf, 0); + /* attributes */ + tpm_buf_append_u8(buf, 0); + /* passphrase */ + tpm_buf_append_u16(buf, passphraselen); + tpm_buf_append(buf, passphrase, passphraselen); +} +static inline void tpm_buf_append_hmac_session_opt(struct tpm_buf *buf, + struct tpm2_auth *auth, + u8 attributes, + u8 *passphrase, + int passphraselen) +{ + int offset = buf->handles * 4 + TPM_HEADER_SIZE; + struct tpm_header *head = (struct tpm_header *) buf->data; + + /* if the only sessions are optional, the command tag + * must change to TPM2_ST_NO_SESSIONS */ + if (tpm_buf_length(buf) == offset) + head->tag = cpu_to_be16(TPM2_ST_NO_SESSIONS); +} +static inline void tpm_buf_fill_hmac_session(struct tpm_buf *buf, + struct tpm2_auth *auth) +{ +} +static inline int tpm_buf_check_hmac_response(struct tpm_buf *buf, + struct tpm2_auth *auth, + int rc) +{ + return rc; +} +#endif /* CONFIG_TPM_BUS_SECURITY */ + +#endif diff --git a/include/linux/tpm.h b/include/linux/tpm.h index 893aa87ea211..52bfb673ab48 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -34,14 +34,23 @@ struct trusted_key_options; enum tpm_algorithms { TPM_ALG_ERROR = 0x0000, TPM_ALG_SHA1 = 0x0004, + TPM_ALG_AES = 0x0006, TPM_ALG_KEYEDHASH = 0x0008, TPM_ALG_SHA256 = 0x000B, TPM_ALG_SHA384 = 0x000C, TPM_ALG_SHA512 = 0x000D, TPM_ALG_NULL = 0x0010, TPM_ALG_SM3_256 = 0x0012, + TPM_ALG_ECC = 0x0023, + TPM_ALG_CFB = 0x0043, }; +enum tpm2_curves { + TPM2_ECC_NONE = 0x0000, + TPM2_ECC_NIST_P256 = 0x0003, +}; + + struct tpm_digest { u16 alg_id; u8 digest[TPM_MAX_DIGEST_SIZE]; @@ -108,6 +117,20 @@ struct tpm_chip_seqops { const struct seq_operations *seqops; }; +/* fixed define for the curve we use which is NIST_P256 */ +#define EC_PT_SZ 32 + +/* + * fixed define for the size of a name. This is actually HASHALG size + * plus 2, so 32 for SHA256 + */ +#define TPM2_NAME_SIZE 34 + +/* + * The maximum size for an object context + */ +#define TPM2_MAX_CONTEXT_SIZE 2048 + struct tpm_chip { struct device dev; struct device devs; @@ -162,6 +185,12 @@ struct tpm_chip { /* active locality */ int locality; + + /* details for communication security via sessions */ + u8 tpmkeycontext[TPM2_MAX_CONTEXT_SIZE]; /* context for NULL seed */ + u8 tpmkeyname[TPM2_NAME_SIZE]; /* name of NULL seed */ + u8 ec_point_x[EC_PT_SZ]; + u8 ec_point_y[EC_PT_SZ]; }; #define TPM_HEADER_SIZE 10 @@ -186,6 +215,7 @@ enum tpm2_timeouts { enum tpm2_structures { TPM2_ST_NO_SESSIONS = 0x8001, TPM2_ST_SESSIONS = 0x8002, + TPM2_ST_CREATION = 0x8021, }; /* Indicates from what layer of the software stack the error comes from */ @@ -222,6 +252,8 @@ enum tpm2_command_codes { TPM2_CC_CONTEXT_LOAD = 0x0161, TPM2_CC_CONTEXT_SAVE = 0x0162, TPM2_CC_FLUSH_CONTEXT = 0x0165, + TPM2_CC_READ_PUBLIC = 0x0173, + TPM2_CC_START_AUTH_SESS = 0x0176, TPM2_CC_VERIFY_SIGNATURE = 0x0177, TPM2_CC_GET_CAPABILITY = 0x017A, TPM2_CC_GET_RANDOM = 0x017B, @@ -234,6 +266,7 @@ enum tpm2_command_codes { }; enum tpm2_permanent_handles { + TPM2_RH_NULL = 0x40000007, TPM2_RS_PW = 0x40000009, }; @@ -295,15 +328,31 @@ enum tpm_buf_flags { struct tpm_buf { struct page *data_page; unsigned int flags; + u8 handles; u8 *data; }; enum tpm2_object_attributes { + TPM2_OA_FIXED_TPM = BIT(1), + TPM2_OA_ST_CLEAR = BIT(2), + TPM2_OA_FIXED_PARENT = BIT(4), + TPM2_OA_SENSITIVE_DATA_ORIGIN = BIT(5), TPM2_OA_USER_WITH_AUTH = BIT(6), + TPM2_OA_ADMIN_WITH_POLICY = BIT(7), + TPM2_OA_NO_DA = BIT(10), + TPM2_OA_ENCRYPTED_DUPLICATION = BIT(11), + TPM2_OA_RESTRICTED = BIT(16), + TPM2_OA_DECRYPT = BIT(17), + TPM2_OA_SIGN = BIT(18), }; enum tpm2_session_attributes { TPM2_SA_CONTINUE_SESSION = BIT(0), + TPM2_SA_AUDIT_EXCLUSIVE = BIT(1), + TPM2_SA_AUDIT_RESET = BIT(3), + TPM2_SA_DECRYPT = BIT(5), + TPM2_SA_ENCRYPT = BIT(6), + TPM2_SA_AUDIT = BIT(7), }; struct tpm2_hash { From patchwork Mon May 18 17:26:53 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555905 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id D63DD912 for ; Mon, 18 May 2020 17:27:20 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id BF50820715 for ; Mon, 18 May 2020 17:27:20 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="IQc7pV3n" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728304AbgERR1U (ORCPT ); Mon, 18 May 2020 13:27:20 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57512 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1727782AbgERR1T (ORCPT ); Mon, 18 May 2020 13:27:19 -0400 Received: from mail-pf1-x441.google.com (mail-pf1-x441.google.com [IPv6:2607:f8b0:4864:20::441]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 7D58DC061A0C for ; Mon, 18 May 2020 10:27:18 -0700 (PDT) Received: by mail-pf1-x441.google.com with SMTP id y198so3679072pfb.4 for ; Mon, 18 May 2020 10:27:18 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=XNkq9XCLnKcT4GfqnEEcwE3/rzXf2A2KNTBDzaCFtpU=; b=IQc7pV3ng61KdGtLYe6PpKyEPhKT3jX7qIpx4T/PYAreFzClp5obtq52IirIKBdejz rG9e7DoYyx3doiaESROvvxGIpzEq+UYSJu06lrN7jPvX3NG5E6Znf7zf9cftB3kA5cQI NYjMFP0LlmHejpAnlmVN/oPcMEDtgXH5UWzhybBzqMPTOgNpvbPVt/TUiCDtZ/p9GJhz Tx0H2FyXIxrSyxUmp0xmUuULa4YCmJmid7/BcAw6Rfy5wpVKzdWVLE8Z1pdpNZKCf3gO sB3M8d25NdkjvWLFfQ3G4UiW5xs0+uxAw9Jgxs60uCpF5lR6m/5A9+mboon0K4z9ZLqC UE9w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=XNkq9XCLnKcT4GfqnEEcwE3/rzXf2A2KNTBDzaCFtpU=; b=Ae19kbzQMOrKV8pdW/dcPLKxOLA62LmcWl270MfLQ3Y0uqjzaEeUkAWJs3PrUrhg8G OVbvNGnvwC5JV9XA4Tst0tOjjiYqBDUBanRlcPGSV3dDEAjb3BZ3uBXieOeayUnTH67G Q4uB85/be+C6XNri5cyUJHu0UKFipJUMQcAXdVhgJmQ2alerdqCV6PAANtvGt9WGIv5k t2niJ7L8LyfJU3qr4uD1/RPB/hJeMBkoJcPavWWOUhtehQ/g4h9WUdtwHixevZqLCJ9E ga6wic4KeYO9k8NLZDcH4kqG8dzIDADs+spY+u5bRDrsIgeKbNX1+yY+3drFXVF4zM80 67Gw== X-Gm-Message-State: AOAM532ZAqBwQhXL4QWuJDdtcija5ApaBqy4HG9/4HXyREEYBoEGOOWC luOA24d/8JdhcRPc1vSYhLPLt1Vmdj0= X-Google-Smtp-Source: ABdhPJwSgVC12gsnpA0p/Hr8h1UZKr4zYM+TtQIohpp2wVyDSre7Ku66GsfRg/1BgOCiMrVQR0IVrQ== X-Received: by 2002:a62:3303:: with SMTP id z3mr16741261pfz.88.1589822837797; Mon, 18 May 2020 10:27:17 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.16 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:17 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 06/17] tpm-buf: add tpm_buf_parameters() Date: Mon, 18 May 2020 10:26:53 -0700 Message-Id: <20200518172704.29608-7-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley Introducing encryption sessions changes where the return parameters are located in the buffer because if a return session is present they're 4 bytes beyond the header with those 4 bytes showing the parameter length. If there is no return session, then they're in the usual place immediately after the header. The tpm_buf_parameters() encapsulates this calculation and should be used everywhere &buf.data[TPM_HEADER_SIZE] is used now Signed-off-by: James Bottomley --- drivers/char/tpm/tpm-buf.c | 10 ++++++++++ drivers/char/tpm/tpm.h | 2 ++ 2 files changed, 12 insertions(+) diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c index f56350123a08..a5d793d8180d 100644 --- a/drivers/char/tpm/tpm-buf.c +++ b/drivers/char/tpm/tpm-buf.c @@ -190,3 +190,13 @@ u32 tpm_get_inc_u32(const u8 **ptr) return val; } EXPORT_SYMBOL_GPL(tpm_get_inc_u32); + +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/tpm.h b/drivers/char/tpm/tpm.h index a1959675a889..ade4af4d52ca 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -169,6 +169,8 @@ u8 tpm_get_inc_u8(const u8 **ptr); u16 tpm_get_inc_u16(const u8 **ptr); u32 tpm_get_inc_u32(const u8 **ptr); +u8 *tpm_buf_parameters(struct tpm_buf *buf); + /* opaque structure, holds auth session parameters like the session key */ struct tpm2_auth; From patchwork Mon May 18 17:26:54 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555907 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 0D0D314C0 for ; Mon, 18 May 2020 17:27:21 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id EA6E720715 for ; Mon, 18 May 2020 17:27:20 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="X9Bea00Q" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1727782AbgERR1U (ORCPT ); Mon, 18 May 2020 13:27:20 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57522 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1727942AbgERR1T (ORCPT ); Mon, 18 May 2020 13:27:19 -0400 Received: from mail-pg1-x541.google.com (mail-pg1-x541.google.com [IPv6:2607:f8b0:4864:20::541]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id AEDC4C05BD0A for ; Mon, 18 May 2020 10:27:19 -0700 (PDT) Received: by mail-pg1-x541.google.com with SMTP id f4so5134888pgi.10 for ; Mon, 18 May 2020 10:27:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=4i0uveCBnjeaPDKYn8Io6J23oMvZPVtv6Zah/nzES1c=; b=X9Bea00QsDEBP3ZK9YxM0YuiRMQFSKJg8+Sb8gg05P/Tnmu9vU5sOLxfTCvBKJMu6R 0AnIv40M/aO/DWkIYCLtkxcbD+eGxJis3Lo9+QmcZzvL4VavYDqDZlz9GkVizknAVxkd B0JxzPZLehEukv3/STQzdycl9MHqCzmwtlCN0k27jxeU/nY7eFB/6Yhi8aXB+ncuctpK 3ZYF5GhTUQQrxuXVIHhHqqGS8uxUukQ9Rk26emaA5no0g8gq3ePB39c65ANGrHJ1KV1s Bu1pWoQ+vSlBmZfXVL18R6GdlIDE6/lkf1TNwxvfHyJADXnrzU2PQ4m5fAJ2UCa5VRLk 9cXw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=4i0uveCBnjeaPDKYn8Io6J23oMvZPVtv6Zah/nzES1c=; b=E/s3L7MTH6lGWIGoEOwUZLGnWioBSZBj/8a+q+crrnLE4IawWl6YVjD/7DlU3PyWfZ yvO5L1AOCyTogW7nn5ECpsuxRyD4kV9GTFiH/+9Hraf7KYCFYYTjEFmsOcWw9YD8AWGH haboj2OiRd1bDf8YtjkxMjvc3KKeqjwlxJf/hHigEjuT3qZNbBPvBEzVcWs+xH+sZk3R DOIaQK6ixFgqm6KP0A4PGzOteO530s/0/NALWgYD2YVk9gdld5IJ8hJI8mbNJiSV1Mfk ik84FBKmCw/uRn91xngvPyhCBgdJHUxNjIxhMvrCc/PFuQTss7uDJPIjCLp9QskpQ3ai u5YA== X-Gm-Message-State: AOAM531ppdgXJj9M/H+z9Ew28ItIxVPg4BLNVWBA4y6oTIBoLjS+gV/m e0EnMrtnwjhiV3ermOH24b3f7GphCps= X-Google-Smtp-Source: ABdhPJwAodeSciIDbXJogkgPb5O+ayBTb1w5qrjI6v3q65j278rtKNgR8Dg+/rdxFaZPB+aynOxT+A== X-Received: by 2002:a63:b649:: with SMTP id v9mr14426139pgt.402.1589822838909; Mon, 18 May 2020 10:27:18 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.17 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:18 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 07/17] tpm2: add hmac checks to tpm2_pcr_extend() Date: Mon, 18 May 2020 10:26:54 -0700 Message-Id: <20200518172704.29608-8-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley We use tpm2_pcr_extend() in trusted keys to extend a PCR to prevent a key from being re-loaded until the next reboot. To use this functionality securely, that extend must be protected by a session hmac. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm2-cmd.c | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c index 8d076c6752eb..b29824ae237c 100644 --- a/drivers/char/tpm/tpm2-cmd.c +++ b/drivers/char/tpm/tpm2-cmd.c @@ -218,13 +218,6 @@ int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx, return rc; } -struct tpm2_null_auth_area { - __be32 handle; - __be16 nonce_size; - u8 attributes; - __be16 auth_size; -} __packed; - /** * tpm2_pcr_extend() - extend a PCR value * @@ -238,24 +231,23 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx, struct tpm_digest *digests) { struct tpm_buf buf; - struct tpm2_null_auth_area auth_area; + struct tpm2_auth *auth; int rc; int i; - rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND); + rc = tpm2_start_auth_session(chip, &auth); if (rc) return rc; - tpm_buf_append_u32(&buf, pcr_idx); + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND); + if (rc) { + tpm2_end_auth_session(auth); + return rc; + } - auth_area.handle = cpu_to_be32(TPM2_RS_PW); - auth_area.nonce_size = 0; - auth_area.attributes = 0; - auth_area.auth_size = 0; + tpm_buf_append_name(&buf, auth, pcr_idx, NULL); + tpm_buf_append_hmac_session(&buf, auth, 0, NULL, 0); - tpm_buf_append_u32(&buf, sizeof(struct tpm2_null_auth_area)); - tpm_buf_append(&buf, (const unsigned char *)&auth_area, - sizeof(auth_area)); tpm_buf_append_u32(&buf, chip->nr_allocated_banks); for (i = 0; i < chip->nr_allocated_banks; i++) { @@ -264,7 +256,9 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx, chip->allocated_banks[i].digest_size); } + tpm_buf_fill_hmac_session(&buf, auth); rc = tpm_transmit_cmd(chip, &buf, 0, "attempting extend a PCR value"); + rc = tpm_buf_check_hmac_response(&buf, auth, rc); tpm_buf_destroy(&buf); From patchwork Mon May 18 17:26:55 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555911 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 2EBCD912 for ; Mon, 18 May 2020 17:27:22 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 17DB620715 for ; Mon, 18 May 2020 17:27:22 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="VDKJcCnX" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728419AbgERR1V (ORCPT ); Mon, 18 May 2020 13:27:21 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57524 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728152AbgERR1V (ORCPT ); Mon, 18 May 2020 13:27:21 -0400 Received: from mail-pg1-x543.google.com (mail-pg1-x543.google.com [IPv6:2607:f8b0:4864:20::543]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 8EE00C061A0C for ; Mon, 18 May 2020 10:27:20 -0700 (PDT) Received: by mail-pg1-x543.google.com with SMTP id j21so5135210pgb.7 for ; Mon, 18 May 2020 10:27:20 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=t+Gs3wCV8z5Hp58qeN8HPrkHmrOrSWXxOkrLszNZdaU=; b=VDKJcCnX5bm1p6sc/y6MalJ8GIbzohkX5+C5JE3Ty51LGVgO/5d6X4inAm0dAXqS0N XldsqzskillnuUoM9WISomccMJAIcn+CJtcQpFxJFKcLQq5HWdnm4gr/JoS3vnUhl4pF i8/irQZrMEpAUHRnpjpyuJNDdSLskJnpkkHgcIbpPe6pSa2ZdAV+PMb1YWtx+syigPpT 3h/oYBLAuDa5TPh5wLQtXjX/4eYLvt1w4rgmNF9bdhlX2mZe5rvh1+sTGcTmmcr7SRTS 4QWL3aGJGVCqfYEHEh+fdIuSvG5n+4jFUEYc7UfC9nIl1mU4EpbZG+bYd6J7RxDxTrKR Wigg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=t+Gs3wCV8z5Hp58qeN8HPrkHmrOrSWXxOkrLszNZdaU=; b=iXCjYN/17AZ+BpM1D+S1wmt2MdNf4yGKh1NT/bTtY6xQo0k6QVNSNfx/LOP8NhAwek M9TNyaK3tXwJ1XTlx0HtkUf9teXXjviFcoo0AaVgbtJcxkOr03HKHaG+peYsYRl+030S YzDKr6ehS7hKYcL04jyz9TXtbX74SuU3hhvhcpSs6a7vVZijzZZAbLkNFppDgxP9KZyU 7193vErwgCKoIyOAjdiNF57nbLu9AZMOOYHaTW4VE67pgcRGWun6ytce1c2MOWCBRI+a f/Hy/wqGkEllHOZR+MHKDSlCdKG9hEhxecEPs327EQ7D66j63UaSTDvOXgBIqOdjMgpy 1qqA== X-Gm-Message-State: AOAM532E/47HojgVyUFLOGtLAq1WZM3+LyrL4gtyhyvkq36++pA/bIok 3iv20NtvKwVZjxrcAS0yOzKA99wt1VA= X-Google-Smtp-Source: ABdhPJzmYIICT+7IlNQamSAlG8aLp2PsRG0gmUQzl6CzfgIEhlbOkmuo8p/4+Nl37uFNWLXOvocC0g== X-Received: by 2002:a63:cf03:: with SMTP id j3mr15610548pgg.24.1589822839915; Mon, 18 May 2020 10:27:19 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.19 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:19 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 08/17] tpm2: add session encryption protection to tpm2_get_random() Date: Mon, 18 May 2020 10:26:55 -0700 Message-Id: <20200518172704.29608-9-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley If some entity is snooping the TPM bus, they can see the random numbers we're extracting from the TPM and do prediction attacks against their consumers. Foil this attack by using response encryption to prevent the attacker from seeing the random sequence. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm2-cmd.c | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c index b29824ae237c..92e381bfd7c8 100644 --- a/drivers/char/tpm/tpm2-cmd.c +++ b/drivers/char/tpm/tpm2-cmd.c @@ -291,29 +291,40 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max) int total = 0; int retries = 5; u8 *dest_ptr = dest; + struct tpm2_auth *auth; if (!num_bytes || max > TPM_MAX_RNG_DATA) return -EINVAL; - err = tpm_buf_init(&buf, 0, 0); + err = tpm2_start_auth_session(chip, &auth); if (err) return err; + err = tpm_buf_init(&buf, 0, 0); + if (err) { + tpm2_end_auth_session(auth); + return err; + } + do { - tpm_buf_reset(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_RANDOM); + tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_GET_RANDOM); + tpm_buf_append_hmac_session_opt(&buf, auth, TPM2_SA_ENCRYPT + | TPM2_SA_CONTINUE_SESSION, + NULL, 0); tpm_buf_append_u16(&buf, num_bytes); + tpm_buf_fill_hmac_session(&buf, auth); err = tpm_transmit_cmd(chip, &buf, offsetof(struct tpm2_get_random_out, buffer), "attempting get random"); + err = tpm_buf_check_hmac_response(&buf, auth, err); if (err) { if (err > 0) err = -EIO; goto out; } - out = (struct tpm2_get_random_out *) - &buf.data[TPM_HEADER_SIZE]; + out = (struct tpm2_get_random_out *)tpm_buf_parameters(&buf); recd = min_t(u32, be16_to_cpu(out->size), num_bytes); if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + @@ -330,6 +341,8 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max) } while (retries-- && total < max); tpm_buf_destroy(&buf); + tpm2_end_auth_session(auth); + return total ? total : -EIO; out: tpm_buf_destroy(&buf); From patchwork Mon May 18 17:26:56 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555913 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 7A61414C0 for ; Mon, 18 May 2020 17:27:22 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 5ECA420715 for ; Mon, 18 May 2020 17:27:22 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="ibwOaFIM" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728295AbgERR1W (ORCPT ); Mon, 18 May 2020 13:27:22 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57530 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728152AbgERR1W (ORCPT ); Mon, 18 May 2020 13:27:22 -0400 Received: from mail-pf1-x441.google.com (mail-pf1-x441.google.com [IPv6:2607:f8b0:4864:20::441]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id E6943C061A0C for ; Mon, 18 May 2020 10:27:21 -0700 (PDT) Received: by mail-pf1-x441.google.com with SMTP id x13so5248198pfn.11 for ; Mon, 18 May 2020 10:27:21 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=tyOHQ4QTzZNgyLVChX0rG8Pdp219VIFQClOVAmrMGzQ=; b=ibwOaFIMcIkoOHC8NFGHwpkHSP2Wj2u3erdpMctg1Fu6lqWIsHDy6aa0r9FNY70N/u KckJtKd5uQ1Daoe6ASdvQKVsJkTkGyJhlCkfQuI0q+EkkPqugqQGa0mk7vuiyIQoeDKm NnlGzU/H+gahpnTsyJRtQRfSc8WFlkBL08xfpp6GINXab58e39QcVjiKwC7WhjaOxR7u RmLblwLn53JZuMG70mkW8Rcp4giKNU2g1GljvvaiTD75RyzgZNLmPYUj+lZrOiGAeUzA cPRr2gcP5Vt65t8BVD83fJpGYEjlfLbgiVPHkj9toOIILkclkvrST1l2wIs2xT99o8mA s5xQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=tyOHQ4QTzZNgyLVChX0rG8Pdp219VIFQClOVAmrMGzQ=; b=WlgyoE3UrD9XQX1RsPFaTVC3Eb3QzDhYhOdj5lCvZyJlFXVem2thjQR2I89tS3kOVB p85dyzPJwVrMr1ruA6H3+Az2BGmAX+z3PEmOH85qyjm6dfg3VXV1gNyDjVhGxyqMr1qi YqgakcJXXtgS7f140Yt1NWoJ7StSRlRGxroRY3Z9dS0w5glM7cCJoiTTpi6yxXf/0JWO D4BDkSjXPmnLyTuoWckEMv54Xj61icTBGm40a5XWI6SYKRIt/oXqyOvhkOWL/DeDEfkU RBfLChH0FmNa0zpOQf19X9Osbig+uKjPEMtkZZ1AWpjl+f1wOtOKwBd7bwM/FvBzZtOB 29PQ== X-Gm-Message-State: AOAM533353BB0Ef/00vUSbB5pLkQ+mbn3tS/ZO75jp3m18UTENi9CzAZ 0bnEMjbEoJ4BC1bSBYGTmbdC18xwoks= X-Google-Smtp-Source: ABdhPJwk4rOsiPw2f6KQEoLHOfUHuQnZjmjvLR4MVYZzCWvpX66elaUfD2AR8CbM/NhWTLnNVa1VKQ== X-Received: by 2002:a63:cc12:: with SMTP id x18mr6571302pgf.140.1589822841116; Mon, 18 May 2020 10:27:21 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:20 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 09/17] trusted keys: Add session encryption protection to the seal/unseal path Date: Mon, 18 May 2020 10:26:56 -0700 Message-Id: <20200518172704.29608-10-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley If some entity is snooping the TPM bus, the can see the data going in to be sealed and the data coming out as it is unsealed. Add parameter and response encryption to these cases to ensure that no secrets are leaked even if the bus is snooped. As part of doing this conversion it was discovered that policy sessions can't work with HMAC protected authority because of missing pieces (the tpm Nonce). I've added code to work the same way as before, which will result in potential authority exposure (while still adding security for the command and the returned blob), and a fixme to redo the API to get rid of this security hole. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm2-cmd.c | 124 ++++++++++++++++++++++++------------ 1 file changed, 85 insertions(+), 39 deletions(-) diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c index 92e381bfd7c8..f11906f95252 100644 --- a/drivers/char/tpm/tpm2-cmd.c +++ b/drivers/char/tpm/tpm2-cmd.c @@ -418,7 +418,9 @@ int tpm2_seal_trusted(struct tpm_chip *chip, { unsigned int blob_len; struct tpm_buf buf; + struct tpm_buf t2b; u32 hash; + struct tpm2_auth *auth; int i; int rc; @@ -432,45 +434,56 @@ int tpm2_seal_trusted(struct tpm_chip *chip, if (i == ARRAY_SIZE(tpm2_hash_map)) return -EINVAL; - rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE); + rc = tpm2_start_auth_session(chip, &auth); if (rc) return rc; - tpm_buf_append_u32(&buf, options->keyhandle); - tpm2_buf_append_auth(&buf, TPM2_RS_PW, - NULL /* nonce */, 0, - 0 /* session_attributes */, - options->keyauth /* hmac */, - TPM_DIGEST_SIZE); + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE); + if (rc) { + tpm2_end_auth_session(auth); + return rc; + } + + rc = tpm_buf_init_2b(&t2b); + if (rc) { + tpm_buf_destroy(&buf); + tpm2_end_auth_session(auth); + return rc; + } + tpm_buf_append_name(&buf, auth, options->keyhandle, NULL); + tpm_buf_append_hmac_session(&buf, auth, TPM2_SA_DECRYPT, + options->keyauth, TPM_DIGEST_SIZE); /* sensitive */ - tpm_buf_append_u16(&buf, 4 + TPM_DIGEST_SIZE + payload->key_len + 1); + tpm_buf_append_u16(&t2b, TPM_DIGEST_SIZE); + tpm_buf_append(&t2b, options->blobauth, TPM_DIGEST_SIZE); + tpm_buf_append_u16(&t2b, payload->key_len + 1); + tpm_buf_append(&t2b, payload->key, payload->key_len); + tpm_buf_append_u8(&t2b, payload->migratable); - tpm_buf_append_u16(&buf, TPM_DIGEST_SIZE); - tpm_buf_append(&buf, options->blobauth, TPM_DIGEST_SIZE); - tpm_buf_append_u16(&buf, payload->key_len + 1); - tpm_buf_append(&buf, payload->key, payload->key_len); - tpm_buf_append_u8(&buf, payload->migratable); + tpm_buf_append_2b(&buf, &t2b); /* public */ - tpm_buf_append_u16(&buf, 14 + options->policydigest_len); - tpm_buf_append_u16(&buf, TPM_ALG_KEYEDHASH); - tpm_buf_append_u16(&buf, hash); + tpm_buf_append_u16(&t2b, TPM_ALG_KEYEDHASH); + tpm_buf_append_u16(&t2b, hash); /* policy */ if (options->policydigest_len) { - tpm_buf_append_u32(&buf, 0); - tpm_buf_append_u16(&buf, options->policydigest_len); - tpm_buf_append(&buf, options->policydigest, + tpm_buf_append_u32(&t2b, 0); + tpm_buf_append_u16(&t2b, options->policydigest_len); + tpm_buf_append(&t2b, options->policydigest, options->policydigest_len); } else { - tpm_buf_append_u32(&buf, TPM2_OA_USER_WITH_AUTH); - tpm_buf_append_u16(&buf, 0); + tpm_buf_append_u32(&t2b, TPM2_OA_USER_WITH_AUTH); + tpm_buf_append_u16(&t2b, 0); } /* public parameters */ - tpm_buf_append_u16(&buf, TPM_ALG_NULL); - tpm_buf_append_u16(&buf, 0); + tpm_buf_append_u16(&t2b, TPM_ALG_NULL); + /* unique (zero) */ + tpm_buf_append_u16(&t2b, 0); + + tpm_buf_append_2b(&buf, &t2b); /* outside info */ tpm_buf_append_u16(&buf, 0); @@ -483,7 +496,9 @@ int tpm2_seal_trusted(struct tpm_chip *chip, goto out; } + tpm_buf_fill_hmac_session(&buf, auth); rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data"); + rc = tpm_buf_check_hmac_response(&buf, auth, rc); if (rc) goto out; @@ -501,6 +516,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip, payload->blob_len = blob_len; out: + tpm_buf_destroy(&t2b); tpm_buf_destroy(&buf); if (rc > 0) { @@ -532,6 +548,7 @@ static int tpm2_load_cmd(struct tpm_chip *chip, u32 *blob_handle) { struct tpm_buf buf; + struct tpm2_auth *auth; unsigned int private_len; unsigned int public_len; unsigned int blob_len; @@ -546,17 +563,18 @@ static int tpm2_load_cmd(struct tpm_chip *chip, if (blob_len > payload->blob_len) return -E2BIG; - rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD); + rc = tpm2_start_auth_session(chip, &auth); if (rc) return rc; - tpm_buf_append_u32(&buf, options->keyhandle); - tpm2_buf_append_auth(&buf, TPM2_RS_PW, - NULL /* nonce */, 0, - 0 /* session_attributes */, - options->keyauth /* hmac */, - TPM_DIGEST_SIZE); + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD); + if (rc) { + tpm2_end_auth_session(auth); + return rc; + } + tpm_buf_append_name(&buf, auth, options->keyhandle, NULL); + tpm_buf_append_hmac_session(&buf, auth, 0, options->keyauth, TPM_DIGEST_SIZE); tpm_buf_append(&buf, payload->blob, blob_len); if (buf.flags & TPM_BUF_OVERFLOW) { @@ -564,7 +582,9 @@ static int tpm2_load_cmd(struct tpm_chip *chip, goto out; } + tpm_buf_fill_hmac_session(&buf, auth); rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob"); + rc = tpm_buf_check_hmac_response(&buf, auth, rc); if (!rc) *blob_handle = be32_to_cpup( (__be32 *) &buf.data[TPM_HEADER_SIZE]); @@ -596,24 +616,50 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip, u32 blob_handle) { struct tpm_buf buf; + struct tpm2_auth *auth; u16 data_len; u8 *data; int rc; - rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL); + rc = tpm2_start_auth_session(chip, &auth); if (rc) return rc; - tpm_buf_append_u32(&buf, blob_handle); - tpm2_buf_append_auth(&buf, - options->policyhandle ? - options->policyhandle : TPM2_RS_PW, - NULL /* nonce */, 0, - TPM2_SA_CONTINUE_SESSION, - options->blobauth /* hmac */, - TPM_DIGEST_SIZE); + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL); + if (rc) { + tpm2_end_auth_session(auth); + return rc; + } + + tpm_buf_append_name(&buf, auth, blob_handle, NULL); + + if (!options->policyhandle) { + tpm_buf_append_hmac_session(&buf, auth, TPM2_SA_ENCRYPT, + options->blobauth, TPM_DIGEST_SIZE); + } else { + /* + * FIXME: the policy can't be used for HMAC protection + * of the authorization because it must be generated + * with the initial nonces which isn't passed in, so + * append a second encryption session to at least HMAC + * protect the command and encrypt the sealed blob on + * return. + * + * Note: this also means the caller either has to use + * an empty password or compute the password HMAC + * based on the policy nonces and place it in blobauth + */ + tpm2_buf_append_auth(&buf, options->policyhandle, + NULL /* nonce */, 0, 0, + options->blobauth /* hmac */, + TPM_DIGEST_SIZE); + tpm_buf_append_hmac_session_opt(&buf, auth, TPM2_SA_ENCRYPT, + NULL, 0); + } + tpm_buf_fill_hmac_session(&buf, auth); rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing"); + rc = tpm_buf_check_hmac_response(&buf, auth, rc); if (rc > 0) rc = -EPERM; From patchwork Mon May 18 17:26:57 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555915 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id D5A02913 for ; Mon, 18 May 2020 17:27:24 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id BE8D120715 for ; Mon, 18 May 2020 17:27:24 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="hE/h8WKO" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728431AbgERR1Y (ORCPT ); Mon, 18 May 2020 13:27:24 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57538 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1726958AbgERR1Y (ORCPT ); Mon, 18 May 2020 13:27:24 -0400 Received: from mail-pl1-x641.google.com (mail-pl1-x641.google.com [IPv6:2607:f8b0:4864:20::641]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D3292C061A0C for ; Mon, 18 May 2020 10:27:22 -0700 (PDT) Received: by mail-pl1-x641.google.com with SMTP id a13so2949605pls.8 for ; Mon, 18 May 2020 10:27:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=uswFJLFE1zvckTnZqmXVEM4z+ZSuyAzwkPaG09V/TTM=; b=hE/h8WKOpIGtMZtftznhI8vdM6WtjqRTlka35gGt07UhKS2mVXvTukO4PVWwcgD/Ny e7xpMw5xEKmlvCEVcdwAcctkVfO12nvfkfOx/NaL7+DTWPpj2Etgc6bhHNL4z9XCS5lp 81uHJg2Ei19Oyn3FTIttIGUuv6IoSk0TD8QSufGGpUczOGymjqJ714MZJOVop0w8x3rH G5gEknzGWLlgi7uw1S7C0Ld/+bURAzgif/7vzyXX2H7X6RsSiIn3UZ1kp0H2iGXde/7B sJKc79zxWZmMPy9zXGSM8MREl1pM9kjGQqo1MqklhEtlrJsnG8s/+kLrwzGLkGbG81e8 EQKg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=uswFJLFE1zvckTnZqmXVEM4z+ZSuyAzwkPaG09V/TTM=; b=spKdjnK62nIUMvckKDf/Hd420uV7tC57IBkcwd5rHuV2p2mhrGZjLvjLqe9BMpMrRe Mk/0l5UQuS2osLQeNExa9+KxNmgaSnLupjM4xrWFD4C0ll0Nii4LhvEKP+LJFtmbAuJ2 U9//iWEvXOeYVub5dK970Cvim8LPuUBV7luRZSorNYIe9wzYENb6oEW0ezYHpZiYF4Nv q1QOUbrG6jq+VrXtMcGiPTpRn15agT+PDIdKgexCT4ez0RCtNQQ2CoWh9rRyEy1Y0m0R rV+nFmZLmcEroligf5b27NuAm4oivTjRHTkAanp5nFskxCl+7jF4vk0O5LR+A3IxDcw9 BSbQ== X-Gm-Message-State: AOAM532lyGpIlugrsqIeM9gZorQZKLyW7Dvn1TFeBFwBu/7YAOBAn3Y1 Hu7yYkTov86BRVgSJx3sOjLRbHlVarY= X-Google-Smtp-Source: ABdhPJzlN8vG0frcHn4pRJKBs7HpOr59OGUCO5k8rKg5g//rYJcTtVYHqjahRIMnUDL20pAQDLSHDg== X-Received: by 2002:a17:90a:264c:: with SMTP id l70mr535551pje.18.1589822842041; Mon, 18 May 2020 10:27:22 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:21 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 10/17] tpm: add the null key name as a tpm2 sysfs variable Date: Mon, 18 May 2020 10:26:57 -0700 Message-Id: <20200518172704.29608-11-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley This is the last component of encrypted tpm2 session handling that allows us to verify from userspace that the key derived from the NULL seed genuinely belongs to the TPM and has not been spoofed. The procedure for doing this involves creating an attestation identity key (which requires verification of the TPM EK certificate) and then using that AIK to sign a certification of the Elliptic Curve key over the NULL seed. Userspace must create this EC Key using the parameters prescribed in TCG TPM v2.0 Provisioning Guidance for the SRK ECC; if this is done correctly the names will match and the TPM can then run a TPM2_Certify operation on this derived primary key using the newly created AIK. Signed-off-by: James Bottomley --- drivers/char/tpm/tpm-sysfs.c | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/drivers/char/tpm/tpm-sysfs.c b/drivers/char/tpm/tpm-sysfs.c index d52bf4df0bca..c2733252320a 100644 --- a/drivers/char/tpm/tpm-sysfs.c +++ b/drivers/char/tpm/tpm-sysfs.c @@ -310,6 +310,19 @@ static ssize_t timeouts_show(struct device *dev, struct device_attribute *attr, } static DEVICE_ATTR_RO(timeouts); +static ssize_t null_name_show(struct device *dev, struct device_attribute *attr, + char *buf) +{ + struct tpm_chip *chip = to_tpm_chip(dev); + int size = TPM2_NAME_SIZE; + + bin2hex(buf, chip->tpmkeyname, size); + size *= 2; + buf[size++] = '\n'; + return size; +} +static DEVICE_ATTR_RO(null_name); + static ssize_t tpm_version_major_show(struct device *dev, struct device_attribute *attr, char *buf) { @@ -336,7 +349,7 @@ static struct attribute *tpm1_dev_attrs[] = { }; static struct attribute *tpm2_dev_attrs[] = { - &dev_attr_tpm_version_major.attr, + &dev_attr_null_name.attr, NULL }; @@ -346,10 +359,24 @@ static const struct attribute_group tpm1_dev_group = { static const struct attribute_group tpm2_dev_group = { .attrs = tpm2_dev_attrs, + }; void tpm_sysfs_add_device(struct tpm_chip *chip) { + /* XXX: If you wish to remove this restriction, you must first update + * tpm_sysfs to explicitly lock chip->ops. + */ + if (chip->flags & TPM_CHIP_FLAG_TPM2) { + WARN_ON(chip->groups_cnt != 0); + chip->groups[chip->groups_cnt++] = &tpm2_dev_group; + return; + } + + /* The sysfs routines rely on an implicit tpm_try_get_ops, device_del + * is called before ops is null'd and the sysfs core synchronizes this + * removal so that no callbacks are running or can run again + */ WARN_ON(chip->groups_cnt != 0); if (chip->flags & TPM_CHIP_FLAG_TPM2) chip->groups[chip->groups_cnt++] = &tpm2_dev_group; From patchwork Mon May 18 17:26:58 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555917 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 36ED614C0 for ; Mon, 18 May 2020 17:27:25 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 157C9207FB for ; Mon, 18 May 2020 17:27:25 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="aq5+pGMW" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728152AbgERR1Y (ORCPT ); Mon, 18 May 2020 13:27:24 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57540 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728416AbgERR1Y (ORCPT ); Mon, 18 May 2020 13:27:24 -0400 Received: from mail-pj1-x1034.google.com (mail-pj1-x1034.google.com [IPv6:2607:f8b0:4864:20::1034]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 5E91EC05BD09 for ; Mon, 18 May 2020 10:27:24 -0700 (PDT) Received: by mail-pj1-x1034.google.com with SMTP id a5so145707pjh.2 for ; Mon, 18 May 2020 10:27:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=4+JhAmACYrGKst40jmDeYo55LB9G4V6DnAgWvanWMBM=; b=aq5+pGMWC+O7ro5FPc8NTOsTHv0qDkKqZ8Sfiz8UEwro9OPNkUHT0Ke/qgzp7m9FRe UBmeD0DyiypQa7rfF5XSzqFOY+uAOh+BAdNaAVtYB4W0eMBoJqlPViJxSBuJ+8XcoDsZ MULgsllRWFOinNtHNj3GcXnbTjQKs+9LOoOek8Ls05TOAvuvWhv2s/sOU3thyZKWxlt9 JmmJU8tR9C7oeiKOJWur1lAHgqB297e9cVbdO3iXfjHANuvw/Vryzz/+x8U664w0jG8E TQ4fb31P+2nDT5ONuw8hUnO0w8dkdWcvoL1MhjazTy3T5OEv3NEfIYxhwUfV4Wdqk3R1 1w/Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=4+JhAmACYrGKst40jmDeYo55LB9G4V6DnAgWvanWMBM=; b=EmpLBdidoc7zz7Xszfsd3CVb4MyICldEKaAsNT6URvQs2usYLVNck5FvICYWKWwzfs MbsutpI5WOwpL8BBe5YjwwhO8hc58BkgIv3kG3EQYvOPpOX7JlGHH0+MD8bJF5mT7i+w dwcfFNPVEWtaIiDrWt3IKbSZk86HfstBzzTrueS4LsouahGMUQ56Ab8Ye5B+9Y9R+9uw Q6qvuy9eCffEMaHzRsmmJdsOr6aoFwnKnHReBCoXjOtOT5tohz+KLUYsPeLTh6rR752g iy9DDEMvNOE8HUeknfFDI7vXDDFm74UHluyynmfQBCW98QIqcp/K1flCFSC9DNeQkLsV vNXQ== X-Gm-Message-State: AOAM533Udp8maC0p0dbjoBjmQz8KLqRdZLMCUt69XbcPQjtnvaWNxshL Fpk6zPTxurqAdg2vsRxbllf7FfYk4uE= X-Google-Smtp-Source: ABdhPJxa6aB9yNPJlqMiZoTEZyFx6aaBlBQt1hEzMsOkhvzbT9G6sITUcXx1oUuyUKyCQk1wMyD6+A== X-Received: by 2002:a17:902:7b94:: with SMTP id w20mr17030001pll.8.1589822843221; Mon, 18 May 2020 10:27:23 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:22 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com Subject: [PATCH 11/17] Documentation: add tpm-security.rst Date: Mon, 18 May 2020 10:26:58 -0700 Message-Id: <20200518172704.29608-12-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley Document how the new encrypted secure interface for TPM2 works and how security can be assured after boot by certifying the NULL seed. Signed-off-by: James Bottomley --- Documentation/security/tpm/tpm-security.rst | 204 ++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 Documentation/security/tpm/tpm-security.rst diff --git a/Documentation/security/tpm/tpm-security.rst b/Documentation/security/tpm/tpm-security.rst new file mode 100644 index 000000000000..3411030505a1 --- /dev/null +++ b/Documentation/security/tpm/tpm-security.rst @@ -0,0 +1,204 @@ +TPM Security +============ + +The object of this document is to describe how we make the kernel's +use of the TPM reasonably robust in the face of external snooping and +packet alteration attacks. The current security document is for TPM +2.0. + +Introduction +------------ + +The TPM is usually a discrete chip attached to a PC via some type of +low bandwidth bus. There are exceptions to this such as the Intel +PTT, which is a software TPM running inside a software environment +close to the CPU, which are subject to different attacks, but right at +the moment, most hardened security environments require a discrete +hardware TPM, which is the use case discussed here. + +Snooping and Alteration Attacks against the bus +----------------------------------------------- + +The current state of the art for snooping the TPM Genie hardware +interposer https://www.nccgroup.trust/us/our-research/tpm-genie/ which +is a simple external device that can be installed in a couple of +seconds on any system or laptop. However, the next phase of research +seems to be hacking existing devices on the bus to act as interposers, +so the fact that the attacker requires physical access for a few +seconds might evaporate. However, the goal of this document is to +protect TPM secrets and integrity as far as we are able in this +environment and to try to insure that if we can't prevent the attack +then at least we can detect it. + +Unfortunately, most of the TPM functionality, including the hardware +reset capability can be controlled by an attacker who has access to +the bus, so we'll discuss some of the disruption possibilities below. + +Measurement (PCR) Integrity +--------------------------- + +Since the attacker can send their own commands to the TPM, they can +send arbitrary PCR extends and thus disrupt the measurement system, +which would be an annoying denial of service attack. However, there +are two, more serious, classes of attack aimed at entities sealed to +trust measurements. + +1. The attacker could intercept all PCR extends coming from the system + and completely substitute their own values, producing a replay of + an untampered state that would cause PCR measurements to attest to + a trusted state and release secrets + +2. At some point in time the attacker could reset the TPM, clearing + the PCRs and then send down their own measurements which would + effectively overwrite the boot time measurements the TPM has + already done. + +The first can be thwarted by always doing HMAC protection of the PCR +extend and read command meaning measurement values cannot be +substituted without producing a detectable HMAC failure in the +response. However, the second can only really be detected by relying +on some sort of mechanism for protection which would change over TPM +reset. + +Secrets Guarding +---------------- + +Certain information passing in and out of the TPM, such as key sealing +and private key import and random number generation, is vulnerable to +interception which HMAC protection alone cannot protect, so for these +types of command we must also employ request and response encryption +to prevent the loss of secret information. + +Establishing Initial Trust with the TPM +--------------------------------------- + +In order to provide security from the beginning, an initial shared or +asymmetric secret must be established which must also be unknown to +the attacker. The most obvious avenues for this are the endorsement +and storage seeds, which can be used to derive asymmetric keys. +However, using these keys is difficult because the only way to pass +them into the kernel would be on the command line, which requires +extensive support in the boot system, and there's no guarantee that +either hierarchy would not have some type of authorization. + +The mechanism chosen for the Linux Kernel is to derive the primary +elliptic curve key from the null seed using the standard storage seed +parameters. The null seed has two advantages: firstly the hierarchy +physically cannot have an authorization, so we are always able to use +it and secondly, the null seed changes across TPM resets, meaning if +we establish trust on the null seed at start of day, all sessions +salted with the derived key will fail if the TPM is reset and the seed +changes. + +Obviously using the null seed without any other prior shared secrets, +we have to create and read the initial public key which could, of +course, be intercepted and substituted by the bus interposer. +However, the TPM has a key certification mechanism (using the EK +endorsement certificate, creating an attestation identity key and +certifying the null seed primary with that key) which is too complex +to run within the kernel, so we keep a copy of the null primary key +name, which is what is certified so user-space can run the full +certification when it boots. The definitive guarantee here is that if +the null primary key certifies correctly, you know all your TPM +transactions since start of day were secure and if it doesn't, you +know there's an interposer on your system (and that any secret used +during boot may have been leaked). + +Stacking Trust +-------------- + +In the current null primary scenario, the TPM must be completely +cleared before handing it on to the next consumer. However the kernel +hands to user-space the name of the derived null seed key which can +then be verified by certification in user-space. Therefore, this chain +of name handoff can be used between the various boot components as +well (via an unspecified mechanism). For instance, grub could use the +null seed scheme for security and hand the name off to the kernel in +the boot area. The kernel could make its own derivation of the key +and the name and know definitively that if they differ from the handed +off version that tampering has occurred. Thus it becomes possible to +chain arbitrary boot components together (UEFI to grub to kernel) via +the name handoff provided each successive component knows how to +collect the name and verifies it against its derived key. + +Session Properties +------------------ + +All TPM commands the kernel uses allow sessions. HMAC sessions may be +used to check the integrity of requests and responses and decrypt and +encrypt flags may be used to shield parameters and responses. The +HMAC and encryption keys are usually derived from the shared +authorization secret, but for a lot of kernel operations that is well +known (and usually empty). Thus, every HMAC session used by the +kernel must be created using the null primary key as the salt key +which thus provides a cryptographic input into the session key +derivation. Thus, the kernel creates the null primary key once (as a +volatile TPM handle) and keeps it around in a saved context stored in +tpm_chip for every in-kernel use of the TPM. Currently, because of a +lack of de-gapping in the in-kernel resource manager, the session must +be created and destroyed for each operation, but, in future, a single +session may also be reused for the in-kernel HMAC, encryption and +decryption sessions. + +Protection Types +---------------- + +For every in-kernel operation we use null primary salted HMAC to +protect the integrity. Additionally, we use parameter encryption to +protect key sealing and parameter decryption to protect key unsealing +and random number generation. + +Null Primary Key Certification in Userspace +=========================================== + +Every TPM comes shipped with a couple of X.509 certificates for the +primary endorsement key. This document assumes that the Elliptic +Curve version of the certificate exists at 01C00002, but will work +equally well with the RSA certificate (at 01C00001). + +The first step in the certification is primary creation using the +template from the `TCG EK Credential Profile`_ which allows comparison +of the generated primary key against the one in the certificate (the +public key must match). Note that generation of the EK primary +requires the EK hierarchy password, but a pre-generated version of the +EC primary should exist at 81010002 and a TPM2_ReadPublic() may be +performed on this without needing the key authority. Next, the +certificate itself must be verified to chain back to the manufacturer +root (which should be published on the manufacturer website). Once +this is done, the generated EK primary key may now be used to run an +attestation on the null seed. The specific problem here is that the +EK primary is not a signing key so cannot on its own be used to sign +the key certification, hence the complex process below. + +Note: this process is a simplified abbreviation of the usual privacy +CA based attestation process. The assumption here is that the +attestation is done by the TPM owner who thus has access to only the +owner hierarchy. The owner creates an external public/private key +pair (assume elliptic curve in this case) and wraps the private key +for import using an inner wrapping process and parented to the EC +derived storage primary. The TPM2_Import() is done using a parameter +decryption HMAC session salted to the EK primary (which also does not +require the EK key authority) meaning that the inner wrapping key is +the encrypted parameter and thus the TPM will not be able to perform +the import unless is possesses the certified EK so if the command +succeeds and the HMAC verifies on return we know we have a loadable +copy of the private key only for the certified TPM. This key is now +loaded into the TPM and the Storage primary flushed (to free up space +for the null key generation). + +The null EC primary is now generated using the Storage profile +outlined in the `TCG TPM v2.0 Provisioning Guidance`_; the name of +this key (the hash of the public area) is computed and compared to the +null seed name presented by the kernel in +/sys/class/tpm/tpm0/null_name. If the names do not match, the TPM is +compromised. If the names match, the user performs a TPM2_Certify() +using the null primary as the object handle and the loaded private key +as the sign handle and providing randomized qualifying data. The +signature of the returned certifyInfo is verified against the public +part of the loaded private key and the qualifying data checked to +prevent replay. If all of these tests pass, the user is now assured +that TPM integrity and privacy was preserved across the entire boot +sequence of this kernel. + +.. _TCG EK Credential Profile: https://trustedcomputinggroup.org/resource/tcg-ek-credential-profile-for-tpm-family-2-0/ +.. _TCG TPM v2.0 Provisioning Guidance: https://trustedcomputinggroup.org/resource/tcg-tpm-v2-0-provisioning-guidance/ From patchwork Mon May 18 17:26:59 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555919 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id A12E2912 for ; Mon, 18 May 2020 17:27:25 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 86C9220715 for ; Mon, 18 May 2020 17:27:25 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="lDDEPXof" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728436AbgERR1Z (ORCPT ); Mon, 18 May 2020 13:27:25 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57542 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728416AbgERR1Z (ORCPT ); Mon, 18 May 2020 13:27:25 -0400 Received: from mail-pj1-x1044.google.com (mail-pj1-x1044.google.com [IPv6:2607:f8b0:4864:20::1044]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id E2EA0C061A0C for ; Mon, 18 May 2020 10:27:24 -0700 (PDT) Received: by mail-pj1-x1044.google.com with SMTP id a5so145720pjh.2 for ; Mon, 18 May 2020 10:27:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=r7ZJo5GSYlG/1HLhJKX4JMXUb05bkA+s5cA697P0kfc=; b=lDDEPXofAI0DhxBwvMHfceNp0e3LgPzaI5PNatAUC0HNJ6e07Fm4K4b6yMz1eGiDBj NHM/YHrOqNZGq2U3+mO3+gsiOkPK4K9MRcPTAU4B3ngRi3qavrjMzSs0bwdFdZNkB9jM fRRQcZTbqA7DUFJFX6kQtHdf/hVtwdMS3G5OQeJZPFpiY/Yi8w10y5clVmabjQlEW2I3 WIIUZD6ghQkTf0L+XyPknGJWa4ZHv1oivr5ypOEpFi3wdRdHq26ebo/D0VGqq53zmdz9 g/g7UjphiQhiLgeQ8pUJnukfctYgr0lhpC2fJiFRCJn8DhN0HPlfQxwHYADBVvxG6GoU 1w3g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=r7ZJo5GSYlG/1HLhJKX4JMXUb05bkA+s5cA697P0kfc=; b=SYn0hy1EGxHE/EyjOgmJnTe89oKWVql3E2nh6PAi3oS10nmql90QG6vHbKmEo2OjAH RepsiJeK6qbxkrit74L6s5LCf5bGfk0rjb8pzTwII7oUCLi/I9J+fPebdgqJhL11PmU9 yvj4khfPvfhoJKpKxbDu+d2ZEFUrgc4PiAKqEdtNOA6L1LLypcu75lcv4oprVv5w0aIG nilM8UwHyc8PAKVEEic0qiHhkjY2Fm07tpZbnZRhdFRPe2teYZYuP8AukWWRrvFbxUEk jqMKAc4Eg13Tj/POS4TwYEFjz6X3i0zQVquc7gD57V1q3IEI3qE3IkokK7SYWZK0fVzh nJMw== X-Gm-Message-State: AOAM530mUWFFd9eiCotD0qm5KQPQZK6s1rcyEdTr5ZNch3C59WAA3d5l ZOBde6e/mj/SIysycyUqKwsfQ+iRjWU= X-Google-Smtp-Source: ABdhPJyBuGwWoWzKq9ndBBLOUFRK9mEb8+qsmf7NhscGcnNcuv+bncqV7bQPRFYAW5SHgJ4aVEn82g== X-Received: by 2002:a17:90a:ea98:: with SMTP id h24mr444534pjz.195.1589822844178; Mon, 18 May 2020 10:27:24 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:23 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, Jarkko Sakkinen Subject: [PATCH 12/17] oid_registry: Add TCG defined OIDS for TPM keys Date: Mon, 18 May 2020 10:26:59 -0700 Message-Id: <20200518172704.29608-13-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org From: James Bottomley The TCG has defined an OID prefix "2.23.133.10.1" for the various TPM key uses. We've defined three of the available numbers: 2.23.133.10.1.3 TPM Loadable key. This is an asymmetric key (Usually RSA2048 or Elliptic Curve) which can be imported by a TPM2_Load() operation. 2.23.133.10.1.4 TPM Importable Key. This is an asymmetric key (Usually RSA2048 or Elliptic Curve) which can be imported by a TPM2_Import() operation. Both loadable and importable keys are specific to a given TPM, the difference is that a loadable key is wrapped with the symmetric secret, so must have been created by the TPM itself. An importable key is wrapped with a DH shared secret, and may be created without access to the TPM provided you know the public part of the parent key. 2.23.133.10.1.5 TPM Sealed Data. This is a set of data (up to 128 bytes) which is sealed by the TPM. It usually represents a symmetric key and must be unsealed before use. The ASN.1 binary key form starts of with this OID as the first element of a sequence, giving the binary form a unique recognizable identity marker regardless of encoding. Signed-off-by: James Bottomley Acked-by: Jarkko Sakkinen --- include/linux/oid_registry.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/include/linux/oid_registry.h b/include/linux/oid_registry.h index 657d6bf2c064..f6e2276e5f30 100644 --- a/include/linux/oid_registry.h +++ b/include/linux/oid_registry.h @@ -107,6 +107,11 @@ enum OID { OID_gostTC26Sign512B, /* 1.2.643.7.1.2.1.2.2 */ OID_gostTC26Sign512C, /* 1.2.643.7.1.2.1.2.3 */ + /* TCG defined OIDS for TPM based keys */ + OID_TPMLoadableKey, /* 2.23.133.10.1.3 */ + OID_TPMImportableKey, /* 2.23.133.10.1.4 */ + OID_TPMSealedData, /* 2.23.133.10.1.5 */ + OID__NR }; From patchwork Mon May 18 17:27:00 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555921 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id CAFB3912 for ; Mon, 18 May 2020 17:27:26 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id AE95020715 for ; Mon, 18 May 2020 17:27:26 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="mfJ7rK3O" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728440AbgERR10 (ORCPT ); Mon, 18 May 2020 13:27:26 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57548 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728416AbgERR10 (ORCPT ); Mon, 18 May 2020 13:27:26 -0400 Received: from mail-pj1-x1042.google.com (mail-pj1-x1042.google.com [IPv6:2607:f8b0:4864:20::1042]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 08DE9C061A0C for ; Mon, 18 May 2020 10:27:26 -0700 (PDT) Received: by mail-pj1-x1042.google.com with SMTP id n15so132465pjt.4 for ; Mon, 18 May 2020 10:27:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=rjfxPFBqdcT1NNn7odkflr/fepRGqK0ZP4DJCVVOfXk=; b=mfJ7rK3Of6UA/8srQgsuJRDncSIQFz2eCJ2zmeK3JGJKUSNfAqnTI4UjSEBqhM26xZ PVwBKdlX7ntk295su+o2HraVPzI8Sg6bo6mLfbldesbhQ6LihZd2U9Wy2UId3qmbiKE7 0rNusvAJTUy3t7YtAWAeZFx5bulOjrXtPCAT8lvAHU99mQuDDjVkvrXdfQLdIoTjQCAU 0TdKkRygyIgCjkDffRka/VrCLTbhiXceaad0V65+WUhhqL0GUInOJpAQ+aoTfb4fShcN ie11vn+26+9nrXZ4ebaqIVL9luAOxHXyQ+9UnbBjLc3pZtW42KSniBOBioFt6fstaIea DH0w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=rjfxPFBqdcT1NNn7odkflr/fepRGqK0ZP4DJCVVOfXk=; b=D3wbdbF2RnBOxl04JNZq7WzB1w0EOCsD13KMc5gJHBu/1o73T1FKL6c4xuUMRfM1Wo gf+iW+I4M6zZQRlbI16DTnzVUqZcfQoSrFeSXC7PAu4ZohkHD/ysxb5Ptn5smzemCRT6 XyN3jt9ilXckO0AZmFdLcPoC7MtIwxxvUm/E1J1EHpav+n12YxzjQuI7d0tukUqlHcEn yxA5rFyBXS1P/na6hM9xPUXMD+/pBk3/ClwLEE8dr9P7Tl52z8/A5DjmgG1Fb9zrhVha 7gSH1BLaq1d9BxP2KhSQT1/z3fYYMlxz66Y/JZ8mQShl5/4dC7GjQWZzxS+3Tpj4MtqO q0CQ== X-Gm-Message-State: AOAM530KjgGwecKfj/rOZVKNWHgo61qGSXTJ+cKkDGYEvOycbfsl1wjN liYG/Q0zLYyMhqYwrdjEabqoda6J9GQ= X-Google-Smtp-Source: ABdhPJwMqqDVXV+o5UrZG9sii5PooR3P93DyzFsq4LEYpTpLuwez63fTNYmDS2ZkpkyddUcjieMotQ== X-Received: by 2002:a17:90a:3201:: with SMTP id k1mr478148pjb.202.1589822845224; Mon, 18 May 2020 10:27:25 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.24 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:24 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, James Prestwood Subject: [PATCH 13/17] tpm: tpm2-cmd: add driver API for RSA decryption Date: Mon, 18 May 2020 10:27:00 -0700 Message-Id: <20200518172704.29608-14-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org Added a new TPM driver level API for RSA decryption. The API parameters take a raw asymmetric key blob rather than depending on trusted types. This is so it can be easily used across the kernel rather than only in the trusted module as this will be used by a new asymmetric key type. The blob does still need to be parsed by the caller and formatted correctly to be accepted by the TPM. At the TPM level decrypt and sign use the same operation, TPM2_CC_RSA_DECRYPT. The difference is that data to be signed is pre-padded with pkcs1 up to the key size. This effectively makes the call to decrypt actually an encryption operation suitable for signing. If the parent handle passed in is TPM2_RH_NULL the null key context is loaded and that key handle is used. Any other handle will use that parent for the operations, and its expected that the parent handle exists in the TPM. --- drivers/char/tpm/tpm.h | 3 + drivers/char/tpm/tpm2-cmd.c | 128 ++++++++++++++++++++++++++++++++++++ include/linux/tpm.h | 1 + 3 files changed, 132 insertions(+) diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h index ade4af4d52ca..f872132f9a68 100644 --- a/drivers/char/tpm/tpm.h +++ b/drivers/char/tpm/tpm.h @@ -259,6 +259,9 @@ int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf, unsigned int buf_size, unsigned int *offset); int tpm2_load_context(struct tpm_chip *chip, u8 *buf, unsigned int *offset, u32 *handle); +int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent, + const unsigned char *keyblob, size_t bloblen, + const void *data, size_t len, void *out); int tpm_bios_log_setup(struct tpm_chip *chip); void tpm_bios_log_teardown(struct tpm_chip *chip); diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c index f11906f95252..f4ebc1e7186a 100644 --- a/drivers/char/tpm/tpm2-cmd.c +++ b/drivers/char/tpm/tpm2-cmd.c @@ -1030,6 +1030,134 @@ static int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip) return rc; } +/** + * tpm2_rsa_decrypt + * + * @chip: TPM chip to use + * @parent: Parent key handle + * @keyblob: Private/Public key pair + * @bloblen: length of keyblob + * @data: encrypted data to decrypt + * @len: length of data + * @out: buffer for decrypted data + */ +int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent, + const unsigned char *keyblob, size_t bloblen, + const void *data, size_t len, void *out) +{ + struct tpm_buf buf; + struct tpm2_auth *auth; + int rc; + u32 blob_handle = 0; + unsigned int private_len; + unsigned int public_len; + unsigned int parsed_len; + u32 key_handle = 0; + unsigned int offset = 0; /* dummy offset for null seed context */ + u8 *pos; + u16 decrypted_len; + + private_len = be16_to_cpup((__be16 *) &keyblob[0]); + if (private_len > (bloblen - 2)) + return -E2BIG; + + public_len = be16_to_cpup((__be16 *) &keyblob[2 + private_len]); + parsed_len = private_len + public_len + 4; + if (parsed_len > bloblen) + return -E2BIG; + + chip = tpm_find_get_ops(chip); + if (!chip) + return -ENODEV; + + rc = tpm2_start_auth_session(chip, &auth); + if (rc) { + tpm_put_ops(chip); + return -EIO; + } + + if (parent == TPM2_RH_NULL) { + rc = tpm2_load_context(chip, chip->tpmkeycontext, &offset, + &key_handle); + if (rc) { + rc = -EIO; + tpm2_end_auth_session(auth); + goto out; + } + } else + key_handle = parent; + + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD); + if (rc < 0) { + tpm2_end_auth_session(auth); + goto out; + } + + tpm_buf_append_name(&buf, auth, key_handle, NULL); + tpm_buf_append_hmac_session(&buf, auth, TPM2_SA_CONTINUE_SESSION | + TPM2_SA_ENCRYPT, NULL, 0); + tpm_buf_append(&buf, keyblob, bloblen); + + if (buf.flags & TPM_BUF_OVERFLOW) { + rc = -E2BIG; + tpm2_end_auth_session(auth); + goto out; + } + + tpm_buf_fill_hmac_session(&buf, auth); + rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob"); + rc = tpm_buf_check_hmac_response(&buf, auth, rc); + if (rc) { + rc = -EIO; + tpm2_end_auth_session(auth); + goto out; + } + + blob_handle = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]); + + tpm_buf_destroy(&buf); + + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_RSA_DECRYPT); + if (rc < 0) { + tpm2_end_auth_session(auth); + goto out; + } + + tpm_buf_append_name(&buf, auth, blob_handle, NULL); + tpm_buf_append_hmac_session(&buf, auth, TPM2_SA_DECRYPT, NULL, 0); + + tpm_buf_append_u16(&buf, len); + tpm_buf_append(&buf, data, len); + tpm_buf_append_u16(&buf, TPM_ALG_NULL); + tpm_buf_append_u16(&buf, 0); + + tpm_buf_fill_hmac_session(&buf, auth); + rc = tpm_transmit_cmd(chip, &buf, 4, "rsa decrypt"); + rc = tpm_buf_check_hmac_response(&buf, auth, rc); + + if (rc) + goto out; + + pos = buf.data + TPM_HEADER_SIZE + 4; + decrypted_len = be16_to_cpup((__be16 *) pos); + pos += 2; + + memcpy(out, pos, decrypted_len); + rc = decrypted_len; + +out: + if (parent == TPM2_RH_NULL && key_handle) + tpm2_flush_context(chip, key_handle); + + if (blob_handle) + tpm2_flush_context(chip, blob_handle); + + tpm_put_ops(chip); + + return rc; +} +EXPORT_SYMBOL_GPL(tpm2_rsa_decrypt); + /** * tpm2_startup - turn on the TPM * @chip: TPM chip to use diff --git a/include/linux/tpm.h b/include/linux/tpm.h index 52bfb673ab48..b1c96ee7b672 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -247,6 +247,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 Mon May 18 17:27:01 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555923 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id A36AF913 for ; Mon, 18 May 2020 17:27:27 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 8C2ED20715 for ; Mon, 18 May 2020 17:27:27 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="EQ7j2Fs3" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728416AbgERR11 (ORCPT ); Mon, 18 May 2020 13:27:27 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57550 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728304AbgERR11 (ORCPT ); Mon, 18 May 2020 13:27:27 -0400 Received: from mail-pj1-x1030.google.com (mail-pj1-x1030.google.com [IPv6:2607:f8b0:4864:20::1030]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 1893FC061A0C for ; Mon, 18 May 2020 10:27:27 -0700 (PDT) Received: by mail-pj1-x1030.google.com with SMTP id q24so140136pjd.1 for ; Mon, 18 May 2020 10:27:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=1BU+0TAFPcTkM0eFuwloyuTiUJdwFdkK3Vk17qlbQrI=; b=EQ7j2Fs3v9jpLfyjLs7fw4e6sCTdeJ2Qv5CqTNpZEbyW9MFzzaopiUjeTKXvewRk3V r1WvGS+YH/qLpW1Czp5IL5kVrVTmAUxboiOHzP1xExXFYoZrAUJTlWzf8N0Q4WbXxM5z mlHpwUDlurLL0A1QiEuKLvAuGtUTlvrVOzxy50FFhzkrIrSKPje9SUuFWb+dJYbYt59c oRxzyIS0anFJVE8pCyOxXwSHfPEvFGHaeNvRatoj2xfqftWfi4uhv2V0Zt5bdjSJpi7B ICSstUeOFloNLuGnMjA2WGFoeEdrYS5NSFm0hgRA5HbaKJKOOueqNjG34/OUP00D1JBs nkBg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=1BU+0TAFPcTkM0eFuwloyuTiUJdwFdkK3Vk17qlbQrI=; b=FF9CVl3Lh8F9YOzmgrJ3Ne73cMJKSyg5E+K4ooI00bjTw5dfs4todfZ8Jy3lrKNgHG QBy61ZdjuHvtnLKBBrH8IXCcUVxTXgJPm9Pm+r8+KGrsrHOzGo0IvkzNLgELx1rgZRuH IAIrQ7YI5vHpFJ4gbd2fpb6j6hHHpxsBOnggzt+dwiz4uU1Ir9Of4EsajAB+TyzQ4Jyu Nfnq1x4XKBy9YJYG9y+3TPHlGxBhJ9eT4vPYIPHeE97Q4NnOK82ywJtiI+7H4kstTElQ Jms8VnlFO3pu3GyDUWQs0CafYUf0P7f4f92WYRDNiIzWW5yMmVPSIhFVKkiN0BWw27iY ZJ/Q== X-Gm-Message-State: AOAM531C+VLqKSEHnmWBJqY+fv03afccJEjf/fSmXzzc/LY2UnA5wBpL FXnXXTGkOzFhj5pn8n7D8tcT3q6EAgo= X-Google-Smtp-Source: ABdhPJzki2/776jLP3bYP1w90+nBKIzK7MQiENosl0vph9Lm8LJDahh3DrVX99v56kG0pywXr4hSpg== X-Received: by 2002:a17:90a:5895:: with SMTP id j21mr521819pji.92.1589822846269; Mon, 18 May 2020 10:27:26 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.25 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:25 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, James Prestwood Subject: [PATCH 14/17] include: linux: tpm: expose tpm2_rsa_decrypt Date: Mon, 18 May 2020 10:27:01 -0700 Message-Id: <20200518172704.29608-15-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org Expose these APIs so other modules can use them. --- include/linux/tpm.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/include/linux/tpm.h b/include/linux/tpm.h index b1c96ee7b672..7dd33f144bce 100644 --- a/include/linux/tpm.h +++ b/include/linux/tpm.h @@ -387,6 +387,9 @@ static inline u32 tpm2_rc_value(u32 rc) return (rc & BIT(7)) ? rc & 0xff : rc; } +extern int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent, + const unsigned char *keyblob, size_t bloblen, + const void *data, size_t len, void *out); #else static inline int tpm_is_tpm2(struct tpm_chip *chip) { @@ -418,5 +421,11 @@ static inline struct tpm_chip *tpm_default_chip(void) { return NULL; } +static inline int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent, + const unsigned char *keyblob, size_t bloblen, + const void *data, size_t len, void *out) +{ + return -ENODEV; +} #endif #endif From patchwork Mon May 18 17:27:02 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555925 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id A874A913 for ; Mon, 18 May 2020 17:27:28 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 911A520715 for ; Mon, 18 May 2020 17:27:28 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="Xp9Nomrp" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728445AbgERR12 (ORCPT ); Mon, 18 May 2020 13:27:28 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57558 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728304AbgERR12 (ORCPT ); Mon, 18 May 2020 13:27:28 -0400 Received: from mail-pj1-x1041.google.com (mail-pj1-x1041.google.com [IPv6:2607:f8b0:4864:20::1041]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 1CCE0C061A0C for ; Mon, 18 May 2020 10:27:28 -0700 (PDT) Received: by mail-pj1-x1041.google.com with SMTP id q9so137130pjm.2 for ; Mon, 18 May 2020 10:27:28 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=Wkkc1Rm+rMed2ZqbMkUHJzTFUh3hfaL1duU5QQp9Nww=; b=Xp9NomrpUKfmkwAKZZsTMOzYc1oy7uJWH2wxodWXW4OUALZclQ+RK8PC/q1hcv79lW K7rjhsu+FjR5o9oefUjp+owVIFm8NOwXVgcqynbUVhX4vLznk7r7yD+YgOjMI3ZqL+cX V6LshKpz+YeIsK6Ny4ml3sdGDdjGS4mqvp6C4rS8YZjm5oZUNZjWa//ZUa/bd1JIkMNf 8gsXQQWYL+DZqS6o03skzncLB3CeX5huZ95JtMRrIvar+uyydjI/PTIpW/N38QpkE5d/ oUpFulJJD3wagltaML+8663rWxHxU/6zDGUvsJsGrXadu45+wlF5d6cdNy36T027/0cD 9BdA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=Wkkc1Rm+rMed2ZqbMkUHJzTFUh3hfaL1duU5QQp9Nww=; b=iDpAImGYH9VqYk2vAr2T4RpvaVLJ5Qn/cL8Sga3+emJA3neoVjM8g06HzPQcJVAsSO TsjTeGFK5v251qLvTlZ4CfAJS3PRAteE+V+7higHaCCLfqInDZ3F15clzO5VwlSM/2cp ehuuVDaKy74XjQhQjR5yRS0SeO1+C+YnM0GCoH+qXUoKj3V1kznHY8FU4FNWyO7Lf6Fz mxIZxa5TWnCdpeS00Q9ihz3nEX4CEAcBq3Buand0Dt3sHKKYHZJiNKYBlQiAGIeNttpX jIfMHzwxAWSe2ftFDTC8AsktLEQPVMgQQCYUmPojTleN3qwsZwTs65frmG58VgrkjY97 7zIQ== X-Gm-Message-State: AOAM530Ta8/JuR8GDi+NhXVRXDhF7N0bdWPDncZWPQsqcs9hntenR8MS IAgRTyBxysTHf3VNnZ+0gN3L89+USqM= X-Google-Smtp-Source: ABdhPJxkG1n/bG47Eu5bO71pGtFGBPeTrE6kdJy5Bk4e8t1a/KBNaC9D2MMTLir9BjTmj+4ngklLQg== X-Received: by 2002:a17:902:bd07:: with SMTP id p7mr16584940pls.293.1589822847404; Mon, 18 May 2020 10:27:27 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.26 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:26 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, James Prestwood Subject: [PATCH 15/17] include: crypto: add asym_tpm2_subtype definition Date: Mon, 18 May 2020 10:27:02 -0700 Message-Id: <20200518172704.29608-16-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org This defines the structure of a TPM2 key in the kernel. Signed-off-by: James Prestwood --- include/crypto/asym_tpm2_subtype.h | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 include/crypto/asym_tpm2_subtype.h diff --git a/include/crypto/asym_tpm2_subtype.h b/include/crypto/asym_tpm2_subtype.h new file mode 100644 index 000000000000..dea80b2e6e66 --- /dev/null +++ b/include/crypto/asym_tpm2_subtype.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_ASYM_TPM2_SUBTYPE_H +#define _LINUX_ASYM_TPM2_SUBTYPE_H + +#include + +struct tpm2_parse_context { + u32 parent; + const u8 *pub; + u32 pub_len; + const u8 *priv; + u32 priv_len; +}; + +struct tpm2_key { + struct tpm_chip *chip; + u32 parent; + + u8 *blob; + u32 bloblen; + + /* pointer into 'blob' where public key begins */ + const u8 *pub; + u32 pub_len; + +}; + +struct tpm2_key *tpm2_key_create(struct tpm2_parse_context *ctx); + +extern struct asymmetric_key_subtype asym_tpm2_subtype; + +#endif /* _LINUX_ASYM_TPM2_SUBTYPE_H */ From patchwork Mon May 18 17:27:03 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555927 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 35884912 for ; Mon, 18 May 2020 17:27:31 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 1DF6820715 for ; Mon, 18 May 2020 17:27:31 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="Ll9F8NFl" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728419AbgERR1a (ORCPT ); Mon, 18 May 2020 13:27:30 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57560 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728304AbgERR1a (ORCPT ); Mon, 18 May 2020 13:27:30 -0400 Received: from mail-pl1-x641.google.com (mail-pl1-x641.google.com [IPv6:2607:f8b0:4864:20::641]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 5F24CC061A0C for ; Mon, 18 May 2020 10:27:29 -0700 (PDT) Received: by mail-pl1-x641.google.com with SMTP id u22so4486470plq.12 for ; Mon, 18 May 2020 10:27:29 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=0DOoC6RMfZHUYe1siAwmYdu5ypSLhE4eC+mZXq5SbvM=; b=Ll9F8NFlU1tpDY768EM2RpsA1a/A0D2rE4NUCyxhvGvSRIc80M9oJldUMGcpy140/J 6gDaSHULILCFMzaTNkj/9WC0Nz2NtNJUTU1haisZ/uSnszcSpcn8QWAjEZYYEg6Zp63e tu6D6NbmZ5pIG3kNhPKqAneAMFsT6eywzgq/WfJ4MqTX/V0LQy/oOAU/kotagGzzMf2n XVw4dF4f9Aumc4pJdz5SXwn7sb+gpuQ9amJNz579qj+1tNmhx7pdvOTbn8FE2h1lP8CC eZa82H5TcYil3ot5gJb6MNWx016+UdIHof+fCgB/yjqHnuxczxdY1+QRi4pL7AVKxvlQ iljQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=0DOoC6RMfZHUYe1siAwmYdu5ypSLhE4eC+mZXq5SbvM=; b=YQGZb4Ou+HS8L0qVpsreHEo65opYvIjvFmi2bDb0Dx6m7LAla4ewGPY5TEKD+IIL0K 4ppTQ6XrmEFPBoweDQxAZ97MEJRtuNVj5Z19C5TSlMw+YCdb1jaqowvQVzTXq2/CvHRH /nhxry2I442Qs3WsxLj0VBoC+CJERL27H4IKmhvCTBKcVQwPnS30/wJ8LKcxCJlrU2JJ XkYt1Q/xQGFNYbMAAlBPZYsOcHVD9yVjO9j+LPumlXptNjl2Q/5XlttYc5Q3nekgZNv9 sooNCQhMH7dlAwMeF9eEgJAM16e6OlKt10wSa4kYsOrb1L9nP3mVUY6leAFFNnaXNivk V5Bw== X-Gm-Message-State: AOAM530cb8rN9LnIsRNrLI0vL5k1mPrOps13TvHddIKpXfuQZAT5PRR9 krPDkE5YdAoGyezbtpsxTkKCgTcHRLc= X-Google-Smtp-Source: ABdhPJxXO+Iijo8QoiBM2gZjrWlDZdKXpOt4S34pUpXvBFKYLT8nCqTZF3zz0jaEfik7vq7WiiHNZA== X-Received: by 2002:a17:902:c254:: with SMTP id 20mr3994883plg.287.1589822848667; Mon, 18 May 2020 10:27:28 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.27 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:28 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, James Prestwood Subject: [PATCH 16/17] asymmetric_keys: add TPM2 ASN1 definition Date: Mon, 18 May 2020 10:27:03 -0700 Message-Id: <20200518172704.29608-17-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org Copied the TPM2 ASN1 definition from trusted-keys Signed-off-by: James Prestwood --- crypto/asymmetric_keys/tpm2key.asn1 | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 crypto/asymmetric_keys/tpm2key.asn1 diff --git a/crypto/asymmetric_keys/tpm2key.asn1 b/crypto/asymmetric_keys/tpm2key.asn1 new file mode 100644 index 000000000000..f930fd812db3 --- /dev/null +++ b/crypto/asymmetric_keys/tpm2key.asn1 @@ -0,0 +1,23 @@ +--- +--- Note: This isn't quite the definition in the standard +--- However, the Linux asn.1 parser doesn't understand +--- [2] EXPLICIT SEQUENCE OF OPTIONAL +--- So there's an extra intermediate TPMPolicySequence +--- definition to work around this + +TPMKey ::= SEQUENCE { + type OBJECT IDENTIFIER ({tpmkey_type}), + emptyAuth [0] EXPLICIT BOOLEAN OPTIONAL, + policy [1] EXPLICIT TPMPolicySequence OPTIONAL, + secret [2] EXPLICIT OCTET STRING OPTIONAL, + parent INTEGER ({tpmkey_parent}), + pubkey OCTET STRING ({tpmkey_pub}), + privkey OCTET STRING ({tpmkey_priv}) + } + +TPMPolicySequence ::= SEQUENCE OF TPMPolicy + +TPMPolicy ::= SEQUENCE { + commandCode [0] EXPLICIT INTEGER ({tpmkey_code}), + commandPolicy [1] EXPLICIT OCTET STRING ({tpmkey_policy}) + } From patchwork Mon May 18 17:27:04 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: James Prestwood X-Patchwork-Id: 11555929 Return-Path: Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org [172.30.200.123]) by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 8106714C0 for ; Mon, 18 May 2020 17:27:31 +0000 (UTC) Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by mail.kernel.org (Postfix) with ESMTP id 5F41B20715 for ; Mon, 18 May 2020 17:27:31 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="ttv5JcA7" Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1728304AbgERR1b (ORCPT ); Mon, 18 May 2020 13:27:31 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57566 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1728431AbgERR1a (ORCPT ); Mon, 18 May 2020 13:27:30 -0400 Received: from mail-pg1-x541.google.com (mail-pg1-x541.google.com [IPv6:2607:f8b0:4864:20::541]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D4D53C061A0C for ; Mon, 18 May 2020 10:27:30 -0700 (PDT) Received: by mail-pg1-x541.google.com with SMTP id r22so5134342pga.12 for ; Mon, 18 May 2020 10:27:30 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=mbcNhwZGtp7M2ujUPrtGuXEmg3QICxFoR1Qaw0sW7AU=; b=ttv5JcA740SpkyqqF9/RO6aJeSu2vvav3KHh0ognttIBDOQh7hVEl4ihVyVqbgclfg JFm7Sc+bnkOAb4UHC40NGn4mi8YqzOuuXWpYs0ZWUjufSYIlDXLVVEUvynDF2K1vhc0X zIbK4V2rM7ng82aLN9FwIfu0OHkz4CM579g56s+gq78DoyMmfB2W7yXhKfQHNIsK3paM DLr9Xr9FwOm7QmCrGBxTx7Lu0PoHb1xyQ2oAkxq2EJYisLxZCUlL7UN4XzMZgP9cVQaJ yD3OptgqviS/348YdcU+x1h0+mXswgeUImtAIzak5Dp37TNQN/EEP6nJCtO6DoVzkzsQ eU5g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=mbcNhwZGtp7M2ujUPrtGuXEmg3QICxFoR1Qaw0sW7AU=; b=d58CXGHgdqqf9p0vyHrUKLmo0H7ttztyMUtuctw89hWCHUc5YljxdE6z9B9KstdvuS C3zkYEWWWk3Qvh8slH58icf1WliZyFKMPnpj60uG72Hh8LXwTscl9uuqssxCzGBxhRTJ 8t2yu99R8f7QXqvLDJ1LxnRmxwuidGGsm8nZO4LBFXnuUE/Ug4VHVnobxusZSYkS1SfS 1aDH3AuOqLx2nivEk1okx9en0T+2vHzx9pL/LmqnhX4LiDHnYJ851epNohLi4SAbpZDm gQhu15DFKRDplLlA07D4e/uTn9Q4FQ2oTTtoghkxCAYIz3/pYsIZ1iB2YOd2f+7F/k6c RNtA== X-Gm-Message-State: AOAM533a4E79MFgldqxXnOr8Qb35CL0DPZ71BCeTY/zhphATc3IbYMDF 0mZ1Gf675nWSrHn1u7xzdoby9lH94lc= X-Google-Smtp-Source: ABdhPJyNv7M+p/7uvyrwQnrCbaiVYhPj+wbWFLsNsYp+z94tj1Zq4eg3ydWHzzuLsjGEfgPaLUOEuQ== X-Received: by 2002:a62:760e:: with SMTP id r14mr17638113pfc.92.1589822849583; Mon, 18 May 2020 10:27:29 -0700 (PDT) Received: from host-29.home (50-39-160-111.bvtn.or.frontiernet.net. [50.39.160.111]) by smtp.gmail.com with ESMTPSA id o14sm4092448pfp.89.2020.05.18.10.27.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 18 May 2020 10:27:29 -0700 (PDT) From: James Prestwood To: keyrings@vger.kernel.org Cc: James.Bottomley@HansenPartnership.com, James Prestwood Subject: [PATCH 17/17] asymmetric_keys: add tpm2 key parser/type Date: Mon, 18 May 2020 10:27:04 -0700 Message-Id: <20200518172704.29608-18-prestwoj@gmail.com> X-Mailer: git-send-email 2.21.1 In-Reply-To: <20200518172704.29608-1-prestwoj@gmail.com> References: <20200518172704.29608-1-prestwoj@gmail.com> MIME-Version: 1.0 Sender: keyrings-owner@vger.kernel.org Precedence: bulk List-ID: X-Mailing-List: keyrings@vger.kernel.org This adds support for RSA key operations using a TPM2 wrapped private key. Encryption and verify are done in software as these are operations using only the public key which is not hidden behind the TPM. Decryption and sign use tpm2_rsa_decrypt() for most of the leg work. The key parser uses the ASN.1 definition for TPM2 keys. This parses out the private and public portion of the keys. From here a bit more parsing is done in order to find the portions of these keys which can be handed directly to the TPM for decryption/sign. Signed-off-by: James Prestwood --- crypto/asymmetric_keys/Kconfig | 20 + crypto/asymmetric_keys/Makefile | 12 + crypto/asymmetric_keys/asym_tpm2.c | 653 +++++++++++++++++++++++++++ crypto/asymmetric_keys/tpm2_parser.c | 155 +++++++ 4 files changed, 840 insertions(+) create mode 100644 crypto/asymmetric_keys/asym_tpm2.c create mode 100644 crypto/asymmetric_keys/tpm2_parser.c diff --git a/crypto/asymmetric_keys/Kconfig b/crypto/asymmetric_keys/Kconfig index 1f1f004dc757..f3f7afffa9b0 100644 --- a/crypto/asymmetric_keys/Kconfig +++ b/crypto/asymmetric_keys/Kconfig @@ -34,6 +34,17 @@ config ASYMMETRIC_TPM_KEY_SUBTYPE Operations such as sign, verify, encrypt, decrypt are performed by the TPM after the private key is loaded. +config ASYMMETRIC_TPM2_KEY_SUBTYPE + tristate "Asymmetric TPM2 backed private key subtype" + depends on TCG_TPM + select CRYPTO_RSA + select CRYPTO_SHA256 + select CRYPTO_HASH_INFO + help + This option provides support for TPM2 backed private key type + handling. Operations such as sign, verify, encrypt, decrypt are + performed by the TPM2 after the private key is loaded. + config X509_CERTIFICATE_PARSER tristate "X.509 certificate parser" depends on ASYMMETRIC_PUBLIC_KEY_SUBTYPE @@ -63,6 +74,15 @@ config TPM_KEY_PARSER private key data and provides the ability to instantiate a crypto key from that data. +config TPM2_KEY_PARSER + tristate "TPM2 private key parser" + depends on ASYMMETRIC_TPM2_KEY_SUBTYPE + select ASN1 + help + This option provides support for parsing TPM2 format blobs for + private key data and provides the ability to instantiate a crypto key + from that data. + config PKCS7_MESSAGE_PARSER tristate "PKCS#7 message parser" depends on X509_CERTIFICATE_PARSER diff --git a/crypto/asymmetric_keys/Makefile b/crypto/asymmetric_keys/Makefile index 28b91adba2ae..7ce121366395 100644 --- a/crypto/asymmetric_keys/Makefile +++ b/crypto/asymmetric_keys/Makefile @@ -12,6 +12,7 @@ asymmetric_keys-y := \ obj-$(CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key.o obj-$(CONFIG_ASYMMETRIC_TPM_KEY_SUBTYPE) += asym_tpm.o +obj-$(CONFIG_ASYMMETRIC_TPM2_KEY_SUBTYPE) += asym_tpm2.o # # X.509 Certificate handling @@ -86,3 +87,14 @@ tpm_key_parser-y := \ $(obj)/tpm_parser.o: $(obj)/tpm.asn1.h $(obj)/tpm.asn1.o: $(obj)/tpm.asn1.c $(obj)/tpm.asn1.h + +# +# TPM2 private key parsing +# +obj-$(CONFIG_TPM2_KEY_PARSER) += tpm2_key_parser.o +tpm2_key_parser-y := \ + tpm2key.asn1.o \ + tpm2_parser.o + +$(obj)/tpm2_parser.o: $(obj)/tpm2key.asn1.h +$(obj)/tpm2key.asn1.o: $(obj)/tpm2key.asn1.c $(obj)/tpm2key.asn1.h diff --git a/crypto/asymmetric_keys/asym_tpm2.c b/crypto/asymmetric_keys/asym_tpm2.c new file mode 100644 index 000000000000..1a5a32a691b9 --- /dev/null +++ b/crypto/asymmetric_keys/asym_tpm2.c @@ -0,0 +1,653 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#define pr_fmt(fmt) "ASYM-TPM2: "fmt +#include +#include +#include +#include +#include +#include +#include +#include +#include "tpm2key.asn1.h" + +/* Room to fit two u32 zeros for algo id and parameters length. */ +#define SETKEY_PARAMS_SIZE (sizeof(u32) * 2) + +/* + * Maximum buffer size for the BER/DER encoded public key. The public key + * is of the form SEQUENCE { INTEGER n, INTEGER e } where n is a maximum 2048 + * bit key and e is usually 65537 + * The encoding overhead is: + * - max 4 bytes for SEQUENCE + * - max 4 bytes for INTEGER n type/length + * - 257 bytes of n + * - max 2 bytes for INTEGER e type/length + * - 3 bytes of e + * - 4+4 of zeros for set_pub_key parameters (SETKEY_PARAMS_SIZE) + */ +#define PUB_KEY_BUF_SIZE (4 + 4 + 257 + 2 + 3 + SETKEY_PARAMS_SIZE) + +/* How many bytes will it take to encode the length */ +static inline u32 definite_length(u32 len) +{ + if (len <= 127) + return 1; + if (len <= 255) + return 2; + return 3; +} + +static inline u8 *encode_tag_length(u8 *buf, u8 tag, u32 len) +{ + *buf++ = tag; + + if (len <= 127) { + buf[0] = len; + return buf + 1; + } + + if (len <= 255) { + buf[0] = 0x81; + buf[1] = len; + return buf + 2; + } + + buf[0] = 0x82; + put_unaligned_be16(len, buf + 1); + return buf + 3; +} + +static u32 derive_pub_key(const void *pub_key, u32 len, u8 *buf) +{ + u8 *cur = buf; + u32 n_len = definite_length(len) + 1 + len + 1; + u32 e_len = definite_length(3) + 1 + 3; + u8 e[3] = { 0x01, 0x00, 0x01 }; + + /* SEQUENCE */ + cur = encode_tag_length(cur, 0x30, n_len + e_len); + /* INTEGER n */ + cur = encode_tag_length(cur, 0x02, len + 1); + cur[0] = 0x00; + memcpy(cur + 1, pub_key, len); + cur += len + 1; + cur = encode_tag_length(cur, 0x02, sizeof(e)); + memcpy(cur, e, sizeof(e)); + cur += sizeof(e); + /* Zero parameters to satisfy set_pub_key ABI. */ + memset(cur, 0, SETKEY_PARAMS_SIZE); + + return cur - buf; +} + +static void asym_tpm2_describe(const struct key *asymmetric_key, + struct seq_file *m) +{ + struct tpm2_key *tk = asymmetric_key->payload.data[asym_crypto]; + + if (!tk) + return; + + seq_puts(m, "TPM2.0/Blob"); +} + +static void asym_tpm2_destroy(void *payload0, void *payload3) +{ + struct tpm2_key *tk = payload0; + + if (!tk) + return; + + kfree(tk->blob); + kfree(tk); +} + +/* + * Determine the crypto algorithm name. + */ +static int determine_akcipher(const char *encoding, const char *hash_algo, + char alg_name[CRYPTO_MAX_ALG_NAME]) +{ + if (strcmp(encoding, "pkcs1") == 0) { + if (!hash_algo) { + strcpy(alg_name, "pkcs1pad(rsa)"); + return 0; + } + + if (snprintf(alg_name, CRYPTO_MAX_ALG_NAME, "pkcs1pad(rsa,%s)", + hash_algo) >= CRYPTO_MAX_ALG_NAME) + return -EINVAL; + + return 0; + } + + if (strcmp(encoding, "raw") == 0) { + strcpy(alg_name, "rsa"); + return 0; + } + + return -ENOPKG; +} + +/* + * Encryption operation is performed with the public key. Hence it is done + * in software + */ +static int tpm2_key_encrypt(struct tpm2_key *tk, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + char alg_name[CRYPTO_MAX_ALG_NAME]; + struct crypto_akcipher *tfm; + struct akcipher_request *req; + struct crypto_wait cwait; + struct scatterlist in_sg, out_sg; + u8 der_pub_key[PUB_KEY_BUF_SIZE]; + u32 der_pub_key_len; + int rc; + + pr_devel("==>%s()\n", __func__); + + rc = determine_akcipher(params->encoding, params->hash_algo, alg_name); + if (rc < 0) + return rc; + + tfm = crypto_alloc_akcipher(alg_name, 0, 0); + if (IS_ERR(tfm)) + return PTR_ERR(tfm); + + der_pub_key_len = derive_pub_key(tk->pub, tk->pub_len, der_pub_key); + + rc = crypto_akcipher_set_pub_key(tfm, der_pub_key, der_pub_key_len); + if (rc < 0) + goto error_free_tfm; + + rc = -ENOMEM; + req = akcipher_request_alloc(tfm, GFP_KERNEL); + if (!req) + goto error_free_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); + + rc = crypto_akcipher_encrypt(req); + rc = crypto_wait_req(rc, &cwait); + + if (rc == 0) + rc = req->dst_len; + + akcipher_request_free(req); +error_free_tfm: + crypto_free_akcipher(tfm); + pr_devel("<==%s() = %d\n", __func__, rc); + return rc; +} + +/* + * PKCS1 padding (type 1) + */ +static int pad_pkcs1(const u8 *m, unsigned int mlen, u8 *em, + unsigned int em_len) +{ + unsigned int ps_len = em_len - mlen - 3; + + if (mlen > em_len - 11) + return -EBADMSG; + + em[0] = 0; + em[1] = 1; + + memset(em + 2, 0xff, ps_len); + + em[2 + ps_len] = 0; + memcpy(em + 2 + ps_len + 1, m, mlen); + + return 0; +} + +/* + * RFC 3447 - Section 7.2.2 + */ +static const u8 *unpad_pkcs1(const u8 *data, unsigned int len, + unsigned int *out_len) +{ + unsigned int i; + + /* + * size of input data should be checked against public key size by + * caller + */ + if (data[0] != 0 || data[1] != 2) + return NULL; + + i = 2; + + while (data[i] != 0 && i < len) + i++; + + if (i == len) + return NULL; + + *out_len = len - i - 1; + + return data + i + 1; +} + +/* + * Decryption operation is performed with the private key in the TPM. + */ +static int tpm2_key_decrypt(struct tpm2_key *tk, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + + int rc; + const u8 *unpadded; + unsigned int unpadded_len; + u8 *decrypted; + + decrypted = kmalloc(tk->pub_len, GFP_KERNEL); + + rc = tpm2_rsa_decrypt(tk->chip, tk->parent, tk->blob, + tk->bloblen, in, params->in_len, decrypted); + if (rc < 0) + return rc; + + unpadded = unpad_pkcs1(decrypted, rc, &unpadded_len); + if (!unpadded) + return -EINVAL; + + memcpy(out, unpadded, unpadded_len); + return unpadded_len; +} + +/* + * Hash algorithm OIDs plus ASN.1 DER wrappings [RFC4880 sec 5.2.2]. + */ +static const u8 digest_info_md5[] = { + 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, /* OID */ + 0x05, 0x00, 0x04, 0x10 +}; + +static const u8 digest_info_sha1[] = { + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, + 0x2b, 0x0e, 0x03, 0x02, 0x1a, + 0x05, 0x00, 0x04, 0x14 +}; + +static const u8 digest_info_rmd160[] = { + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, + 0x2b, 0x24, 0x03, 0x02, 0x01, + 0x05, 0x00, 0x04, 0x14 +}; + +static const u8 digest_info_sha224[] = { + 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, + 0x05, 0x00, 0x04, 0x1c +}; + +static const u8 digest_info_sha256[] = { + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, + 0x05, 0x00, 0x04, 0x20 +}; + +static const u8 digest_info_sha384[] = { + 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, + 0x05, 0x00, 0x04, 0x30 +}; + +static const u8 digest_info_sha512[] = { + 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, + 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, + 0x05, 0x00, 0x04, 0x40 +}; + +static const struct asn1_template { + const char *name; + const u8 *data; + size_t size; +} asn1_templates[] = { +#define _(X) { #X, digest_info_##X, sizeof(digest_info_##X) } + _(md5), + _(sha1), + _(rmd160), + _(sha256), + _(sha384), + _(sha512), + _(sha224), + { NULL } +#undef _ +}; + +static const struct asn1_template *lookup_asn1(const char *name) +{ + const struct asn1_template *p; + + for (p = asn1_templates; p->name; p++) + if (strcmp(name, p->name) == 0) + return p; + return NULL; +} + +/* + * Sign operation is really just an encryption using the TPM's private key. + * With RSA the only difference between encrypt/decrypt is where the padding + * goes. Since we can apply our own padding the TPM2 RSA_Decrypt call can be + * repurposed to do encryption. + */ +static int tpm2_key_sign(struct tpm2_key *tk, + struct kernel_pkey_params *params, + const void *in, void *out) +{ + int rc; + u8 *padded; + void *asn1_wrapped = NULL; + u32 in_len = params->in_len; + + pr_devel("==>%s()\n", __func__); + + if (strcmp(params->encoding, "pkcs1")) { + rc = -ENOPKG; + goto done; + } + + if (params->hash_algo) { + const struct asn1_template *asn1 = + lookup_asn1(params->hash_algo); + + if (!asn1) { + rc = -ENOPKG; + goto done; + } + + /* request enough space for the ASN.1 template + input hash */ + asn1_wrapped = kzalloc(in_len + asn1->size, GFP_KERNEL); + if (!asn1_wrapped) { + rc = -ENOMEM; + goto done; + } + + /* 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; + } + + /* We are using the TPM's decrypt call to sign (aka encrypt). This + * requires pre-padding the data with PKCS1. + */ + padded = kmalloc(tk->pub_len, GFP_KERNEL); + pad_pkcs1(in, in_len, padded, tk->pub_len); + + rc = tpm2_rsa_decrypt(tk->chip, tk->parent, tk->blob, tk->bloblen, + padded, tk->pub_len, out); + + kfree(padded); +done: + kfree(asn1_wrapped); + pr_devel("<==%s() = %d\n", __func__, rc); + return rc; +} + +/* + * Do encryption, decryption and signing ops. + */ +static int tpm2_key_eds_op(struct kernel_pkey_params *params, + const void *in, void *out) +{ + struct tpm2_key *tk = params->key->payload.data[asym_crypto]; + int rc = -EOPNOTSUPP; + + /* Perform the encryption calculation. */ + switch (params->op) { + case kernel_pkey_encrypt: + rc = tpm2_key_encrypt(tk, params, in, out); + break; + case kernel_pkey_decrypt: + rc = tpm2_key_decrypt(tk, params, in, out); + break; + case kernel_pkey_sign: + rc = tpm2_key_sign(tk, params, in, out); + break; + default: + return -EINVAL; + } + + return rc; +} + +/* + * Verify a signature using a public key. + */ +static int tpm2_key_verify_signature(const struct key *key, + const struct public_key_signature *sig) +{ + const struct tpm2_key *tk = key->payload.data[asym_crypto]; + struct crypto_wait cwait; + struct crypto_akcipher *tfm; + struct akcipher_request *req; + struct scatterlist src_sg[2]; + char alg_name[CRYPTO_MAX_ALG_NAME]; + u8 der_pub_key[PUB_KEY_BUF_SIZE]; + u32 der_pub_key_len; + int rc; + + pr_devel("==>%s()\n", __func__); + + if (WARN_ON(!tk || !sig || !sig->s)) + return -EINVAL; + + if (!sig->digest) + return -ENOPKG; + + rc = determine_akcipher(sig->encoding, sig->hash_algo, alg_name); + if (rc < 0) + return rc; + + tfm = crypto_alloc_akcipher(alg_name, 0, 0); + if (IS_ERR(tfm)) + return PTR_ERR(tfm); + + der_pub_key_len = derive_pub_key(tk->pub, tk->pub_len, + der_pub_key); + + rc = crypto_akcipher_set_pub_key(tfm, der_pub_key, der_pub_key_len); + if (rc < 0) + goto error_free_tfm; + + rc = -ENOMEM; + req = akcipher_request_alloc(tfm, GFP_KERNEL); + if (!req) + goto error_free_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); + rc = crypto_wait_req(crypto_akcipher_verify(req), &cwait); + + akcipher_request_free(req); +error_free_tfm: + crypto_free_akcipher(tfm); + pr_devel("<==%s() = %d\n", __func__, rc); + if (WARN_ON_ONCE(rc > 0)) + rc = -EINVAL; + return rc; +} + +/* + * Query information about a key. + */ +static int tpm2_key_query(const struct kernel_pkey_params *params, + struct kernel_pkey_query *info) +{ + int r; + u8 der_pub_key[PUB_KEY_BUF_SIZE]; + u32 der_pub_key_len = 0; + struct tpm2_key *tk = params->key->payload.data[asym_crypto]; + char alg_name[CRYPTO_MAX_ALG_NAME]; + struct crypto_akcipher *tfm; + unsigned int len; + + r = determine_akcipher(params->encoding, params->hash_algo, alg_name); + if (r < 0) + return r; + + tfm = crypto_alloc_akcipher(alg_name, 0, 0); + if (IS_ERR(tfm)) + return PTR_ERR(tfm); + + der_pub_key_len = derive_pub_key(tk->pub, tk->pub_len, + der_pub_key); + + r = crypto_akcipher_set_pub_key(tfm, der_pub_key, der_pub_key_len); + if (r < 0) + goto error_free_tfm; + + len = crypto_akcipher_maxsize(tfm); + + info->key_size = tk->pub_len * 8; + info->max_data_size = tk->pub_len; + info->max_sig_size = len; + info->max_enc_size = len; + info->max_dec_size = tk->pub_len; + + info->supported_ops = KEYCTL_SUPPORTS_ENCRYPT | + KEYCTL_SUPPORTS_DECRYPT | + KEYCTL_SUPPORTS_VERIFY | + KEYCTL_SUPPORTS_SIGN; + + r = 0; +error_free_tfm: + crypto_free_akcipher(tfm); + return r; +} + +static int extract_key_parameters(struct tpm2_parse_context *ctx, + struct tpm2_key *tk) +{ + const u8 *cur = ctx->pub; + int total; + u16 policy_len; + u16 len; + + total = get_unaligned_be16(cur); + + if (total != ctx->pub_len - 2) + return -EMSGSIZE; + cur += 2; + + /* type: TPMI_ALG_PUBLIC: TPM2_ALG_RSA */ + if (get_unaligned_be16(cur) != 0x0001) + return -EINVAL; + cur += 2; + + /* nameAlg: TPMI_ALG_HASH: */ + cur += 2; + + /* skip past TPMA_OBJECT */ + cur += 4; + + policy_len = get_unaligned_be16(cur); + cur += 2; + cur += policy_len; + + /* ALG_NULL */ + if (get_unaligned_be16(cur) != 0x0010) + return -EINVAL; + cur += 2; + + if (get_unaligned_be16(cur) != 0x0010) + return -EINVAL; + cur += 2; + + /* key bits */ + cur += 2; + + if (get_unaligned_be32(cur) != 0x00000000) + return -EINVAL; + cur += 4; + + len = get_unaligned_be16(cur); + cur += 2; + + /* + * Copy both private/public parts into the blob. This buffer can be + * given directly to the TPM as-is + */ + tk->blob = kmalloc(ctx->priv_len + ctx->pub_len, GFP_KERNEL); + tk->bloblen = ctx->priv_len + ctx->pub_len; + memcpy(tk->blob, ctx->priv, ctx->priv_len); + memcpy(tk->blob + ctx->priv_len, ctx->pub, ctx->pub_len); + + /* set offset to public key, for encrypt/verify */ + tk->pub = (tk->blob + ctx->priv_len) + (cur - ctx->pub); + tk->pub_len = len; + + tk->parent = ctx->parent; + + return 0; +} + +/* Given the blob, parse it and load it into the TPM */ +struct tpm2_key *tpm2_key_create(struct tpm2_parse_context *ctx) +{ + int r; + struct tpm2_key *tk; + + r = -ENOMEM; + tk = kzalloc(sizeof(struct tpm2_key), GFP_KERNEL); + if (!tk) + goto error; + + r = extract_key_parameters(ctx, tk); + if (r < 0) { + pr_devel("Failed to extract key parameters (%d)\n", r); + goto error; + } + + tk->chip = tpm_default_chip(); + + return tk; + +error: + return ERR_PTR(r); +} +EXPORT_SYMBOL_GPL(tpm2_key_create); + +/* + * TPM-based asymmetric key subtype + */ +struct asymmetric_key_subtype asym_tpm2_subtype = { + .owner = THIS_MODULE, + .name = "asym_tpm2", + .name_len = sizeof("asym_tpm2") - 1, + .describe = asym_tpm2_describe, + .destroy = asym_tpm2_destroy, + .query = tpm2_key_query, + .eds_op = tpm2_key_eds_op, + .verify_signature = tpm2_key_verify_signature, +}; +EXPORT_SYMBOL_GPL(asym_tpm2_subtype); + +MODULE_DESCRIPTION("TPM2 based asymmetric key subtype"); +MODULE_AUTHOR("Intel Corporation"); +MODULE_LICENSE("GPL v2"); diff --git a/crypto/asymmetric_keys/tpm2_parser.c b/crypto/asymmetric_keys/tpm2_parser.c new file mode 100644 index 000000000000..4e80cd6cdd2c --- /dev/null +++ b/crypto/asymmetric_keys/tpm2_parser.c @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-2.0 +#define pr_fmt(fmt) "TPM-PARSER: "fmt +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "tpm2key.asn1.h" + +int tpmkey_parent(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_parse_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 tpmkey_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_TPMLoadableKey) { + char buffer[50]; + + sprint_oid(value, vlen, buffer, sizeof(buffer)); + pr_debug("OID is \"%s\" which is not TPMLoadableKey\n", + buffer); + return -EINVAL; + } + return 0; +} + +int tpmkey_pub(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_parse_context *ctx = context; + + ctx->pub = value; + ctx->pub_len = vlen; + return 0; +} + +int tpmkey_priv(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + struct tpm2_parse_context *ctx = context; + + ctx->priv = value; + ctx->priv_len = vlen; + return 0; +} + +int tpmkey_code(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + return 0; +} + +int tpmkey_policy(void *context, size_t hdrlen, + unsigned char tag, + const void *value, size_t vlen) +{ + return 0; +} + +/* + * Parse a TPM2-encrypted private key blob. + */ +static struct tpm2_key *tpm2_parse(const void *data, size_t datalen) +{ + struct tpm2_parse_context ctx; + long ret; + + memset(&ctx, 0, sizeof(ctx)); + + /* Attempt to decode the private key */ + ret = asn1_ber_decoder(&tpm2key_decoder, &ctx, data, datalen); + if (ret < 0) { + pr_devel("asn1_ber_decorder failed %ld\n", ret); + goto error; + } + + return tpm2_key_create(&ctx); + +error: + return ERR_PTR(ret); +} + +/* + * Attempt to parse a data blob for a key as a TPM private key blob. + */ +static int tpm2_key_preparse(struct key_preparsed_payload *prep) +{ + struct tpm2_key *tk; + + /* + * TPM 2.0 RSA keys are recommended to be 2048 bits long, so assume the + * blob is no more than 4x that + */ + if (prep->datalen > 256 * 4) + return -EMSGSIZE; + + tk = tpm2_parse(prep->data, prep->datalen); + + if (IS_ERR(tk)) + return PTR_ERR(tk); + + /* We're pinning the module by being linked against it */ + __module_get(asym_tpm2_subtype.owner); + prep->payload.data[asym_subtype] = &asym_tpm2_subtype; + prep->payload.data[asym_key_ids] = NULL; + prep->payload.data[asym_crypto] = tk; + prep->payload.data[asym_auth] = NULL; + prep->quotalen = 100; + return 0; +} + +static struct asymmetric_key_parser tpm2_key_parser = { + .owner = THIS_MODULE, + .name = "tpm2_parser", + .parse = tpm2_key_preparse, +}; + +static int __init tpm2_key_init(void) +{ + return register_asymmetric_key_parser(&tpm2_key_parser); +} + +static void __exit tpm2_key_exit(void) +{ + unregister_asymmetric_key_parser(&tpm2_key_parser); +} + +module_init(tpm2_key_init); +module_exit(tpm2_key_exit); + +MODULE_DESCRIPTION("TPM2 private key-blob parser"); +MODULE_LICENSE("GPL v2");