Skip to contentSkip to conversation

add integrity and security to TPM2 transactions

PATCH Superseded James Bottomley 6 participants 32 messages Jan 24, 2023 – Feb 17, 2023

Subsystems (5)

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

James Bottomley

author maintainer
#0 lore raw

v2 cover add integrity and security to TPM2 transactions

The interest in securing the TPM against interposers, both active and passive has risen to fever pitch with the demonstration of key recovery against windows bitlocker:

https://dolosgroup.io/blog/2021/7/9/from-stolen-laptop-to-inside-the-company-network

And subsequently the same attack being successful against all the Linux TPM based security solutions:

https://www.secura.com/blog/tpm-sniffing-attacks-against-non-bitlocker-targets

The attacks fall into two categories:

1. Passive Interposers, which sit on the bus and merely observe
2. Active Interposers, which try to manipulate TPM transactions on the bus using man in the middle and packet stealing to create TPM state the interposer owner desires.

Our broadest interposer target is the use of TPM_RS_PW for password authorization which sends the actual password to the TPM without any obfuscation and effectively hands it to any interposer. The way to fix this is to use real sessions for HMAC capabilities to ensure integrity and to use parameter and response encryption to ensure confidentiality of the data flowing over the TPM bus. HMAC sessions by agreeing a challenge with the TPM and then giving a response which is a HMAC of the password and the challenge, so the application proves knowledge of the password to the TPM without ever transmitting the password itself. Using HMAC sessions when sending commands to the TPM also provides some measure of protection against active interposers, since the interposer can't interfere with or delete a HMAC'd command (because they can't manufacture a response with the correct HMAC).

To protect TPM transactions where there isn't a shared secret (i.e. the command is something like a PCR extension which doesn't involve a TPM object with a password) we have to do a bit more work to set up sessions with a passed in encrypted secret (called a salt) to act in place of the shared secret in the HMAC. This secret salt is effectively a random number encrypted to a public key of the TPM. The final piece of the puzzle is using parameter input and response return encryption, so any interposer can't see the data passing from the application to the TPM and vice versa.

The most insidious interposer attack of all is a reset attack: since the interposer has access to the TPM bus, it can assert the TPM reset line any time it wants. When a TPM resets it mostly comes back in the same state except that all the PCRs are reset to their initial values. Controlling the reset line allows the interposer to change the PCR state after the fact by resetting the TPM and then replaying PCR extends to get the PCRs into a valid state to release secrets, so even if an attack event was recorded, the record is erased. This reset attack violates the fundamental princible of non-repudiability of TPM logs. Defeating the reset attack involves tying all TPM operations within the kernel to a property which will change detectably if the TPM is reset. For that reason, we tie all TPM sessions to the null hierarchy we obtain at start of day and whose seed changes on every reset. If an active interposer asserts a TPM reset, the new null primary won't match the kernel's stored one and all TPM operations will start failing because of HMAC mismatches in the sessions. So if the kernel TPM code keeps operating, it guarantees that a reset hasn't occurred.

The final part of the puzzle is that the machine owner must have a fixed idea of the EK of their TPM and should have certified this with the TPM manufacturer. On every boot, the certified EK public key should be used to do a make credential/activate credential attestation key insertion and then the null key certified with the attestation key. We can follow a trust on first use model where an OS installation will extract and verify a public EK and save it to a read only file.

This patch series adds a simple API which can ensure the above properties as a layered addition to the existing TPM handling code. This series now includes protections for PCR extend, getting random numbers from the TPM and data sealing and unsealing. It therefore eliminates all uses of TPM2_RS_PW in the kernel and adds encryption protection to sensitive data flowing into and out of the TPM. The first four patches add more sophisticated buffer handling to the TPM which is needed to build the more complex encryption and authentication based commands. Patch 6 adds all the generic cryptography primitives and patches 7-9 use them in critical TPM operations where we want to avoid or detect interposers. Patch 10 exports the name of the null key we used for boot/run time verification and patch 11 documents the security guarantees and expectations.

This was originally sent over four years ago, with the last iteration being:

https://lore.kernel.org/linux-integrity/[email protected]/

I'm dusting it off now because various forces at Microsoft and Google via the Open Compute Platform are making a lot of noise about interposers and we in the linux kernel look critically lacking in that regard, particularly for TPM trusted keys.

---
v2 fixes the problems smatch reported and adds more explanation about the code motion in the first few patches

James

---

James Bottomley (11):
tpm: move buffer handling from static inlines to real functions
tpm: add buffer handling for TPM2B types
tpm: add cursor based buffer functions for response parsing
tpm: add buffer function to point to returned parameters
tpm: export the context save and load commands
tpm: Add full HMAC and encrypt/decrypt session handling code
tpm: add hmac checks to tpm2_pcr_extend()
tpm: add session encryption protection to tpm2_get_random()
KEYS: trusted: Add session encryption protection to the seal/unseal
path
tpm: add the null key name as a sysfs export
Documentation: add tpm-security.rst

 Documentation/security/tpm/tpm-security.rst |  214 ++++
 drivers/char/tpm/Kconfig                    |   13 +
 drivers/char/tpm/Makefile                   |    2 +
 drivers/char/tpm/tpm-buf.c                  |  197 +++
 drivers/char/tpm/tpm-sysfs.c                |   14 +
 drivers/char/tpm/tpm.h                      |   14 +
 drivers/char/tpm/tpm2-cmd.c                 |   54 +-
 drivers/char/tpm/tpm2-sessions.c            | 1216 +++++++++++++++++++
 drivers/char/tpm/tpm2-space.c               |    8 +-
 include/linux/tpm.h                         |  252 ++--
 security/keys/trusted-keys/trusted_tpm2.c   |   85 +-
 11 files changed, 1944 insertions(+), 125 deletions(-)
 create mode 100644 Documentation/security/tpm/tpm-security.rst
 create mode 100644 drivers/char/tpm/tpm-buf.c
 create mode 100644 drivers/char/tpm/tpm2-sessions.c
Signature · 1 line
2.35.3
author maintainer
#1 lore raw

PATCH v2 1/11 tpm: move buffer handling from static inlines to real functions

separate out the tpm_buf_... handling functions from static inlines in tpm.h and move them to their own tpm-buf.c file. This is a precursor to adding new functions for other TPM type handling becuase the amount of code will grow from the current 70 lines in tpm.h to about 200 lines when the additions are done. 200 lines of inline functions is a bit too much to keep in a header file.

---
 drivers/char/tpm/Makefile  |  1 +
 drivers/char/tpm/tpm-buf.c | 96 ++++++++++++++++++++++++++++++++++++++
 include/linux/tpm.h        | 86 ++++------------------------------
 3 files changed, 106 insertions(+), 77 deletions(-)
 create mode 100644 drivers/char/tpm/tpm-buf.c
drivers/char/tpm/Makefile +1 -0
index 0222b1ddb310..ad3594e383e1 100644
@@ -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
drivers/char/tpm/tpm-buf.c new file +96 -0

96 lines not on this page · raw message

include/linux/tpm.h +9 -77

93 lines not on this page · raw message

Signature · 1 line
2.35.3
#2 lore raw

Re: [PATCH v2 01/11] tpm: move buffer handling from static inlines to real functions

I love your patch! Perhaps something to improve:

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-20230124] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:    https://lore.kernel.org/r/20230124175516.5984-2-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 01/11] tpm: move buffer handling from static inlines to real functions
config: sparc-allyesconfig (https://download.01.org/0day-ci/archive/20230125/[email protected]/config)
compiler: sparc64-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/484b879d0bfceec899fea147a76d12f7072d9f23
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout 484b879d0bfceec899fea147a76d12f7072d9f23
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=sparc olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=sparc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

>> drivers/char/tpm/tpm-buf.c:46:5: warning: no previous prototype for 'tpm_buf_tag' [-Wmissing-prototypes]
      46 | u16 tpm_buf_tag(struct tpm_buf *buf)
         |     ^~~~~~~~~~~

vim +/tpm_buf_tag +46 drivers/char/tpm/tpm-buf.c

    45	
  > 46	u16 tpm_buf_tag(struct tpm_buf *buf)
    47	{
    48		struct tpm_header *head = (struct tpm_header *)buf->data;
    49	
    50		return be16_to_cpu(head->tag);
    51	}
    52	EXPORT_SYMBOL_GPL(tpm_buf_tag);
    53	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
author maintainer
#3 lore raw

Re: [PATCH v2 01/11] tpm: move buffer handling from static inlines to real functions

Quoted 45 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char-misc/char- misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next- 20230124]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-2-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 01/11] tpm: move buffer handling from static inlines to real functions
config: sparc-allyesconfig
(https://download.01.org/0day-ci/archive/20230125/202301250315.ZgtsNz
[email protected]/config)
compiler: sparc64-linux-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/484b879d0bfceec899fea147a76d12f7072d9f23
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm-move- buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout 484b879d0bfceec899fea147a76d12f7072d9f23

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=sparc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=sparc SHELL=/bin/bash
drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 8 lines
Quoted 1 line

All warnings (new ones prefixed by >>):

Quoted 2 lines
Quoted 2 lines

drivers/char/tpm/tpm-buf.c:46:5: warning: no previous prototype for 'tpm_buf_tag' [-Wmissing-prototypes]

      46 | u16 tpm_buf_tag(struct tpm_buf *buf)
         |     ^~~~~~~~~~~

This looks like an initial header got missed in the code motion. However, the fact that nothing broke shows that tpm_buf_tag isn't used outside of the tpm-buf.c functions, so I think I can make it static to them.

James

author maintainer
#4 lore raw

PATCH v2 2/11 tpm: add buffer handling for TPM2B types

In reply to 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.

---
 drivers/char/tpm/tpm-buf.c | 71 +++++++++++++++++++++++++++++++++++---
 include/linux/tpm.h        |  3 ++
 2 files changed, 69 insertions(+), 5 deletions(-)
drivers/char/tpm/tpm-buf.c +66 -5
index 4e6e8b281f6a..f1d48f22d4b4 100644
@@ -7,17 +7,16 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static int __tpm_buf_init(struct tpm_buf *buf)
 {
 	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
 	if (!buf->data)
 		return -ENOMEM;
 
 	buf->flags = 0;
-	tpm_buf_reset(buf, tag, ordinal);
+
 	return 0;
 }
-EXPORT_SYMBOL_GPL(tpm_buf_init);
 
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
@@ -29,17 +28,60 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 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);
+
+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)
 {
 	free_page((unsigned long)buf->data);
 }
 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;
+	u32 len;
 
-	return be32_to_cpu(head->length);
+	len = be32_to_cpu(head->length);
+	if (buf->flags & TPM_BUF_2B)
+		len -= sizeof(*head);
+	return len;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
 
@@ -56,7 +98,7 @@ void tpm_buf_append(struct tpm_buf *buf,
 		    unsigned int new_len)
 {
 	struct tpm_header *head = (struct tpm_header *) buf->data;
-	u32 len = tpm_buf_length(buf);
+	u32 len = be32_to_cpu(head->length);
 
 	/* Return silently if overflow has already happened. */
 	if (buf->flags & TPM_BUF_OVERFLOW)
@@ -94,3 +136,22 @@ 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);
include/linux/tpm.h +3 -0
index 150b39b6190e..f2d4dab6d832 100644
@@ -300,6 +300,7 @@ struct tpm_header {
 
 enum tpm_buf_flags {
 	TPM_BUF_OVERFLOW	= BIT(0),
+	TPM_BUF_2B		= BIT(1),
 };
 
 struct tpm_buf {
@@ -324,6 +325,7 @@ struct tpm2_hash {
 
 
 int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
+int tpm_buf_init_2b(struct tpm_buf *buf);
 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);
@@ -332,6 +334,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);
 
 /*
  * Check if TPM device is in the firmware upgrade mode.
Signature · 1 line
2.35.3
author maintainer
#5 lore raw

PATCH v2 3/11 tpm: add cursor based buffer functions for response parsing

In reply to James Bottomley

Once we have encryption and authentication, marshalling and unmarshalling sessions becomes hugely complex. Add cursor based functions which update the current pointer to make response parsing easier.

---
 drivers/char/tpm/tpm-buf.c | 29 +++++++++++++++++++++++++++++
 include/linux/tpm.h        |  3 +++
 2 files changed, 32 insertions(+)
drivers/char/tpm/tpm-buf.c +29 -0
index f1d48f22d4b4..046b00bf7a81 100644
@@ -7,6 +7,8 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
+#include <asm/unaligned.h>
+
 static int __tpm_buf_init(struct tpm_buf *buf)
 {
 	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
@@ -155,3 +157,30 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
 	tpm_buf_reset_int(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);
include/linux/tpm.h +3 -0
index f2d4dab6d832..f7cff1d114b0 100644
@@ -335,6 +335,9 @@ 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);
+u8 tpm_get_inc_u8(const u8 **ptr);
+u16 tpm_get_inc_u16(const u8 **ptr);
+u32 tpm_get_inc_u32(const u8 **ptr);
 
 /*
  * Check if TPM device is in the firmware upgrade mode.
Signature · 1 line
2.35.3
author maintainer
#6 lore raw

PATCH v2 4/11 tpm: add buffer function to point to returned parameters

In reply to 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

---
 drivers/char/tpm/tpm-buf.c | 10 ++++++++++
 include/linux/tpm.h        |  2 ++
 2 files changed, 12 insertions(+)
drivers/char/tpm/tpm-buf.c +10 -0
index 046b00bf7a81..b054aa2fc84b 100644
@@ -184,3 +184,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];
+}
include/linux/tpm.h +2 -0
index f7cff1d114b0..fa8d1f932c0f 100644
@@ -339,6 +339,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);
+
 /*
  * Check if TPM device is in the firmware upgrade mode.
  */
Signature · 1 line
2.35.3
author maintainer
#7 lore raw

PATCH v2 5/11 tpm: export the context save and load commands

In reply to James Bottomley

The TPM2 session HMAC and encryption 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.

---
 drivers/char/tpm/tpm.h        | 4 ++++
 drivers/char/tpm/tpm2-space.c | 8 ++++----
 2 files changed, 8 insertions(+), 4 deletions(-)
drivers/char/tpm/tpm.h +4 -0
index 24ee4e1cc452..a5fe37977103 100644
@@ -237,6 +237,10 @@ int tpm2_commit_space(struct tpm_chip *chip, struct tpm_space *space, void *buf,
 		      size_t *bufsiz);
 int tpm_devs_add(struct tpm_chip *chip);
 void tpm_devs_remove(struct tpm_chip *chip);
+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);
 
 void tpm_bios_log_setup(struct tpm_chip *chip);
 void tpm_bios_log_teardown(struct tpm_chip *chip);
drivers/char/tpm/tpm2-space.c +4 -4
index ffb35f0154c1..d77ee4af9d65 100644
@@ -68,8 +68,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;
@@ -119,8 +119,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;
Signature · 1 line
2.35.3
author maintainer
#8 lore raw

PATCH v2 6/11 tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to James Bottomley

Add true session based HMAC authentication plus parameter decryption and response encryption using AES. The basic design 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 needs a primary key to encrypt the session salt to, so an EC key from the NULL seed is derived and its context saved 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.

---

v2: fix memory leaks from smatch; adjust for name hash size

---
 drivers/char/tpm/Kconfig         |   13 +
 drivers/char/tpm/Makefile        |    1 +
 drivers/char/tpm/tpm-buf.c       |    1 +
 drivers/char/tpm/tpm.h           |   10 +
 drivers/char/tpm/tpm2-cmd.c      |    5 +
 drivers/char/tpm/tpm2-sessions.c | 1216 ++++++++++++++++++++++++++++++
 include/linux/tpm.h              |  160 ++++
 7 files changed, 1406 insertions(+)
 create mode 100644 drivers/char/tpm/tpm2-sessions.c
drivers/char/tpm/Kconfig +13 -0
index 927088b2c3d3..74bd174f1a7b 100644
@@ -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,16 @@ 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 and iterposer 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)
drivers/char/tpm/Makefile +1 -0
index ad3594e383e1..10dc214aa093 100644
@@ -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
drivers/char/tpm/tpm-buf.c +1 -0
index b054aa2fc84b..fe3320731217 100644
@@ -27,6 +27,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);
 
drivers/char/tpm/tpm.h +10 -0
index a5fe37977103..b3eb0f31bfd9 100644
@@ -246,4 +246,14 @@ void 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
drivers/char/tpm/tpm2-cmd.c +5 -0
index 65d03867e114..056dad3dd5c9 100644
@@ -759,6 +759,11 @@ int tpm2_auto_startup(struct tpm_chip *chip)
 		rc = 0;
 	}
 
+	if (rc)
+		goto out;
+
+	rc = tpm2_sessions_init(chip);
+
 out:
 	/*
 	 * Infineon TPM in field upgrade mode will return no data for the number
drivers/char/tpm/tpm2-sessions.c new file +1216 -0

1,216 lines not on this page · raw message

include/linux/tpm.h +160 -0

240 lines not on this page · raw message

Signature · 1 line
2.35.3
#9 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

I love your patch! Perhaps something to improve:

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-20230124] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:    https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: sparc-allyesconfig (https://download.01.org/0day-ci/archive/20230125/[email protected]/config)
compiler: sparc64-linux-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=sparc olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=sparc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

>> drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes]
    1184 | int tpm2_create_null_primary(struct tpm_chip *chip) {
         |     ^~~~~~~~~~~~~~~~~~~~~~~~
--
>> drivers/char/tpm/tpm2-sessions.c:352: warning: This comment starts with '/**', but isn't a kernel-doc comment. Refer Documentation/doc-guide/kernel-doc.rst

* tpm_buf_append_hmac_session() append a TPM session element

vim +/tpm2_create_null_primary +1184 drivers/char/tpm/tpm2-sessions.c

1183

> 1184	int tpm2_create_null_primary(struct tpm_chip *chip) {

1185 u32 nullkey;
1186 int rc;
1187
1188 rc = tpm2_create_primary(chip, TPM2_RH_NULL, &nullkey);
1189
1190 if (rc == TPM2_RC_SUCCESS) {
1191 unsigned int offset = 0; /* dummy offset for tpmkeycontext */
1192
1193 rc = tpm2_save_context(chip, nullkey, chip->tpmkeycontext,
1194 sizeof(chip->tpmkeycontext), &offset);
1195 tpm2_flush_context(chip, nullkey);
1196 }
1197
1198 return rc;
1199 }
1200

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#10 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to James Bottomley
I love your patch! Perhaps something to improve:

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-20230124] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:    https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig (https://download.01.org/0day-ci/archive/20230125/[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=arc olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

All warnings (new ones prefixed by >>):

drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes]

    1184 | int tpm2_create_null_primary(struct tpm_chip *chip) {
         |     ^~~~~~~~~~~~~~~~~~~~~~~~
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':
>> drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]
     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]
     579 | }
         | ^

vim +831 drivers/char/tpm/tpm2-sessions.c

676
677 /**
678 * tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness
679 * @buf: the original command buffer (which now contains the response)
680 * @auth: the auth structure allocated by tpm2_start_auth_session()
681 * @rc: the return code from tpm_transmit_cmd
682 *
683 * If @rc is non zero, @buf may not contain an actual return, so @rc
684 * is passed through as the return and the session cleaned up and
685 * de-allocated if required (this is required if
686 * TPM2_SA_CONTINUE_SESSION was not specified as a session flag).
687 *
688 * If @rc is zero, the response HMAC is computed against the returned
689 * @buf and matched to the TPM one in the session area. If there is a
690 * mismatch, an error is logged and -EINVAL returned.
691 *
692 * The reason for this is that the command issue and HMAC check
693 * sequence should look like:
694 *
695 * rc = tpm_transmit_cmd(...);
696 * rc = tpm_buf_check_hmac_response(&buf, auth, rc);
697 * if (rc)
698 * ...
699 *
700 * Which is easily layered into the current contrl flow.
701 *
702 * Returns: 0 on success or an error.
703 */
704 int tpm_buf_check_hmac_response(struct tpm_buf *buf, struct tpm2_auth *auth,
705 int rc)
706 {
707 struct tpm_header *head = (struct tpm_header *)buf->data;
708 struct tpm_chip *chip = auth->chip;
709 const u8 *s, *p;
710 u8 rphash[SHA256_DIGEST_SIZE];
711 u32 attrs;
712 SHASH_DESC_ON_STACK(desc, sha256_hash);
713 u16 tag = be16_to_cpu(head->tag);
714 u32 cc = be32_to_cpu(auth->ordinal);
715 int parm_len, len, i, handles;
716
717 if (auth->session >= TPM_HEADER_SIZE) {
718 WARN(1, "tpm session not filled correctly\n");
719 goto out;
720 }
721
722 if (rc != 0)
723 /* pass non success rc through and close the session */
724 goto out;
725
726 rc = -EINVAL;
727 if (tag != TPM2_ST_SESSIONS) {
728 dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");
729 goto out;
730 }
731
732 i = tpm2_find_cc(chip, cc);
733 if (i < 0)
734 goto out;
735 attrs = chip->cc_attrs_tbl[i];
736 handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;
737
738 /* point to area beyond handles */
739 s = &buf->data[TPM_HEADER_SIZE + handles * 4];
740 parm_len = tpm_get_inc_u32(&s);
741 p = s;
742 s += parm_len;
743 /* skip over any sessions before ours */
744 for (i = 0; i < auth->session - 1; i++) {
745 len = tpm_get_inc_u16(&s);
746 s += len + 1;
747 len = tpm_get_inc_u16(&s);
748 s += len;
749 }
750 /* TPM nonce */
751 len = tpm_get_inc_u16(&s);
752 if (s - buf->data + len > tpm_buf_length(buf))
753 goto out;
754 if (len != SHA256_DIGEST_SIZE)
755 goto out;
756 memcpy(auth->tpm_nonce, s, len);
757 s += len;
758 attrs = *s++;
759 len = tpm_get_inc_u16(&s);
760 if (s - buf->data + len != tpm_buf_length(buf))
761 goto out;
762 if (len != SHA256_DIGEST_SIZE)
763 goto out;
764 /*
765 * s points to the HMAC. now calculate comparison, beginning
766 * with rphash
767 */
768 desc->tfm = sha256_hash;
769 crypto_shash_init(desc);
770 /* yes, I know this is now zero, but it's what the standard says */
771 crypto_shash_update(desc, (u8 *)&head->return_code,
772 sizeof(head->return_code));
773 /* ordinal is already BE */
774 crypto_shash_update(desc, (u8 *)&auth->ordinal, sizeof(auth->ordinal));
775 crypto_shash_update(desc, p, parm_len);
776 crypto_shash_final(desc, rphash);
777
778 /* now calculate the hmac */
779 hmac_init(desc, auth->session_key, sizeof(auth->session_key)
780 + auth->passphraselen);
781 crypto_shash_update(desc, rphash, sizeof(rphash));
782 crypto_shash_update(desc, auth->tpm_nonce, sizeof(auth->tpm_nonce));
783 crypto_shash_update(desc, auth->our_nonce, sizeof(auth->our_nonce));
784 crypto_shash_update(desc, &auth->attrs, 1);
785 /* we're done with the rphash, so put our idea of the hmac there */
786 hmac_final(desc, auth->session_key, sizeof(auth->session_key)
787 + auth->passphraselen, rphash);
788 if (memcmp(rphash, s, SHA256_DIGEST_SIZE) == 0) {
789 rc = 0;
790 } else {
791 dev_err(&auth->chip->dev, "TPM: HMAC check failed\n");
792 goto out;
793 }
794
795 /* now do response decryption */
796 if (auth->attrs & TPM2_SA_ENCRYPT) {
797 struct scatterlist sg[1];
798 SYNC_SKCIPHER_REQUEST_ON_STACK(req, auth->aes);
799 DECLARE_CRYPTO_WAIT(wait);
800
801 skcipher_request_set_sync_tfm(req, auth->aes);
802 skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
803 crypto_req_done, &wait);
804
805 /* need key and IV */
806 KDFa(auth->session_key, SHA256_DIGEST_SIZE

   807			     + auth->passphraselen, "CFB", auth->tpm_nonce,
   808			     auth->our_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
   809			     auth->scratch);
   810			crypto_sync_skcipher_setkey(auth->aes, auth->scratch, AES_KEYBYTES);
   811			len = tpm_get_inc_u16(&p);
   812			sg_init_one(sg, p, len);
   813			skcipher_request_set_crypt(req, sg, sg, len,
   814						   auth->scratch + AES_KEYBYTES);
   815			crypto_wait_req(crypto_skcipher_decrypt(req), &wait);
   816		}
   817	
   818	 out:
   819		if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {
   820			/* manually close the session if it wasn't consumed */
   821			if (rc)
   822				tpm2_flush_context(chip, auth->handle);
   823			crypto_free_sync_skcipher(auth->aes);
   824			kfree(auth);
   825		} else {
   826			/* reset for next use  */
   827			auth->session = TPM_HEADER_SIZE;
   828		}
   829	
   830		return rc;
 > 831	}

832 EXPORT_SYMBOL(tpm_buf_check_hmac_response);
833

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
author maintainer
#11 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 56 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char-misc/char- misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next- 20230124]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(https://download.01.org/0day-ci/archive/20230125/202301250706.deGvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm-move- buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) { |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 2 lines
Quoted 2 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]

Quoted 8 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Is this a test problem? I can't see why the code would only blow the stack on the arc architecture and not on any other ... does it have something funny with on stack crypto structures?

James

#12 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Hi James,

Quoted 66 lines · James Bottomley
Quoted 56 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char-misc/char- misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next- 20230124]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(https://download.01.org/0day-ci/archive/20230125/202301250706.deGvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm-move- buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) { |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 2 lines
Quoted 2 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]

Quoted 8 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Quoted 3 lines

Is this a test problem? I can't see why the code would only blow the stack on the arc architecture and not on any other ... does it have something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

maintainer
#13 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 81 lines · Yujie Liu

Hi James,

Quoted 66 lines · James Bottomley
Quoted 56 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char-misc/char- misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next- 20230124]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(https://download.01.org/0day-ci/archive/20230125/202301250706.deGvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm-move- buffer-handling-from-static-inlines-to-real-functions/20230125-020146 git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) { |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 2 lines
Quoted 2 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]

Quoted 8 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of 1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Quoted 3 lines

Is this a test problem? I can't see why the code would only blow the stack on the arc architecture and not on any other ... does it have something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Quoted 6 lines

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now. This is wrong place to reconsider.

And we do not want to add functions that bloat the stack this way.

Shash just needs to be allocated from heap instead of stack.

BR, Jarkko

author maintainer
#14 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 106 lines · Jarkko Sakkinen
Quoted 98 lines · Yujie Liu

Hi James,

Quoted 81 lines · James Bottomley
Quoted 70 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char- misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us a
note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information
]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.de
Gvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm- move- buffer-handling-from-static-inlines-to-real-functions/20230125- 020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash
drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous
prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) {
         |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 4 lines
Quoted 4 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size
of 1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

Quoted 9 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of
1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Quoted 5 lines

Is this a test problem?  I can't see why the code would only blow the
stack on the arc architecture and not on any other ... does it have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Quoted 6 lines

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

Quoted 7 lines

*Must* be fixed given that it is how the default value is set now. This is wrong place to reconsider.

And we do not want to add functions that bloat the stack this way.

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than jumping to conclusions let's root cause why this is a problem only on the arc architecture. I suspect it's something to do with the alignment constraints of shash. I've also noted it shouldn't actually warn on arc because the default stack warning size there should be 2048 (like x86_64).

James

maintainer
#15 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 113 lines · James Bottomley
Quoted 112 lines · Jarkko Sakkinen
Quoted 98 lines · Yujie Liu

Hi James,

Quoted 81 lines · James Bottomley
Quoted 70 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char- misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us a
note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information
]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.de
Gvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm- move- buffer-handling-from-static-inlines-to-real-functions/20230125- 020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash
drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous
prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) {
         |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 4 lines
Quoted 4 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size
of 1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

Quoted 9 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of
1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Quoted 5 lines

Is this a test problem?  I can't see why the code would only blow the
stack on the arc architecture and not on any other ... does it have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Quoted 6 lines

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now. This is wrong place to reconsider.

And we do not want to add functions that bloat the stack this way.

Quoted 8 lines
Quoted 1 line

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than jumping to conclusions let's root cause why this is a problem only on the arc architecture. I suspect it's something to do with the alignment constraints of shash. I've also noted it shouldn't actually warn on arc because the default stack warning size there should be 2048 (like x86_64).

Would it such a big deal to allocate shash from heap? That would be IMHO more robust in the end.

BR, Jarkko

#16 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 62 lines · Jarkko Sakkinen
Quoted 61 lines · James Bottomley
Quoted 60 lines · Jarkko Sakkinen
Quoted 46 lines · Yujie Liu

Hi James,

Quoted 29 lines · James Bottomley
Quoted 18 lines · kernel test robot

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous
prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) {
         |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 4 lines
Quoted 4 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size
of 1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

Quoted 9 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of
1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Quoted 5 lines

Is this a test problem?  I can't see why the code would only blow the
stack on the arc architecture and not on any other ... does it have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Quoted 6 lines

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now. This is wrong place to reconsider.

And we do not want to add functions that bloat the stack this way.

Quoted 8 lines
Quoted 8 lines
Quoted 1 line

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than jumping to conclusions let's root cause why this is a problem only on the arc architecture. I suspect it's something to do with the alignment constraints of shash. I've also noted it shouldn't actually warn on arc because the default stack warning size there should be 2048 (like x86_64).

The stack usage varies on different architectures, so does the default value of CONFIG_FRAME_WARN. The warning shows up when the stack usage exceeds the default warning size.

For arc arch, I reconfirmed that the default stack warning size is 1024 no matter allyesconfig or defconfig, while the usage could reach 1132 bytes.

$ make ARCH=arc allyesconfig
$ grep FRAME_WARN .config
CONFIG_FRAME_WARN=1024
$ make ARCH=arc defconfig
$ grep FRAME_WARN .config
CONFIG_FRAME_WARN=1024
Quoted 2 lines

Would it such a big deal to allocate shash from heap? That would be IMHO more robust in the end.

Thanks Jarkko for the suggestion. This would be a faster and better fix without having to look into this arc-specific problem.

Best Regards,
Yujie

Quoted 1 line

BR, Jarkko

#17 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to Jarkko Sakkinen
Quoted 124 lines · Jarkko Sakkinen
Quoted 113 lines · James Bottomley
Quoted 112 lines · Jarkko Sakkinen
Quoted 98 lines · Yujie Liu

Hi James,

Quoted 81 lines · James Bottomley
Quoted 72 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char- misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us a
note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information
]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.de
Gvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0 reproduce (this is a W=1 build):
wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
-O ~/bin/make.cross
chmod +x ~/bin/make.cross
#
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
git remote add linux-review
https://github.com/intel-lab-lkp/linux

        git fetch --no-tags linux-review James-Bottomley/tpm-
move-
buffer-handling-from-static-inlines-to-real-functions/20230125-
020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0

make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no
previous
prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes]
    1184 | int tpm2_create_null_primary(struct tpm_chip *chip)
{
         |     ^~~~~~~~~~~~~~~~~~~~~~~~

drivers/char/tpm/tpm2-sessions.c: In function
'tpm_buf_check_hmac_response':

Quoted 4 lines
Quoted 4 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size
of 1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

     831 | }
         | ^
Quoted 7 lines

drivers/char/tpm/tpm2-sessions.c: In function
'tpm_buf_fill_hmac_session':
drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame
size of
1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]

     579 | }
         | ^
Quoted 5 lines

Is this a test problem? I can't see why the code would only blow the
stack on the arc architecture and not on any other ... does it have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Quoted 6 lines

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now. This is wrong place to reconsider.

And we do not want to add functions that bloat the stack this way.

Quoted 8 lines
Quoted 1 line

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than jumping to conclusions let's root cause why this is a problem only on the arc architecture. I suspect it's something to do with the alignment constraints of shash. I've also noted it shouldn't actually warn on arc because the default stack warning size there should be 2048 (like x86_64).

Quoted 3 lines

Would it such a big deal to allocate shash from heap? That would be IMHO more robust in the end.

Can we avoid shashes and sync skciphers at all? We have sha256 and AES library routines these days, and AES in CFB mode seems like a good candidate for a library implementation as well - it uses AES encryption only, and is quite straight forward to implement. [0]

The crypto API is far too clunky for synchronous operations of algorithms that are known at compile time, and the requirement to use scatterlists for skciphers is especially horrid.

[0] https://git.kernel.org/pub/scm/linux/kernel/git/ardb/linux.git/log/?h=crypto-aes-cfb-library

author maintainer
#18 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 153 lines · Ard Biesheuvel
Quoted 151 lines · Jarkko Sakkinen
Quoted 148 lines · James Bottomley
Quoted 132 lines · Jarkko Sakkinen
Quoted 118 lines · Yujie Liu

Hi James,

Quoted 96 lines · James Bottomley
Quoted 83 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char-
misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5
next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us
a
note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information
]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.de
Gvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0 reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James- Bottomley/tpm-
move- buffer-handling-from-static-inlines-to-real- functions/20230125-
020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-
12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-
12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash
drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous
prototype for 'tpm2_create_null_primary' [-Wmissing- prototypes]
    1184 | int tpm2_create_null_primary(struct tpm_chip *chip)
{
         |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 6 lines
Quoted 6 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame
size
of 1132 bytes is larger than 1024 bytes [-Wframe- larger-
than=]

Quoted 11 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame
size of
1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]
     579 | }
         | ^

Quoted 7 lines

Is this a test problem?  I can't see why the code would only blow
the
stack on the arc architecture and not on any other ... does it
have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so
this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default
value would be 2048 and won't have this warning.

Quoted 7 lines

Not sure if this is a real problem that need to be fixed, here just
providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now.
This is wrong place to reconsider.

Quoted 4 lines

And we do not want to add functions that bloat the stack this way.

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than
jumping to conclusions let's root cause why this is a problem only on
the arc architecture.  I suspect it's something to do with the alignment constraints of shash.  I've also noted it shouldn't actually
warn on arc because the default stack warning size there should be 2048
(like x86_64).

Quoted 2 lines
Quoted 2 lines

Would it such a big deal to allocate shash from heap? That would be IMHO more robust in the end.

Heap allocation is time indeterminate and eventually Mimi is going to want me to make this go faster.

Quoted 5 lines

Can we avoid shashes and sync skciphers at all? We have sha256 and AES library routines these days, and AES in CFB mode seems like a good candidate for a library implementation as well - it uses AES encryption only, and is quite straight forward to implement. [0]

Yes, sure. I originally suggested something like this way back four years ago, but it got overruled on the grounds that if I didn't use shashes and skciphers some architectures would be unable to use crypto acceleration. If that's no longer a consideration, I'm all for simplification of static cipher types.

Quoted 6 lines

The crypto API is far too clunky for synchronous operations of algorithms that are known at compile time, and the requirement to use scatterlists for skciphers is especially horrid.

[0]
https://git.kernel.org/pub/scm/linux/kernel/git/ardb/linux.git/log/?h=crypto-aes-cfb-library

OK, let me have a go at respinning based on this.

Regards,

James

#19 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 167 lines · James Bottomley
Quoted 153 lines · Ard Biesheuvel
Quoted 151 lines · Jarkko Sakkinen
Quoted 148 lines · James Bottomley
Quoted 132 lines · Jarkko Sakkinen
Quoted 118 lines · Yujie Liu

Hi James,

Quoted 96 lines · James Bottomley
Quoted 88 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char-
misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5
next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us
a
note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information
]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.de
Gvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0 reproduce (this is a W=1 build):
wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
-O ~/bin/make.cross
chmod +x ~/bin/make.cross
#
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
git remote add linux-review
https://github.com/intel-lab-lkp/linux

        git fetch --no-tags linux-review James-

Bottomley/tpm-
move-
buffer-handling-from-static-inlines-to-real-
functions/20230125-
020146
git checkout
dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-
12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-
12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash
drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no

previous
prototype for 'tpm2_create_null_primary' [-Wmissing- prototypes]
1184 | int tpm2_create_null_primary(struct tpm_chip
*chip)

{
         |     ^~~~~~~~~~~~~~~~~~~~~~~~

drivers/char/tpm/tpm2-sessions.c: In function
'tpm_buf_check_hmac_response':

Quoted 6 lines
Quoted 6 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame
size
of 1132 bytes is larger than 1024 bytes [-Wframe- larger-
than=]

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function
'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the
Quoted 6 lines

frame
size of
1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

     579 | }
         | ^
Quoted 7 lines

Is this a test problem? I can't see why the code would only blow
the
stack on the arc architecture and not on any other ... does it
have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so
this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default
value would be 2048 and won't have this warning.

Quoted 7 lines

Not sure if this is a real problem that need to be fixed, here just
providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now.
This is wrong place to reconsider.

Quoted 4 lines

And we do not want to add functions that bloat the stack this way.

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than
jumping to conclusions let's root cause why this is a problem only on
the arc architecture. I suspect it's something to do with the alignment constraints of shash. I've also noted it shouldn't actually
warn on arc because the default stack warning size there should be 2048
(like x86_64).

Quoted 2 lines
Quoted 2 lines

Would it such a big deal to allocate shash from heap? That would be IMHO more robust in the end.

Heap allocation is time indeterminate and eventually Mimi is going to want me to make this go faster.

Quoted 5 lines

Can we avoid shashes and sync skciphers at all? We have sha256 and AES library routines these days, and AES in CFB mode seems like a good candidate for a library implementation as well - it uses AES encryption only, and is quite straight forward to implement. [0]

Quoted 6 lines

Yes, sure. I originally suggested something like this way back four years ago, but it got overruled on the grounds that if I didn't use shashes and skciphers some architectures would be unable to use crypto acceleration. If that's no longer a consideration, I'm all for simplification of static cipher types.

I don't know if that is a consideration or not. The AES library code is generic C code that was written to be constant-time, rather than fast. The fact that CFB only uses the encryption side of it is fortunate, because decryption is even slower.

So the question is whether this will actually be a bottleneck in this particular scenario. The synchronous accelerated AES implementations are all SIMD based, which means there is some overhead, and some degree of parallelism is also needed to take full advantage, and CFB only allows this for decryption to begin with, as encryption uses ciphertext block N-1 as AES input for encrypting block N.

So maybe this is terrible advice, but the code will look so much better for it, and we can always add back the performance later if it is really an impediment.

Quoted 13 lines
Quoted 6 lines

The crypto API is far too clunky for synchronous operations of algorithms that are known at compile time, and the requirement to use scatterlists for skciphers is especially horrid.

[0]
https://git.kernel.org/pub/scm/linux/kernel/git/ardb/linux.git/log/?h=crypto-aes-cfb-library

OK, let me have a go at respinning based on this.

Regards,

James

author maintainer
#20 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 3 lines · Ard Biesheuvel
Quoted 1 line · James Bottomley

On Tue, 2023-02-14 at 14:54 +0100, Ard Biesheuvel wrote:

[...]

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

Can we avoid shashes and sync skciphers at all? We have sha256 and AES library routines these days, and AES in CFB mode seems like a good candidate for a library implementation as well - it uses AES encryption only, and is quite straight forward to implement. [0]

Quoted 6 lines
Quoted 6 lines

Yes, sure.  I originally suggested something like this way back four years ago, but it got overruled on the grounds that if I didn't use shashes and skciphers some architectures would be unable to use crypto acceleration.  If that's no longer a consideration, I'm all for simplification of static cipher types.

I now have this all implemented, and I looked over your code, so you can add my tested/reviewed-by to the aescfb implementation. On the acceleration issue, I'm happy to ignore external accelerators because they're a huge pain for small fragments of encryption like the TPM, but it would be nice if we could integrate CPU instruction acceleration (like AES-NI on x86) into the library functions.

I also got a test rig to investigate arc. It seems there is a huge problem with the SKCIPHER stack structure on that platform. For reasons I still can't fathom, the compiler thinks it needs at least 0.5k of stack for this one structure. I'm sure its something to do with an incorrect crypto alignment on arc, but I can't yet find the root cause.

Quoted 4 lines

I don't know if that is a consideration or not. The AES library code is generic C code that was written to be constant-time, rather than fast. The fact that CFB only uses the encryption side of it is fortunate, because decryption is even slower.

I think for the TPM, since the encryption isn't exactly bulk (it's really under 1k for command and response encryption) it doesn't matter ... in fact setting up the accelerator is likely a bigger overhead.

Quoted 10 lines

So the question is whether this will actually be a bottleneck in this particular scenario. The synchronous accelerated AES implementations are all SIMD based, which means there is some overhead, and some degree of parallelism is also needed to take full advantage, and CFB only allows this for decryption to begin with, as encryption uses ciphertext block N-1 as AES input for encrypting block N.

So maybe this is terrible advice, but the code will look so much better for it, and we can always add back the performance later if it is really an impediment.

It's definitely smaller and neater, yes. I'll post a v3 based on this, but when might it go upstream? In my post I'll put your aescfb as patch 1 so the static checkers don't go haywire about missing function exports, and we can drop that patch when it is upstream.

James

Quoted 10 lines
Quoted 10 lines
Quoted 8 lines

The crypto API is far too clunky for synchronous operations of algorithms that are known at compile time, and the requirement to use scatterlists for skciphers is especially horrid.

[0]
https://git.kernel.org/pub/scm/linux/kernel/git/ardb/linux.git/log/?h=crypto-aes-cfb-library

OK, let me have a go at respinning based on this.

#21 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

Quoted 20 lines · James Bottomley
Quoted 3 lines · Ard Biesheuvel
Quoted 1 line · James Bottomley

On Tue, 2023-02-14 at 14:54 +0100, Ard Biesheuvel wrote:

[...]

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

Can we avoid shashes and sync skciphers at all? We have sha256 and AES library routines these days, and AES in CFB mode seems like a good candidate for a library implementation as well - it uses AES encryption only, and is quite straight forward to implement. [0]

Quoted 6 lines
Quoted 6 lines

Yes, sure. I originally suggested something like this way back four years ago, but it got overruled on the grounds that if I didn't use shashes and skciphers some architectures would be unable to use crypto acceleration. If that's no longer a consideration, I'm all for simplification of static cipher types.

Quoted 7 lines

I now have this all implemented, and I looked over your code, so you can add my tested/reviewed-by to the aescfb implementation. On the acceleration issue, I'm happy to ignore external accelerators because they're a huge pain for small fragments of encryption like the TPM, but it would be nice if we could integrate CPU instruction acceleration (like AES-NI on x86) into the library functions.

Agreed that async crypto makes no sense here, and it is rather unfortunate that even use cases such as this one require the scatterlist handling, which requires direct mapped memory etc etc

As for the accelerated algos: it wouldn't be too complicated to build the CFB library interface around the 'AES' crypto cipher, which is synchronous and operates on virtual addresses directly. But it should only use ones that are constant time (like AES-NI) and not use generic AES or the asm accelerated ones, and so this would require an additional annotation (or an allowlist) which makes things a bit clunky.

However, doing the math on the back of an envelope: taking arm64 as an example, which manages ~1 cycle per byte for AES instructions and 25 cycles per byte for AES encryption using this library, processing 1k of data takes an additional 24k cycles, which comes down to 10 microseconds on a 2.4 GHz CPU.

Given that this particular use case is about communicating with off chip discrete components, I wonder whether spending 10 microseconds more is going to have a noticeable impact.

Quoted 7 lines

I also got a test rig to investigate arc. It seems there is a huge problem with the SKCIPHER stack structure on that platform. For reasons I still can't fathom, the compiler thinks it needs at least 0.5k of stack for this one structure. I'm sure its something to do with an incorrect crypto alignment on arc, but I can't yet find the root cause.

Maybe SKCIPHER_ON_STACK() needs the same treatment as 660d2062190db131d2feaf19914e90f868fe285c?

The catch here is that if we reduce the alignment of the buffer, the req pointer will not have the alignment of the typedef, and so we will be lying to the compiler.

This is all a result of the way we abuse alignment to pad out data fields that may be used for inbound non-coherent DMA, and this is something that is being fixed at the moment.

Quoted 16 lines
Quoted 4 lines

I don't know if that is a consideration or not. The AES library code is generic C code that was written to be constant-time, rather than fast. The fact that CFB only uses the encryption side of it is fortunate, because decryption is even slower.

I think for the TPM, since the encryption isn't exactly bulk (it's really under 1k for command and response encryption) it doesn't matter ... in fact setting up the accelerator is likely a bigger overhead.

Quoted 7 lines

So the question is whether this will actually be a bottleneck in this particular scenario. The synchronous accelerated AES implementations are all SIMD based, which means there is some overhead, and some degree of parallelism is also needed to take full advantage, and CFB only allows this for decryption to begin with, as encryption uses ciphertext block N-1 as AES input for encrypting block N.

Quoted 9 lines
Quoted 3 lines

So maybe this is terrible advice, but the code will look so much better for it, and we can always add back the performance later if it is really an impediment.

It's definitely smaller and neater, yes. I'll post a v3 based on this, but when might it go upstream? In my post I'll put your aescfb as patch 1 so the static checkers don't go haywire about missing function exports, and we can drop that patch when it is upstream.

I'll add some test cases and send it to the list.

author maintainer
#22 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to Ard Biesheuvel

On Tue, 2023-02-14 at 14:54 +0100, Ard Biesheuvel wrote:
[...]

Quoted 2 lines

and the requirement to use
scatterlists for skciphers is especially horrid.

Just by way of irony, we do have one place that does use a two element scatterlist. It's how I found this bug: 95ec01ba1ef0 ("crypto: ecdh - fix to allow multi segment scatterlists"). And that does mean I could do with a library version of ecdh with the nist P-256 curve ... pretty please ...

Regards,

James

maintainer
#23 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to Ard Biesheuvel
Quoted 129 lines · Ard Biesheuvel
Quoted 124 lines · Jarkko Sakkinen
Quoted 113 lines · James Bottomley
Quoted 112 lines · Jarkko Sakkinen
Quoted 98 lines · Yujie Liu

Hi James,

Quoted 81 lines · James Bottomley
Quoted 72 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char- misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us a
note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information
]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.de
Gvd0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0 reproduce (this is a W=1 build):
wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
-O ~/bin/make.cross
chmod +x ~/bin/make.cross
#
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
git remote add linux-review
https://github.com/intel-lab-lkp/linux

        git fetch --no-tags linux-review James-Bottomley/tpm-
move-
buffer-handling-from-static-inlines-to-real-functions/20230125-
020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0

make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no
previous
prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes]
    1184 | int tpm2_create_null_primary(struct tpm_chip *chip)
{
         |     ^~~~~~~~~~~~~~~~~~~~~~~~

drivers/char/tpm/tpm2-sessions.c: In function
'tpm_buf_check_hmac_response':

Quoted 4 lines
Quoted 4 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size
of 1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

     831 | }
         | ^
Quoted 7 lines

drivers/char/tpm/tpm2-sessions.c: In function
'tpm_buf_fill_hmac_session':
drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame
size of
1132 bytes is larger than 1024 bytes [-Wframe-larger-than=]

     579 | }
         | ^
Quoted 5 lines

Is this a test problem? I can't see why the code would only blow the
stack on the arc architecture and not on any other ... does it have
something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Quoted 6 lines

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

--
Best Regards,
Yujie

*Must* be fixed given that it is how the default value is set now. This is wrong place to reconsider.

And we do not want to add functions that bloat the stack this way.

Quoted 8 lines
Quoted 1 line

Shash just needs to be allocated from heap instead of stack.

On x86_64 the stack usage is measured at 984 bytes, so rather than jumping to conclusions let's root cause why this is a problem only on the arc architecture. I suspect it's something to do with the alignment constraints of shash. I've also noted it shouldn't actually warn on arc because the default stack warning size there should be 2048 (like x86_64).

Quoted 3 lines

Would it such a big deal to allocate shash from heap? That would be IMHO more robust in the end.

Quoted 8 lines

Can we avoid shashes and sync skciphers at all? We have sha256 and AES library routines these days, and AES in CFB mode seems like a good candidate for a library implementation as well - it uses AES encryption only, and is quite straight forward to implement. [0]

The crypto API is far too clunky for synchronous operations of algorithms that are known at compile time, and the requirement to use scatterlists for skciphers is especially horrid.

I'm cool with any solution not polluting the stack to its limits...

BR, Jarkko

author maintainer
#24 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to Yujie Liu
Quoted 86 lines · Yujie Liu

Hi James,

Quoted 77 lines · James Bottomley
Quoted 66 lines · kernel test robot

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing] [also build test WARNING on char-misc/char-misc-next char- misc/char-
misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-
20230124]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented
in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:
https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:
https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: arc-allyesconfig
(
https://download.01.org/0day-ci/archive/20230125/202301250706.deGv
d0
[email protected]/config)
compiler: arceb-elf-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
        wget
https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross
 -O ~/bin/make.cross
        chmod +x ~/bin/make.cross
        #
https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review
https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm- move- buffer-handling-from-static-inlines-to-real-functions/20230125- 020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c

        # save the config file
        mkdir build_dir && cp config build_dir/.config
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc olddefconfig
        COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0
make.cross W=1 O=build_dir ARCH=arc SHELL=/bin/bash
drivers/char/tpm/

If you fix the issue, kindly add following tag where applicable

Quoted 1 line

All warnings (new ones prefixed by >>):

   drivers/char/tpm/tpm2-sessions.c:1184:5: warning: no previous prototype for 'tpm2_create_null_primary' [-Wmissing-prototypes] 1184 | int tpm2_create_null_primary(struct tpm_chip *chip) { |     ^~~~~~~~~~~~~~~~~~~~~~~~ drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_check_hmac_response':

Quoted 4 lines
Quoted 4 lines

drivers/char/tpm/tpm2-sessions.c:831:1: warning: the frame size
of 1132 bytes is larger than 1024 bytes [-Wframe-larger- than=]

Quoted 9 lines

     831 | }
         | ^
   drivers/char/tpm/tpm2-sessions.c: In function 'tpm_buf_fill_hmac_session':
   drivers/char/tpm/tpm2-sessions.c:579:1: warning: the frame size of
1132 bytes is larger than 1024 bytes [-Wframe-larger-than=] 579 | }
         | ^

Quoted 3 lines

Is this a test problem?  I can't see why the code would only blow the stack on the arc architecture and not on any other ... does it have something funny with on stack crypto structures?

This warning is controlled by the value of CONFIG_FRAME_WARN.

Quoted 8 lines

For "make ARCH=arc allyesconfig", the default value is 1024, so this frame warning shows up during the build.

For other arch such as "make ARCH=x86_64 allyesconfig", the default value would be 2048 and won't have this warning.

Not sure if this is a real problem that need to be fixed, here just providing above information for your reference.

Is there something weird about arc, though, since a quick trawl through defconfigs shows quite a few systems (including i386) have it set to 1024:

mips/configs/lemote2f_defconfig:CONFIG_FRAME_WARN=1024 mips/configs/loongson2k_defconfig:CONFIG_FRAME_WARN=1024 powerpc/configs/fsl-emb-nonhw.config:CONFIG_FRAME_WARN=1024 um/configs/x86_64_defconfig:CONFIG_FRAME_WARN=1024 x86/configs/i386_defconfig:CONFIG_FRAME_WARN=1024

That also seems to show, by the way, that the default on arc should be the standard 2048.

James

#25 lore raw

Re: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code

In reply to James Bottomley
I love your patch! Perhaps something to improve:

Hi James,

I love your patch! Perhaps something to improve:

[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus zohar-integrity/next-integrity linus/master v6.2-rc5 next-20230124] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
patch link:    https://lore.kernel.org/r/20230124175516.5984-7-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v2 06/11] tpm: Add full HMAC and encrypt/decrypt session handling code
config: i386-randconfig-s002-20230123 (https://download.01.org/0day-ci/archive/20230125/[email protected]/config)
compiler: gcc-11 (Debian 11.3.0-8) 11.3.0
reproduce:
        # apt-get install sparse
        # sparse version: v0.6.4-39-gce1a6720-dirty
        # https://github.com/intel-lab-lkp/linux/commit/dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        git remote add linux-review https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review James-Bottomley/tpm-move-buffer-handling-from-static-inlines-to-real-functions/20230125-020146
        git checkout dc0fc74718b4a786aba4a954233e8ab3afdcc03c
        # save the config file
        mkdir build_dir && cp config build_dir/.config
        make W=1 C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=i386 olddefconfig
        make W=1 C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=i386 SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable | Reported-by: kernel test robot <[email protected]>

sparse warnings: (new ones prefixed by >>)

>> drivers/char/tpm/tpm2-sessions.c:1184:5: sparse: sparse: symbol 'tpm2_create_null_primary' was not declared. Should it be static?
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
author maintainer
#26 lore raw

PATCH v2 7/11 tpm: add hmac checks to tpm2_pcr_extend()

In reply to 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.

---
 drivers/char/tpm/tpm2-cmd.c | 28 +++++++++++-----------------
 1 file changed, 11 insertions(+), 17 deletions(-)
drivers/char/tpm/tpm2-cmd.c +11 -17
index 056dad3dd5c9..001360d5956d 100644
@@ -216,13 +216,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
  *
@@ -236,24 +229,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++) {
@@ -262,7 +254,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);
 
Signature · 1 line
2.35.3
author maintainer
#27 lore raw

PATCH v2 8/11 tpm: add session encryption protection to tpm2_get_random()

In reply to 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.

---
 drivers/char/tpm/tpm2-cmd.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
drivers/char/tpm/tpm2-cmd.c +17 -4
index 001360d5956d..3ac438e8ffbb 100644
@@ -289,29 +289,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 +
@@ -328,6 +339,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);
Signature · 1 line
2.35.3
author maintainer
#28 lore raw

PATCH v2 9/11 KEYS: trusted: Add session encryption protection to the seal/unseal path

In reply to 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.

---

v2: fix unseal with policy and password

---
 security/keys/trusted-keys/trusted_tpm2.c | 85 ++++++++++++++++-------
 1 file changed, 61 insertions(+), 24 deletions(-)
security/keys/trusted-keys/trusted_tpm2.c +61 -24
index 2b2c8eb258d5..0ed308d400da 100644
@@ -230,6 +230,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 {
 	int blob_len = 0;
 	struct tpm_buf buf;
+	struct tpm2_auth *auth;
 	u32 hash;
 	u32 flags;
 	int i;
@@ -252,18 +253,19 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	if (rc)
 		return rc;
 
+	rc = tpm2_start_auth_session(chip, &auth);
+	if (rc)
+		goto out_put;
+
 	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
 	if (rc) {
-		tpm_put_ops(chip);
-		return rc;
+		tpm2_end_auth_session(auth);
+		goto out_put;
 	}
 
-	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_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 + options->blobauth_len + payload->key_len);
@@ -308,7 +310,11 @@ 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");
+	if (rc)
+		goto out;
+	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
 	if (rc)
 		goto out;
 
@@ -340,6 +346,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	else
 		payload->blob_len = blob_len;
 
+out_put:
 	tpm_put_ops(chip);
 	return rc;
 }
@@ -363,6 +370,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;
@@ -409,16 +417,19 @@ 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, blob, blob_len);
 
@@ -427,7 +438,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]);
@@ -461,24 +474,48 @@ 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 */,
-			     options->blobauth_len);
+	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 session was generated outside the
+		 * kernel so we don't known the nonce and thus can't
+		 * calculate a HMAC on it.  Therefore, the user can
+		 * only really use TPM2_PolicyPassword and we must
+		 * send down the plain text password, which could be
+		 * intercepted.  We can still encrypt the returned
+		 * key, but that's small comfort since the interposer
+		 * could repeat our actions with the exfiltrated
+		 * password.
+		 */
+		tpm2_buf_append_auth(&buf, options->policyhandle,
+				     NULL /* nonce */, 0, 0,
+				     options->blobauth, options->blobauth_len);
+		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;
 
Signature · 1 line
2.35.3
#29 lore raw

Re: [PATCH v2 09/11] KEYS: trusted: Add session encryption protection to the seal/unseal path

Quoted 1 line · James Bottomley

If some entity is snooping the TPM bus, the can see the data going in

                                          ^^^ they
Quoted 10 lines

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.

--Ben

author maintainer
#30 lore raw

PATCH v2 10/11 tpm: add the null key name as a sysfs export

In reply to 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.

---
 drivers/char/tpm/tpm-sysfs.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
drivers/char/tpm/tpm-sysfs.c +14 -0
index 54c71473aa29..27a16addab93 100644
@@ -309,6 +309,19 @@ static ssize_t tpm_version_major_show(struct device *dev,
 }
 static DEVICE_ATTR_RO(tpm_version_major);
 
+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 struct attribute *tpm1_dev_attrs[] = {
 	&dev_attr_pubek.attr,
 	&dev_attr_pcrs.attr,
@@ -326,6 +339,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
 };
 
Signature · 1 line
2.35.3
author maintainer
#31 lore raw

PATCH v2 11/11 Documentation: add tpm-security.rst

In reply to 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.

---
 Documentation/security/tpm/tpm-security.rst | 214 ++++++++++++++++++++
 1 file changed, 214 insertions(+)
 create mode 100644 Documentation/security/tpm/tpm-security.rst
Documentation/security/tpm/tpm-security.rst new file +214 -0
new file mode 100644
index 000000000000..922b80db3d48
@@ -0,0 +1,214 @@
+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 (called passive and active interposer attack
+in the literature).  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 which is a simple external device that can be installed in
+a couple of seconds on any system or laptop.  Recently attacks were
+successfully demonstrated against the `Windows Bitlocker TPM`_ system.
+Most recently the same `attack against TPM based Linux disk
+encryption`_ schemes.  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 against, 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 exported via sysfs 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, an attestation key (AK) is generated within the TPM and
+it's name and the EK public key can be used to encrypt a secret using
+TPM2_MakeCredential.  The TPM then runs TPM2_ActivateCredential which
+will only recover the secret if the binding between the TPM, the EK
+and the AK is true. the generated AK may now be used to run a
+certification of the null primary key whose name the kernel has
+exported.  Since TPM2_MakeCredential/ActivateCredential are somewhat
+complicated, a more simplified process involving an externally
+generated private key is described below.
+
+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.
+
+.. _TPM Genie: https://www.nccgroup.trust/globalassets/about-us/us/documents/tpm-genie.pdf
+.. _Windows Bitlocker TPM: https://dolosgroup.io/blog/2021/7/9/from-stolen-laptop-to-inside-the-company-network
+.. _attack against TPM based Linux disk encryption: https://www.secura.com/blog/tpm-sniffing-attacks-against-non-bitlocker-targets
+.. _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/
Signature · 1 line
2.35.3