linux-integrity.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v8 00/22] add integrity and security to TPM2 transactions
@ 2024-04-29 20:27 James Bottomley
  2024-04-29 20:27 ` [PATCH v8 01/22] tpm: Remove unused tpm_buf_tag() James Bottomley
                   ` (22 more replies)
  0 siblings, 23 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

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/1568031515.6613.31.camel@HansenPartnership.com/

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
v3 rebases the encryption to be against Ard's new library function, the
aescfb addition of which appears as patch 1.
v4 refreshes Ard's patch, adds kernel doc (including a new patch to
add it to the moved tpm-buf functions) updates and rewords some commit
logs
v5: update to proposed tpm-buf implementation (for ease of use all
precursor patches are part of this series, so the actual session HMAC
and encryption begins at patch 10) and add review feedback
v6: split the original sessions patch into three and change the config
variable name
v7: Collect reviews and add extra patch to check for and disable the TPM on
detecting a reset attack.
v8: split KDF out, add tpm_ prefix + other cosmetic updates

James

---

Ard Biesheuvel (1):
  crypto: lib - implement library version of AES in CFB mode

James Bottomley (14):
  tpm: Move buffer handling from static inlines to real functions
  tpm: add buffer function to point to returned parameters
  tpm: export the context save and load commands
  tpm: Add NULL primary creation
  tpm: Add TCG mandated Key Derivation Functions (KDFs)
  tpm: Add HMAC session start and end functions
  tpm: Add HMAC session name/handle append
  tpm: Add the rest of the session HMAC API
  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
  tpm: disable the TPM if NULL name changes

Jarkko Sakkinen (7):
  tpm: Remove unused tpm_buf_tag()
  tpm: Remove tpm_send()
  tpm: Update struct tpm_buf documentation comments
  tpm: Store the length of the tpm_buf data separately.
  tpm: TPM2B formatted buffers
  tpm: Add tpm_buf_read_{u8,u16,u32}
  KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers

 Documentation/security/tpm/tpm-security.rst |  216 ++++
 drivers/char/tpm/Kconfig                    |   14 +
 drivers/char/tpm/Makefile                   |    2 +
 drivers/char/tpm/tpm-buf.c                  |  251 ++++
 drivers/char/tpm/tpm-chip.c                 |    6 +
 drivers/char/tpm/tpm-interface.c            |   26 +-
 drivers/char/tpm/tpm-sysfs.c                |   18 +
 drivers/char/tpm/tpm.h                      |   14 +
 drivers/char/tpm/tpm2-cmd.c                 |   53 +-
 drivers/char/tpm/tpm2-sessions.c            | 1280 +++++++++++++++++++
 drivers/char/tpm/tpm2-space.c               |   11 +-
 include/crypto/aes.h                        |    5 +
 include/keys/trusted_tpm.h                  |    2 -
 include/linux/tpm.h                         |  316 +++--
 lib/crypto/Kconfig                          |    5 +
 lib/crypto/Makefile                         |    3 +
 lib/crypto/aescfb.c                         |  257 ++++
 security/keys/trusted-keys/trusted_tpm1.c   |   23 +-
 security/keys/trusted-keys/trusted_tpm2.c   |  136 +-
 19 files changed, 2443 insertions(+), 195 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
 create mode 100644 lib/crypto/aescfb.c

-- 
2.35.3


^ permalink raw reply	[flat|nested] 75+ messages in thread

* [PATCH v8 01/22] tpm: Remove unused tpm_buf_tag()
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 02/22] tpm: Remove tpm_send() James Bottomley
                   ` (21 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

The helper function has no call sites. Thus, remove it.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 include/linux/tpm.h | 7 -------
 1 file changed, 7 deletions(-)

diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 4ee9d13749ad..6588ca87cf93 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -358,13 +358,6 @@ static inline u32 tpm_buf_length(struct tpm_buf *buf)
 	return be32_to_cpu(head->length);
 }
 
-static inline u16 tpm_buf_tag(struct tpm_buf *buf)
-{
-	struct tpm_header *head = (struct tpm_header *)buf->data;
-
-	return be16_to_cpu(head->tag);
-}
-
 static inline void tpm_buf_append(struct tpm_buf *buf,
 				  const unsigned char *new_data,
 				  unsigned int new_len)
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 02/22] tpm: Remove tpm_send()
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
  2024-04-29 20:27 ` [PATCH v8 01/22] tpm: Remove unused tpm_buf_tag() James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 03/22] tpm: Move buffer handling from static inlines to real functions James Bottomley
                   ` (20 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

Open code the last remaining call site for tpm_send().

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/tpm-interface.c          | 25 -----------------------
 include/linux/tpm.h                       |  5 -----
 security/keys/trusted-keys/trusted_tpm1.c | 14 +++++++++++--
 3 files changed, 12 insertions(+), 32 deletions(-)

diff --git a/drivers/char/tpm/tpm-interface.c b/drivers/char/tpm/tpm-interface.c
index 757336324c90..f940045a014e 100644
--- a/drivers/char/tpm/tpm-interface.c
+++ b/drivers/char/tpm/tpm-interface.c
@@ -342,31 +342,6 @@ int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 }
 EXPORT_SYMBOL_GPL(tpm_pcr_extend);
 
-/**
- * tpm_send - send a TPM command
- * @chip:	a &struct tpm_chip instance, %NULL for the default chip
- * @cmd:	a TPM command buffer
- * @buflen:	the length of the TPM command buffer
- *
- * Return: same as with tpm_transmit_cmd()
- */
-int tpm_send(struct tpm_chip *chip, void *cmd, size_t buflen)
-{
-	struct tpm_buf buf;
-	int rc;
-
-	chip = tpm_find_get_ops(chip);
-	if (!chip)
-		return -ENODEV;
-
-	buf.data = cmd;
-	rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to a send a command");
-
-	tpm_put_ops(chip);
-	return rc;
-}
-EXPORT_SYMBOL_GPL(tpm_send);
-
 int tpm_auto_startup(struct tpm_chip *chip)
 {
 	int rc;
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 6588ca87cf93..d9d645e9c52c 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -422,7 +422,6 @@ extern int tpm_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
 			struct tpm_digest *digest);
 extern int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 			  struct tpm_digest *digests);
-extern int tpm_send(struct tpm_chip *chip, void *cmd, size_t buflen);
 extern int tpm_get_random(struct tpm_chip *chip, u8 *data, size_t max);
 extern struct tpm_chip *tpm_default_chip(void);
 void tpm2_flush_context(struct tpm_chip *chip, u32 handle);
@@ -443,10 +442,6 @@ static inline int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 	return -ENODEV;
 }
 
-static inline int tpm_send(struct tpm_chip *chip, void *cmd, size_t buflen)
-{
-	return -ENODEV;
-}
 static inline int tpm_get_random(struct tpm_chip *chip, u8 *data, size_t max)
 {
 	return -ENODEV;
diff --git a/security/keys/trusted-keys/trusted_tpm1.c b/security/keys/trusted-keys/trusted_tpm1.c
index aa108bea6739..37bce84eef99 100644
--- a/security/keys/trusted-keys/trusted_tpm1.c
+++ b/security/keys/trusted-keys/trusted_tpm1.c
@@ -356,17 +356,27 @@ static int TSS_checkhmac2(unsigned char *buffer,
  */
 int trusted_tpm_send(unsigned char *cmd, size_t buflen)
 {
+	struct tpm_buf buf;
 	int rc;
 
 	if (!chip)
 		return -ENODEV;
 
+	rc = tpm_try_get_ops(chip);
+	if (rc)
+		return rc;
+
+	buf.flags = 0;
+	buf.data = cmd;
 	dump_tpm_buf(cmd);
-	rc = tpm_send(chip, cmd, buflen);
+	rc = tpm_transmit_cmd(chip, &buf, 4, "sending data");
 	dump_tpm_buf(cmd);
+
 	if (rc > 0)
-		/* Can't return positive return codes values to keyctl */
+		/* TPM error */
 		rc = -EPERM;
+
+	tpm_put_ops(chip);
 	return rc;
 }
 EXPORT_SYMBOL_GPL(trusted_tpm_send);
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 03/22] tpm: Move buffer handling from static inlines to real functions
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
  2024-04-29 20:27 ` [PATCH v8 01/22] tpm: Remove unused tpm_buf_tag() James Bottomley
  2024-04-29 20:27 ` [PATCH v8 02/22] tpm: Remove tpm_send() James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 04/22] tpm: Update struct tpm_buf documentation comments James Bottomley
                   ` (19 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

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 because 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.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/Makefile  |  1 +
 drivers/char/tpm/tpm-buf.c | 87 ++++++++++++++++++++++++++++++++++++++
 include/linux/tpm.h        | 80 ++++-------------------------------
 3 files changed, 97 insertions(+), 71 deletions(-)
 create mode 100644 drivers/char/tpm/tpm-buf.c

diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile
index 0222b1ddb310..ad3594e383e1 100644
--- a/drivers/char/tpm/Makefile
+++ b/drivers/char/tpm/Makefile
@@ -15,6 +15,7 @@ tpm-y += tpm-sysfs.o
 tpm-y += eventlog/common.o
 tpm-y += eventlog/tpm1.o
 tpm-y += eventlog/tpm2.o
+tpm-y += tpm-buf.o
 
 tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
 tpm-$(CONFIG_EFI) += eventlog/efi.o
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
new file mode 100644
index 000000000000..96cee41d5b9c
--- /dev/null
+++ b/drivers/char/tpm/tpm-buf.c
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Handling of TPM command and other buffers.
+ */
+
+#include <linux/module.h>
+#include <linux/tpm.h>
+
+int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+{
+	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
+	if (!buf->data)
+		return -ENOMEM;
+
+	buf->flags = 0;
+	tpm_buf_reset(buf, tag, ordinal);
+	return 0;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
+
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+
+	head->tag = cpu_to_be16(tag);
+	head->length = cpu_to_be32(sizeof(*head));
+	head->ordinal = cpu_to_be32(ordinal);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_reset);
+
+void tpm_buf_destroy(struct tpm_buf *buf)
+{
+	free_page((unsigned long)buf->data);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+
+u32 tpm_buf_length(struct tpm_buf *buf)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+
+	return be32_to_cpu(head->length);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_length);
+
+void tpm_buf_append(struct tpm_buf *buf,
+		    const unsigned char *new_data,
+		    unsigned int new_len)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+	u32 len = tpm_buf_length(buf);
+
+	/* Return silently if overflow has already happened. */
+	if (buf->flags & TPM_BUF_OVERFLOW)
+		return;
+
+	if ((len + new_len) > PAGE_SIZE) {
+		WARN(1, "tpm_buf: overflow\n");
+		buf->flags |= TPM_BUF_OVERFLOW;
+		return;
+	}
+
+	memcpy(&buf->data[len], new_data, new_len);
+	head->length = cpu_to_be32(len + new_len);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_append);
+
+void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value)
+{
+	tpm_buf_append(buf, &value, 1);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_append_u8);
+
+void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
+{
+	__be16 value2 = cpu_to_be16(value);
+
+	tpm_buf_append(buf, (u8 *)&value2, 2);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_append_u16);
+
+void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
+{
+	__be32 value2 = cpu_to_be32(value);
+
+	tpm_buf_append(buf, (u8 *)&value2, 4);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index d9d645e9c52c..bb0e8718a432 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -326,77 +326,15 @@ struct tpm2_hash {
 	unsigned int tpm_id;
 };
 
-static inline void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
-{
-	struct tpm_header *head = (struct tpm_header *)buf->data;
-
-	head->tag = cpu_to_be16(tag);
-	head->length = cpu_to_be32(sizeof(*head));
-	head->ordinal = cpu_to_be32(ordinal);
-}
-
-static inline int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
-{
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
-
-	buf->flags = 0;
-	tpm_buf_reset(buf, tag, ordinal);
-	return 0;
-}
-
-static inline void tpm_buf_destroy(struct tpm_buf *buf)
-{
-	free_page((unsigned long)buf->data);
-}
-
-static inline u32 tpm_buf_length(struct tpm_buf *buf)
-{
-	struct tpm_header *head = (struct tpm_header *)buf->data;
-
-	return be32_to_cpu(head->length);
-}
-
-static inline void tpm_buf_append(struct tpm_buf *buf,
-				  const unsigned char *new_data,
-				  unsigned int new_len)
-{
-	struct tpm_header *head = (struct tpm_header *)buf->data;
-	u32 len = tpm_buf_length(buf);
-
-	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_OVERFLOW)
-		return;
-
-	if ((len + new_len) > PAGE_SIZE) {
-		WARN(1, "tpm_buf: overflow\n");
-		buf->flags |= TPM_BUF_OVERFLOW;
-		return;
-	}
-
-	memcpy(&buf->data[len], new_data, new_len);
-	head->length = cpu_to_be32(len + new_len);
-}
-
-static inline void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value)
-{
-	tpm_buf_append(buf, &value, 1);
-}
-
-static inline void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
-{
-	__be16 value2 = cpu_to_be16(value);
-
-	tpm_buf_append(buf, (u8 *) &value2, 2);
-}
-
-static inline void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
-{
-	__be32 value2 = cpu_to_be32(value);
-
-	tpm_buf_append(buf, (u8 *) &value2, 4);
-}
+int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
+void tpm_buf_destroy(struct tpm_buf *buf);
+u32 tpm_buf_length(struct tpm_buf *buf);
+void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
+		    unsigned int new_len);
+void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
+void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
+void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
 
 /*
  * Check if TPM device is in the firmware upgrade mode.
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 04/22] tpm: Update struct tpm_buf documentation comments
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (2 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 03/22] tpm: Move buffer handling from static inlines to real functions James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 05/22] tpm: Store the length of the tpm_buf data separately James Bottomley
                   ` (18 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

Remove deprecated portions and document enum values.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 include/linux/tpm.h | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index bb0e8718a432..0a8c1351adc2 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -297,15 +297,14 @@ struct tpm_header {
 	};
 } __packed;
 
-/* A string buffer type for constructing TPM commands. This is based on the
- * ideas of string buffer code in security/keys/trusted.h but is heap based
- * in order to keep the stack usage minimal.
- */
-
 enum tpm_buf_flags {
+	/* the capacity exceeded: */
 	TPM_BUF_OVERFLOW	= BIT(0),
 };
 
+/*
+ * A string buffer type for constructing TPM commands.
+ */
 struct tpm_buf {
 	unsigned int flags;
 	u8 *data;
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 05/22] tpm: Store the length of the tpm_buf data separately.
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (3 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 04/22] tpm: Update struct tpm_buf documentation comments James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 06/22] tpm: TPM2B formatted buffers James Bottomley
                   ` (17 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

TPM2B buffers, or sized buffers, have a two byte header, which contains the
length of the payload as a 16-bit big-endian number, without counting in
the space taken by the header. This differs from encoding in the TPM header
where the length includes also the bytes taken by the header.

Unbound the length of a tpm_buf from the value stored to the TPM command
header. A separate encoding and decoding step so that different buffer
types can be supported, with variant header format and length encoding.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/tpm-buf.c                | 48 +++++++++++++++++------
 drivers/char/tpm/tpm-interface.c          |  1 +
 include/keys/trusted_tpm.h                |  2 -
 include/linux/tpm.h                       |  6 +--
 security/keys/trusted-keys/trusted_tpm1.c |  9 +++--
 5 files changed, 46 insertions(+), 20 deletions(-)

diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 96cee41d5b9c..3f39893f3bb1 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -3,25 +3,44 @@
  * Handling of TPM command and other buffers.
  */
 
+#include <linux/tpm_command.h>
 #include <linux/module.h>
 #include <linux/tpm.h>
 
+/**
+ * tpm_buf_init() - Allocate and initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
+ *
+ * Return: 0 or -ENOMEM
+ */
 int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
 	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
 	if (!buf->data)
 		return -ENOMEM;
 
-	buf->flags = 0;
 	tpm_buf_reset(buf, tag, ordinal);
 	return 0;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init);
 
+/**
+ * tpm_buf_reset() - Initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
+ */
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 
+	WARN_ON(tag != TPM_TAG_RQU_COMMAND && tag != TPM2_ST_NO_SESSIONS &&
+		tag != TPM2_ST_SESSIONS && tag != 0);
+
+	buf->flags = 0;
+	buf->length = sizeof(*head);
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
@@ -34,33 +53,40 @@ void tpm_buf_destroy(struct tpm_buf *buf)
 }
 EXPORT_SYMBOL_GPL(tpm_buf_destroy);
 
+/**
+ * tpm_buf_length() - Return the number of bytes consumed by the data
+ *
+ * Return: The number of bytes consumed by the buffer
+ */
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
-	struct tpm_header *head = (struct tpm_header *)buf->data;
-
-	return be32_to_cpu(head->length);
+	return buf->length;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
 
-void tpm_buf_append(struct tpm_buf *buf,
-		    const unsigned char *new_data,
-		    unsigned int new_len)
+/**
+ * tpm_buf_append() - Append data to an initialized buffer
+ * @buf:	A &tpm_buf
+ * @new_data:	A data blob
+ * @new_length:	Size of the appended data
+ */
+void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
-	u32 len = tpm_buf_length(buf);
 
 	/* Return silently if overflow has already happened. */
 	if (buf->flags & TPM_BUF_OVERFLOW)
 		return;
 
-	if ((len + new_len) > PAGE_SIZE) {
+	if ((buf->length + new_length) > PAGE_SIZE) {
 		WARN(1, "tpm_buf: overflow\n");
 		buf->flags |= TPM_BUF_OVERFLOW;
 		return;
 	}
 
-	memcpy(&buf->data[len], new_data, new_len);
-	head->length = cpu_to_be32(len + new_len);
+	memcpy(&buf->data[buf->length], new_data, new_length);
+	buf->length += new_length;
+	head->length = cpu_to_be32(buf->length);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_append);
 
diff --git a/drivers/char/tpm/tpm-interface.c b/drivers/char/tpm/tpm-interface.c
index f940045a014e..5da134f12c9a 100644
--- a/drivers/char/tpm/tpm-interface.c
+++ b/drivers/char/tpm/tpm-interface.c
@@ -232,6 +232,7 @@ ssize_t tpm_transmit_cmd(struct tpm_chip *chip, struct tpm_buf *buf,
 	if (len < min_rsp_body_length + TPM_HEADER_SIZE)
 		return -EFAULT;
 
+	buf->length = len;
 	return 0;
 }
 EXPORT_SYMBOL_GPL(tpm_transmit_cmd);
diff --git a/include/keys/trusted_tpm.h b/include/keys/trusted_tpm.h
index 7769b726863a..a088b33fd0e3 100644
--- a/include/keys/trusted_tpm.h
+++ b/include/keys/trusted_tpm.h
@@ -6,8 +6,6 @@
 #include <linux/tpm_command.h>
 
 /* implementation specific TPM constants */
-#define MAX_BUF_SIZE			1024
-#define TPM_GETRANDOM_SIZE		14
 #define TPM_SIZE_OFFSET			2
 #define TPM_RETURN_OFFSET		6
 #define TPM_DATA_OFFSET			10
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 0a8c1351adc2..1d7b39b5c383 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -306,7 +306,8 @@ enum tpm_buf_flags {
  * A string buffer type for constructing TPM commands.
  */
 struct tpm_buf {
-	unsigned int flags;
+	u32 flags;
+	u32 length;
 	u8 *data;
 };
 
@@ -329,8 +330,7 @@ int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
 void tpm_buf_destroy(struct tpm_buf *buf);
 u32 tpm_buf_length(struct tpm_buf *buf);
-void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
-		    unsigned int new_len);
+void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length);
 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);
diff --git a/security/keys/trusted-keys/trusted_tpm1.c b/security/keys/trusted-keys/trusted_tpm1.c
index 37bce84eef99..89c9798d1800 100644
--- a/security/keys/trusted-keys/trusted_tpm1.c
+++ b/security/keys/trusted-keys/trusted_tpm1.c
@@ -367,6 +367,7 @@ int trusted_tpm_send(unsigned char *cmd, size_t buflen)
 		return rc;
 
 	buf.flags = 0;
+	buf.length = buflen;
 	buf.data = cmd;
 	dump_tpm_buf(cmd);
 	rc = tpm_transmit_cmd(chip, &buf, 4, "sending data");
@@ -417,7 +418,7 @@ static int osap(struct tpm_buf *tb, struct osapsess *s,
 	tpm_buf_append_u32(tb, handle);
 	tpm_buf_append(tb, ononce, TPM_NONCE_SIZE);
 
-	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
+	ret = trusted_tpm_send(tb->data, tb->length);
 	if (ret < 0)
 		return ret;
 
@@ -441,7 +442,7 @@ int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
 		return -ENODEV;
 
 	tpm_buf_reset(tb, TPM_TAG_RQU_COMMAND, TPM_ORD_OIAP);
-	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
+	ret = trusted_tpm_send(tb->data, tb->length);
 	if (ret < 0)
 		return ret;
 
@@ -553,7 +554,7 @@ static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
 	tpm_buf_append_u8(tb, cont);
 	tpm_buf_append(tb, td->pubauth, SHA1_DIGEST_SIZE);
 
-	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
+	ret = trusted_tpm_send(tb->data, tb->length);
 	if (ret < 0)
 		goto out;
 
@@ -644,7 +645,7 @@ static int tpm_unseal(struct tpm_buf *tb,
 	tpm_buf_append_u8(tb, cont);
 	tpm_buf_append(tb, authdata2, SHA1_DIGEST_SIZE);
 
-	ret = trusted_tpm_send(tb->data, MAX_BUF_SIZE);
+	ret = trusted_tpm_send(tb->data, tb->length);
 	if (ret < 0) {
 		pr_info("authhmac failed (%d)\n", ret);
 		return ret;
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 06/22] tpm: TPM2B formatted buffers
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (4 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 05/22] tpm: Store the length of the tpm_buf data separately James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 07/22] tpm: Add tpm_buf_read_{u8,u16,u32} James Bottomley
                   ` (16 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

Declare tpm_buf_init_sized() and tpm_buf_reset_sized() for creating TPM2B
formatted buffers. These buffers are also known as sized buffers in the
specifications and literature.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/tpm-buf.c | 38 +++++++++++++++++++++++++++++++++++---
 include/linux/tpm.h        |  4 ++++
 2 files changed, 39 insertions(+), 3 deletions(-)

diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 3f39893f3bb1..099b4a56c5d5 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -47,6 +47,36 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 }
 EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
+/**
+ * tpm_buf_init_sized() - Allocate and initialize a sized (TPM2B) buffer
+ * @buf:	A @tpm_buf
+ *
+ * Return: 0 or -ENOMEM
+ */
+int tpm_buf_init_sized(struct tpm_buf *buf)
+{
+	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
+	if (!buf->data)
+		return -ENOMEM;
+
+	tpm_buf_reset_sized(buf);
+	return 0;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init_sized);
+
+/**
+ * tpm_buf_reset_sized() - Initialize a sized buffer
+ * @buf:	A &tpm_buf
+ */
+void tpm_buf_reset_sized(struct tpm_buf *buf)
+{
+	buf->flags = TPM_BUF_TPM2B;
+	buf->length = 2;
+	buf->data[0] = 0;
+	buf->data[1] = 0;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
+
 void tpm_buf_destroy(struct tpm_buf *buf)
 {
 	free_page((unsigned long)buf->data);
@@ -72,8 +102,6 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
  */
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
-	struct tpm_header *head = (struct tpm_header *)buf->data;
-
 	/* Return silently if overflow has already happened. */
 	if (buf->flags & TPM_BUF_OVERFLOW)
 		return;
@@ -86,7 +114,11 @@ void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 
 	memcpy(&buf->data[buf->length], new_data, new_length);
 	buf->length += new_length;
-	head->length = cpu_to_be32(buf->length);
+
+	if (buf->flags & TPM_BUF_TPM2B)
+		((__be16 *)buf->data)[0] = cpu_to_be16(buf->length - 2);
+	else
+		((struct tpm_header *)buf->data)->length = cpu_to_be32(buf->length);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_append);
 
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 1d7b39b5c383..715db4a91c1f 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -300,6 +300,8 @@ struct tpm_header {
 enum tpm_buf_flags {
 	/* the capacity exceeded: */
 	TPM_BUF_OVERFLOW	= BIT(0),
+	/* TPM2B format: */
+	TPM_BUF_TPM2B		= BIT(1),
 };
 
 /*
@@ -328,6 +330,8 @@ struct tpm2_hash {
 
 int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
+int tpm_buf_init_sized(struct tpm_buf *buf);
+void tpm_buf_reset_sized(struct tpm_buf *buf);
 void tpm_buf_destroy(struct tpm_buf *buf);
 u32 tpm_buf_length(struct tpm_buf *buf);
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length);
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 07/22] tpm: Add tpm_buf_read_{u8,u16,u32}
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (5 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 06/22] tpm: TPM2B formatted buffers James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 08/22] KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers James Bottomley
                   ` (15 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

Declare reader functions for the instances of struct tpm_buf. If the read
goes out of boundary, TPM_BUF_BOUNDARY_ERROR is set, and subsequent read
will do nothing.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/tpm-buf.c | 79 +++++++++++++++++++++++++++++++++++++-
 include/linux/tpm.h        |  5 +++
 2 files changed, 83 insertions(+), 1 deletion(-)

diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 099b4a56c5d5..32619e9ab4fa 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -107,7 +107,7 @@ void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 		return;
 
 	if ((buf->length + new_length) > PAGE_SIZE) {
-		WARN(1, "tpm_buf: overflow\n");
+		WARN(1, "tpm_buf: write overflow\n");
 		buf->flags |= TPM_BUF_OVERFLOW;
 		return;
 	}
@@ -143,3 +143,80 @@ 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);
+
+/**
+ * tpm_buf_read() - Read from a TPM buffer
+ * @buf:	&tpm_buf instance
+ * @offset:	offset within the buffer
+ * @count:	the number of bytes to read
+ * @output:	the output buffer
+ */
+static void tpm_buf_read(struct tpm_buf *buf, off_t *offset, size_t count, void *output)
+{
+	off_t next_offset;
+
+	/* Return silently if overflow has already happened. */
+	if (buf->flags & TPM_BUF_BOUNDARY_ERROR)
+		return;
+
+	next_offset = *offset + count;
+	if (next_offset > buf->length) {
+		WARN(1, "tpm_buf: read out of boundary\n");
+		buf->flags |= TPM_BUF_BOUNDARY_ERROR;
+		return;
+	}
+
+	memcpy(output, &buf->data[*offset], count);
+	*offset = next_offset;
+}
+
+/**
+ * tpm_buf_read_u8() - Read 8-bit word from a TPM buffer
+ * @buf:	&tpm_buf instance
+ * @offset:	offset within the buffer
+ *
+ * Return: next 8-bit word
+ */
+u8 tpm_buf_read_u8(struct tpm_buf *buf, off_t *offset)
+{
+	u8 value;
+
+	tpm_buf_read(buf, offset, sizeof(value), &value);
+
+	return value;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_read_u8);
+
+/**
+ * tpm_buf_read_u16() - Read 16-bit word from a TPM buffer
+ * @buf:	&tpm_buf instance
+ * @offset:	offset within the buffer
+ *
+ * Return: next 16-bit word
+ */
+u16 tpm_buf_read_u16(struct tpm_buf *buf, off_t *offset)
+{
+	u16 value;
+
+	tpm_buf_read(buf, offset, sizeof(value), &value);
+
+	return be16_to_cpu(value);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_read_u16);
+
+/**
+ * tpm_buf_read_u32() - Read 32-bit word from a TPM buffer
+ * @buf:	&tpm_buf instance
+ * @offset:	offset within the buffer
+ *
+ * Return: next 32-bit word
+ */
+u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
+{
+	u32 value;
+
+	tpm_buf_read(buf, offset, sizeof(value), &value);
+
+	return be32_to_cpu(value);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 715db4a91c1f..e8172f81c562 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -302,6 +302,8 @@ enum tpm_buf_flags {
 	TPM_BUF_OVERFLOW	= BIT(0),
 	/* TPM2B format: */
 	TPM_BUF_TPM2B		= BIT(1),
+	/* read out of boundary: */
+	TPM_BUF_BOUNDARY_ERROR	= BIT(2),
 };
 
 /*
@@ -338,6 +340,9 @@ void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length);
 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);
+u8 tpm_buf_read_u8(struct tpm_buf *buf, off_t *offset);
+u16 tpm_buf_read_u16(struct tpm_buf *buf, off_t *offset);
+u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset);
 
 /*
  * Check if TPM device is in the firmware upgrade mode.
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 08/22] KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (6 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 07/22] tpm: Add tpm_buf_read_{u8,u16,u32} James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 09/22] crypto: lib - implement library version of AES in CFB mode James Bottomley
                   ` (14 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Jarkko Sakkinen <jarkko@kernel.org>

Take advantage of the new sized buffer (TPM2B) mode of struct tpm_buf in
tpm2_seal_trusted(). This allows to add robustness to the command
construction without requiring to calculate buffer sizes manually.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 security/keys/trusted-keys/trusted_tpm2.c | 54 +++++++++++++----------
 1 file changed, 31 insertions(+), 23 deletions(-)

diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index bc700f85f80b..97b1dfca2dba 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -228,8 +228,9 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 		      struct trusted_key_payload *payload,
 		      struct trusted_key_options *options)
 {
+	off_t offset = TPM_HEADER_SIZE;
+	struct tpm_buf buf, sized;
 	int blob_len = 0;
-	struct tpm_buf buf;
 	u32 hash;
 	u32 flags;
 	int i;
@@ -258,6 +259,14 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 		return rc;
 	}
 
+	rc = tpm_buf_init_sized(&sized);
+	if (rc) {
+		tpm_buf_destroy(&buf);
+		tpm_put_ops(chip);
+		return rc;
+	}
+
+	tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
 	tpm_buf_append_u32(&buf, options->keyhandle);
 	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
 			     NULL /* nonce */, 0,
@@ -266,36 +275,36 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 			     TPM_DIGEST_SIZE);
 
 	/* sensitive */
-	tpm_buf_append_u16(&buf, 4 + options->blobauth_len + payload->key_len);
+	tpm_buf_append_u16(&sized, options->blobauth_len);
 
-	tpm_buf_append_u16(&buf, options->blobauth_len);
 	if (options->blobauth_len)
-		tpm_buf_append(&buf, options->blobauth, options->blobauth_len);
+		tpm_buf_append(&sized, options->blobauth, options->blobauth_len);
 
-	tpm_buf_append_u16(&buf, payload->key_len);
-	tpm_buf_append(&buf, payload->key, payload->key_len);
+	tpm_buf_append_u16(&sized, payload->key_len);
+	tpm_buf_append(&sized, payload->key, payload->key_len);
+	tpm_buf_append(&buf, sized.data, sized.length);
 
 	/* public */
-	tpm_buf_append_u16(&buf, 14 + options->policydigest_len);
-	tpm_buf_append_u16(&buf, TPM_ALG_KEYEDHASH);
-	tpm_buf_append_u16(&buf, hash);
+	tpm_buf_reset_sized(&sized);
+	tpm_buf_append_u16(&sized, TPM_ALG_KEYEDHASH);
+	tpm_buf_append_u16(&sized, hash);
 
 	/* key properties */
 	flags = 0;
 	flags |= options->policydigest_len ? 0 : TPM2_OA_USER_WITH_AUTH;
-	flags |= payload->migratable ? 0 : (TPM2_OA_FIXED_TPM |
-					    TPM2_OA_FIXED_PARENT);
-	tpm_buf_append_u32(&buf, flags);
+	flags |= payload->migratable ? 0 : (TPM2_OA_FIXED_TPM | TPM2_OA_FIXED_PARENT);
+	tpm_buf_append_u32(&sized, flags);
 
 	/* policy */
-	tpm_buf_append_u16(&buf, options->policydigest_len);
+	tpm_buf_append_u16(&sized, options->policydigest_len);
 	if (options->policydigest_len)
-		tpm_buf_append(&buf, options->policydigest,
-			       options->policydigest_len);
+		tpm_buf_append(&sized, options->policydigest, options->policydigest_len);
 
 	/* public parameters */
-	tpm_buf_append_u16(&buf, TPM_ALG_NULL);
-	tpm_buf_append_u16(&buf, 0);
+	tpm_buf_append_u16(&sized, TPM_ALG_NULL);
+	tpm_buf_append_u16(&sized, 0);
+
+	tpm_buf_append(&buf, sized.data, sized.length);
 
 	/* outside info */
 	tpm_buf_append_u16(&buf, 0);
@@ -312,21 +321,20 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	if (rc)
 		goto out;
 
-	blob_len = be32_to_cpup((__be32 *) &buf.data[TPM_HEADER_SIZE]);
-	if (blob_len > MAX_BLOB_SIZE) {
+	blob_len = tpm_buf_read_u32(&buf, &offset);
+	if (blob_len > MAX_BLOB_SIZE || buf.flags & TPM_BUF_BOUNDARY_ERROR) {
 		rc = -E2BIG;
 		goto out;
 	}
-	if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 4 + blob_len) {
+	if (buf.length - offset < blob_len) {
 		rc = -EFAULT;
 		goto out;
 	}
 
-	blob_len = tpm2_key_encode(payload, options,
-				   &buf.data[TPM_HEADER_SIZE + 4],
-				   blob_len);
+	blob_len = tpm2_key_encode(payload, options, &buf.data[offset], blob_len);
 
 out:
+	tpm_buf_destroy(&sized);
 	tpm_buf_destroy(&buf);
 
 	if (rc > 0) {
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 09/22] crypto: lib - implement library version of AES in CFB mode
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (7 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 08/22] KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:27 ` [PATCH v8 10/22] tpm: add buffer function to point to returned parameters James Bottomley
                   ` (13 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

From: Ard Biesheuvel <ardb@kernel.org>

Implement AES in CFB mode using the existing, mostly constant-time
generic AES library implementation. This will be used by the TPM code
to encrypt communications with TPM hardware, which is often a discrete
component connected using sniffable wires or traces.

While a CFB template does exist, using a skcipher is a major pain for
non-performance critical synchronous crypto where the algorithm is known
at compile time and the data is in contiguous buffers with valid kernel
virtual addresses.

Tested-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/all/20230216201410.15010-1-James.Bottomley@HansenPartnership.com/
Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 include/crypto/aes.h |   5 +
 lib/crypto/Kconfig   |   5 +
 lib/crypto/Makefile  |   3 +
 lib/crypto/aescfb.c  | 257 +++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 270 insertions(+)
 create mode 100644 lib/crypto/aescfb.c

diff --git a/include/crypto/aes.h b/include/crypto/aes.h
index 2090729701ab..9339da7c20a8 100644
--- a/include/crypto/aes.h
+++ b/include/crypto/aes.h
@@ -87,4 +87,9 @@ void aes_decrypt(const struct crypto_aes_ctx *ctx, u8 *out, const u8 *in);
 extern const u8 crypto_aes_sbox[];
 extern const u8 crypto_aes_inv_sbox[];
 
+void aescfb_encrypt(const struct crypto_aes_ctx *ctx, u8 *dst, const u8 *src,
+		    int len, const u8 iv[AES_BLOCK_SIZE]);
+void aescfb_decrypt(const struct crypto_aes_ctx *ctx, u8 *dst, const u8 *src,
+		    int len, const u8 iv[AES_BLOCK_SIZE]);
+
 #endif
diff --git a/lib/crypto/Kconfig b/lib/crypto/Kconfig
index 45436bfc6dff..b01253cac70a 100644
--- a/lib/crypto/Kconfig
+++ b/lib/crypto/Kconfig
@@ -8,6 +8,11 @@ config CRYPTO_LIB_UTILS
 config CRYPTO_LIB_AES
 	tristate
 
+config CRYPTO_LIB_AESCFB
+	tristate
+	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_UTILS
+
 config CRYPTO_LIB_AESGCM
 	tristate
 	select CRYPTO_LIB_AES
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index 8d1446c2be71..969baab8c805 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -10,6 +10,9 @@ obj-$(CONFIG_CRYPTO_LIB_CHACHA_GENERIC)		+= libchacha.o
 obj-$(CONFIG_CRYPTO_LIB_AES)			+= libaes.o
 libaes-y					:= aes.o
 
+obj-$(CONFIG_CRYPTO_LIB_AESCFB)			+= libaescfb.o
+libaescfb-y					:= aescfb.o
+
 obj-$(CONFIG_CRYPTO_LIB_AESGCM)			+= libaesgcm.o
 libaesgcm-y					:= aesgcm.o
 
diff --git a/lib/crypto/aescfb.c b/lib/crypto/aescfb.c
new file mode 100644
index 000000000000..749dc1258a44
--- /dev/null
+++ b/lib/crypto/aescfb.c
@@ -0,0 +1,257 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Minimal library implementation of AES in CFB mode
+ *
+ * Copyright 2023 Google LLC
+ */
+
+#include <linux/module.h>
+
+#include <crypto/algapi.h>
+#include <crypto/aes.h>
+
+#include <asm/irqflags.h>
+
+static void aescfb_encrypt_block(const struct crypto_aes_ctx *ctx, void *dst,
+				 const void *src)
+{
+	unsigned long flags;
+
+	/*
+	 * In AES-CFB, the AES encryption operates on known 'plaintext' (the IV
+	 * and ciphertext), making it susceptible to timing attacks on the
+	 * encryption key. The AES library already mitigates this risk to some
+	 * extent by pulling the entire S-box into the caches before doing any
+	 * substitutions, but this strategy is more effective when running with
+	 * interrupts disabled.
+	 */
+	local_irq_save(flags);
+	aes_encrypt(ctx, dst, src);
+	local_irq_restore(flags);
+}
+
+/**
+ * aescfb_encrypt - Perform AES-CFB encryption on a block of data
+ *
+ * @ctx:	The AES-CFB key schedule
+ * @dst:	Pointer to the ciphertext output buffer
+ * @src:	Pointer the plaintext (may equal @dst for encryption in place)
+ * @len:	The size in bytes of the plaintext and ciphertext.
+ * @iv:		The initialization vector (IV) to use for this block of data
+ */
+void aescfb_encrypt(const struct crypto_aes_ctx *ctx, u8 *dst, const u8 *src,
+		    int len, const u8 iv[AES_BLOCK_SIZE])
+{
+	u8 ks[AES_BLOCK_SIZE];
+	const u8 *v = iv;
+
+	while (len > 0) {
+		aescfb_encrypt_block(ctx, ks, v);
+		crypto_xor_cpy(dst, src, ks, min(len, AES_BLOCK_SIZE));
+		v = dst;
+
+		dst += AES_BLOCK_SIZE;
+		src += AES_BLOCK_SIZE;
+		len -= AES_BLOCK_SIZE;
+	}
+
+	memzero_explicit(ks, sizeof(ks));
+}
+EXPORT_SYMBOL(aescfb_encrypt);
+
+/**
+ * aescfb_decrypt - Perform AES-CFB decryption on a block of data
+ *
+ * @ctx:	The AES-CFB key schedule
+ * @dst:	Pointer to the plaintext output buffer
+ * @src:	Pointer the ciphertext (may equal @dst for decryption in place)
+ * @len:	The size in bytes of the plaintext and ciphertext.
+ * @iv:		The initialization vector (IV) to use for this block of data
+ */
+void aescfb_decrypt(const struct crypto_aes_ctx *ctx, u8 *dst, const u8 *src,
+		    int len, const u8 iv[AES_BLOCK_SIZE])
+{
+	u8 ks[2][AES_BLOCK_SIZE];
+
+	aescfb_encrypt_block(ctx, ks[0], iv);
+
+	for (int i = 0; len > 0; i ^= 1) {
+		if (len > AES_BLOCK_SIZE)
+			/*
+			 * Generate the keystream for the next block before
+			 * performing the XOR, as that may update in place and
+			 * overwrite the ciphertext.
+			 */
+			aescfb_encrypt_block(ctx, ks[!i], src);
+
+		crypto_xor_cpy(dst, src, ks[i], min(len, AES_BLOCK_SIZE));
+
+		dst += AES_BLOCK_SIZE;
+		src += AES_BLOCK_SIZE;
+		len -= AES_BLOCK_SIZE;
+	}
+
+	memzero_explicit(ks, sizeof(ks));
+}
+EXPORT_SYMBOL(aescfb_decrypt);
+
+MODULE_DESCRIPTION("Generic AES-CFB library");
+MODULE_AUTHOR("Ard Biesheuvel <ardb@kernel.org>");
+MODULE_LICENSE("GPL");
+
+#ifndef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
+
+/*
+ * Test code below. Vectors taken from crypto/testmgr.h
+ */
+
+static struct {
+	u8	ptext[64];
+	u8	ctext[64];
+
+	u8	key[AES_MAX_KEY_SIZE];
+	u8	iv[AES_BLOCK_SIZE];
+
+	int	klen;
+	int	len;
+} const aescfb_tv[] __initconst = {
+	{ /* From NIST SP800-38A */
+		.key    = "\x2b\x7e\x15\x16\x28\xae\xd2\xa6"
+			  "\xab\xf7\x15\x88\x09\xcf\x4f\x3c",
+		.klen	= 16,
+		.iv	= "\x00\x01\x02\x03\x04\x05\x06\x07"
+			  "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
+		.ptext	= "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96"
+			  "\xe9\x3d\x7e\x11\x73\x93\x17\x2a"
+			  "\xae\x2d\x8a\x57\x1e\x03\xac\x9c"
+			  "\x9e\xb7\x6f\xac\x45\xaf\x8e\x51"
+			  "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11"
+			  "\xe5\xfb\xc1\x19\x1a\x0a\x52\xef"
+			  "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17"
+			  "\xad\x2b\x41\x7b\xe6\x6c\x37\x10",
+		.ctext	= "\x3b\x3f\xd9\x2e\xb7\x2d\xad\x20"
+			  "\x33\x34\x49\xf8\xe8\x3c\xfb\x4a"
+			  "\xc8\xa6\x45\x37\xa0\xb3\xa9\x3f"
+			  "\xcd\xe3\xcd\xad\x9f\x1c\xe5\x8b"
+			  "\x26\x75\x1f\x67\xa3\xcb\xb1\x40"
+			  "\xb1\x80\x8c\xf1\x87\xa4\xf4\xdf"
+			  "\xc0\x4b\x05\x35\x7c\x5d\x1c\x0e"
+			  "\xea\xc4\xc6\x6f\x9f\xf7\xf2\xe6",
+		.len	= 64,
+	}, {
+		.key	= "\x8e\x73\xb0\xf7\xda\x0e\x64\x52"
+			  "\xc8\x10\xf3\x2b\x80\x90\x79\xe5"
+			  "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b",
+		.klen	= 24,
+		.iv	= "\x00\x01\x02\x03\x04\x05\x06\x07"
+			  "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
+		.ptext	= "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96"
+			  "\xe9\x3d\x7e\x11\x73\x93\x17\x2a"
+			  "\xae\x2d\x8a\x57\x1e\x03\xac\x9c"
+			  "\x9e\xb7\x6f\xac\x45\xaf\x8e\x51"
+			  "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11"
+			  "\xe5\xfb\xc1\x19\x1a\x0a\x52\xef"
+			  "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17"
+			  "\xad\x2b\x41\x7b\xe6\x6c\x37\x10",
+		.ctext	= "\xcd\xc8\x0d\x6f\xdd\xf1\x8c\xab"
+			  "\x34\xc2\x59\x09\xc9\x9a\x41\x74"
+			  "\x67\xce\x7f\x7f\x81\x17\x36\x21"
+			  "\x96\x1a\x2b\x70\x17\x1d\x3d\x7a"
+			  "\x2e\x1e\x8a\x1d\xd5\x9b\x88\xb1"
+			  "\xc8\xe6\x0f\xed\x1e\xfa\xc4\xc9"
+			  "\xc0\x5f\x9f\x9c\xa9\x83\x4f\xa0"
+			  "\x42\xae\x8f\xba\x58\x4b\x09\xff",
+		.len	= 64,
+	}, {
+		.key	= "\x60\x3d\xeb\x10\x15\xca\x71\xbe"
+			  "\x2b\x73\xae\xf0\x85\x7d\x77\x81"
+			  "\x1f\x35\x2c\x07\x3b\x61\x08\xd7"
+			  "\x2d\x98\x10\xa3\x09\x14\xdf\xf4",
+		.klen	= 32,
+		.iv	= "\x00\x01\x02\x03\x04\x05\x06\x07"
+			  "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
+		.ptext	= "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96"
+			  "\xe9\x3d\x7e\x11\x73\x93\x17\x2a"
+			  "\xae\x2d\x8a\x57\x1e\x03\xac\x9c"
+			  "\x9e\xb7\x6f\xac\x45\xaf\x8e\x51"
+			  "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11"
+			  "\xe5\xfb\xc1\x19\x1a\x0a\x52\xef"
+			  "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17"
+			  "\xad\x2b\x41\x7b\xe6\x6c\x37\x10",
+		.ctext	= "\xdc\x7e\x84\xbf\xda\x79\x16\x4b"
+			  "\x7e\xcd\x84\x86\x98\x5d\x38\x60"
+			  "\x39\xff\xed\x14\x3b\x28\xb1\xc8"
+			  "\x32\x11\x3c\x63\x31\xe5\x40\x7b"
+			  "\xdf\x10\x13\x24\x15\xe5\x4b\x92"
+			  "\xa1\x3e\xd0\xa8\x26\x7a\xe2\xf9"
+			  "\x75\xa3\x85\x74\x1a\xb9\xce\xf8"
+			  "\x20\x31\x62\x3d\x55\xb1\xe4\x71",
+		.len	= 64,
+	}, { /* > 16 bytes, not a multiple of 16 bytes */
+		.key	= "\x2b\x7e\x15\x16\x28\xae\xd2\xa6"
+			  "\xab\xf7\x15\x88\x09\xcf\x4f\x3c",
+		.klen	= 16,
+		.iv	= "\x00\x01\x02\x03\x04\x05\x06\x07"
+			  "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
+		.ptext	= "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96"
+			  "\xe9\x3d\x7e\x11\x73\x93\x17\x2a"
+			  "\xae",
+		.ctext	= "\x3b\x3f\xd9\x2e\xb7\x2d\xad\x20"
+			  "\x33\x34\x49\xf8\xe8\x3c\xfb\x4a"
+			  "\xc8",
+		.len	= 17,
+	}, { /* < 16 bytes */
+		.key	= "\x2b\x7e\x15\x16\x28\xae\xd2\xa6"
+			  "\xab\xf7\x15\x88\x09\xcf\x4f\x3c",
+		.klen	= 16,
+		.iv	= "\x00\x01\x02\x03\x04\x05\x06\x07"
+			  "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
+		.ptext	= "\x6b\xc1\xbe\xe2\x2e\x40\x9f",
+		.ctext	= "\x3b\x3f\xd9\x2e\xb7\x2d\xad",
+		.len	= 7,
+	},
+};
+
+static int __init libaescfb_init(void)
+{
+	for (int i = 0; i < ARRAY_SIZE(aescfb_tv); i++) {
+		struct crypto_aes_ctx ctx;
+		u8 buf[64];
+
+		if (aes_expandkey(&ctx, aescfb_tv[i].key, aescfb_tv[i].klen)) {
+			pr_err("aes_expandkey() failed on vector %d\n", i);
+			return -ENODEV;
+		}
+
+		aescfb_encrypt(&ctx, buf, aescfb_tv[i].ptext, aescfb_tv[i].len,
+			       aescfb_tv[i].iv);
+		if (memcmp(buf, aescfb_tv[i].ctext, aescfb_tv[i].len)) {
+			pr_err("aescfb_encrypt() #1 failed on vector %d\n", i);
+			return -ENODEV;
+		}
+
+		/* decrypt in place */
+		aescfb_decrypt(&ctx, buf, buf, aescfb_tv[i].len, aescfb_tv[i].iv);
+		if (memcmp(buf, aescfb_tv[i].ptext, aescfb_tv[i].len)) {
+			pr_err("aescfb_decrypt() failed on vector %d\n", i);
+			return -ENODEV;
+		}
+
+		/* encrypt in place */
+		aescfb_encrypt(&ctx, buf, buf, aescfb_tv[i].len, aescfb_tv[i].iv);
+		if (memcmp(buf, aescfb_tv[i].ctext, aescfb_tv[i].len)) {
+			pr_err("aescfb_encrypt() #2 failed on vector %d\n", i);
+
+			return -ENODEV;
+		}
+
+	}
+	return 0;
+}
+module_init(libaescfb_init);
+
+static void __exit libaescfb_exit(void)
+{
+}
+module_exit(libaescfb_exit);
+#endif
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 10/22] tpm: add buffer function to point to returned parameters
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (8 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 09/22] crypto: lib - implement library version of AES in CFB mode James Bottomley
@ 2024-04-29 20:27 ` James Bottomley
  2024-04-29 20:28 ` [PATCH v8 11/22] tpm: export the context save and load commands James Bottomley
                   ` (12 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:27 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

Replace all instances of &buf.data[TPM_HEADER_SIZE] with a new
function tpm_buf_parameters() because encryption sessions change
where the return parameters are located in the buffer since if a
return session is present they're 4 bytes beyond the header with those
4 bytes giving the parameter length.  If there is no return session,
then they're in the usual place immediately after the header.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---
v4: add kdoc
v5: update kdoc add review
v7: add review
---
 drivers/char/tpm/tpm-buf.c | 28 ++++++++++++++++++++++++++++
 include/linux/tpm.h        |  2 ++
 2 files changed, 30 insertions(+)

diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 32619e9ab4fa..bb81180495d1 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -220,3 +220,31 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
 	return be32_to_cpu(value);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
+
+static u16 tpm_buf_tag(struct tpm_buf *buf)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+
+	return be16_to_cpu(head->tag);
+}
+
+/**
+ * tpm_buf_parameters - return the TPM response parameters area of the tpm_buf
+ * @buf: tpm_buf to use
+ *
+ * Where the parameters are located depends on the tag of a TPM
+ * command (it's immediately after the header for TPM_ST_NO_SESSIONS
+ * or 4 bytes after for TPM_ST_SESSIONS). Evaluate this and return a
+ * pointer to the first byte of the parameters area.
+ *
+ * @return: pointer to parameters area
+ */
+u8 *tpm_buf_parameters(struct tpm_buf *buf)
+{
+	int offset = TPM_HEADER_SIZE;
+
+	if (tpm_buf_tag(buf) == TPM2_ST_SESSIONS)
+		offset += 4;
+
+	return &buf->data[offset];
+}
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index e8172f81c562..6be263509e81 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -344,6 +344,8 @@ u8 tpm_buf_read_u8(struct tpm_buf *buf, off_t *offset);
 u16 tpm_buf_read_u16(struct tpm_buf *buf, off_t *offset);
 u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset);
 
+u8 *tpm_buf_parameters(struct tpm_buf *buf);
+
 /*
  * Check if TPM device is in the firmware upgrade mode.
  */
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 11/22] tpm: export the context save and load commands
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (9 preceding siblings ...)
  2024-04-29 20:27 ` [PATCH v8 10/22] tpm: add buffer function to point to returned parameters James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 20:28 ` [PATCH v8 12/22] tpm: Add NULL primary creation James Bottomley
                   ` (11 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

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.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---

v5: add review
v7: add review
---
 drivers/char/tpm/tpm.h        | 4 ++++
 drivers/char/tpm/tpm2-space.c | 8 ++++----
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
index 61445f1dc46d..cbc9d1e2974d 100644
--- a/drivers/char/tpm/tpm.h
+++ b/drivers/char/tpm/tpm.h
@@ -312,6 +312,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);
diff --git a/drivers/char/tpm/tpm2-space.c b/drivers/char/tpm/tpm2-space.c
index 363afdd4d1d3..24479a81c23c 100644
--- a/drivers/char/tpm/tpm2-space.c
+++ b/drivers/char/tpm/tpm2-space.c
@@ -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;
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 12/22] tpm: Add NULL primary creation
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (10 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 11/22] tpm: export the context save and load commands James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 22:37   ` Jarkko Sakkinen
  2024-04-29 20:28 ` [PATCH v8 13/22] tpm: Add TCG mandated Key Derivation Functions (KDFs) James Bottomley
                   ` (10 subsequent siblings)
  22 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

The session handling code uses a "salted" session, meaning a session
whose salt is encrypted to the public part of another TPM key so an
observer cannot obtain it (and thus deduce the session keys).  This
patch creates and context saves in the tpm_chip area the primary key
of the NULL hierarchy for this purpose.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>

---
v6: split out of original HMAC patch update config name
v7: rename null seed parameters
v8: format changes and move template to tpm.h
---
 drivers/char/tpm/Kconfig         |  11 ++
 drivers/char/tpm/Makefile        |   1 +
 drivers/char/tpm/tpm.h           |  10 +
 drivers/char/tpm/tpm2-cmd.c      |   5 +
 drivers/char/tpm/tpm2-sessions.c | 316 +++++++++++++++++++++++++++++++
 include/linux/tpm.h              |  69 +++++++
 6 files changed, 412 insertions(+)
 create mode 100644 drivers/char/tpm/tpm2-sessions.c

diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
index 927088b2c3d3..ab16d347579f 100644
--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -27,6 +27,17 @@ menuconfig TCG_TPM
 
 if TCG_TPM
 
+config TCG_TPM2_HMAC
+	bool "Use HMAC and encrypted transactions on the TPM bus"
+	default y
+	help
+	  Setting this causes us to deploy a scheme which uses request
+	  and response HMACs in addition to encryption for
+	  communicating with the TPM to prevent or detect bus snooping
+	  and interposer attacks (see tpm-security.rst).  Saying Y
+	  here adds some encryption overhead to all kernel to TPM
+	  transactions.
+
 config HW_RANDOM_TPM
 	bool "TPM HW Random Number Generator support"
 	depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m)
diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile
index ad3594e383e1..4c695b0388f3 100644
--- a/drivers/char/tpm/Makefile
+++ b/drivers/char/tpm/Makefile
@@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o
 tpm-y += eventlog/tpm2.o
 tpm-y += tpm-buf.o
 
+tpm-$(CONFIG_TCG_TPM2_HMAC) += tpm2-sessions.o
 tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
 tpm-$(CONFIG_EFI) += eventlog/efi.o
 tpm-$(CONFIG_OF) += eventlog/of.o
diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
index cbc9d1e2974d..6b8b9956ba69 100644
--- a/drivers/char/tpm/tpm.h
+++ b/drivers/char/tpm/tpm.h
@@ -321,4 +321,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_TCG_TPM2_HMAC
+int tpm2_sessions_init(struct tpm_chip *chip);
+#else
+static inline int tpm2_sessions_init(struct tpm_chip *chip)
+{
+	return 0;
+}
+#endif
+
 #endif
diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index 93545be190a5..b0e72fb563d9 100644
--- a/drivers/char/tpm/tpm2-cmd.c
+++ b/drivers/char/tpm/tpm2-cmd.c
@@ -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
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
new file mode 100644
index 000000000000..fc3f032df467
--- /dev/null
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -0,0 +1,316 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
+ *
+ */
+
+#include "tpm.h"
+#include <asm/unaligned.h>
+
+/**
+ * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
+ *
+ * @chip:	The TPM the primary was created under
+ * @buf:	The response buffer from the chip
+ * @handle:	pointer to be filled in with the return handle of the primary
+ * @hierarchy:	The hierarchy the primary was created for
+ *
+ * @returns: 0 on success or a positive TPM or negative standard error
+ */
+static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
+				     u32 *handle, u32 hierarchy)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+	off_t offset_r = TPM_HEADER_SIZE, offset_t;
+	u16 len = TPM_HEADER_SIZE;
+	u32 total_len = be32_to_cpu(head->length);
+	u32 val, param_len;
+
+	*handle = tpm_buf_read_u32(buf, &offset_r);
+	param_len = tpm_buf_read_u32(buf, &offset_r);
+	/*
+	 * param_len doesn't include the header, but all the other
+	 * lengths and offsets do, so add it to parm len to make
+	 * the comparisons easier
+	 */
+	param_len += TPM_HEADER_SIZE;
+
+	if (param_len + 8 > total_len)
+		return -EINVAL;
+	len = tpm_buf_read_u16(buf, &offset_r);
+	offset_t = offset_r;
+	/* now we have the public area, compute the name of the object */
+	put_unaligned_be16(TPM_ALG_SHA256, chip->null_key_name);
+	sha256(&buf->data[offset_r], len, chip->null_key_name + 2);
+
+	/* validate the public key */
+	val = tpm_buf_read_u16(buf, &offset_t);
+
+	/* key type (must be what we asked for) */
+	if (val != TPM_ALG_ECC)
+		return -EINVAL;
+	val = tpm_buf_read_u16(buf, &offset_t);
+
+	/* name algorithm */
+	if (val != TPM_ALG_SHA256)
+		return -EINVAL;
+	val = tpm_buf_read_u32(buf, &offset_t);
+
+	/* object properties */
+	if (val != TPM2_OA_TMPL)
+		return -EINVAL;
+
+	/* auth policy (empty) */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != 0)
+		return -EINVAL;
+
+	/* symmetric key parameters */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != TPM_ALG_AES)
+		return -EINVAL;
+
+	/* symmetric key length */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != AES_KEY_BITS)
+		return -EINVAL;
+
+	/* symmetric encryption scheme */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != TPM_ALG_CFB)
+		return -EINVAL;
+
+	/* signing scheme */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != TPM_ALG_NULL)
+		return -EINVAL;
+
+	/* ECC Curve */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != TPM2_ECC_NIST_P256)
+		return -EINVAL;
+
+	/* KDF Scheme */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != TPM_ALG_NULL)
+		return -EINVAL;
+
+	/* extract public key (x and y points) */
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != EC_PT_SZ)
+		return -EINVAL;
+	memcpy(chip->null_ec_key_x, &buf->data[offset_t], val);
+	offset_t += val;
+	val = tpm_buf_read_u16(buf, &offset_t);
+	if (val != EC_PT_SZ)
+		return -EINVAL;
+	memcpy(chip->null_ec_key_y, &buf->data[offset_t], val);
+	offset_t += val;
+
+	/* original length of the whole TPM2B */
+	offset_r += len;
+
+	/* should have exactly consumed the TPM2B public structure */
+	if (offset_t != offset_r)
+		return -EINVAL;
+	if (offset_r > param_len)
+		return -EINVAL;
+
+	/* creation data (skip) */
+	len = tpm_buf_read_u16(buf, &offset_r);
+	offset_r += len;
+	if (offset_r > param_len)
+		return -EINVAL;
+
+	/* creation digest (must be sha256) */
+	len = tpm_buf_read_u16(buf, &offset_r);
+	offset_r += len;
+	if (len != SHA256_DIGEST_SIZE || offset_r > param_len)
+		return -EINVAL;
+
+	/* TPMT_TK_CREATION follows */
+	/* tag, must be TPM_ST_CREATION (0x8021) */
+	val = tpm_buf_read_u16(buf, &offset_r);
+	if (val != TPM2_ST_CREATION || offset_r > param_len)
+		return -EINVAL;
+
+	/* hierarchy */
+	val = tpm_buf_read_u32(buf, &offset_r);
+	if (val != hierarchy || offset_r > param_len)
+		return -EINVAL;
+
+	/* the ticket digest HMAC (might not be sha256) */
+	len = tpm_buf_read_u16(buf, &offset_r);
+	offset_r += len;
+	if (offset_r > param_len)
+		return -EINVAL;
+
+	/*
+	 * finally we have the name, which is a sha256 digest plus a 2
+	 * byte algorithm type
+	 */
+	len = tpm_buf_read_u16(buf, &offset_r);
+	if (offset_r + len != param_len + 8)
+		return -EINVAL;
+	if (len != SHA256_DIGEST_SIZE + 2)
+		return -EINVAL;
+
+	if (memcmp(chip->null_key_name, &buf->data[offset_r],
+		   SHA256_DIGEST_SIZE + 2) != 0) {
+		dev_err(&chip->dev, "NULL Seed name comparison failed\n");
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+/**
+ * tpm2_create_primary() - create a primary key using a fixed P-256 template
+ *
+ * @chip:      the TPM chip to create under
+ * @hierarchy: The hierarchy handle to create under
+ * @handle:    The returned volatile handle on success
+ *
+ * For platforms that might not have a persistent primary, this can be
+ * used to create one quickly on the fly (it uses Elliptic Curve not
+ * RSA, so even slow TPMs can create one fast).  The template uses the
+ * TCG mandated H one for non-endorsement ECC primaries, i.e. P-256
+ * elliptic curve (the only current one all TPM2s are required to
+ * have) a sha256 name hash and no policy.
+ *
+ * @returns: 0 on success or positive TPM or negative error.
+ */
+static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
+			       u32 *handle)
+{
+	int rc;
+	struct tpm_buf buf;
+	struct tpm_buf template;
+
+	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
+	if (rc)
+		return rc;
+
+	rc = tpm_buf_init_sized(&template);
+	if (rc) {
+		tpm_buf_destroy(&buf);
+		return rc;
+	}
+
+	/*
+	 * create the template.  Note: in order for userspace to
+	 * verify the security of the system, it will have to create
+	 * and certify this NULL primary, meaning all the template
+	 * parameters will have to be identical, so conform exactly to
+	 * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
+	 * key H template (H has zero size unique points)
+	 */
+
+	/* key type */
+	tpm_buf_append_u16(&template, TPM_ALG_ECC);
+
+	/* name algorithm */
+	tpm_buf_append_u16(&template, TPM_ALG_SHA256);
+
+	/* object properties */
+	tpm_buf_append_u32(&template, TPM2_OA_TMPL);
+
+	/* sauth policy (empty) */
+	tpm_buf_append_u16(&template, 0);
+
+	/* BEGIN parameters: key specific; for ECC*/
+
+	/* symmetric algorithm */
+	tpm_buf_append_u16(&template, TPM_ALG_AES);
+
+	/* bits for symmetric algorithm */
+	tpm_buf_append_u16(&template, AES_KEY_BITS);
+
+	/* algorithm mode (must be CFB) */
+	tpm_buf_append_u16(&template, TPM_ALG_CFB);
+
+	/* scheme (NULL means any scheme) */
+	tpm_buf_append_u16(&template, TPM_ALG_NULL);
+
+	/* ECC Curve ID */
+	tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
+
+	/* KDF Scheme */
+	tpm_buf_append_u16(&template, TPM_ALG_NULL);
+
+	/* unique: key specific; for ECC it is two zero size points */
+	tpm_buf_append_u16(&template, 0);
+	tpm_buf_append_u16(&template, 0);
+
+	/* END parameters */
+
+	/* primary handle */
+	tpm_buf_append_u32(&buf, hierarchy);
+	tpm_buf_append_empty_auth(&buf, TPM2_RS_PW);
+
+	/* sensitive create size is 4 for two empty buffers */
+	tpm_buf_append_u16(&buf, 4);
+
+	/* sensitive create auth data (empty) */
+	tpm_buf_append_u16(&buf, 0);
+
+	/* sensitive create sensitive data (empty) */
+	tpm_buf_append_u16(&buf, 0);
+
+	/* the public template */
+	tpm_buf_append(&buf, template.data, template.length);
+	tpm_buf_destroy(&template);
+
+	/* outside info (empty) */
+	tpm_buf_append_u16(&buf, 0);
+
+	/* creation PCR (none) */
+	tpm_buf_append_u32(&buf, 0);
+
+	rc = tpm_transmit_cmd(chip, &buf, 0,
+			      "attempting to create NULL primary");
+
+	if (rc == TPM2_RC_SUCCESS)
+		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy);
+
+	tpm_buf_destroy(&buf);
+
+	return rc;
+}
+
+static int tpm2_create_null_primary(struct tpm_chip *chip)
+{
+	u32 null_key;
+	int rc;
+
+	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key);
+
+	if (rc == TPM2_RC_SUCCESS) {
+		unsigned int offset = 0; /* dummy offset for null key context */
+
+		rc = tpm2_save_context(chip, null_key, chip->null_key_context,
+				       sizeof(chip->null_key_context), &offset);
+		tpm2_flush_context(chip, null_key);
+	}
+
+	return rc;
+}
+
+/**
+ * tpm2_sessions_init() - start of day initialization for the sessions code
+ * @chip: TPM chip
+ *
+ * Derive and context save the null primary and allocate memory in the
+ * struct tpm_chip for the authorizations.
+ */
+int tpm2_sessions_init(struct tpm_chip *chip)
+{
+	int rc;
+
+	rc = tpm2_create_null_primary(chip);
+	if (rc)
+		dev_err(&chip->dev, "TPM: security failed (NULL seed derivation): %d\n", rc);
+
+	return rc;
+}
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 6be263509e81..bc8c9a350e23 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -23,6 +23,7 @@
 #include <linux/fs.h>
 #include <linux/highmem.h>
 #include <crypto/hash_info.h>
+#include <crypto/aes.h>
 
 #define TPM_DIGEST_SIZE 20	/* Max TPM v1.2 PCR size */
 #define TPM_MAX_DIGEST_SIZE SHA512_DIGEST_SIZE
@@ -35,12 +36,15 @@ struct trusted_key_options;
 enum tpm_algorithms {
 	TPM_ALG_ERROR		= 0x0000,
 	TPM_ALG_SHA1		= 0x0004,
+	TPM_ALG_AES		= 0x0006,
 	TPM_ALG_KEYEDHASH	= 0x0008,
 	TPM_ALG_SHA256		= 0x000B,
 	TPM_ALG_SHA384		= 0x000C,
 	TPM_ALG_SHA512		= 0x000D,
 	TPM_ALG_NULL		= 0x0010,
 	TPM_ALG_SM3_256		= 0x0012,
+	TPM_ALG_ECC		= 0x0023,
+	TPM_ALG_CFB		= 0x0043,
 };
 
 /*
@@ -49,6 +53,11 @@ enum tpm_algorithms {
  */
 #define TPM_MAX_HASHES	5
 
+enum tpm2_curves {
+	TPM2_ECC_NONE		= 0x0000,
+	TPM2_ECC_NIST_P256	= 0x0003,
+};
+
 struct tpm_digest {
 	u16 alg_id;
 	u8 digest[TPM_MAX_DIGEST_SIZE];
@@ -116,6 +125,20 @@ struct tpm_chip_seqops {
 	const struct seq_operations *seqops;
 };
 
+/* fixed define for the curve we use which is NIST_P256 */
+#define EC_PT_SZ	32
+
+/*
+ * fixed define for the size of a name.  This is actually HASHALG size
+ * plus 2, so 32 for SHA256
+ */
+#define TPM2_NAME_SIZE	34
+
+/*
+ * The maximum size for an object context
+ */
+#define TPM2_MAX_CONTEXT_SIZE 4096
+
 struct tpm_chip {
 	struct device dev;
 	struct device devs;
@@ -170,6 +193,17 @@ struct tpm_chip {
 
 	/* active locality */
 	int locality;
+
+#ifdef CONFIG_TCG_TPM2_HMAC
+	/* details for communication security via sessions */
+
+	/* saved context for NULL seed */
+	u8 null_key_context[TPM2_MAX_CONTEXT_SIZE];
+	 /* name of NULL seed */
+	u8 null_key_name[TPM2_NAME_SIZE];
+	u8 null_ec_key_x[EC_PT_SZ];
+	u8 null_ec_key_y[EC_PT_SZ];
+#endif
 };
 
 #define TPM_HEADER_SIZE		10
@@ -194,6 +228,7 @@ enum tpm2_timeouts {
 enum tpm2_structures {
 	TPM2_ST_NO_SESSIONS	= 0x8001,
 	TPM2_ST_SESSIONS	= 0x8002,
+	TPM2_ST_CREATION	= 0x8021,
 };
 
 /* Indicates from what layer of the software stack the error comes from */
@@ -243,6 +278,7 @@ enum tpm2_command_codes {
 };
 
 enum tpm2_permanent_handles {
+	TPM2_RH_NULL		= 0x40000007,
 	TPM2_RS_PW		= 0x40000009,
 };
 
@@ -318,9 +354,28 @@ struct tpm_buf {
 enum tpm2_object_attributes {
 	TPM2_OA_FIXED_TPM		= BIT(1),
 	TPM2_OA_FIXED_PARENT		= BIT(4),
+	TPM2_OA_SENSITIVE_DATA_ORIGIN	= BIT(5),
 	TPM2_OA_USER_WITH_AUTH		= BIT(6),
+	TPM2_OA_NO_DA			= BIT(10),
+	TPM2_OA_RESTRICTED		= BIT(16),
+	TPM2_OA_DECRYPT			= BIT(17),
 };
 
+/*
+ * definitions for the canonical template.  These are mandated
+ * by the TCG key template documents
+ */
+
+#define AES_KEY_BYTES	AES_KEYSIZE_128
+#define AES_KEY_BITS	(AES_KEY_BYTES*8)
+#define TPM2_OA_TMPL	(TPM2_OA_NO_DA |			\
+			 TPM2_OA_FIXED_TPM |			\
+			 TPM2_OA_FIXED_PARENT |			\
+			 TPM2_OA_SENSITIVE_DATA_ORIGIN |	\
+			 TPM2_OA_USER_WITH_AUTH |		\
+			 TPM2_OA_DECRYPT |			\
+			 TPM2_OA_RESTRICTED)
+
 enum tpm2_session_attributes {
 	TPM2_SA_CONTINUE_SESSION	= BIT(0),
 };
@@ -373,6 +428,16 @@ extern int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 extern int tpm_get_random(struct tpm_chip *chip, u8 *data, size_t max);
 extern struct tpm_chip *tpm_default_chip(void);
 void tpm2_flush_context(struct tpm_chip *chip, u32 handle);
+
+static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
+{
+	/* simple authorization for empty auth */
+	tpm_buf_append_u32(buf, 9);		/* total length of auth */
+	tpm_buf_append_u32(buf, handle);
+	tpm_buf_append_u16(buf, 0);		/* nonce len */
+	tpm_buf_append_u8(buf, 0);		/* attributes */
+	tpm_buf_append_u16(buf, 0);		/* hmac len */
+}
 #else
 static inline int tpm_is_tpm2(struct tpm_chip *chip)
 {
@@ -399,5 +464,9 @@ static inline struct tpm_chip *tpm_default_chip(void)
 {
 	return NULL;
 }
+
+static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
+{
+}
 #endif
 #endif
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 13/22] tpm: Add TCG mandated Key Derivation Functions (KDFs)
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (11 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 12/22] tpm: Add NULL primary creation James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 22:37   ` Jarkko Sakkinen
  2024-04-29 20:28 ` [PATCH v8 14/22] tpm: Add HMAC session start and end functions James Bottomley
                   ` (9 subsequent siblings)
  22 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

The TCG mandates two Key derivation functions called KDFa and KDFe
used to derive keys from seeds and elliptic curve points respectively.
The definitions for these functions are found in the TPM 2.0 Library
Specification Part 1 - Architecture Guide

https://trustedcomputinggroup.org/resource/tpm-library-specification/

Implement a cut down version of each of these functions sufficient to
support the key derivation needs of HMAC sessions.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>

---

v8: Add new patch containing KDFs
---
 drivers/char/tpm/Kconfig         |   1 +
 drivers/char/tpm/tpm2-sessions.c | 105 +++++++++++++++++++++++++++++++
 2 files changed, 106 insertions(+)

diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
index ab16d347579f..4873e6eae255 100644
--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -30,6 +30,7 @@ if TCG_TPM
 config TCG_TPM2_HMAC
 	bool "Use HMAC and encrypted transactions on the TPM bus"
 	default y
+	select CRYPTO_LIB_SHA256
 	help
 	  Setting this causes us to deploy a scheme which uses request
 	  and response HMACs in addition to encryption for
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index fc3f032df467..8429e596f1eb 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -7,6 +7,111 @@
 
 #include "tpm.h"
 #include <asm/unaligned.h>
+#include <crypto/hash.h>
+#include <crypto/hmac.h>
+
+/*
+ * It turns out the crypto hmac(sha256) is hard for us to consume
+ * because it assumes a fixed key and the TPM seems to change the key
+ * on every operation, so we weld the hmac init and final functions in
+ * here to give it the same usage characteristics as a regular hash
+ */
+static void tpm2_hmac_init(struct sha256_state *sctx, u8 *key, u32 key_len)
+{
+	u8 pad[SHA256_BLOCK_SIZE];
+	int i;
+
+	sha256_init(sctx);
+	for (i = 0; i < sizeof(pad); i++) {
+		if (i < key_len)
+			pad[i] = key[i];
+		else
+			pad[i] = 0;
+		pad[i] ^= HMAC_IPAD_VALUE;
+	}
+	sha256_update(sctx, pad, sizeof(pad));
+}
+
+static void tpm2_hmac_final(struct sha256_state *sctx, u8 *key, u32 key_len,
+			    u8 *out)
+{
+	u8 pad[SHA256_BLOCK_SIZE];
+	int i;
+
+	for (i = 0; i < sizeof(pad); i++) {
+		if (i < key_len)
+			pad[i] = key[i];
+		else
+			pad[i] = 0;
+		pad[i] ^= HMAC_OPAD_VALUE;
+	}
+
+	/* collect the final hash;  use out as temporary storage */
+	sha256_final(sctx, out);
+
+	sha256_init(sctx);
+	sha256_update(sctx, pad, sizeof(pad));
+	sha256_update(sctx, out, SHA256_DIGEST_SIZE);
+	sha256_final(sctx, out);
+}
+
+/*
+ * assume hash sha256 and nonces u, v of size SHA256_DIGEST_SIZE but
+ * otherwise standard tpm2_KDFa.  Note output is in bytes not bits.
+ */
+static void tpm2_KDFa(u8 *key, u32 key_len, const char *label, u8 *u,
+		      u8 *v, u32 bytes, u8 *out)
+{
+	u32 counter = 1;
+	const __be32 bits = cpu_to_be32(bytes * 8);
+
+	while (bytes > 0) {
+		struct sha256_state sctx;
+		__be32 c = cpu_to_be32(counter);
+
+		tpm2_hmac_init(&sctx, key, key_len);
+		sha256_update(&sctx, (u8 *)&c, sizeof(c));
+		sha256_update(&sctx, label, strlen(label)+1);
+		sha256_update(&sctx, u, SHA256_DIGEST_SIZE);
+		sha256_update(&sctx, v, SHA256_DIGEST_SIZE);
+		sha256_update(&sctx, (u8 *)&bits, sizeof(bits));
+		tpm2_hmac_final(&sctx, key, key_len, out);
+
+		bytes -= SHA256_DIGEST_SIZE;
+		counter++;
+		out += SHA256_DIGEST_SIZE;
+	}
+}
+
+/*
+ * Somewhat of a bastardization of the real KDFe.  We're assuming
+ * we're working with known point sizes for the input parameters and
+ * the hash algorithm is fixed at sha256.  Because we know that the
+ * point size is 32 bytes like the hash size, there's no need to loop
+ * in this KDF.
+ */
+static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
+		      u8 *out)
+{
+	struct sha256_state sctx;
+	/*
+	 * this should be an iterative counter, but because we know
+	 *  we're only taking 32 bytes for the point using a sha256
+	 *  hash which is also 32 bytes, there's only one loop
+	 */
+	__be32 c = cpu_to_be32(1);
+
+	sha256_init(&sctx);
+	/* counter (BE) */
+	sha256_update(&sctx, (u8 *)&c, sizeof(c));
+	/* secret value */
+	sha256_update(&sctx, z, EC_PT_SZ);
+	/* string including trailing zero */
+	sha256_update(&sctx, str, strlen(str)+1);
+	sha256_update(&sctx, pt_u, EC_PT_SZ);
+	sha256_update(&sctx, pt_v, EC_PT_SZ);
+	sha256_final(&sctx, out);
+}
 
 /**
  * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 14/22] tpm: Add HMAC session start and end functions
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (12 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 13/22] tpm: Add TCG mandated Key Derivation Functions (KDFs) James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 22:38   ` Jarkko Sakkinen
  2024-04-30 16:49   ` Jarkko Sakkinen
  2024-04-29 20:28 ` [PATCH v8 15/22] tpm: Add HMAC session name/handle append James Bottomley
                   ` (8 subsequent siblings)
  22 siblings, 2 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

Add 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.  The  design is that  session use will be  single threaded
from start to finish under the ops lock, so the tpm2_auth structure is
stored in struct tpm2_chip to simpify the externally visible API.

The session can be ended with tpm2_end_auth_session() which is
designed only to be used in error legs.  Ordinarily the further
session API (future patches) will end or continue the session
appropriately without having to call this.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts

---

v6: split into new patch, update config variable
v7: add tpm2_ prefix and memzero_explicit
v8: cosmetic changes, split out KDFe and KDFa
---
 drivers/char/tpm/Kconfig         |   2 +
 drivers/char/tpm/tpm-buf.c       |   1 +
 drivers/char/tpm/tpm-chip.c      |   3 +
 drivers/char/tpm/tpm2-sessions.c | 285 +++++++++++++++++++++++++++++++
 include/linux/tpm.h              |  34 ++++
 5 files changed, 325 insertions(+)

diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
index 4873e6eae255..cecf617c9c90 100644
--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -30,6 +30,8 @@ if TCG_TPM
 config TCG_TPM2_HMAC
 	bool "Use HMAC and encrypted transactions on the TPM bus"
 	default y
+	select CRYPTO_ECDH
+	select CRYPTO_LIB_AESCFB
 	select CRYPTO_LIB_SHA256
 	help
 	  Setting this causes us to deploy a scheme which uses request
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index bb81180495d1..274130398569 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -44,6 +44,7 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+	buf->handles = 0;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
diff --git a/drivers/char/tpm/tpm-chip.c b/drivers/char/tpm/tpm-chip.c
index 42b1062e33cd..d93937326b2e 100644
--- a/drivers/char/tpm/tpm-chip.c
+++ b/drivers/char/tpm/tpm-chip.c
@@ -275,6 +275,9 @@ static void tpm_dev_release(struct device *dev)
 	kfree(chip->work_space.context_buf);
 	kfree(chip->work_space.session_buf);
 	kfree(chip->allocated_banks);
+#ifdef CONFIG_TCG_TPM2_HMAC
+	kfree(chip->auth);
+#endif
 	kfree(chip);
 }
 
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 8429e596f1eb..71b3c0e75760 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -3,13 +3,101 @@
 /*
  * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
  *
+ * Cryptographic helper routines for handling TPM2 sessions for
+ * authorization HMAC and request response encryption.
+ *
+ * The idea is to ensure that every TPM command is HMAC protected by a
+ * session, meaning in-flight tampering would be detected and in
+ * addition all sensitive inputs and responses should be encrypted.
+ *
+ * The basic way this works is to use a TPM feature called salted
+ * sessions where a random secret used in session construction is
+ * encrypted to the public part of a known TPM key.  The problem is we
+ * have no known keys, so initially a primary Elliptic Curve key is
+ * derived from the NULL seed (we use EC because most TPMs generate
+ * these keys much faster than RSA ones).  The curve used is NIST_P256
+ * because that's now mandated to be present in 'TCG TPM v2.0
+ * Provisioning Guidance'
+ *
+ * Threat problems: the initial TPM2_CreatePrimary is not (and cannot
+ * be) session protected, so a clever Man in the Middle could return a
+ * public key they control to this command and from there intercept
+ * and decode all subsequent session based transactions.  The kernel
+ * cannot mitigate this threat but, after boot, userspace can get
+ * proof this has not happened by asking the TPM to certify the NULL
+ * key.  This certification would chain back to the TPM Endorsement
+ * Certificate and prove the NULL seed primary had not been tampered
+ * with and thus all sessions must have been cryptographically secure.
+ * To assist with this, the initial NULL seed public key name is made
+ * available in a sysfs file.
+ *
+ * Use of these functions:
+ *
+ * The design is all the crypto, hash and hmac gunk is confined in this
+ * file and never needs to be seen even by the kernel internal user.  To
+ * the user there's an init function tpm2_sessions_init() that needs to
+ * be called once per TPM which generates the NULL seed primary key.
+ *
+ * These are the usage functions:
+ *
+ * tpm2_start_auth_session() which allocates the opaque auth structure
+ *	and gets a session from the TPM.  This must be called before
+ *	any of the following functions.  The session is protected by a
+ *	session_key which is derived from a random salt value
+ *	encrypted to the NULL seed.
+ * tpm2_end_auth_session() kills the session and frees the resources.
+ *	Under normal operation this function is done by
+ *	tpm_buf_check_hmac_response(), so this is only to be used on
+ *	error legs where the latter is not executed.
  */
 
 #include "tpm.h"
+#include <linux/random.h>
+#include <linux/scatterlist.h>
 #include <asm/unaligned.h>
+#include <crypto/kpp.h>
+#include <crypto/ecdh.h>
 #include <crypto/hash.h>
 #include <crypto/hmac.h>
 
+/*
+ * This is the structure that carries all the auth information (like
+ * session handle, nonces, session key and auth) from use to use it is
+ * designed to be opaque to anything outside.
+ */
+struct tpm2_auth {
+	u32 handle;
+	/*
+	 * This has two meanings: before tpm_buf_fill_hmac_session()
+	 * it marks the offset in the buffer of the start of the
+	 * sessions (i.e. after all the handles).  Once the buffer has
+	 * been filled it markes the session number of our auth
+	 * session so we can find it again in the response buffer.
+	 *
+	 * The two cases are distinguished because the first offset
+	 * must always be greater than TPM_HEADER_SIZE and the second
+	 * must be less than or equal to 5.
+	 */
+	u32 session;
+	/*
+	 * the size here is variable and set by the size of our_nonce
+	 * which must be between 16 and the name hash length. we set
+	 * the maximum sha256 size for the greatest protection
+	 */
+	u8 our_nonce[SHA256_DIGEST_SIZE];
+	u8 tpm_nonce[SHA256_DIGEST_SIZE];
+	/*
+	 * the salt is only used across the session command/response
+	 * after that it can be used as a scratch area
+	 */
+	union {
+		u8 salt[EC_PT_SZ];
+		/* scratch for key + IV */
+		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
+	};
+	u8 session_key[SHA256_DIGEST_SIZE];
+};
+
 /*
  * It turns out the crypto hmac(sha256) is hard for us to consume
  * because it assumes a fixed key and the TPM seems to change the key
@@ -113,6 +201,199 @@ static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
 	sha256_final(&sctx, out);
 }
 
+static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip)
+{
+	struct crypto_kpp *kpp;
+	struct kpp_request *req;
+	struct scatterlist s[2], d[1];
+	struct ecdh p = {0};
+	u8 encoded_key[EC_PT_SZ], *x, *y;
+	unsigned int buf_len;
+
+	/* secret is two sized points */
+	tpm_buf_append_u16(buf, (EC_PT_SZ + 2)*2);
+	/*
+	 * we cheat here and append uninitialized data to form
+	 * the points.  All we care about is getting the two
+	 * co-ordinate pointers, which will be used to overwrite
+	 * the uninitialized data
+	 */
+	tpm_buf_append_u16(buf, EC_PT_SZ);
+	x = &buf->data[tpm_buf_length(buf)];
+	tpm_buf_append(buf, encoded_key, EC_PT_SZ);
+	tpm_buf_append_u16(buf, EC_PT_SZ);
+	y = &buf->data[tpm_buf_length(buf)];
+	tpm_buf_append(buf, encoded_key, EC_PT_SZ);
+	sg_init_table(s, 2);
+	sg_set_buf(&s[0], x, EC_PT_SZ);
+	sg_set_buf(&s[1], y, EC_PT_SZ);
+
+	kpp = crypto_alloc_kpp("ecdh-nist-p256", CRYPTO_ALG_INTERNAL, 0);
+	if (IS_ERR(kpp)) {
+		dev_err(&chip->dev, "crypto ecdh allocation failed\n");
+		return;
+	}
+
+	buf_len = crypto_ecdh_key_len(&p);
+	if (sizeof(encoded_key) < buf_len) {
+		dev_err(&chip->dev, "salt buffer too small needs %d\n",
+			buf_len);
+		goto out;
+	}
+	crypto_ecdh_encode_key(encoded_key, buf_len, &p);
+	/* this generates a random private key */
+	crypto_kpp_set_secret(kpp, encoded_key, buf_len);
+
+	/* salt is now the public point of this private key */
+	req = kpp_request_alloc(kpp, GFP_KERNEL);
+	if (!req)
+		goto out;
+	kpp_request_set_input(req, NULL, 0);
+	kpp_request_set_output(req, s, EC_PT_SZ*2);
+	crypto_kpp_generate_public_key(req);
+	/*
+	 * we're not done: now we have to compute the shared secret
+	 * which is our private key multiplied by the tpm_key public
+	 * point, we actually only take the x point and discard the y
+	 * point and feed it through KDFe to get the final secret salt
+	 */
+	sg_set_buf(&s[0], chip->null_ec_key_x, EC_PT_SZ);
+	sg_set_buf(&s[1], chip->null_ec_key_y, EC_PT_SZ);
+	kpp_request_set_input(req, s, EC_PT_SZ*2);
+	sg_init_one(d, chip->auth->salt, EC_PT_SZ);
+	kpp_request_set_output(req, d, EC_PT_SZ);
+	crypto_kpp_compute_shared_secret(req);
+	kpp_request_free(req);
+
+	/*
+	 * pass the shared secret through KDFe for salt. Note salt
+	 * area is used both for input shared secret and output salt.
+	 * This works because KDFe fully consumes the secret before it
+	 * writes the salt
+	 */
+	tpm2_KDFe(chip->auth->salt, "SECRET", x, chip->null_ec_key_x,
+		  chip->auth->salt);
+
+ out:
+	crypto_free_kpp(kpp);
+}
+/**
+ * tpm2_end_auth_session() - kill the allocated auth session
+ * @chip: the TPM chip structure
+ *
+ * ends the session started by tpm2_start_auth_session and frees all
+ * the resources.  Under normal conditions,
+ * tpm_buf_check_hmac_response() will correctly end the session if
+ * required, so this function is only for use in error legs that will
+ * bypass the normal invocation of tpm_buf_check_hmac_response().
+ */
+void tpm2_end_auth_session(struct tpm_chip *chip)
+{
+	tpm2_flush_context(chip, chip->auth->handle);
+	memzero_explicit(chip->auth, sizeof(*chip->auth));
+}
+EXPORT_SYMBOL(tpm2_end_auth_session);
+
+static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,
+					 struct tpm_buf *buf)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+	u32 tot_len = be32_to_cpu(head->length);
+	off_t offset = TPM_HEADER_SIZE;
+	u32 val;
+
+	/* we're starting after the header so adjust the length */
+	tot_len -= TPM_HEADER_SIZE;
+
+	/* should have handle plus nonce */
+	if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
+		return -EINVAL;
+
+	auth->handle = tpm_buf_read_u32(buf, &offset);
+	val = tpm_buf_read_u16(buf, &offset);
+	if (val != sizeof(auth->tpm_nonce))
+		return -EINVAL;
+	memcpy(auth->tpm_nonce, &buf->data[offset], sizeof(auth->tpm_nonce));
+	/* now compute the session key from the nonces */
+	tpm2_KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
+		  auth->our_nonce, sizeof(auth->session_key),
+		  auth->session_key);
+
+	return 0;
+}
+
+/**
+ * tpm2_start_auth_session() - create a HMAC authentication session with the TPM
+ * @chip: the TPM chip structure to create the session with
+ *
+ * This function loads the NULL seed from its saved context and starts
+ * an authentication session on the null seed, fills in the
+ * @chip->auth structure to contain all the session details necessary
+ * for performing the HMAC, encrypt and decrypt operations and
+ * returns.  The NULL seed is flushed before this function returns.
+ *
+ * Return: zero on success or actual error encountered.
+ */
+int tpm2_start_auth_session(struct tpm_chip *chip)
+{
+	struct tpm_buf buf;
+	struct tpm2_auth *auth = chip->auth;
+	int rc;
+	/* null seed context has no offset, but we must provide one */
+	unsigned int offset = 0;
+	u32 nullkey;
+
+	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
+			       &nullkey);
+	if (rc)
+		goto out;
+
+	auth->session = TPM_HEADER_SIZE;
+
+	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
+	if (rc)
+		goto out;
+
+	/* salt key handle */
+	tpm_buf_append_u32(&buf, nullkey);
+	/* bind key handle */
+	tpm_buf_append_u32(&buf, TPM2_RH_NULL);
+	/* nonce caller */
+	get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce));
+	tpm_buf_append_u16(&buf, sizeof(auth->our_nonce));
+	tpm_buf_append(&buf, auth->our_nonce, sizeof(auth->our_nonce));
+
+	/* append encrypted salt and squirrel away unencrypted in auth */
+	tpm_buf_append_salt(&buf, chip);
+	/* session type (HMAC, audit or policy) */
+	tpm_buf_append_u8(&buf, TPM2_SE_HMAC);
+
+	/* symmetric encryption parameters */
+	/* symmetric algorithm */
+	tpm_buf_append_u16(&buf, TPM_ALG_AES);
+	/* bits for symmetric algorithm */
+	tpm_buf_append_u16(&buf, AES_KEY_BITS);
+	/* symmetric algorithm mode (must be CFB) */
+	tpm_buf_append_u16(&buf, TPM_ALG_CFB);
+	/* hash algorithm for session */
+	tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
+
+	rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
+	tpm2_flush_context(chip, nullkey);
+
+	if (rc == TPM2_RC_SUCCESS)
+		rc = tpm2_parse_start_auth_session(auth, &buf);
+
+	tpm_buf_destroy(&buf);
+
+	if (rc)
+		goto out;
+
+ out:
+	return rc;
+}
+EXPORT_SYMBOL(tpm2_start_auth_session);
+
 /**
  * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
  *
@@ -417,5 +698,9 @@ int tpm2_sessions_init(struct tpm_chip *chip)
 	if (rc)
 		dev_err(&chip->dev, "TPM: security failed (NULL seed derivation): %d\n", rc);
 
+	chip->auth = kmalloc(sizeof(*chip->auth), GFP_KERNEL);
+	if (!chip->auth)
+		return -ENOMEM;
+
 	return rc;
 }
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index bc8c9a350e23..81b5a70ff80d 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -31,6 +31,14 @@
 struct tpm_chip;
 struct trusted_key_payload;
 struct trusted_key_options;
+/* opaque structure, holds auth session parameters like the session key */
+struct tpm2_auth;
+
+enum tpm2_session_types {
+	TPM2_SE_HMAC	= 0x00,
+	TPM2_SE_POLICY	= 0x01,
+	TPM2_SE_TRIAL	= 0x02,
+};
 
 /* if you add a new hash to this, increment TPM_MAX_HASHES below */
 enum tpm_algorithms {
@@ -203,6 +211,7 @@ struct tpm_chip {
 	u8 null_key_name[TPM2_NAME_SIZE];
 	u8 null_ec_key_x[EC_PT_SZ];
 	u8 null_ec_key_y[EC_PT_SZ];
+	struct tpm2_auth *auth;
 #endif
 };
 
@@ -266,6 +275,7 @@ enum tpm2_command_codes {
 	TPM2_CC_CONTEXT_LOAD	        = 0x0161,
 	TPM2_CC_CONTEXT_SAVE	        = 0x0162,
 	TPM2_CC_FLUSH_CONTEXT	        = 0x0165,
+	TPM2_CC_START_AUTH_SESS		= 0x0176,
 	TPM2_CC_VERIFY_SIGNATURE        = 0x0177,
 	TPM2_CC_GET_CAPABILITY	        = 0x017A,
 	TPM2_CC_GET_RANDOM	        = 0x017B,
@@ -349,16 +359,21 @@ struct tpm_buf {
 	u32 flags;
 	u32 length;
 	u8 *data;
+	u8 handles;
 };
 
 enum tpm2_object_attributes {
 	TPM2_OA_FIXED_TPM		= BIT(1),
+	TPM2_OA_ST_CLEAR		= BIT(2),
 	TPM2_OA_FIXED_PARENT		= BIT(4),
 	TPM2_OA_SENSITIVE_DATA_ORIGIN	= BIT(5),
 	TPM2_OA_USER_WITH_AUTH		= BIT(6),
+	TPM2_OA_ADMIN_WITH_POLICY	= BIT(7),
 	TPM2_OA_NO_DA			= BIT(10),
+	TPM2_OA_ENCRYPTED_DUPLICATION	= BIT(11),
 	TPM2_OA_RESTRICTED		= BIT(16),
 	TPM2_OA_DECRYPT			= BIT(17),
+	TPM2_OA_SIGN			= BIT(18),
 };
 
 /*
@@ -378,6 +393,11 @@ enum tpm2_object_attributes {
 
 enum tpm2_session_attributes {
 	TPM2_SA_CONTINUE_SESSION	= BIT(0),
+	TPM2_SA_AUDIT_EXCLUSIVE		= BIT(1),
+	TPM2_SA_AUDIT_RESET		= BIT(3),
+	TPM2_SA_DECRYPT			= BIT(5),
+	TPM2_SA_ENCRYPT			= BIT(6),
+	TPM2_SA_AUDIT			= BIT(7),
 };
 
 struct tpm2_hash {
@@ -469,4 +489,18 @@ static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
 {
 }
 #endif
+#ifdef CONFIG_TCG_TPM2_HMAC
+
+int tpm2_start_auth_session(struct tpm_chip *chip);
+void tpm2_end_auth_session(struct tpm_chip *chip);
+#else
+static inline int tpm2_start_auth_session(struct tpm_chip *chip)
+{
+	return 0;
+}
+static inline void tpm2_end_auth_session(struct tpm_chip *chip)
+{
+}
+#endif	/* CONFIG_TCG_TPM2_HMAC */
+
 #endif
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 15/22] tpm: Add HMAC session name/handle append
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (13 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 14/22] tpm: Add HMAC session start and end functions James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 22:38   ` Jarkko Sakkinen
  2024-04-29 20:28 ` [PATCH v8 16/22] tpm: Add the rest of the session HMAC API James Bottomley
                   ` (7 subsequent siblings)
  22 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

Add tpm2_append_name() for appending to the handle area of the TPM
command.  When TPM_BUS_SECURITY is enabled and HMAC sessions are in
use this adds the standard u32 handle to the buffer but additionally
records the name of the object which must be used as part of the HMAC
computation.  The name of certain object types (volatile and permanent
handles and NV indexes) is a hash of the public area of the object.
Since this hash is not known ahead of time, it must be requested from
the TPM using TPM2_ReadPublic() (which cannot be HMAC protected, but
if an interposer lies about it, the HMAC check will fail and the
problem will be detected).

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts

---

v6: split into new patch, update config variable
v7: add tpm2_ prefix
v8: minor updates
---
 drivers/char/tpm/tpm2-sessions.c | 129 +++++++++++++++++++++++++++++++
 include/linux/tpm.h              |  26 +++++++
 2 files changed, 155 insertions(+)

diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 71b3c0e75760..99eb048f18c8 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -49,6 +49,11 @@
  *	Under normal operation this function is done by
  *	tpm_buf_check_hmac_response(), so this is only to be used on
  *	error legs where the latter is not executed.
+ * tpm_buf_append_name() to add a handle to the buffer.  This must be
+ *	used in place of the usual tpm_buf_append_u32() for adding
+ *	handles because handles have to be processed specially when
+ *	calculating the HMAC.  In particular, for NV, volatile and
+ *	permanent objects you now need to provide the name.
  */
 
 #include "tpm.h"
@@ -60,6 +65,9 @@
 #include <crypto/hash.h>
 #include <crypto/hmac.h>
 
+/* maximum number of names the TPM must remember for authorization */
+#define AUTH_MAX_NAMES	3
+
 /*
  * This is the structure that carries all the auth information (like
  * session handle, nonces, session key and auth) from use to use it is
@@ -96,8 +104,31 @@ struct tpm2_auth {
 		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
 	};
 	u8 session_key[SHA256_DIGEST_SIZE];
+
+	/*
+	 * memory for three authorization handles.  We know them by
+	 * handle, but they are part of the session by name, which
+	 * we must compute and remember
+	 */
+	u32 name_h[AUTH_MAX_NAMES];
+	u8 name[AUTH_MAX_NAMES][2 + SHA512_DIGEST_SIZE];
 };
 
+/*
+ * Name Size based on TPM algorithm (assumes no hash bigger than 255)
+ */
+static u8 name_size(const u8 *name)
+{
+	static u8 size_map[] = {
+		[TPM_ALG_SHA1] = SHA1_DIGEST_SIZE,
+		[TPM_ALG_SHA256] = SHA256_DIGEST_SIZE,
+		[TPM_ALG_SHA384] = SHA384_DIGEST_SIZE,
+		[TPM_ALG_SHA512] = SHA512_DIGEST_SIZE,
+	};
+	u16 alg = get_unaligned_be16(name);
+	return size_map[alg] + 2;
+}
+
 /*
  * It turns out the crypto hmac(sha256) is hard for us to consume
  * because it assumes a fixed key and the TPM seems to change the key
@@ -277,6 +308,104 @@ static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip)
  out:
 	crypto_free_kpp(kpp);
 }
+
+static int tpm2_parse_read_public(char *name, struct tpm_buf *buf)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+	off_t offset = TPM_HEADER_SIZE;
+	u32 tot_len = be32_to_cpu(head->length);
+	u32 val;
+
+	/* we're starting after the header so adjust the length */
+	tot_len -= TPM_HEADER_SIZE;
+
+	/* skip public */
+	val = tpm_buf_read_u16(buf, &offset);
+	if (val > tot_len)
+		return -EINVAL;
+	offset += val;
+	/* name */
+	val = tpm_buf_read_u16(buf, &offset);
+	if (val != name_size(&buf->data[offset]))
+		return -EINVAL;
+	memcpy(name, &buf->data[offset], val);
+	/* forget the rest */
+	return 0;
+}
+
+static int tpm2_read_public(struct tpm_chip *chip, u32 handle, char *name)
+{
+	struct tpm_buf buf;
+	int rc;
+
+	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
+	if (rc)
+		return rc;
+
+	tpm_buf_append_u32(&buf, handle);
+	rc = tpm_transmit_cmd(chip, &buf, 0, "read public");
+	if (rc == TPM2_RC_SUCCESS)
+		rc = tpm2_parse_read_public(name, &buf);
+
+	tpm_buf_destroy(&buf);
+
+	return rc;
+}
+
+/**
+ * tpm_buf_append_name() - add a handle area to the buffer
+ * @chip: the TPM chip structure
+ * @buf: The buffer to be appended
+ * @handle: The handle to be appended
+ * @name: The name of the handle (may be NULL)
+ *
+ * In order to compute session HMACs, we need to know the names of the
+ * objects pointed to by the handles.  For most objects, this is simply
+ * the actual 4 byte handle or an empty buf (in these cases @name
+ * should be NULL) but for volatile objects, permanent objects and NV
+ * areas, the name is defined as the hash (according to the name
+ * algorithm which should be set to sha256) of the public area to
+ * which the two byte algorithm id has been appended.  For these
+ * objects, the @name pointer should point to this.  If a name is
+ * required but @name is NULL, then TPM2_ReadPublic() will be called
+ * on the handle to obtain the name.
+ *
+ * As with most tpm_buf operations, success is assumed because failure
+ * will be caused by an incorrect programming model and indicated by a
+ * kernel message.
+ */
+void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
+			 u32 handle, u8 *name)
+{
+	enum tpm2_mso_type mso = tpm2_handle_mso(handle);
+	struct tpm2_auth *auth = chip->auth;
+	int slot;
+
+	slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE)/4;
+	if (slot >= AUTH_MAX_NAMES) {
+		dev_err(&chip->dev, "TPM: too many handles\n");
+		return;
+	}
+	WARN(auth->session != tpm_buf_length(buf),
+	     "name added in wrong place\n");
+	tpm_buf_append_u32(buf, handle);
+	auth->session += 4;
+
+	if (mso == TPM2_MSO_PERSISTENT ||
+	    mso == TPM2_MSO_VOLATILE ||
+	    mso == TPM2_MSO_NVRAM) {
+		if (!name)
+			tpm2_read_public(chip, handle, auth->name[slot]);
+	} else {
+		if (name)
+			dev_err(&chip->dev, "TPM: Handle does not require name but one is specified\n");
+	}
+
+	auth->name_h[slot] = handle;
+	if (name)
+		memcpy(auth->name[slot], name, name_size(name));
+}
+EXPORT_SYMBOL(tpm_buf_append_name);
 /**
  * tpm2_end_auth_session() - kill the allocated auth session
  * @chip: the TPM chip structure
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 81b5a70ff80d..31c2065fcd35 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -275,6 +275,7 @@ enum tpm2_command_codes {
 	TPM2_CC_CONTEXT_LOAD	        = 0x0161,
 	TPM2_CC_CONTEXT_SAVE	        = 0x0162,
 	TPM2_CC_FLUSH_CONTEXT	        = 0x0165,
+	TPM2_CC_READ_PUBLIC		= 0x0173,
 	TPM2_CC_START_AUTH_SESS		= 0x0176,
 	TPM2_CC_VERIFY_SIGNATURE        = 0x0177,
 	TPM2_CC_GET_CAPABILITY	        = 0x017A,
@@ -292,6 +293,21 @@ enum tpm2_permanent_handles {
 	TPM2_RS_PW		= 0x40000009,
 };
 
+/* Most Significant Octet for key types  */
+enum tpm2_mso_type {
+	TPM2_MSO_NVRAM		= 0x01,
+	TPM2_MSO_SESSION	= 0x02,
+	TPM2_MSO_POLICY		= 0x03,
+	TPM2_MSO_PERMANENT	= 0x40,
+	TPM2_MSO_VOLATILE	= 0x80,
+	TPM2_MSO_PERSISTENT	= 0x81,
+};
+
+static inline enum tpm2_mso_type tpm2_handle_mso(u32 handle)
+{
+	return handle >> 24;
+}
+
 enum tpm2_capabilities {
 	TPM2_CAP_HANDLES	= 1,
 	TPM2_CAP_COMMANDS	= 2,
@@ -492,6 +508,8 @@ static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
 #ifdef CONFIG_TCG_TPM2_HMAC
 
 int tpm2_start_auth_session(struct tpm_chip *chip);
+void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
+			 u32 handle, u8 *name);
 void tpm2_end_auth_session(struct tpm_chip *chip);
 #else
 static inline int tpm2_start_auth_session(struct tpm_chip *chip)
@@ -501,6 +519,14 @@ static inline int tpm2_start_auth_session(struct tpm_chip *chip)
 static inline void tpm2_end_auth_session(struct tpm_chip *chip)
 {
 }
+static inline void tpm_buf_append_name(struct tpm_chip *chip,
+				       struct tpm_buf *buf,
+				       u32 handle, u8 *name)
+{
+	tpm_buf_append_u32(buf, handle);
+	/* count the number of handles in the upper bits of flags */
+	buf->handles++;
+}
 #endif	/* CONFIG_TCG_TPM2_HMAC */
 
 #endif
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 16/22] tpm: Add the rest of the session HMAC API
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (14 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 15/22] tpm: Add HMAC session name/handle append James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 22:39   ` Jarkko Sakkinen
  2024-04-29 20:28 ` [PATCH v8 17/22] tpm: add hmac checks to tpm2_pcr_extend() James Bottomley
                   ` (6 subsequent siblings)
  22 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

The final pieces of the HMAC API are for manipulating the session area
of the command.  To add an authentication HMAC session
tpm_buf_append_hmac_session() is called where tpm2_append_auth() would
go. If a non empty password is passed in, this is correctly added to
the HMAC to prove knowledge of it without revealing it.  Note that if
the session is only used to encrypt or decrypt parameters (no
authentication) then tpm_buf_append_hmac_session_opt() must be used
instead.  This functions identically to tpm_buf_append_hmac_session()
when TPM_BUS_SECURITY is enabled, but differently when it isn't,
because effectively nothing is appended to the session area.

Next the parameters should be filled in for the command and finally
tpm_buf_fill_hmac_session() is called immediately prior to transmitting
the command which computes the correct HMAC and places it in the
command at the session location in the tpm buffer

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 are 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.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts

---

v6: split into new patch, update config variable
v7: add memzero_explicit
v8: minor updates
---
 drivers/char/tpm/tpm2-sessions.c | 400 +++++++++++++++++++++++++++++++
 include/linux/tpm.h              |  69 ++++++
 2 files changed, 469 insertions(+)

diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 99eb048f18c8..3c97d3d5e00e 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -54,6 +54,18 @@
  *	handles because handles have to be processed specially when
  *	calculating the HMAC.  In particular, for NV, volatile and
  *	permanent objects you now need to provide the name.
+ * tpm_buf_append_hmac_session() which appends the hmac session to the
+ *	buf in the same way tpm_buf_append_auth does().
+ * tpm_buf_fill_hmac_session() This calculates the correct hash and
+ *	places it in the buffer.  It must be called after the complete
+ *	command buffer is finalized so it can fill in the correct HMAC
+ *	based on the parameters.
+ * tpm_buf_check_hmac_response() which checks the session response in
+ *	the buffer and calculates what it should be.  If there's a
+ *	mismatch it will log a warning and return an error.  If
+ *	tpm_buf_append_hmac_session() did not specify
+ *	TPM_SA_CONTINUE_SESSION then the session will be closed (if it
+ *	hasn't been consumed) and the auth structure freed.
  */
 
 #include "tpm.h"
@@ -103,7 +115,23 @@ struct tpm2_auth {
 		/* scratch for key + IV */
 		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
 	};
+	/*
+	 * the session key and passphrase are the same size as the
+	 * name digest (sha256 again).  The session key is constant
+	 * for the use of the session and the passphrase can change
+	 * with every invocation.
+	 *
+	 * Note: these fields must be adjacent and in this order
+	 * because several HMAC/KDF schemes use the combination of the
+	 * session_key and passphrase.
+	 */
 	u8 session_key[SHA256_DIGEST_SIZE];
+	u8 passphrase[SHA256_DIGEST_SIZE];
+	int passphrase_len;
+	struct crypto_aes_ctx aes_ctx;
+	/* saved session attributes: */
+	u8 attrs;
+	__be32 ordinal;
 
 	/*
 	 * memory for three authorization handles.  We know them by
@@ -309,6 +337,230 @@ static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip)
 	crypto_free_kpp(kpp);
 }
 
+/**
+ * tpm_buf_append_hmac_session() - Append a TPM session element
+ * @chip: the TPM chip structure
+ * @buf: The buffer to be appended
+ * @attributes: The session attributes
+ * @passphrase: The session authority (NULL if none)
+ * @passphrase_len: The length of the session authority (0 if none)
+ *
+ * This fills in a session structure in the TPM command buffer, except
+ * for the HMAC which cannot be computed until the command buffer is
+ * complete.  The type of session is controlled by the @attributes,
+ * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
+ * session won't terminate after tpm_buf_check_hmac_response(),
+ * TPM2_SA_DECRYPT which means this buffers first parameter should be
+ * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
+ * response buffer's first parameter needs to be decrypted (confusing,
+ * but the defines are written from the point of view of the TPM).
+ *
+ * Any session appended by this command must be finalized by calling
+ * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
+ * and the TPM will reject the command.
+ *
+ * As with most tpm_buf operations, success is assumed because failure
+ * will be caused by an incorrect programming model and indicated by a
+ * kernel message.
+ */
+void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
+				 u8 attributes, u8 *passphrase,
+				 int passphrase_len)
+{
+	u8 nonce[SHA256_DIGEST_SIZE];
+	u32 len;
+	struct tpm2_auth *auth = chip->auth;
+
+	/*
+	 * The Architecture Guide requires us to strip trailing zeros
+	 * before computing the HMAC
+	 */
+	while (passphrase && passphrase_len > 0
+	       && passphrase[passphrase_len - 1] == '\0')
+		passphrase_len--;
+
+	auth->attrs = attributes;
+	auth->passphrase_len = passphrase_len;
+	if (passphrase_len)
+		memcpy(auth->passphrase, passphrase, passphrase_len);
+
+	if (auth->session != tpm_buf_length(buf)) {
+		/* we're not the first session */
+		len = get_unaligned_be32(&buf->data[auth->session]);
+		if (4 + len + auth->session != tpm_buf_length(buf)) {
+			WARN(1, "session length mismatch, cannot append");
+			return;
+		}
+
+		/* add our new session */
+		len += 9 + 2 * SHA256_DIGEST_SIZE;
+		put_unaligned_be32(len, &buf->data[auth->session]);
+	} else {
+		tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
+	}
+
+	/* random number for our nonce */
+	get_random_bytes(nonce, sizeof(nonce));
+	memcpy(auth->our_nonce, nonce, sizeof(nonce));
+	tpm_buf_append_u32(buf, auth->handle);
+	/* our new nonce */
+	tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
+	tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
+	tpm_buf_append_u8(buf, auth->attrs);
+	/* and put a placeholder for the hmac */
+	tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
+	tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
+}
+EXPORT_SYMBOL(tpm_buf_append_hmac_session);
+
+/**
+ * tpm_buf_fill_hmac_session() - finalize the session HMAC
+ * @chip: the TPM chip structure
+ * @buf: The buffer to be appended
+ *
+ * This command must not be called until all of the parameters have
+ * been appended to @buf otherwise the computed HMAC will be
+ * incorrect.
+ *
+ * This function computes and fills in the session HMAC using the
+ * session key and, if TPM2_SA_DECRYPT was specified, computes the
+ * encryption key and encrypts the first parameter of the command
+ * buffer with it.
+ *
+ * As with most tpm_buf operations, success is assumed because failure
+ * will be caused by an incorrect programming model and indicated by a
+ * kernel message.
+ */
+void tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)
+{
+	u32 cc, handles, val;
+	struct tpm2_auth *auth = chip->auth;
+	int i;
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+	off_t offset_s = TPM_HEADER_SIZE, offset_p;
+	u8 *hmac = NULL;
+	u32 attrs;
+	u8 cphash[SHA256_DIGEST_SIZE];
+	struct sha256_state sctx;
+
+	/* save the command code in BE format */
+	auth->ordinal = head->ordinal;
+
+	cc = be32_to_cpu(head->ordinal);
+
+	i = tpm2_find_cc(chip, cc);
+	if (i < 0) {
+		dev_err(&chip->dev, "Command 0x%x not found in TPM\n", cc);
+		return;
+	}
+	attrs = chip->cc_attrs_tbl[i];
+
+	handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0);
+
+	/*
+	 * just check the names, it's easy to make mistakes.  This
+	 * would happen if someone added a handle via
+	 * tpm_buf_append_u32() instead of tpm_buf_append_name()
+	 */
+	for (i = 0; i < handles; i++) {
+		u32 handle = tpm_buf_read_u32(buf, &offset_s);
+
+		if (auth->name_h[i] != handle) {
+			dev_err(&chip->dev, "TPM: handle %d wrong for name\n",
+				  i);
+			return;
+		}
+	}
+	/* point offset_s to the start of the sessions */
+	val = tpm_buf_read_u32(buf, &offset_s);
+	/* point offset_p to the start of the parameters */
+	offset_p = offset_s + val;
+	for (i = 1; offset_s < offset_p; i++) {
+		u32 handle = tpm_buf_read_u32(buf, &offset_s);
+		u16 len;
+		u8 a;
+
+		/* nonce (already in auth) */
+		len = tpm_buf_read_u16(buf, &offset_s);
+		offset_s += len;
+
+		a = tpm_buf_read_u8(buf, &offset_s);
+
+		len = tpm_buf_read_u16(buf, &offset_s);
+		if (handle == auth->handle && auth->attrs == a) {
+			hmac = &buf->data[offset_s];
+			/*
+			 * save our session number so we know which
+			 * session in the response belongs to us
+			 */
+			auth->session = i;
+		}
+
+		offset_s += len;
+	}
+	if (offset_s != offset_p) {
+		dev_err(&chip->dev, "TPM session length is incorrect\n");
+		return;
+	}
+	if (!hmac) {
+		dev_err(&chip->dev, "TPM could not find HMAC session\n");
+		return;
+	}
+
+	/* encrypt before HMAC */
+	if (auth->attrs & TPM2_SA_DECRYPT) {
+		u16 len;
+
+		/* need key and IV */
+		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
+			  + auth->passphrase_len, "CFB", auth->our_nonce,
+			  auth->tpm_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
+			  auth->scratch);
+
+		len = tpm_buf_read_u16(buf, &offset_p);
+		aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);
+		aescfb_encrypt(&auth->aes_ctx, &buf->data[offset_p],
+			       &buf->data[offset_p], len,
+			       auth->scratch + AES_KEY_BYTES);
+		/* reset p to beginning of parameters for HMAC */
+		offset_p -= 2;
+	}
+
+	sha256_init(&sctx);
+	/* ordinal is already BE */
+	sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));
+	/* add the handle names */
+	for (i = 0; i < handles; i++) {
+		enum tpm2_mso_type mso = tpm2_handle_mso(auth->name_h[i]);
+
+		if (mso == TPM2_MSO_PERSISTENT ||
+		    mso == TPM2_MSO_VOLATILE ||
+		    mso == TPM2_MSO_NVRAM) {
+			sha256_update(&sctx, auth->name[i],
+				      name_size(auth->name[i]));
+		} else {
+			__be32 h = cpu_to_be32(auth->name_h[i]);
+
+			sha256_update(&sctx, (u8 *)&h, 4);
+		}
+	}
+	if (offset_s != tpm_buf_length(buf))
+		sha256_update(&sctx, &buf->data[offset_s],
+			      tpm_buf_length(buf) - offset_s);
+	sha256_final(&sctx, cphash);
+
+	/* now calculate the hmac */
+	tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
+		       + auth->passphrase_len);
+	sha256_update(&sctx, cphash, sizeof(cphash));
+	sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));
+	sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
+	sha256_update(&sctx, &auth->attrs, 1);
+	tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
+			+ auth->passphrase_len, hmac);
+}
+EXPORT_SYMBOL(tpm_buf_fill_hmac_session);
+
 static int tpm2_parse_read_public(char *name, struct tpm_buf *buf)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
@@ -406,6 +658,154 @@ void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
 		memcpy(auth->name[slot], name, name_size(name));
 }
 EXPORT_SYMBOL(tpm_buf_append_name);
+
+/**
+ * tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness
+ * @chip: the TPM chip structure
+ * @buf: the original command buffer (which now contains the response)
+ * @rc: the return code from tpm_transmit_cmd
+ *
+ * If @rc is non zero, @buf may not contain an actual return, so @rc
+ * is passed through as the return and the session cleaned up and
+ * de-allocated if required (this is required if
+ * TPM2_SA_CONTINUE_SESSION was not specified as a session flag).
+ *
+ * If @rc is zero, the response HMAC is computed against the returned
+ * @buf and matched to the TPM one in the session area.  If there is a
+ * mismatch, an error is logged and -EINVAL returned.
+ *
+ * The reason for this is that the command issue and HMAC check
+ * sequence should look like:
+ *
+ *	rc = tpm_transmit_cmd(...);
+ *	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
+ *	if (rc)
+ *		...
+ *
+ * Which is easily layered into the current contrl flow.
+ *
+ * Returns: 0 on success or an error.
+ */
+int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,
+				int rc)
+{
+	struct tpm_header *head = (struct tpm_header *)buf->data;
+	struct tpm2_auth *auth = chip->auth;
+	off_t offset_s, offset_p;
+	u8 rphash[SHA256_DIGEST_SIZE];
+	u32 attrs;
+	struct sha256_state sctx;
+	u16 tag = be16_to_cpu(head->tag);
+	u32 cc = be32_to_cpu(auth->ordinal);
+	int parm_len, len, i, handles;
+
+	if (auth->session >= TPM_HEADER_SIZE) {
+		WARN(1, "tpm session not filled correctly\n");
+		goto out;
+	}
+
+	if (rc != 0)
+		/* pass non success rc through and close the session */
+		goto out;
+
+	rc = -EINVAL;
+	if (tag != TPM2_ST_SESSIONS) {
+		dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");
+		goto out;
+	}
+
+	i = tpm2_find_cc(chip, cc);
+	if (i < 0)
+		goto out;
+	attrs = chip->cc_attrs_tbl[i];
+	handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;
+
+	/* point to area beyond handles */
+	offset_s = TPM_HEADER_SIZE + handles * 4;
+	parm_len = tpm_buf_read_u32(buf, &offset_s);
+	offset_p = offset_s;
+	offset_s += parm_len;
+	/* skip over any sessions before ours */
+	for (i = 0; i < auth->session - 1; i++) {
+		len = tpm_buf_read_u16(buf, &offset_s);
+		offset_s += len + 1;
+		len = tpm_buf_read_u16(buf, &offset_s);
+		offset_s += len;
+	}
+	/* TPM nonce */
+	len = tpm_buf_read_u16(buf, &offset_s);
+	if (offset_s + len > tpm_buf_length(buf))
+		goto out;
+	if (len != SHA256_DIGEST_SIZE)
+		goto out;
+	memcpy(auth->tpm_nonce, &buf->data[offset_s], len);
+	offset_s += len;
+	attrs = tpm_buf_read_u8(buf, &offset_s);
+	len = tpm_buf_read_u16(buf, &offset_s);
+	if (offset_s + len != tpm_buf_length(buf))
+		goto out;
+	if (len != SHA256_DIGEST_SIZE)
+		goto out;
+	/*
+	 * offset_s points to the HMAC. now calculate comparison, beginning
+	 * with rphash
+	 */
+	sha256_init(&sctx);
+	/* yes, I know this is now zero, but it's what the standard says */
+	sha256_update(&sctx, (u8 *)&head->return_code,
+		      sizeof(head->return_code));
+	/* ordinal is already BE */
+	sha256_update(&sctx, (u8 *)&auth->ordinal, sizeof(auth->ordinal));
+	sha256_update(&sctx, &buf->data[offset_p], parm_len);
+	sha256_final(&sctx, rphash);
+
+	/* now calculate the hmac */
+	tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
+		       + auth->passphrase_len);
+	sha256_update(&sctx, rphash, sizeof(rphash));
+	sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
+	sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));
+	sha256_update(&sctx, &auth->attrs, 1);
+	/* we're done with the rphash, so put our idea of the hmac there */
+	tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
+			+ auth->passphrase_len, rphash);
+	if (memcmp(rphash, &buf->data[offset_s], SHA256_DIGEST_SIZE) == 0) {
+		rc = 0;
+	} else {
+		dev_err(&chip->dev, "TPM: HMAC check failed\n");
+		goto out;
+	}
+
+	/* now do response decryption */
+	if (auth->attrs & TPM2_SA_ENCRYPT) {
+		/* need key and IV */
+		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
+			  + auth->passphrase_len, "CFB", auth->tpm_nonce,
+			  auth->our_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
+			  auth->scratch);
+
+		len = tpm_buf_read_u16(buf, &offset_p);
+		aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);
+		aescfb_decrypt(&auth->aes_ctx, &buf->data[offset_p],
+			       &buf->data[offset_p], len,
+			       auth->scratch + AES_KEY_BYTES);
+	}
+
+ out:
+	if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {
+		if (rc)
+			/* manually close the session if it wasn't consumed */
+			tpm2_flush_context(chip, auth->handle);
+		memzero_explicit(auth, sizeof(*auth));
+	} else {
+		/* reset for next use  */
+		auth->session = TPM_HEADER_SIZE;
+	}
+
+	return rc;
+}
+EXPORT_SYMBOL(tpm_buf_check_hmac_response);
+
 /**
  * tpm2_end_auth_session() - kill the allocated auth session
  * @chip: the TPM chip structure
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 31c2065fcd35..dd4d6a6158c4 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -510,8 +510,25 @@ static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
 int tpm2_start_auth_session(struct tpm_chip *chip);
 void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
 			 u32 handle, u8 *name);
+void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
+				 u8 attributes, u8 *passphrase,
+				 int passphraselen);
+static inline void tpm_buf_append_hmac_session_opt(struct tpm_chip *chip,
+						   struct tpm_buf *buf,
+						   u8 attributes,
+						   u8 *passphrase,
+						   int passphraselen)
+{
+	tpm_buf_append_hmac_session(chip, buf, attributes, passphrase,
+				    passphraselen);
+}
+void tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf);
+int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,
+				int rc);
 void tpm2_end_auth_session(struct tpm_chip *chip);
 #else
+#include <asm/unaligned.h>
+
 static inline int tpm2_start_auth_session(struct tpm_chip *chip)
 {
 	return 0;
@@ -527,6 +544,58 @@ static inline void tpm_buf_append_name(struct tpm_chip *chip,
 	/* count the number of handles in the upper bits of flags */
 	buf->handles++;
 }
+static inline void tpm_buf_append_hmac_session(struct tpm_chip *chip,
+					       struct tpm_buf *buf,
+					       u8 attributes, u8 *passphrase,
+					       int passphraselen)
+{
+	/* offset tells us where the sessions area begins */
+	int offset = buf->handles * 4 + TPM_HEADER_SIZE;
+	u32 len = 9 + passphraselen;
+
+	if (tpm_buf_length(buf) != offset) {
+		/* not the first session so update the existing length */
+		len += get_unaligned_be32(&buf->data[offset]);
+		put_unaligned_be32(len, &buf->data[offset]);
+	} else {
+		tpm_buf_append_u32(buf, len);
+	}
+	/* auth handle */
+	tpm_buf_append_u32(buf, TPM2_RS_PW);
+	/* nonce */
+	tpm_buf_append_u16(buf, 0);
+	/* attributes */
+	tpm_buf_append_u8(buf, 0);
+	/* passphrase */
+	tpm_buf_append_u16(buf, passphraselen);
+	tpm_buf_append(buf, passphrase, passphraselen);
+}
+static inline void tpm_buf_append_hmac_session_opt(struct tpm_chip *chip,
+						   struct tpm_buf *buf,
+						   u8 attributes,
+						   u8 *passphrase,
+						   int passphraselen)
+{
+	int offset = buf->handles * 4 + TPM_HEADER_SIZE;
+	struct tpm_header *head = (struct tpm_header *) buf->data;
+
+	/*
+	 * if the only sessions are optional, the command tag
+	 * must change to TPM2_ST_NO_SESSIONS
+	 */
+	if (tpm_buf_length(buf) == offset)
+		head->tag = cpu_to_be16(TPM2_ST_NO_SESSIONS);
+}
+static inline void tpm_buf_fill_hmac_session(struct tpm_chip *chip,
+					     struct tpm_buf *buf)
+{
+}
+static inline int tpm_buf_check_hmac_response(struct tpm_chip *chip,
+					      struct tpm_buf *buf,
+					      int rc)
+{
+	return rc;
+}
 #endif	/* CONFIG_TCG_TPM2_HMAC */
 
 #endif
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 17/22] tpm: add hmac checks to tpm2_pcr_extend()
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (15 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 16/22] tpm: Add the rest of the session HMAC API James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 20:28 ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() James Bottomley
                   ` (5 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

tpm2_pcr_extend() is used by 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.  This patch adds HMAC protection so tampering with the
tpm2_pcr_extend() command in flight is detected.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---
v7: add review
---
 drivers/char/tpm/tpm2-cmd.c | 27 ++++++++++-----------------
 1 file changed, 10 insertions(+), 17 deletions(-)

diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index b0e72fb563d9..a53a843294ed 100644
--- a/drivers/char/tpm/tpm2-cmd.c
+++ b/drivers/char/tpm/tpm2-cmd.c
@@ -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,22 @@ 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;
 	int rc;
 	int i;
 
-	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
+	rc = tpm2_start_auth_session(chip);
 	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(chip);
+		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(chip, &buf, pcr_idx, NULL);
+	tpm_buf_append_hmac_session(chip, &buf, 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 +253,9 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 			       chip->allocated_banks[i].digest_size);
 	}
 
+	tpm_buf_fill_hmac_session(chip, &buf);
 	rc = tpm_transmit_cmd(chip, &buf, 0, "attempting extend a PCR value");
+	rc = tpm_buf_check_hmac_response(chip, &buf, rc);
 
 	tpm_buf_destroy(&buf);
 
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (16 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 17/22] tpm: add hmac checks to tpm2_pcr_extend() James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-05-17  0:25   ` Nícolas F. R. A. Prado
  2024-04-29 20:28 ` [PATCH v8 19/22] KEYS: trusted: Add session encryption protection to the seal/unseal path James Bottomley
                   ` (4 subsequent siblings)
  22 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

If some entity is snooping the TPM bus, they can see the random
numbers we're extracting from the TPM and do prediction attacks
against their consumers.  Foil this attack by using response
encryption to prevent the attacker from seeing the random sequence.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---
v7: add review
---
 drivers/char/tpm/tpm2-cmd.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)

diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index a53a843294ed..0cdf892ec2a7 100644
--- a/drivers/char/tpm/tpm2-cmd.c
+++ b/drivers/char/tpm/tpm2-cmd.c
@@ -292,25 +292,35 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
 	if (!num_bytes || max > TPM_MAX_RNG_DATA)
 		return -EINVAL;
 
-	err = tpm_buf_init(&buf, 0, 0);
+	err = tpm2_start_auth_session(chip);
 	if (err)
 		return err;
 
+	err = tpm_buf_init(&buf, 0, 0);
+	if (err) {
+		tpm2_end_auth_session(chip);
+		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(chip, &buf, TPM2_SA_ENCRYPT
+						| TPM2_SA_CONTINUE_SESSION,
+						NULL, 0);
 		tpm_buf_append_u16(&buf, num_bytes);
+		tpm_buf_fill_hmac_session(chip, &buf);
 		err = tpm_transmit_cmd(chip, &buf,
 				       offsetof(struct tpm2_get_random_out,
 						buffer),
 				       "attempting get random");
+		err = tpm_buf_check_hmac_response(chip, &buf, 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 +
@@ -327,9 +337,12 @@ 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(chip);
+
 	return total ? total : -EIO;
 out:
 	tpm_buf_destroy(&buf);
+	tpm2_end_auth_session(chip);
 	return err;
 }
 
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 19/22] KEYS: trusted: Add session encryption protection to the seal/unseal path
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (17 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 20:28 ` [PATCH v8 20/22] tpm: add the null key name as a sysfs export James Bottomley
                   ` (3 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

If some entity is snooping the TPM bus, the can see the data going in
to be sealed and the data coming out as it is unsealed.  Add parameter
and response encryption to these cases to ensure that no secrets are
leaked even if the bus is snooped.

As part of doing this conversion it was discovered that policy
sessions can't work with HMAC protected authority because of missing
pieces (the tpm Nonce).  I've added code to work the same way as
before, which will result in potential authority exposure (while still
adding security for the command and the returned blob), and a fixme to
redo the API to get rid of this security hole.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---
v2: fix unseal with policy and password
v3: fix session memory leak
v7: add review
---
 security/keys/trusted-keys/trusted_tpm2.c | 88 ++++++++++++++++-------
 1 file changed, 61 insertions(+), 27 deletions(-)

diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index 97b1dfca2dba..dfeec06301ce 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -253,26 +253,26 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	if (rc)
 		return rc;
 
+	rc = tpm2_start_auth_session(chip);
+	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(chip);
+		goto out_put;
 	}
 
 	rc = tpm_buf_init_sized(&sized);
 	if (rc) {
 		tpm_buf_destroy(&buf);
-		tpm_put_ops(chip);
-		return rc;
+		tpm2_end_auth_session(chip);
+		goto out_put;
 	}
 
-	tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
-	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(chip, &buf, options->keyhandle, NULL);
+	tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_DECRYPT,
+				    options->keyauth, TPM_DIGEST_SIZE);
 
 	/* sensitive */
 	tpm_buf_append_u16(&sized, options->blobauth_len);
@@ -314,10 +314,13 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 
 	if (buf.flags & TPM_BUF_OVERFLOW) {
 		rc = -E2BIG;
+		tpm2_end_auth_session(chip);
 		goto out;
 	}
 
+	tpm_buf_fill_hmac_session(chip, &buf);
 	rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data");
+	rc = tpm_buf_check_hmac_response(chip, &buf, rc);
 	if (rc)
 		goto out;
 
@@ -348,6 +351,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	else
 		payload->blob_len = blob_len;
 
+out_put:
 	tpm_put_ops(chip);
 	return rc;
 }
@@ -417,25 +421,31 @@ 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);
 	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(chip);
+		return rc;
+	}
+
+	tpm_buf_append_name(chip, &buf, options->keyhandle, NULL);
+	tpm_buf_append_hmac_session(chip, &buf, 0, options->keyauth,
+				    TPM_DIGEST_SIZE);
 
 	tpm_buf_append(&buf, blob, blob_len);
 
 	if (buf.flags & TPM_BUF_OVERFLOW) {
 		rc = -E2BIG;
+		tpm2_end_auth_session(chip);
 		goto out;
 	}
 
+	tpm_buf_fill_hmac_session(chip, &buf);
 	rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob");
+	rc = tpm_buf_check_hmac_response(chip, &buf, rc);
 	if (!rc)
 		*blob_handle = be32_to_cpup(
 			(__be32 *) &buf.data[TPM_HEADER_SIZE]);
@@ -473,20 +483,44 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
 	u8 *data;
 	int rc;
 
-	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
+	rc = tpm2_start_auth_session(chip);
 	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(chip);
+		return rc;
+	}
+
+	tpm_buf_append_name(chip, &buf, blob_handle, NULL);
+
+	if (!options->policyhandle) {
+		tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_ENCRYPT,
+					    options->blobauth,
+					    options->blobauth_len);
+	} 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(chip, &buf, TPM2_SA_ENCRYPT,
+						NULL, 0);
+	}
 
+	tpm_buf_fill_hmac_session(chip, &buf);
 	rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing");
+	rc = tpm_buf_check_hmac_response(chip, &buf, rc);
 	if (rc > 0)
 		rc = -EPERM;
 
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 20/22] tpm: add the null key name as a sysfs export
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (18 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 19/22] KEYS: trusted: Add session encryption protection to the seal/unseal path James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 20:28 ` [PATCH v8 21/22] Documentation: add tpm-security.rst James Bottomley
                   ` (2 subsequent siblings)
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

This is the last component of encrypted tpm2 session handling that
allows us to verify from userspace that the key derived from the NULL
seed genuinely belongs to the TPM and has not been spoofed.

The procedure for doing this involves creating an attestation identity
key (which requires verification of the TPM EK certificate) and then
using that AIK to sign a certification of the Elliptic Curve key over
the NULL seed.  Userspace must create this EC Key using the parameters
prescribed in TCG TPM v2.0 Provisioning Guidance for the SRK ECC; if
this is done correctly the names will match and the TPM can then run a
TPM2_Certify operation on this derived primary key using the newly
created AIK.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---
v6: change config name
v7: add review
---
 drivers/char/tpm/tpm-sysfs.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/drivers/char/tpm/tpm-sysfs.c b/drivers/char/tpm/tpm-sysfs.c
index 54c71473aa29..94231f052ea7 100644
--- a/drivers/char/tpm/tpm-sysfs.c
+++ b/drivers/char/tpm/tpm-sysfs.c
@@ -309,6 +309,21 @@ static ssize_t tpm_version_major_show(struct device *dev,
 }
 static DEVICE_ATTR_RO(tpm_version_major);
 
+#ifdef CONFIG_TCG_TPM2_HMAC
+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->null_key_name, size);
+	size *= 2;
+	buf[size++] = '\n';
+	return size;
+}
+static DEVICE_ATTR_RO(null_name);
+#endif
+
 static struct attribute *tpm1_dev_attrs[] = {
 	&dev_attr_pubek.attr,
 	&dev_attr_pcrs.attr,
@@ -326,6 +341,9 @@ static struct attribute *tpm1_dev_attrs[] = {
 
 static struct attribute *tpm2_dev_attrs[] = {
 	&dev_attr_tpm_version_major.attr,
+#ifdef CONFIG_TCG_TPM2_HMAC
+	&dev_attr_null_name.attr,
+#endif
 	NULL
 };
 
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 21/22] Documentation: add tpm-security.rst
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (19 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 20/22] tpm: add the null key name as a sysfs export James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 20:28 ` [PATCH v8 22/22] tpm: disable the TPM if NULL name changes James Bottomley
  2024-04-29 22:22 ` [PATCH v8 00/22] add integrity and security to TPM2 transactions Jarkko Sakkinen
  22 siblings, 0 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

Document how the new encrypted secure interface for TPM2 works and how
security can be assured after boot by certifying the NULL seed.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

---
v7: add review
---
 Documentation/security/tpm/tpm-security.rst | 216 ++++++++++++++++++++
 1 file changed, 216 insertions(+)
 create mode 100644 Documentation/security/tpm/tpm-security.rst

diff --git a/Documentation/security/tpm/tpm-security.rst b/Documentation/security/tpm/tpm-security.rst
new file mode 100644
index 000000000000..4f633f251033
--- /dev/null
+++ b/Documentation/security/tpm/tpm-security.rst
@@ -0,0 +1,216 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+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/
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* [PATCH v8 22/22] tpm: disable the TPM if NULL name changes
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (20 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 21/22] Documentation: add tpm-security.rst James Bottomley
@ 2024-04-29 20:28 ` James Bottomley
  2024-04-29 22:59   ` Jarkko Sakkinen
  2024-04-29 23:34   ` Jarkko Sakkinen
  2024-04-29 22:22 ` [PATCH v8 00/22] add integrity and security to TPM2 transactions Jarkko Sakkinen
  22 siblings, 2 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-29 20:28 UTC (permalink / raw)
  To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel

Update tpm2_load_context() to return -EINVAL on integrity failures and
use this as a signal when loading the NULL context that something
might be wrong.  If the signal fails, check the name of the NULL
primary against the one stored in the chip data and if there is a
mismatch disable the TPM because it is likely to have suffered a reset
attack.

Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/tpm-chip.c      |  3 ++
 drivers/char/tpm/tpm2-sessions.c | 77 +++++++++++++++++++++++++-------
 drivers/char/tpm/tpm2-space.c    |  3 ++
 include/linux/tpm.h              |  4 +-
 4 files changed, 70 insertions(+), 17 deletions(-)

diff --git a/drivers/char/tpm/tpm-chip.c b/drivers/char/tpm/tpm-chip.c
index d93937326b2e..854546000c92 100644
--- a/drivers/char/tpm/tpm-chip.c
+++ b/drivers/char/tpm/tpm-chip.c
@@ -158,6 +158,9 @@ int tpm_try_get_ops(struct tpm_chip *chip)
 {
 	int rc = -EIO;
 
+	if (chip->flags & TPM_CHIP_FLAG_DISABLE)
+		return rc;
+
 	get_device(&chip->dev);
 
 	down_read(&chip->ops_sem);
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 3c97d3d5e00e..98819c9a0913 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -80,6 +80,9 @@
 /* maximum number of names the TPM must remember for authorization */
 #define AUTH_MAX_NAMES	3
 
+static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
+			       u32 *handle, u8 *name);
+
 /*
  * This is the structure that carries all the auth information (like
  * session handle, nonces, session key and auth) from use to use it is
@@ -851,6 +854,37 @@ static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,
 	return 0;
 }
 
+static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)
+{
+	int rc;
+	unsigned int offset = 0; /* dummy offset for null seed context */
+	u8 name[SHA256_DIGEST_SIZE + 2];
+
+	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
+			       null_key);
+	if (rc != -EINVAL)
+		return rc;
+
+	/* an integrity failure may mean the TPM has been reset */
+	dev_err(&chip->dev, "NULL key integrity failure!\n");
+	/* check the null name against what we know */
+	tpm2_create_primary(chip, TPM2_RH_NULL, NULL, name);
+	if (memcmp(name, chip->null_key_name, sizeof(name)) == 0)
+		/* name unchanged, assume transient integrity failure */
+		return rc;
+	/*
+	 * Fatal TPM failure: the NULL seed has actually changed, so
+	 * the TPM must have been illegally reset.  All in-kernel TPM
+	 * operations will fail because the NULL primary can't be
+	 * loaded to salt the sessions, but disable the TPM anyway so
+	 * userspace programmes can't be compromised by it.
+	 */
+	dev_err(&chip->dev, "NULL name has changed, disabling TPM due to interference\n");
+	chip->flags |= TPM_CHIP_FLAG_DISABLE;
+
+	return rc;
+}
+
 /**
  * tpm2_start_auth_session() - create a HMAC authentication session with the TPM
  * @chip: the TPM chip structure to create the session with
@@ -868,12 +902,9 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
 	struct tpm_buf buf;
 	struct tpm2_auth *auth = chip->auth;
 	int rc;
-	/* null seed context has no offset, but we must provide one */
-	unsigned int offset = 0;
-	u32 nullkey;
+	u32 null_key;
 
-	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
-			       &nullkey);
+	rc = tpm2_load_null(chip, &null_key);
 	if (rc)
 		goto out;
 
@@ -884,7 +915,7 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
 		goto out;
 
 	/* salt key handle */
-	tpm_buf_append_u32(&buf, nullkey);
+	tpm_buf_append_u32(&buf, null_key);
 	/* bind key handle */
 	tpm_buf_append_u32(&buf, TPM2_RH_NULL);
 	/* nonce caller */
@@ -908,7 +939,7 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
 	tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
 
 	rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
-	tpm2_flush_context(chip, nullkey);
+	tpm2_flush_context(chip, null_key);
 
 	if (rc == TPM2_RC_SUCCESS)
 		rc = tpm2_parse_start_auth_session(auth, &buf);
@@ -930,19 +961,25 @@ EXPORT_SYMBOL(tpm2_start_auth_session);
  * @buf:	The response buffer from the chip
  * @handle:	pointer to be filled in with the return handle of the primary
  * @hierarchy:	The hierarchy the primary was created for
+ * @name:	pointer to be filled in with the primary key name
  *
  * @returns: 0 on success or a positive TPM or negative standard error
  */
 static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
-				     u32 *handle, u32 hierarchy)
+				     u32 *handle, u32 hierarchy, u8 *name)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 	off_t offset_r = TPM_HEADER_SIZE, offset_t;
 	u16 len = TPM_HEADER_SIZE;
 	u32 total_len = be32_to_cpu(head->length);
-	u32 val, param_len;
+	u32 val, param_len, keyhandle;
+
+	keyhandle = tpm_buf_read_u32(buf, &offset_r);
+	if (handle)
+		*handle = keyhandle;
+	else
+		tpm2_flush_context(chip, keyhandle);
 
-	*handle = tpm_buf_read_u32(buf, &offset_r);
 	param_len = tpm_buf_read_u32(buf, &offset_r);
 	/*
 	 * param_len doesn't include the header, but all the other
@@ -955,9 +992,14 @@ static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
 		return -EINVAL;
 	len = tpm_buf_read_u16(buf, &offset_r);
 	offset_t = offset_r;
-	/* now we have the public area, compute the name of the object */
-	put_unaligned_be16(TPM_ALG_SHA256, chip->null_key_name);
-	sha256(&buf->data[offset_r], len, chip->null_key_name + 2);
+	if (name) {
+		/*
+		 * now we have the public area, compute the name of
+		 * the object
+		 */
+		put_unaligned_be16(TPM_ALG_SHA256, name);
+		sha256(&buf->data[offset_r], len, name + 2);
+	}
 
 	/* validate the public key */
 	val = tpm_buf_read_u16(buf, &offset_t);
@@ -1086,6 +1128,7 @@ static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
  * @chip:      the TPM chip to create under
  * @hierarchy: The hierarchy handle to create under
  * @handle:    The returned volatile handle on success
+ * @name:      The name of the returned key
  *
  * For platforms that might not have a persistent primary, this can be
  * used to create one quickly on the fly (it uses Elliptic Curve not
@@ -1097,7 +1140,7 @@ static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
  * @returns: 0 on success or positive TPM or negative error.
  */
 static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
-			       u32 *handle)
+			       u32 *handle, u8 *name)
 {
 	int rc;
 	struct tpm_buf buf;
@@ -1187,7 +1230,8 @@ static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
 			      "attempting to create NULL primary");
 
 	if (rc == TPM2_RC_SUCCESS)
-		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy);
+		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy,
+					       name);
 
 	tpm_buf_destroy(&buf);
 
@@ -1199,7 +1243,8 @@ static int tpm2_create_null_primary(struct tpm_chip *chip)
 	u32 null_key;
 	int rc;
 
-	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key);
+	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key,
+				 chip->null_key_name);
 
 	if (rc == TPM2_RC_SUCCESS) {
 		unsigned int offset = 0; /* dummy offset for null key context */
diff --git a/drivers/char/tpm/tpm2-space.c b/drivers/char/tpm/tpm2-space.c
index 24479a81c23c..4892d491da8d 100644
--- a/drivers/char/tpm/tpm2-space.c
+++ b/drivers/char/tpm/tpm2-space.c
@@ -105,6 +105,9 @@ int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
 		*handle = 0;
 		tpm_buf_destroy(&tbuf);
 		return -ENOENT;
+	} else if (tpm2_rc_value(rc) == TPM2_RC_INTEGRITY) {
+		tpm_buf_destroy(&tbuf);
+		return -EINVAL;
 	} else if (rc > 0) {
 		dev_warn(&chip->dev, "%s: failed with a TPM error 0x%04X\n",
 			 __func__, rc);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index dd4d6a6158c4..c17e4efbb2e5 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -248,6 +248,7 @@ enum tpm2_return_codes {
 	TPM2_RC_SUCCESS		= 0x0000,
 	TPM2_RC_HASH		= 0x0083, /* RC_FMT1 */
 	TPM2_RC_HANDLE		= 0x008B,
+	TPM2_RC_INTEGRITY	= 0x009F,
 	TPM2_RC_INITIALIZE	= 0x0100, /* RC_VER1 */
 	TPM2_RC_FAILURE		= 0x0101,
 	TPM2_RC_DISABLED	= 0x0120,
@@ -346,6 +347,7 @@ enum tpm_chip_flags {
 	TPM_CHIP_FLAG_FIRMWARE_UPGRADE		= BIT(7),
 	TPM_CHIP_FLAG_SUSPENDED			= BIT(8),
 	TPM_CHIP_FLAG_HWRNG_DISABLED		= BIT(9),
+	TPM_CHIP_FLAG_DISABLE			= BIT(10),
 };
 
 #define to_tpm_chip(d) container_of(d, struct tpm_chip, dev)
@@ -447,7 +449,7 @@ static inline bool tpm_is_firmware_upgrade(struct tpm_chip *chip)
 
 static inline u32 tpm2_rc_value(u32 rc)
 {
-	return (rc & BIT(7)) ? rc & 0xff : rc;
+	return (rc & BIT(7)) ? rc & 0xbf : rc;
 }
 
 #if defined(CONFIG_TCG_TPM) || defined(CONFIG_TCG_TPM_MODULE)
-- 
2.35.3


^ permalink raw reply related	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
                   ` (21 preceding siblings ...)
  2024-04-29 20:28 ` [PATCH v8 22/22] tpm: disable the TPM if NULL name changes James Bottomley
@ 2024-04-29 22:22 ` Jarkko Sakkinen
  2024-04-29 22:26   ` Jarkko Sakkinen
  2024-04-30 19:23   ` James Bottomley
  22 siblings, 2 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:22 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:27 PM EEST, James Bottomley wrote:
> 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/1568031515.6613.31.camel@HansenPartnership.com/
>
> 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
> v3 rebases the encryption to be against Ard's new library function, the
> aescfb addition of which appears as patch 1.
> v4 refreshes Ard's patch, adds kernel doc (including a new patch to
> add it to the moved tpm-buf functions) updates and rewords some commit
> logs
> v5: update to proposed tpm-buf implementation (for ease of use all
> precursor patches are part of this series, so the actual session HMAC
> and encryption begins at patch 10) and add review feedback
> v6: split the original sessions patch into three and change the config
> variable name
> v7: Collect reviews and add extra patch to check for and disable the TPM on
> detecting a reset attack.
> v8: split KDF out, add tpm_ prefix + other cosmetic updates
>
> James
>
> ---
>
> Ard Biesheuvel (1):
>   crypto: lib - implement library version of AES in CFB mode
>
> James Bottomley (14):
>   tpm: Move buffer handling from static inlines to real functions
>   tpm: add buffer function to point to returned parameters
>   tpm: export the context save and load commands
>   tpm: Add NULL primary creation
>   tpm: Add TCG mandated Key Derivation Functions (KDFs)
>   tpm: Add HMAC session start and end functions
>   tpm: Add HMAC session name/handle append
>   tpm: Add the rest of the session HMAC API
>   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
>   tpm: disable the TPM if NULL name changes
>
> Jarkko Sakkinen (7):
>   tpm: Remove unused tpm_buf_tag()
>   tpm: Remove tpm_send()
>   tpm: Update struct tpm_buf documentation comments
>   tpm: Store the length of the tpm_buf data separately.
>   tpm: TPM2B formatted buffers
>   tpm: Add tpm_buf_read_{u8,u16,u32}
>   KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers
>
>  Documentation/security/tpm/tpm-security.rst |  216 ++++
>  drivers/char/tpm/Kconfig                    |   14 +
>  drivers/char/tpm/Makefile                   |    2 +
>  drivers/char/tpm/tpm-buf.c                  |  251 ++++
>  drivers/char/tpm/tpm-chip.c                 |    6 +
>  drivers/char/tpm/tpm-interface.c            |   26 +-
>  drivers/char/tpm/tpm-sysfs.c                |   18 +
>  drivers/char/tpm/tpm.h                      |   14 +
>  drivers/char/tpm/tpm2-cmd.c                 |   53 +-
>  drivers/char/tpm/tpm2-sessions.c            | 1280 +++++++++++++++++++
>  drivers/char/tpm/tpm2-space.c               |   11 +-
>  include/crypto/aes.h                        |    5 +
>  include/keys/trusted_tpm.h                  |    2 -
>  include/linux/tpm.h                         |  316 +++--
>  lib/crypto/Kconfig                          |    5 +
>  lib/crypto/Makefile                         |    3 +
>  lib/crypto/aescfb.c                         |  257 ++++
>  security/keys/trusted-keys/trusted_tpm1.c   |   23 +-
>  security/keys/trusted-keys/trusted_tpm2.c   |  136 +-
>  19 files changed, 2443 insertions(+), 195 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
>  create mode 100644 lib/crypto/aescfb.c

Thanks for the update!

I think I asked this already earlier but unfortunately could not
find the corresponding email from lore.

Anyway, I've tested this series with QEMU i.e. to the point that
I know that it does not break anything in the case when things are
working as expected.

What I would like to test is the negative case when the null key
name changes and see what happens.

I recall that you had some version of QEMU that had ability to test
this and my latest question on that was what QEMU baseline it was
expected to be applied over.

Since I could not find the email subthread I neither have the patch nor
do know the baseline. So if you could help with these details then we
can move forward.

I can also work with QEMU Git fork if you have one and point out
QEMU_OVERRIDE_SRCDIR to the clone.

It is somewhat mandatory IMHO to be able to test this to both 
directions, right?

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-29 22:22 ` [PATCH v8 00/22] add integrity and security to TPM2 transactions Jarkko Sakkinen
@ 2024-04-29 22:26   ` Jarkko Sakkinen
  2024-04-29 23:49     ` Jarkko Sakkinen
  2024-04-30 19:23   ` James Bottomley
  1 sibling, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:26 UTC (permalink / raw)
  To: Jarkko Sakkinen, James Bottomley, linux-integrity
  Cc: keyrings, Ard Biesheuvel

On Tue Apr 30, 2024 at 1:22 AM EEST, Jarkko Sakkinen wrote:
> On Mon Apr 29, 2024 at 11:27 PM EEST, James Bottomley wrote:
> > 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/1568031515.6613.31.camel@HansenPartnership.com/
> >
> > 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
> > v3 rebases the encryption to be against Ard's new library function, the
> > aescfb addition of which appears as patch 1.
> > v4 refreshes Ard's patch, adds kernel doc (including a new patch to
> > add it to the moved tpm-buf functions) updates and rewords some commit
> > logs
> > v5: update to proposed tpm-buf implementation (for ease of use all
> > precursor patches are part of this series, so the actual session HMAC
> > and encryption begins at patch 10) and add review feedback
> > v6: split the original sessions patch into three and change the config
> > variable name
> > v7: Collect reviews and add extra patch to check for and disable the TPM on
> > detecting a reset attack.
> > v8: split KDF out, add tpm_ prefix + other cosmetic updates
> >
> > James
> >
> > ---
> >
> > Ard Biesheuvel (1):
> >   crypto: lib - implement library version of AES in CFB mode
> >
> > James Bottomley (14):
> >   tpm: Move buffer handling from static inlines to real functions
> >   tpm: add buffer function to point to returned parameters
> >   tpm: export the context save and load commands
> >   tpm: Add NULL primary creation
> >   tpm: Add TCG mandated Key Derivation Functions (KDFs)
> >   tpm: Add HMAC session start and end functions
> >   tpm: Add HMAC session name/handle append
> >   tpm: Add the rest of the session HMAC API
> >   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
> >   tpm: disable the TPM if NULL name changes
> >
> > Jarkko Sakkinen (7):
> >   tpm: Remove unused tpm_buf_tag()
> >   tpm: Remove tpm_send()
> >   tpm: Update struct tpm_buf documentation comments
> >   tpm: Store the length of the tpm_buf data separately.
> >   tpm: TPM2B formatted buffers
> >   tpm: Add tpm_buf_read_{u8,u16,u32}
> >   KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers
> >
> >  Documentation/security/tpm/tpm-security.rst |  216 ++++
> >  drivers/char/tpm/Kconfig                    |   14 +
> >  drivers/char/tpm/Makefile                   |    2 +
> >  drivers/char/tpm/tpm-buf.c                  |  251 ++++
> >  drivers/char/tpm/tpm-chip.c                 |    6 +
> >  drivers/char/tpm/tpm-interface.c            |   26 +-
> >  drivers/char/tpm/tpm-sysfs.c                |   18 +
> >  drivers/char/tpm/tpm.h                      |   14 +
> >  drivers/char/tpm/tpm2-cmd.c                 |   53 +-
> >  drivers/char/tpm/tpm2-sessions.c            | 1280 +++++++++++++++++++
> >  drivers/char/tpm/tpm2-space.c               |   11 +-
> >  include/crypto/aes.h                        |    5 +
> >  include/keys/trusted_tpm.h                  |    2 -
> >  include/linux/tpm.h                         |  316 +++--
> >  lib/crypto/Kconfig                          |    5 +
> >  lib/crypto/Makefile                         |    3 +
> >  lib/crypto/aescfb.c                         |  257 ++++
> >  security/keys/trusted-keys/trusted_tpm1.c   |   23 +-
> >  security/keys/trusted-keys/trusted_tpm2.c   |  136 +-
> >  19 files changed, 2443 insertions(+), 195 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
> >  create mode 100644 lib/crypto/aescfb.c
>
> Thanks for the update!
>
> I think I asked this already earlier but unfortunately could not
> find the corresponding email from lore.
>
> Anyway, I've tested this series with QEMU i.e. to the point that
> I know that it does not break anything in the case when things are
> working as expected.
>
> What I would like to test is the negative case when the null key
> name changes and see what happens.
>
> I recall that you had some version of QEMU that had ability to test
> this and my latest question on that was what QEMU baseline it was
> expected to be applied over.
>
> Since I could not find the email subthread I neither have the patch nor
> do know the baseline. So if you could help with these details then we
> can move forward.
>
> I can also work with QEMU Git fork if you have one and point out
> QEMU_OVERRIDE_SRCDIR to the clone.
>
> It is somewhat mandatory IMHO to be able to test this to both 
> directions, right?

Right and obviously 3rd option is to send a PR to
https://gitlab.com/jarkkojs/linux-tpmdd-test.

I.e. patch file goes to patches/qemu (BR2_GLOBAL_PATCH_DIR
points there).

BR, Jarkko


^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 12/22] tpm: Add NULL primary creation
  2024-04-29 20:28 ` [PATCH v8 12/22] tpm: Add NULL primary creation James Bottomley
@ 2024-04-29 22:37   ` Jarkko Sakkinen
  0 siblings, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:37 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> The session handling code uses a "salted" session, meaning a session
> whose salt is encrypted to the public part of another TPM key so an
> observer cannot obtain it (and thus deduce the session keys).  This
> patch creates and context saves in the tpm_chip area the primary key
> of the NULL hierarchy for this purpose.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
> v6: split out of original HMAC patch update config name
> v7: rename null seed parameters
> v8: format changes and move template to tpm.h
> ---
>  drivers/char/tpm/Kconfig         |  11 ++
>  drivers/char/tpm/Makefile        |   1 +
>  drivers/char/tpm/tpm.h           |  10 +
>  drivers/char/tpm/tpm2-cmd.c      |   5 +
>  drivers/char/tpm/tpm2-sessions.c | 316 +++++++++++++++++++++++++++++++
>  include/linux/tpm.h              |  69 +++++++
>  6 files changed, 412 insertions(+)
>  create mode 100644 drivers/char/tpm/tpm2-sessions.c
>
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index 927088b2c3d3..ab16d347579f 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -27,6 +27,17 @@ menuconfig TCG_TPM
>  
>  if TCG_TPM
>  
> +config TCG_TPM2_HMAC
> +	bool "Use HMAC and encrypted transactions on the TPM bus"
> +	default y
> +	help
> +	  Setting this causes us to deploy a scheme which uses request
> +	  and response HMACs in addition to encryption for
> +	  communicating with the TPM to prevent or detect bus snooping
> +	  and interposer attacks (see tpm-security.rst).  Saying Y
> +	  here adds some encryption overhead to all kernel to TPM
> +	  transactions.
> +
>  config HW_RANDOM_TPM
>  	bool "TPM HW Random Number Generator support"
>  	depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m)
> diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile
> index ad3594e383e1..4c695b0388f3 100644
> --- a/drivers/char/tpm/Makefile
> +++ b/drivers/char/tpm/Makefile
> @@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o
>  tpm-y += eventlog/tpm2.o
>  tpm-y += tpm-buf.o
>  
> +tpm-$(CONFIG_TCG_TPM2_HMAC) += tpm2-sessions.o
>  tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
>  tpm-$(CONFIG_EFI) += eventlog/efi.o
>  tpm-$(CONFIG_OF) += eventlog/of.o
> diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
> index cbc9d1e2974d..6b8b9956ba69 100644
> --- a/drivers/char/tpm/tpm.h
> +++ b/drivers/char/tpm/tpm.h
> @@ -321,4 +321,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_TCG_TPM2_HMAC
> +int tpm2_sessions_init(struct tpm_chip *chip);
> +#else
> +static inline int tpm2_sessions_init(struct tpm_chip *chip)
> +{
> +	return 0;
> +}
> +#endif
> +
>  #endif
> diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
> index 93545be190a5..b0e72fb563d9 100644
> --- a/drivers/char/tpm/tpm2-cmd.c
> +++ b/drivers/char/tpm/tpm2-cmd.c
> @@ -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
> diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
> new file mode 100644
> index 000000000000..fc3f032df467
> --- /dev/null
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -0,0 +1,316 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +/*
> + * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
> + *
> + */
> +
> +#include "tpm.h"
> +#include <asm/unaligned.h>
> +
> +/**
> + * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
> + *
> + * @chip:	The TPM the primary was created under
> + * @buf:	The response buffer from the chip
> + * @handle:	pointer to be filled in with the return handle of the primary
> + * @hierarchy:	The hierarchy the primary was created for
> + *
> + * @returns: 0 on success or a positive TPM or negative standard error
> + */
> +static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
> +				     u32 *handle, u32 hierarchy)
> +{
> +	struct tpm_header *head = (struct tpm_header *)buf->data;
> +	off_t offset_r = TPM_HEADER_SIZE, offset_t;
> +	u16 len = TPM_HEADER_SIZE;
> +	u32 total_len = be32_to_cpu(head->length);
> +	u32 val, param_len;
> +
> +	*handle = tpm_buf_read_u32(buf, &offset_r);
> +	param_len = tpm_buf_read_u32(buf, &offset_r);
> +	/*
> +	 * param_len doesn't include the header, but all the other
> +	 * lengths and offsets do, so add it to parm len to make
> +	 * the comparisons easier
> +	 */
> +	param_len += TPM_HEADER_SIZE;
> +
> +	if (param_len + 8 > total_len)
> +		return -EINVAL;
> +	len = tpm_buf_read_u16(buf, &offset_r);
> +	offset_t = offset_r;
> +	/* now we have the public area, compute the name of the object */
> +	put_unaligned_be16(TPM_ALG_SHA256, chip->null_key_name);
> +	sha256(&buf->data[offset_r], len, chip->null_key_name + 2);
> +
> +	/* validate the public key */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +
> +	/* key type (must be what we asked for) */
> +	if (val != TPM_ALG_ECC)
> +		return -EINVAL;
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +
> +	/* name algorithm */
> +	if (val != TPM_ALG_SHA256)
> +		return -EINVAL;
> +	val = tpm_buf_read_u32(buf, &offset_t);
> +
> +	/* object properties */
> +	if (val != TPM2_OA_TMPL)
> +		return -EINVAL;
> +
> +	/* auth policy (empty) */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != 0)
> +		return -EINVAL;
> +
> +	/* symmetric key parameters */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != TPM_ALG_AES)
> +		return -EINVAL;
> +
> +	/* symmetric key length */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != AES_KEY_BITS)
> +		return -EINVAL;
> +
> +	/* symmetric encryption scheme */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != TPM_ALG_CFB)
> +		return -EINVAL;
> +
> +	/* signing scheme */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != TPM_ALG_NULL)
> +		return -EINVAL;
> +
> +	/* ECC Curve */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != TPM2_ECC_NIST_P256)
> +		return -EINVAL;
> +
> +	/* KDF Scheme */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != TPM_ALG_NULL)
> +		return -EINVAL;
> +
> +	/* extract public key (x and y points) */
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != EC_PT_SZ)
> +		return -EINVAL;
> +	memcpy(chip->null_ec_key_x, &buf->data[offset_t], val);
> +	offset_t += val;
> +	val = tpm_buf_read_u16(buf, &offset_t);
> +	if (val != EC_PT_SZ)
> +		return -EINVAL;
> +	memcpy(chip->null_ec_key_y, &buf->data[offset_t], val);
> +	offset_t += val;
> +
> +	/* original length of the whole TPM2B */
> +	offset_r += len;
> +
> +	/* should have exactly consumed the TPM2B public structure */
> +	if (offset_t != offset_r)
> +		return -EINVAL;
> +	if (offset_r > param_len)
> +		return -EINVAL;
> +
> +	/* creation data (skip) */
> +	len = tpm_buf_read_u16(buf, &offset_r);
> +	offset_r += len;
> +	if (offset_r > param_len)
> +		return -EINVAL;
> +
> +	/* creation digest (must be sha256) */
> +	len = tpm_buf_read_u16(buf, &offset_r);
> +	offset_r += len;
> +	if (len != SHA256_DIGEST_SIZE || offset_r > param_len)
> +		return -EINVAL;
> +
> +	/* TPMT_TK_CREATION follows */
> +	/* tag, must be TPM_ST_CREATION (0x8021) */
> +	val = tpm_buf_read_u16(buf, &offset_r);
> +	if (val != TPM2_ST_CREATION || offset_r > param_len)
> +		return -EINVAL;
> +
> +	/* hierarchy */
> +	val = tpm_buf_read_u32(buf, &offset_r);
> +	if (val != hierarchy || offset_r > param_len)
> +		return -EINVAL;
> +
> +	/* the ticket digest HMAC (might not be sha256) */
> +	len = tpm_buf_read_u16(buf, &offset_r);
> +	offset_r += len;
> +	if (offset_r > param_len)
> +		return -EINVAL;
> +
> +	/*
> +	 * finally we have the name, which is a sha256 digest plus a 2
> +	 * byte algorithm type
> +	 */
> +	len = tpm_buf_read_u16(buf, &offset_r);
> +	if (offset_r + len != param_len + 8)
> +		return -EINVAL;
> +	if (len != SHA256_DIGEST_SIZE + 2)
> +		return -EINVAL;
> +
> +	if (memcmp(chip->null_key_name, &buf->data[offset_r],
> +		   SHA256_DIGEST_SIZE + 2) != 0) {
> +		dev_err(&chip->dev, "NULL Seed name comparison failed\n");
> +		return -EINVAL;
> +	}
> +
> +	return 0;
> +}
> +
> +/**
> + * tpm2_create_primary() - create a primary key using a fixed P-256 template
> + *
> + * @chip:      the TPM chip to create under
> + * @hierarchy: The hierarchy handle to create under
> + * @handle:    The returned volatile handle on success
> + *
> + * For platforms that might not have a persistent primary, this can be
> + * used to create one quickly on the fly (it uses Elliptic Curve not
> + * RSA, so even slow TPMs can create one fast).  The template uses the
> + * TCG mandated H one for non-endorsement ECC primaries, i.e. P-256
> + * elliptic curve (the only current one all TPM2s are required to
> + * have) a sha256 name hash and no policy.
> + *
> + * @returns: 0 on success or positive TPM or negative error.
> + */
> +static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
> +			       u32 *handle)
> +{
> +	int rc;
> +	struct tpm_buf buf;
> +	struct tpm_buf template;
> +
> +	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
> +	if (rc)
> +		return rc;
> +
> +	rc = tpm_buf_init_sized(&template);
> +	if (rc) {
> +		tpm_buf_destroy(&buf);
> +		return rc;
> +	}
> +
> +	/*
> +	 * create the template.  Note: in order for userspace to
> +	 * verify the security of the system, it will have to create
> +	 * and certify this NULL primary, meaning all the template
> +	 * parameters will have to be identical, so conform exactly to
> +	 * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
> +	 * key H template (H has zero size unique points)
> +	 */
> +
> +	/* key type */
> +	tpm_buf_append_u16(&template, TPM_ALG_ECC);
> +
> +	/* name algorithm */
> +	tpm_buf_append_u16(&template, TPM_ALG_SHA256);
> +
> +	/* object properties */
> +	tpm_buf_append_u32(&template, TPM2_OA_TMPL);
> +
> +	/* sauth policy (empty) */
> +	tpm_buf_append_u16(&template, 0);
> +
> +	/* BEGIN parameters: key specific; for ECC*/
> +
> +	/* symmetric algorithm */
> +	tpm_buf_append_u16(&template, TPM_ALG_AES);
> +
> +	/* bits for symmetric algorithm */
> +	tpm_buf_append_u16(&template, AES_KEY_BITS);
> +
> +	/* algorithm mode (must be CFB) */
> +	tpm_buf_append_u16(&template, TPM_ALG_CFB);
> +
> +	/* scheme (NULL means any scheme) */
> +	tpm_buf_append_u16(&template, TPM_ALG_NULL);
> +
> +	/* ECC Curve ID */
> +	tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
> +
> +	/* KDF Scheme */
> +	tpm_buf_append_u16(&template, TPM_ALG_NULL);
> +
> +	/* unique: key specific; for ECC it is two zero size points */
> +	tpm_buf_append_u16(&template, 0);
> +	tpm_buf_append_u16(&template, 0);
> +
> +	/* END parameters */
> +
> +	/* primary handle */
> +	tpm_buf_append_u32(&buf, hierarchy);
> +	tpm_buf_append_empty_auth(&buf, TPM2_RS_PW);
> +
> +	/* sensitive create size is 4 for two empty buffers */
> +	tpm_buf_append_u16(&buf, 4);
> +
> +	/* sensitive create auth data (empty) */
> +	tpm_buf_append_u16(&buf, 0);
> +
> +	/* sensitive create sensitive data (empty) */
> +	tpm_buf_append_u16(&buf, 0);
> +
> +	/* the public template */
> +	tpm_buf_append(&buf, template.data, template.length);
> +	tpm_buf_destroy(&template);
> +
> +	/* outside info (empty) */
> +	tpm_buf_append_u16(&buf, 0);
> +
> +	/* creation PCR (none) */
> +	tpm_buf_append_u32(&buf, 0);
> +
> +	rc = tpm_transmit_cmd(chip, &buf, 0,
> +			      "attempting to create NULL primary");
> +
> +	if (rc == TPM2_RC_SUCCESS)
> +		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy);
> +
> +	tpm_buf_destroy(&buf);
> +
> +	return rc;
> +}
> +
> +static int tpm2_create_null_primary(struct tpm_chip *chip)
> +{
> +	u32 null_key;
> +	int rc;
> +
> +	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key);
> +
> +	if (rc == TPM2_RC_SUCCESS) {
> +		unsigned int offset = 0; /* dummy offset for null key context */
> +
> +		rc = tpm2_save_context(chip, null_key, chip->null_key_context,
> +				       sizeof(chip->null_key_context), &offset);
> +		tpm2_flush_context(chip, null_key);
> +	}
> +
> +	return rc;
> +}
> +
> +/**
> + * tpm2_sessions_init() - start of day initialization for the sessions code
> + * @chip: TPM chip
> + *
> + * Derive and context save the null primary and allocate memory in the
> + * struct tpm_chip for the authorizations.
> + */
> +int tpm2_sessions_init(struct tpm_chip *chip)
> +{
> +	int rc;
> +
> +	rc = tpm2_create_null_primary(chip);
> +	if (rc)
> +		dev_err(&chip->dev, "TPM: security failed (NULL seed derivation): %d\n", rc);
> +
> +	return rc;
> +}
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 6be263509e81..bc8c9a350e23 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -23,6 +23,7 @@
>  #include <linux/fs.h>
>  #include <linux/highmem.h>
>  #include <crypto/hash_info.h>
> +#include <crypto/aes.h>
>  
>  #define TPM_DIGEST_SIZE 20	/* Max TPM v1.2 PCR size */
>  #define TPM_MAX_DIGEST_SIZE SHA512_DIGEST_SIZE
> @@ -35,12 +36,15 @@ struct trusted_key_options;
>  enum tpm_algorithms {
>  	TPM_ALG_ERROR		= 0x0000,
>  	TPM_ALG_SHA1		= 0x0004,
> +	TPM_ALG_AES		= 0x0006,
>  	TPM_ALG_KEYEDHASH	= 0x0008,
>  	TPM_ALG_SHA256		= 0x000B,
>  	TPM_ALG_SHA384		= 0x000C,
>  	TPM_ALG_SHA512		= 0x000D,
>  	TPM_ALG_NULL		= 0x0010,
>  	TPM_ALG_SM3_256		= 0x0012,
> +	TPM_ALG_ECC		= 0x0023,
> +	TPM_ALG_CFB		= 0x0043,
>  };
>  
>  /*
> @@ -49,6 +53,11 @@ enum tpm_algorithms {
>   */
>  #define TPM_MAX_HASHES	5
>  
> +enum tpm2_curves {
> +	TPM2_ECC_NONE		= 0x0000,
> +	TPM2_ECC_NIST_P256	= 0x0003,
> +};
> +
>  struct tpm_digest {
>  	u16 alg_id;
>  	u8 digest[TPM_MAX_DIGEST_SIZE];
> @@ -116,6 +125,20 @@ struct tpm_chip_seqops {
>  	const struct seq_operations *seqops;
>  };
>  
> +/* fixed define for the curve we use which is NIST_P256 */
> +#define EC_PT_SZ	32
> +
> +/*
> + * fixed define for the size of a name.  This is actually HASHALG size
> + * plus 2, so 32 for SHA256
> + */
> +#define TPM2_NAME_SIZE	34
> +
> +/*
> + * The maximum size for an object context
> + */
> +#define TPM2_MAX_CONTEXT_SIZE 4096
> +
>  struct tpm_chip {
>  	struct device dev;
>  	struct device devs;
> @@ -170,6 +193,17 @@ struct tpm_chip {
>  
>  	/* active locality */
>  	int locality;
> +
> +#ifdef CONFIG_TCG_TPM2_HMAC
> +	/* details for communication security via sessions */
> +
> +	/* saved context for NULL seed */
> +	u8 null_key_context[TPM2_MAX_CONTEXT_SIZE];
> +	 /* name of NULL seed */
> +	u8 null_key_name[TPM2_NAME_SIZE];
> +	u8 null_ec_key_x[EC_PT_SZ];
> +	u8 null_ec_key_y[EC_PT_SZ];
> +#endif
>  };
>  
>  #define TPM_HEADER_SIZE		10
> @@ -194,6 +228,7 @@ enum tpm2_timeouts {
>  enum tpm2_structures {
>  	TPM2_ST_NO_SESSIONS	= 0x8001,
>  	TPM2_ST_SESSIONS	= 0x8002,
> +	TPM2_ST_CREATION	= 0x8021,
>  };
>  
>  /* Indicates from what layer of the software stack the error comes from */
> @@ -243,6 +278,7 @@ enum tpm2_command_codes {
>  };
>  
>  enum tpm2_permanent_handles {
> +	TPM2_RH_NULL		= 0x40000007,
>  	TPM2_RS_PW		= 0x40000009,
>  };
>  
> @@ -318,9 +354,28 @@ struct tpm_buf {
>  enum tpm2_object_attributes {
>  	TPM2_OA_FIXED_TPM		= BIT(1),
>  	TPM2_OA_FIXED_PARENT		= BIT(4),
> +	TPM2_OA_SENSITIVE_DATA_ORIGIN	= BIT(5),
>  	TPM2_OA_USER_WITH_AUTH		= BIT(6),
> +	TPM2_OA_NO_DA			= BIT(10),
> +	TPM2_OA_RESTRICTED		= BIT(16),
> +	TPM2_OA_DECRYPT			= BIT(17),
>  };
>  
> +/*
> + * definitions for the canonical template.  These are mandated
> + * by the TCG key template documents
> + */
> +
> +#define AES_KEY_BYTES	AES_KEYSIZE_128
> +#define AES_KEY_BITS	(AES_KEY_BYTES*8)
> +#define TPM2_OA_TMPL	(TPM2_OA_NO_DA |			\
> +			 TPM2_OA_FIXED_TPM |			\
> +			 TPM2_OA_FIXED_PARENT |			\
> +			 TPM2_OA_SENSITIVE_DATA_ORIGIN |	\
> +			 TPM2_OA_USER_WITH_AUTH |		\
> +			 TPM2_OA_DECRYPT |			\
> +			 TPM2_OA_RESTRICTED)
> +
>  enum tpm2_session_attributes {
>  	TPM2_SA_CONTINUE_SESSION	= BIT(0),
>  };
> @@ -373,6 +428,16 @@ extern int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
>  extern int tpm_get_random(struct tpm_chip *chip, u8 *data, size_t max);
>  extern struct tpm_chip *tpm_default_chip(void);
>  void tpm2_flush_context(struct tpm_chip *chip, u32 handle);
> +
> +static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
> +{
> +	/* simple authorization for empty auth */
> +	tpm_buf_append_u32(buf, 9);		/* total length of auth */
> +	tpm_buf_append_u32(buf, handle);
> +	tpm_buf_append_u16(buf, 0);		/* nonce len */
> +	tpm_buf_append_u8(buf, 0);		/* attributes */
> +	tpm_buf_append_u16(buf, 0);		/* hmac len */
> +}
>  #else
>  static inline int tpm_is_tpm2(struct tpm_chip *chip)
>  {
> @@ -399,5 +464,9 @@ static inline struct tpm_chip *tpm_default_chip(void)
>  {
>  	return NULL;
>  }
> +
> +static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
> +{
> +}
>  #endif
>  #endif


Good enough!

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 13/22] tpm: Add TCG mandated Key Derivation Functions (KDFs)
  2024-04-29 20:28 ` [PATCH v8 13/22] tpm: Add TCG mandated Key Derivation Functions (KDFs) James Bottomley
@ 2024-04-29 22:37   ` Jarkko Sakkinen
  0 siblings, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:37 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> The TCG mandates two Key derivation functions called KDFa and KDFe
> used to derive keys from seeds and elliptic curve points respectively.
> The definitions for these functions are found in the TPM 2.0 Library
> Specification Part 1 - Architecture Guide
>
> https://trustedcomputinggroup.org/resource/tpm-library-specification/
>
> Implement a cut down version of each of these functions sufficient to
> support the key derivation needs of HMAC sessions.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
>
> v8: Add new patch containing KDFs
> ---
>  drivers/char/tpm/Kconfig         |   1 +
>  drivers/char/tpm/tpm2-sessions.c | 105 +++++++++++++++++++++++++++++++
>  2 files changed, 106 insertions(+)
>
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index ab16d347579f..4873e6eae255 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -30,6 +30,7 @@ if TCG_TPM
>  config TCG_TPM2_HMAC
>  	bool "Use HMAC and encrypted transactions on the TPM bus"
>  	default y
> +	select CRYPTO_LIB_SHA256
>  	help
>  	  Setting this causes us to deploy a scheme which uses request
>  	  and response HMACs in addition to encryption for
> diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
> index fc3f032df467..8429e596f1eb 100644
> --- a/drivers/char/tpm/tpm2-sessions.c
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -7,6 +7,111 @@
>  
>  #include "tpm.h"
>  #include <asm/unaligned.h>
> +#include <crypto/hash.h>
> +#include <crypto/hmac.h>
> +
> +/*
> + * It turns out the crypto hmac(sha256) is hard for us to consume
> + * because it assumes a fixed key and the TPM seems to change the key
> + * on every operation, so we weld the hmac init and final functions in
> + * here to give it the same usage characteristics as a regular hash
> + */
> +static void tpm2_hmac_init(struct sha256_state *sctx, u8 *key, u32 key_len)
> +{
> +	u8 pad[SHA256_BLOCK_SIZE];
> +	int i;
> +
> +	sha256_init(sctx);
> +	for (i = 0; i < sizeof(pad); i++) {
> +		if (i < key_len)
> +			pad[i] = key[i];
> +		else
> +			pad[i] = 0;
> +		pad[i] ^= HMAC_IPAD_VALUE;
> +	}
> +	sha256_update(sctx, pad, sizeof(pad));
> +}
> +
> +static void tpm2_hmac_final(struct sha256_state *sctx, u8 *key, u32 key_len,
> +			    u8 *out)
> +{
> +	u8 pad[SHA256_BLOCK_SIZE];
> +	int i;
> +
> +	for (i = 0; i < sizeof(pad); i++) {
> +		if (i < key_len)
> +			pad[i] = key[i];
> +		else
> +			pad[i] = 0;
> +		pad[i] ^= HMAC_OPAD_VALUE;
> +	}
> +
> +	/* collect the final hash;  use out as temporary storage */
> +	sha256_final(sctx, out);
> +
> +	sha256_init(sctx);
> +	sha256_update(sctx, pad, sizeof(pad));
> +	sha256_update(sctx, out, SHA256_DIGEST_SIZE);
> +	sha256_final(sctx, out);
> +}
> +
> +/*
> + * assume hash sha256 and nonces u, v of size SHA256_DIGEST_SIZE but
> + * otherwise standard tpm2_KDFa.  Note output is in bytes not bits.
> + */
> +static void tpm2_KDFa(u8 *key, u32 key_len, const char *label, u8 *u,
> +		      u8 *v, u32 bytes, u8 *out)
> +{
> +	u32 counter = 1;
> +	const __be32 bits = cpu_to_be32(bytes * 8);
> +
> +	while (bytes > 0) {
> +		struct sha256_state sctx;
> +		__be32 c = cpu_to_be32(counter);
> +
> +		tpm2_hmac_init(&sctx, key, key_len);
> +		sha256_update(&sctx, (u8 *)&c, sizeof(c));
> +		sha256_update(&sctx, label, strlen(label)+1);
> +		sha256_update(&sctx, u, SHA256_DIGEST_SIZE);
> +		sha256_update(&sctx, v, SHA256_DIGEST_SIZE);
> +		sha256_update(&sctx, (u8 *)&bits, sizeof(bits));
> +		tpm2_hmac_final(&sctx, key, key_len, out);
> +
> +		bytes -= SHA256_DIGEST_SIZE;
> +		counter++;
> +		out += SHA256_DIGEST_SIZE;
> +	}
> +}
> +
> +/*
> + * Somewhat of a bastardization of the real KDFe.  We're assuming
> + * we're working with known point sizes for the input parameters and
> + * the hash algorithm is fixed at sha256.  Because we know that the
> + * point size is 32 bytes like the hash size, there's no need to loop
> + * in this KDF.
> + */
> +static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
> +		      u8 *out)
> +{
> +	struct sha256_state sctx;
> +	/*
> +	 * this should be an iterative counter, but because we know
> +	 *  we're only taking 32 bytes for the point using a sha256
> +	 *  hash which is also 32 bytes, there's only one loop
> +	 */
> +	__be32 c = cpu_to_be32(1);
> +
> +	sha256_init(&sctx);
> +	/* counter (BE) */
> +	sha256_update(&sctx, (u8 *)&c, sizeof(c));
> +	/* secret value */
> +	sha256_update(&sctx, z, EC_PT_SZ);
> +	/* string including trailing zero */
> +	sha256_update(&sctx, str, strlen(str)+1);
> +	sha256_update(&sctx, pt_u, EC_PT_SZ);
> +	sha256_update(&sctx, pt_v, EC_PT_SZ);
> +	sha256_final(&sctx, out);
> +}
>  
>  /**
>   * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 14/22] tpm: Add HMAC session start and end functions
  2024-04-29 20:28 ` [PATCH v8 14/22] tpm: Add HMAC session start and end functions James Bottomley
@ 2024-04-29 22:38   ` Jarkko Sakkinen
  2024-04-30 16:49   ` Jarkko Sakkinen
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:38 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> Add 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.  The  design is that  session use will be  single threaded
> from start to finish under the ops lock, so the tpm2_auth structure is
> stored in struct tpm2_chip to simpify the externally visible API.
>
> The session can be ended with tpm2_end_auth_session() which is
> designed only to be used in error legs.  Ordinarily the further
> session API (future patches) will end or continue the session
> appropriately without having to call this.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
>
> ---
>
> v6: split into new patch, update config variable
> v7: add tpm2_ prefix and memzero_explicit
> v8: cosmetic changes, split out KDFe and KDFa
> ---
>  drivers/char/tpm/Kconfig         |   2 +
>  drivers/char/tpm/tpm-buf.c       |   1 +
>  drivers/char/tpm/tpm-chip.c      |   3 +
>  drivers/char/tpm/tpm2-sessions.c | 285 +++++++++++++++++++++++++++++++
>  include/linux/tpm.h              |  34 ++++
>  5 files changed, 325 insertions(+)
>
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index 4873e6eae255..cecf617c9c90 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -30,6 +30,8 @@ if TCG_TPM
>  config TCG_TPM2_HMAC
>  	bool "Use HMAC and encrypted transactions on the TPM bus"
>  	default y
> +	select CRYPTO_ECDH
> +	select CRYPTO_LIB_AESCFB
>  	select CRYPTO_LIB_SHA256
>  	help
>  	  Setting this causes us to deploy a scheme which uses request
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index bb81180495d1..274130398569 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -44,6 +44,7 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
>  	head->tag = cpu_to_be16(tag);
>  	head->length = cpu_to_be32(sizeof(*head));
>  	head->ordinal = cpu_to_be32(ordinal);
> +	buf->handles = 0;
>  }
>  EXPORT_SYMBOL_GPL(tpm_buf_reset);
>  
> diff --git a/drivers/char/tpm/tpm-chip.c b/drivers/char/tpm/tpm-chip.c
> index 42b1062e33cd..d93937326b2e 100644
> --- a/drivers/char/tpm/tpm-chip.c
> +++ b/drivers/char/tpm/tpm-chip.c
> @@ -275,6 +275,9 @@ static void tpm_dev_release(struct device *dev)
>  	kfree(chip->work_space.context_buf);
>  	kfree(chip->work_space.session_buf);
>  	kfree(chip->allocated_banks);
> +#ifdef CONFIG_TCG_TPM2_HMAC
> +	kfree(chip->auth);
> +#endif
>  	kfree(chip);
>  }
>  
> diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
> index 8429e596f1eb..71b3c0e75760 100644
> --- a/drivers/char/tpm/tpm2-sessions.c
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -3,13 +3,101 @@
>  /*
>   * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
>   *
> + * Cryptographic helper routines for handling TPM2 sessions for
> + * authorization HMAC and request response encryption.
> + *
> + * The idea is to ensure that every TPM command is HMAC protected by a
> + * session, meaning in-flight tampering would be detected and in
> + * addition all sensitive inputs and responses should be encrypted.
> + *
> + * The basic way this works is to use a TPM feature called salted
> + * sessions where a random secret used in session construction is
> + * encrypted to the public part of a known TPM key.  The problem is we
> + * have no known keys, so initially a primary Elliptic Curve key is
> + * derived from the NULL seed (we use EC because most TPMs generate
> + * these keys much faster than RSA ones).  The curve used is NIST_P256
> + * because that's now mandated to be present in 'TCG TPM v2.0
> + * Provisioning Guidance'
> + *
> + * Threat problems: the initial TPM2_CreatePrimary is not (and cannot
> + * be) session protected, so a clever Man in the Middle could return a
> + * public key they control to this command and from there intercept
> + * and decode all subsequent session based transactions.  The kernel
> + * cannot mitigate this threat but, after boot, userspace can get
> + * proof this has not happened by asking the TPM to certify the NULL
> + * key.  This certification would chain back to the TPM Endorsement
> + * Certificate and prove the NULL seed primary had not been tampered
> + * with and thus all sessions must have been cryptographically secure.
> + * To assist with this, the initial NULL seed public key name is made
> + * available in a sysfs file.
> + *
> + * Use of these functions:
> + *
> + * The design is all the crypto, hash and hmac gunk is confined in this
> + * file and never needs to be seen even by the kernel internal user.  To
> + * the user there's an init function tpm2_sessions_init() that needs to
> + * be called once per TPM which generates the NULL seed primary key.
> + *
> + * These are the usage functions:
> + *
> + * tpm2_start_auth_session() which allocates the opaque auth structure
> + *	and gets a session from the TPM.  This must be called before
> + *	any of the following functions.  The session is protected by a
> + *	session_key which is derived from a random salt value
> + *	encrypted to the NULL seed.
> + * tpm2_end_auth_session() kills the session and frees the resources.
> + *	Under normal operation this function is done by
> + *	tpm_buf_check_hmac_response(), so this is only to be used on
> + *	error legs where the latter is not executed.
>   */
>  
>  #include "tpm.h"
> +#include <linux/random.h>
> +#include <linux/scatterlist.h>
>  #include <asm/unaligned.h>
> +#include <crypto/kpp.h>
> +#include <crypto/ecdh.h>
>  #include <crypto/hash.h>
>  #include <crypto/hmac.h>
>  
> +/*
> + * This is the structure that carries all the auth information (like
> + * session handle, nonces, session key and auth) from use to use it is
> + * designed to be opaque to anything outside.
> + */
> +struct tpm2_auth {
> +	u32 handle;
> +	/*
> +	 * This has two meanings: before tpm_buf_fill_hmac_session()
> +	 * it marks the offset in the buffer of the start of the
> +	 * sessions (i.e. after all the handles).  Once the buffer has
> +	 * been filled it markes the session number of our auth
> +	 * session so we can find it again in the response buffer.
> +	 *
> +	 * The two cases are distinguished because the first offset
> +	 * must always be greater than TPM_HEADER_SIZE and the second
> +	 * must be less than or equal to 5.
> +	 */
> +	u32 session;
> +	/*
> +	 * the size here is variable and set by the size of our_nonce
> +	 * which must be between 16 and the name hash length. we set
> +	 * the maximum sha256 size for the greatest protection
> +	 */
> +	u8 our_nonce[SHA256_DIGEST_SIZE];
> +	u8 tpm_nonce[SHA256_DIGEST_SIZE];
> +	/*
> +	 * the salt is only used across the session command/response
> +	 * after that it can be used as a scratch area
> +	 */
> +	union {
> +		u8 salt[EC_PT_SZ];
> +		/* scratch for key + IV */
> +		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
> +	};
> +	u8 session_key[SHA256_DIGEST_SIZE];
> +};
> +
>  /*
>   * It turns out the crypto hmac(sha256) is hard for us to consume
>   * because it assumes a fixed key and the TPM seems to change the key
> @@ -113,6 +201,199 @@ static void tpm2_KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
>  	sha256_final(&sctx, out);
>  }
>  
> +static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip)
> +{
> +	struct crypto_kpp *kpp;
> +	struct kpp_request *req;
> +	struct scatterlist s[2], d[1];
> +	struct ecdh p = {0};
> +	u8 encoded_key[EC_PT_SZ], *x, *y;
> +	unsigned int buf_len;
> +
> +	/* secret is two sized points */
> +	tpm_buf_append_u16(buf, (EC_PT_SZ + 2)*2);
> +	/*
> +	 * we cheat here and append uninitialized data to form
> +	 * the points.  All we care about is getting the two
> +	 * co-ordinate pointers, which will be used to overwrite
> +	 * the uninitialized data
> +	 */
> +	tpm_buf_append_u16(buf, EC_PT_SZ);
> +	x = &buf->data[tpm_buf_length(buf)];
> +	tpm_buf_append(buf, encoded_key, EC_PT_SZ);
> +	tpm_buf_append_u16(buf, EC_PT_SZ);
> +	y = &buf->data[tpm_buf_length(buf)];
> +	tpm_buf_append(buf, encoded_key, EC_PT_SZ);
> +	sg_init_table(s, 2);
> +	sg_set_buf(&s[0], x, EC_PT_SZ);
> +	sg_set_buf(&s[1], y, EC_PT_SZ);
> +
> +	kpp = crypto_alloc_kpp("ecdh-nist-p256", CRYPTO_ALG_INTERNAL, 0);
> +	if (IS_ERR(kpp)) {
> +		dev_err(&chip->dev, "crypto ecdh allocation failed\n");
> +		return;
> +	}
> +
> +	buf_len = crypto_ecdh_key_len(&p);
> +	if (sizeof(encoded_key) < buf_len) {
> +		dev_err(&chip->dev, "salt buffer too small needs %d\n",
> +			buf_len);
> +		goto out;
> +	}
> +	crypto_ecdh_encode_key(encoded_key, buf_len, &p);
> +	/* this generates a random private key */
> +	crypto_kpp_set_secret(kpp, encoded_key, buf_len);
> +
> +	/* salt is now the public point of this private key */
> +	req = kpp_request_alloc(kpp, GFP_KERNEL);
> +	if (!req)
> +		goto out;
> +	kpp_request_set_input(req, NULL, 0);
> +	kpp_request_set_output(req, s, EC_PT_SZ*2);
> +	crypto_kpp_generate_public_key(req);
> +	/*
> +	 * we're not done: now we have to compute the shared secret
> +	 * which is our private key multiplied by the tpm_key public
> +	 * point, we actually only take the x point and discard the y
> +	 * point and feed it through KDFe to get the final secret salt
> +	 */
> +	sg_set_buf(&s[0], chip->null_ec_key_x, EC_PT_SZ);
> +	sg_set_buf(&s[1], chip->null_ec_key_y, EC_PT_SZ);
> +	kpp_request_set_input(req, s, EC_PT_SZ*2);
> +	sg_init_one(d, chip->auth->salt, EC_PT_SZ);
> +	kpp_request_set_output(req, d, EC_PT_SZ);
> +	crypto_kpp_compute_shared_secret(req);
> +	kpp_request_free(req);
> +
> +	/*
> +	 * pass the shared secret through KDFe for salt. Note salt
> +	 * area is used both for input shared secret and output salt.
> +	 * This works because KDFe fully consumes the secret before it
> +	 * writes the salt
> +	 */
> +	tpm2_KDFe(chip->auth->salt, "SECRET", x, chip->null_ec_key_x,
> +		  chip->auth->salt);
> +
> + out:
> +	crypto_free_kpp(kpp);
> +}
> +/**
> + * tpm2_end_auth_session() - kill the allocated auth session
> + * @chip: the TPM chip structure
> + *
> + * ends the session started by tpm2_start_auth_session and frees all
> + * the resources.  Under normal conditions,
> + * tpm_buf_check_hmac_response() will correctly end the session if
> + * required, so this function is only for use in error legs that will
> + * bypass the normal invocation of tpm_buf_check_hmac_response().
> + */
> +void tpm2_end_auth_session(struct tpm_chip *chip)
> +{
> +	tpm2_flush_context(chip, chip->auth->handle);
> +	memzero_explicit(chip->auth, sizeof(*chip->auth));
> +}
> +EXPORT_SYMBOL(tpm2_end_auth_session);
> +
> +static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,
> +					 struct tpm_buf *buf)
> +{
> +	struct tpm_header *head = (struct tpm_header *)buf->data;
> +	u32 tot_len = be32_to_cpu(head->length);
> +	off_t offset = TPM_HEADER_SIZE;
> +	u32 val;
> +
> +	/* we're starting after the header so adjust the length */
> +	tot_len -= TPM_HEADER_SIZE;
> +
> +	/* should have handle plus nonce */
> +	if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
> +		return -EINVAL;
> +
> +	auth->handle = tpm_buf_read_u32(buf, &offset);
> +	val = tpm_buf_read_u16(buf, &offset);
> +	if (val != sizeof(auth->tpm_nonce))
> +		return -EINVAL;
> +	memcpy(auth->tpm_nonce, &buf->data[offset], sizeof(auth->tpm_nonce));
> +	/* now compute the session key from the nonces */
> +	tpm2_KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
> +		  auth->our_nonce, sizeof(auth->session_key),
> +		  auth->session_key);
> +
> +	return 0;
> +}
> +
> +/**
> + * tpm2_start_auth_session() - create a HMAC authentication session with the TPM
> + * @chip: the TPM chip structure to create the session with
> + *
> + * This function loads the NULL seed from its saved context and starts
> + * an authentication session on the null seed, fills in the
> + * @chip->auth structure to contain all the session details necessary
> + * for performing the HMAC, encrypt and decrypt operations and
> + * returns.  The NULL seed is flushed before this function returns.
> + *
> + * Return: zero on success or actual error encountered.
> + */
> +int tpm2_start_auth_session(struct tpm_chip *chip)
> +{
> +	struct tpm_buf buf;
> +	struct tpm2_auth *auth = chip->auth;
> +	int rc;
> +	/* null seed context has no offset, but we must provide one */
> +	unsigned int offset = 0;
> +	u32 nullkey;
> +
> +	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
> +			       &nullkey);
> +	if (rc)
> +		goto out;
> +
> +	auth->session = TPM_HEADER_SIZE;
> +
> +	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
> +	if (rc)
> +		goto out;
> +
> +	/* salt key handle */
> +	tpm_buf_append_u32(&buf, nullkey);
> +	/* bind key handle */
> +	tpm_buf_append_u32(&buf, TPM2_RH_NULL);
> +	/* nonce caller */
> +	get_random_bytes(auth->our_nonce, sizeof(auth->our_nonce));
> +	tpm_buf_append_u16(&buf, sizeof(auth->our_nonce));
> +	tpm_buf_append(&buf, auth->our_nonce, sizeof(auth->our_nonce));
> +
> +	/* append encrypted salt and squirrel away unencrypted in auth */
> +	tpm_buf_append_salt(&buf, chip);
> +	/* session type (HMAC, audit or policy) */
> +	tpm_buf_append_u8(&buf, TPM2_SE_HMAC);
> +
> +	/* symmetric encryption parameters */
> +	/* symmetric algorithm */
> +	tpm_buf_append_u16(&buf, TPM_ALG_AES);
> +	/* bits for symmetric algorithm */
> +	tpm_buf_append_u16(&buf, AES_KEY_BITS);
> +	/* symmetric algorithm mode (must be CFB) */
> +	tpm_buf_append_u16(&buf, TPM_ALG_CFB);
> +	/* hash algorithm for session */
> +	tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
> +
> +	rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
> +	tpm2_flush_context(chip, nullkey);
> +
> +	if (rc == TPM2_RC_SUCCESS)
> +		rc = tpm2_parse_start_auth_session(auth, &buf);
> +
> +	tpm_buf_destroy(&buf);
> +
> +	if (rc)
> +		goto out;
> +
> + out:
> +	return rc;
> +}
> +EXPORT_SYMBOL(tpm2_start_auth_session);
> +
>  /**
>   * tpm2_parse_create_primary() - parse the data returned from TPM_CC_CREATE_PRIMARY
>   *
> @@ -417,5 +698,9 @@ int tpm2_sessions_init(struct tpm_chip *chip)
>  	if (rc)
>  		dev_err(&chip->dev, "TPM: security failed (NULL seed derivation): %d\n", rc);
>  
> +	chip->auth = kmalloc(sizeof(*chip->auth), GFP_KERNEL);
> +	if (!chip->auth)
> +		return -ENOMEM;
> +
>  	return rc;
>  }
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index bc8c9a350e23..81b5a70ff80d 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -31,6 +31,14 @@
>  struct tpm_chip;
>  struct trusted_key_payload;
>  struct trusted_key_options;
> +/* opaque structure, holds auth session parameters like the session key */
> +struct tpm2_auth;
> +
> +enum tpm2_session_types {
> +	TPM2_SE_HMAC	= 0x00,
> +	TPM2_SE_POLICY	= 0x01,
> +	TPM2_SE_TRIAL	= 0x02,
> +};
>  
>  /* if you add a new hash to this, increment TPM_MAX_HASHES below */
>  enum tpm_algorithms {
> @@ -203,6 +211,7 @@ struct tpm_chip {
>  	u8 null_key_name[TPM2_NAME_SIZE];
>  	u8 null_ec_key_x[EC_PT_SZ];
>  	u8 null_ec_key_y[EC_PT_SZ];
> +	struct tpm2_auth *auth;
>  #endif
>  };
>  
> @@ -266,6 +275,7 @@ enum tpm2_command_codes {
>  	TPM2_CC_CONTEXT_LOAD	        = 0x0161,
>  	TPM2_CC_CONTEXT_SAVE	        = 0x0162,
>  	TPM2_CC_FLUSH_CONTEXT	        = 0x0165,
> +	TPM2_CC_START_AUTH_SESS		= 0x0176,
>  	TPM2_CC_VERIFY_SIGNATURE        = 0x0177,
>  	TPM2_CC_GET_CAPABILITY	        = 0x017A,
>  	TPM2_CC_GET_RANDOM	        = 0x017B,
> @@ -349,16 +359,21 @@ struct tpm_buf {
>  	u32 flags;
>  	u32 length;
>  	u8 *data;
> +	u8 handles;
>  };
>  
>  enum tpm2_object_attributes {
>  	TPM2_OA_FIXED_TPM		= BIT(1),
> +	TPM2_OA_ST_CLEAR		= BIT(2),
>  	TPM2_OA_FIXED_PARENT		= BIT(4),
>  	TPM2_OA_SENSITIVE_DATA_ORIGIN	= BIT(5),
>  	TPM2_OA_USER_WITH_AUTH		= BIT(6),
> +	TPM2_OA_ADMIN_WITH_POLICY	= BIT(7),
>  	TPM2_OA_NO_DA			= BIT(10),
> +	TPM2_OA_ENCRYPTED_DUPLICATION	= BIT(11),
>  	TPM2_OA_RESTRICTED		= BIT(16),
>  	TPM2_OA_DECRYPT			= BIT(17),
> +	TPM2_OA_SIGN			= BIT(18),
>  };
>  
>  /*
> @@ -378,6 +393,11 @@ enum tpm2_object_attributes {
>  
>  enum tpm2_session_attributes {
>  	TPM2_SA_CONTINUE_SESSION	= BIT(0),
> +	TPM2_SA_AUDIT_EXCLUSIVE		= BIT(1),
> +	TPM2_SA_AUDIT_RESET		= BIT(3),
> +	TPM2_SA_DECRYPT			= BIT(5),
> +	TPM2_SA_ENCRYPT			= BIT(6),
> +	TPM2_SA_AUDIT			= BIT(7),
>  };
>  
>  struct tpm2_hash {
> @@ -469,4 +489,18 @@ static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
>  {
>  }
>  #endif
> +#ifdef CONFIG_TCG_TPM2_HMAC
> +
> +int tpm2_start_auth_session(struct tpm_chip *chip);
> +void tpm2_end_auth_session(struct tpm_chip *chip);
> +#else
> +static inline int tpm2_start_auth_session(struct tpm_chip *chip)
> +{
> +	return 0;
> +}
> +static inline void tpm2_end_auth_session(struct tpm_chip *chip)
> +{
> +}
> +#endif	/* CONFIG_TCG_TPM2_HMAC */
> +
>  #endif

This is IMHO now also good enough.

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 15/22] tpm: Add HMAC session name/handle append
  2024-04-29 20:28 ` [PATCH v8 15/22] tpm: Add HMAC session name/handle append James Bottomley
@ 2024-04-29 22:38   ` Jarkko Sakkinen
  0 siblings, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:38 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> Add tpm2_append_name() for appending to the handle area of the TPM
> command.  When TPM_BUS_SECURITY is enabled and HMAC sessions are in
> use this adds the standard u32 handle to the buffer but additionally
> records the name of the object which must be used as part of the HMAC
> computation.  The name of certain object types (volatile and permanent
> handles and NV indexes) is a hash of the public area of the object.
> Since this hash is not known ahead of time, it must be requested from
> the TPM using TPM2_ReadPublic() (which cannot be HMAC protected, but
> if an interposer lies about it, the HMAC check will fail and the
> problem will be detected).
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
>
> ---
>
> v6: split into new patch, update config variable
> v7: add tpm2_ prefix
> v8: minor updates
> ---
>  drivers/char/tpm/tpm2-sessions.c | 129 +++++++++++++++++++++++++++++++
>  include/linux/tpm.h              |  26 +++++++
>  2 files changed, 155 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
> index 71b3c0e75760..99eb048f18c8 100644
> --- a/drivers/char/tpm/tpm2-sessions.c
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -49,6 +49,11 @@
>   *	Under normal operation this function is done by
>   *	tpm_buf_check_hmac_response(), so this is only to be used on
>   *	error legs where the latter is not executed.
> + * tpm_buf_append_name() to add a handle to the buffer.  This must be
> + *	used in place of the usual tpm_buf_append_u32() for adding
> + *	handles because handles have to be processed specially when
> + *	calculating the HMAC.  In particular, for NV, volatile and
> + *	permanent objects you now need to provide the name.
>   */
>  
>  #include "tpm.h"
> @@ -60,6 +65,9 @@
>  #include <crypto/hash.h>
>  #include <crypto/hmac.h>
>  
> +/* maximum number of names the TPM must remember for authorization */
> +#define AUTH_MAX_NAMES	3
> +
>  /*
>   * This is the structure that carries all the auth information (like
>   * session handle, nonces, session key and auth) from use to use it is
> @@ -96,8 +104,31 @@ struct tpm2_auth {
>  		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
>  	};
>  	u8 session_key[SHA256_DIGEST_SIZE];
> +
> +	/*
> +	 * memory for three authorization handles.  We know them by
> +	 * handle, but they are part of the session by name, which
> +	 * we must compute and remember
> +	 */
> +	u32 name_h[AUTH_MAX_NAMES];
> +	u8 name[AUTH_MAX_NAMES][2 + SHA512_DIGEST_SIZE];
>  };
>  
> +/*
> + * Name Size based on TPM algorithm (assumes no hash bigger than 255)
> + */
> +static u8 name_size(const u8 *name)
> +{
> +	static u8 size_map[] = {
> +		[TPM_ALG_SHA1] = SHA1_DIGEST_SIZE,
> +		[TPM_ALG_SHA256] = SHA256_DIGEST_SIZE,
> +		[TPM_ALG_SHA384] = SHA384_DIGEST_SIZE,
> +		[TPM_ALG_SHA512] = SHA512_DIGEST_SIZE,
> +	};
> +	u16 alg = get_unaligned_be16(name);
> +	return size_map[alg] + 2;
> +}
> +
>  /*
>   * It turns out the crypto hmac(sha256) is hard for us to consume
>   * because it assumes a fixed key and the TPM seems to change the key
> @@ -277,6 +308,104 @@ static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip)
>   out:
>  	crypto_free_kpp(kpp);
>  }
> +
> +static int tpm2_parse_read_public(char *name, struct tpm_buf *buf)
> +{
> +	struct tpm_header *head = (struct tpm_header *)buf->data;
> +	off_t offset = TPM_HEADER_SIZE;
> +	u32 tot_len = be32_to_cpu(head->length);
> +	u32 val;
> +
> +	/* we're starting after the header so adjust the length */
> +	tot_len -= TPM_HEADER_SIZE;
> +
> +	/* skip public */
> +	val = tpm_buf_read_u16(buf, &offset);
> +	if (val > tot_len)
> +		return -EINVAL;
> +	offset += val;
> +	/* name */
> +	val = tpm_buf_read_u16(buf, &offset);
> +	if (val != name_size(&buf->data[offset]))
> +		return -EINVAL;
> +	memcpy(name, &buf->data[offset], val);
> +	/* forget the rest */
> +	return 0;
> +}
> +
> +static int tpm2_read_public(struct tpm_chip *chip, u32 handle, char *name)
> +{
> +	struct tpm_buf buf;
> +	int rc;
> +
> +	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
> +	if (rc)
> +		return rc;
> +
> +	tpm_buf_append_u32(&buf, handle);
> +	rc = tpm_transmit_cmd(chip, &buf, 0, "read public");
> +	if (rc == TPM2_RC_SUCCESS)
> +		rc = tpm2_parse_read_public(name, &buf);
> +
> +	tpm_buf_destroy(&buf);
> +
> +	return rc;
> +}
> +
> +/**
> + * tpm_buf_append_name() - add a handle area to the buffer
> + * @chip: the TPM chip structure
> + * @buf: The buffer to be appended
> + * @handle: The handle to be appended
> + * @name: The name of the handle (may be NULL)
> + *
> + * In order to compute session HMACs, we need to know the names of the
> + * objects pointed to by the handles.  For most objects, this is simply
> + * the actual 4 byte handle or an empty buf (in these cases @name
> + * should be NULL) but for volatile objects, permanent objects and NV
> + * areas, the name is defined as the hash (according to the name
> + * algorithm which should be set to sha256) of the public area to
> + * which the two byte algorithm id has been appended.  For these
> + * objects, the @name pointer should point to this.  If a name is
> + * required but @name is NULL, then TPM2_ReadPublic() will be called
> + * on the handle to obtain the name.
> + *
> + * As with most tpm_buf operations, success is assumed because failure
> + * will be caused by an incorrect programming model and indicated by a
> + * kernel message.
> + */
> +void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
> +			 u32 handle, u8 *name)
> +{
> +	enum tpm2_mso_type mso = tpm2_handle_mso(handle);
> +	struct tpm2_auth *auth = chip->auth;
> +	int slot;
> +
> +	slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE)/4;
> +	if (slot >= AUTH_MAX_NAMES) {
> +		dev_err(&chip->dev, "TPM: too many handles\n");
> +		return;
> +	}
> +	WARN(auth->session != tpm_buf_length(buf),
> +	     "name added in wrong place\n");
> +	tpm_buf_append_u32(buf, handle);
> +	auth->session += 4;
> +
> +	if (mso == TPM2_MSO_PERSISTENT ||
> +	    mso == TPM2_MSO_VOLATILE ||
> +	    mso == TPM2_MSO_NVRAM) {
> +		if (!name)
> +			tpm2_read_public(chip, handle, auth->name[slot]);
> +	} else {
> +		if (name)
> +			dev_err(&chip->dev, "TPM: Handle does not require name but one is specified\n");
> +	}
> +
> +	auth->name_h[slot] = handle;
> +	if (name)
> +		memcpy(auth->name[slot], name, name_size(name));
> +}
> +EXPORT_SYMBOL(tpm_buf_append_name);
>  /**
>   * tpm2_end_auth_session() - kill the allocated auth session
>   * @chip: the TPM chip structure
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 81b5a70ff80d..31c2065fcd35 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -275,6 +275,7 @@ enum tpm2_command_codes {
>  	TPM2_CC_CONTEXT_LOAD	        = 0x0161,
>  	TPM2_CC_CONTEXT_SAVE	        = 0x0162,
>  	TPM2_CC_FLUSH_CONTEXT	        = 0x0165,
> +	TPM2_CC_READ_PUBLIC		= 0x0173,
>  	TPM2_CC_START_AUTH_SESS		= 0x0176,
>  	TPM2_CC_VERIFY_SIGNATURE        = 0x0177,
>  	TPM2_CC_GET_CAPABILITY	        = 0x017A,
> @@ -292,6 +293,21 @@ enum tpm2_permanent_handles {
>  	TPM2_RS_PW		= 0x40000009,
>  };
>  
> +/* Most Significant Octet for key types  */
> +enum tpm2_mso_type {
> +	TPM2_MSO_NVRAM		= 0x01,
> +	TPM2_MSO_SESSION	= 0x02,
> +	TPM2_MSO_POLICY		= 0x03,
> +	TPM2_MSO_PERMANENT	= 0x40,
> +	TPM2_MSO_VOLATILE	= 0x80,
> +	TPM2_MSO_PERSISTENT	= 0x81,
> +};
> +
> +static inline enum tpm2_mso_type tpm2_handle_mso(u32 handle)
> +{
> +	return handle >> 24;
> +}
> +
>  enum tpm2_capabilities {
>  	TPM2_CAP_HANDLES	= 1,
>  	TPM2_CAP_COMMANDS	= 2,
> @@ -492,6 +508,8 @@ static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
>  #ifdef CONFIG_TCG_TPM2_HMAC
>  
>  int tpm2_start_auth_session(struct tpm_chip *chip);
> +void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
> +			 u32 handle, u8 *name);
>  void tpm2_end_auth_session(struct tpm_chip *chip);
>  #else
>  static inline int tpm2_start_auth_session(struct tpm_chip *chip)
> @@ -501,6 +519,14 @@ static inline int tpm2_start_auth_session(struct tpm_chip *chip)
>  static inline void tpm2_end_auth_session(struct tpm_chip *chip)
>  {
>  }
> +static inline void tpm_buf_append_name(struct tpm_chip *chip,
> +				       struct tpm_buf *buf,
> +				       u32 handle, u8 *name)
> +{
> +	tpm_buf_append_u32(buf, handle);
> +	/* count the number of handles in the upper bits of flags */
> +	buf->handles++;
> +}
>  #endif	/* CONFIG_TCG_TPM2_HMAC */
>  
>  #endif

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko


^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 16/22] tpm: Add the rest of the session HMAC API
  2024-04-29 20:28 ` [PATCH v8 16/22] tpm: Add the rest of the session HMAC API James Bottomley
@ 2024-04-29 22:39   ` Jarkko Sakkinen
  0 siblings, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:39 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> The final pieces of the HMAC API are for manipulating the session area
> of the command.  To add an authentication HMAC session
> tpm_buf_append_hmac_session() is called where tpm2_append_auth() would
> go. If a non empty password is passed in, this is correctly added to
> the HMAC to prove knowledge of it without revealing it.  Note that if
> the session is only used to encrypt or decrypt parameters (no
> authentication) then tpm_buf_append_hmac_session_opt() must be used
> instead.  This functions identically to tpm_buf_append_hmac_session()
> when TPM_BUS_SECURITY is enabled, but differently when it isn't,
> because effectively nothing is appended to the session area.
>
> Next the parameters should be filled in for the command and finally
> tpm_buf_fill_hmac_session() is called immediately prior to transmitting
> the command which computes the correct HMAC and places it in the
> command at the session location in the tpm buffer
>
> 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 are 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.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
>
> ---
>
> v6: split into new patch, update config variable
> v7: add memzero_explicit
> v8: minor updates
> ---
>  drivers/char/tpm/tpm2-sessions.c | 400 +++++++++++++++++++++++++++++++
>  include/linux/tpm.h              |  69 ++++++
>  2 files changed, 469 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
> index 99eb048f18c8..3c97d3d5e00e 100644
> --- a/drivers/char/tpm/tpm2-sessions.c
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -54,6 +54,18 @@
>   *	handles because handles have to be processed specially when
>   *	calculating the HMAC.  In particular, for NV, volatile and
>   *	permanent objects you now need to provide the name.
> + * tpm_buf_append_hmac_session() which appends the hmac session to the
> + *	buf in the same way tpm_buf_append_auth does().
> + * tpm_buf_fill_hmac_session() This calculates the correct hash and
> + *	places it in the buffer.  It must be called after the complete
> + *	command buffer is finalized so it can fill in the correct HMAC
> + *	based on the parameters.
> + * tpm_buf_check_hmac_response() which checks the session response in
> + *	the buffer and calculates what it should be.  If there's a
> + *	mismatch it will log a warning and return an error.  If
> + *	tpm_buf_append_hmac_session() did not specify
> + *	TPM_SA_CONTINUE_SESSION then the session will be closed (if it
> + *	hasn't been consumed) and the auth structure freed.
>   */
>  
>  #include "tpm.h"
> @@ -103,7 +115,23 @@ struct tpm2_auth {
>  		/* scratch for key + IV */
>  		u8 scratch[AES_KEY_BYTES + AES_BLOCK_SIZE];
>  	};
> +	/*
> +	 * the session key and passphrase are the same size as the
> +	 * name digest (sha256 again).  The session key is constant
> +	 * for the use of the session and the passphrase can change
> +	 * with every invocation.
> +	 *
> +	 * Note: these fields must be adjacent and in this order
> +	 * because several HMAC/KDF schemes use the combination of the
> +	 * session_key and passphrase.
> +	 */
>  	u8 session_key[SHA256_DIGEST_SIZE];
> +	u8 passphrase[SHA256_DIGEST_SIZE];
> +	int passphrase_len;
> +	struct crypto_aes_ctx aes_ctx;
> +	/* saved session attributes: */
> +	u8 attrs;
> +	__be32 ordinal;
>  
>  	/*
>  	 * memory for three authorization handles.  We know them by
> @@ -309,6 +337,230 @@ static void tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip)
>  	crypto_free_kpp(kpp);
>  }
>  
> +/**
> + * tpm_buf_append_hmac_session() - Append a TPM session element
> + * @chip: the TPM chip structure
> + * @buf: The buffer to be appended
> + * @attributes: The session attributes
> + * @passphrase: The session authority (NULL if none)
> + * @passphrase_len: The length of the session authority (0 if none)
> + *
> + * This fills in a session structure in the TPM command buffer, except
> + * for the HMAC which cannot be computed until the command buffer is
> + * complete.  The type of session is controlled by the @attributes,
> + * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
> + * session won't terminate after tpm_buf_check_hmac_response(),
> + * TPM2_SA_DECRYPT which means this buffers first parameter should be
> + * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
> + * response buffer's first parameter needs to be decrypted (confusing,
> + * but the defines are written from the point of view of the TPM).
> + *
> + * Any session appended by this command must be finalized by calling
> + * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
> + * and the TPM will reject the command.
> + *
> + * As with most tpm_buf operations, success is assumed because failure
> + * will be caused by an incorrect programming model and indicated by a
> + * kernel message.
> + */
> +void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
> +				 u8 attributes, u8 *passphrase,
> +				 int passphrase_len)
> +{
> +	u8 nonce[SHA256_DIGEST_SIZE];
> +	u32 len;
> +	struct tpm2_auth *auth = chip->auth;
> +
> +	/*
> +	 * The Architecture Guide requires us to strip trailing zeros
> +	 * before computing the HMAC
> +	 */
> +	while (passphrase && passphrase_len > 0
> +	       && passphrase[passphrase_len - 1] == '\0')
> +		passphrase_len--;
> +
> +	auth->attrs = attributes;
> +	auth->passphrase_len = passphrase_len;
> +	if (passphrase_len)
> +		memcpy(auth->passphrase, passphrase, passphrase_len);
> +
> +	if (auth->session != tpm_buf_length(buf)) {
> +		/* we're not the first session */
> +		len = get_unaligned_be32(&buf->data[auth->session]);
> +		if (4 + len + auth->session != tpm_buf_length(buf)) {
> +			WARN(1, "session length mismatch, cannot append");
> +			return;
> +		}
> +
> +		/* add our new session */
> +		len += 9 + 2 * SHA256_DIGEST_SIZE;
> +		put_unaligned_be32(len, &buf->data[auth->session]);
> +	} else {
> +		tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
> +	}
> +
> +	/* random number for our nonce */
> +	get_random_bytes(nonce, sizeof(nonce));
> +	memcpy(auth->our_nonce, nonce, sizeof(nonce));
> +	tpm_buf_append_u32(buf, auth->handle);
> +	/* our new nonce */
> +	tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
> +	tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
> +	tpm_buf_append_u8(buf, auth->attrs);
> +	/* and put a placeholder for the hmac */
> +	tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
> +	tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
> +}
> +EXPORT_SYMBOL(tpm_buf_append_hmac_session);
> +
> +/**
> + * tpm_buf_fill_hmac_session() - finalize the session HMAC
> + * @chip: the TPM chip structure
> + * @buf: The buffer to be appended
> + *
> + * This command must not be called until all of the parameters have
> + * been appended to @buf otherwise the computed HMAC will be
> + * incorrect.
> + *
> + * This function computes and fills in the session HMAC using the
> + * session key and, if TPM2_SA_DECRYPT was specified, computes the
> + * encryption key and encrypts the first parameter of the command
> + * buffer with it.
> + *
> + * As with most tpm_buf operations, success is assumed because failure
> + * will be caused by an incorrect programming model and indicated by a
> + * kernel message.
> + */
> +void tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)
> +{
> +	u32 cc, handles, val;
> +	struct tpm2_auth *auth = chip->auth;
> +	int i;
> +	struct tpm_header *head = (struct tpm_header *)buf->data;
> +	off_t offset_s = TPM_HEADER_SIZE, offset_p;
> +	u8 *hmac = NULL;
> +	u32 attrs;
> +	u8 cphash[SHA256_DIGEST_SIZE];
> +	struct sha256_state sctx;
> +
> +	/* save the command code in BE format */
> +	auth->ordinal = head->ordinal;
> +
> +	cc = be32_to_cpu(head->ordinal);
> +
> +	i = tpm2_find_cc(chip, cc);
> +	if (i < 0) {
> +		dev_err(&chip->dev, "Command 0x%x not found in TPM\n", cc);
> +		return;
> +	}
> +	attrs = chip->cc_attrs_tbl[i];
> +
> +	handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0);
> +
> +	/*
> +	 * just check the names, it's easy to make mistakes.  This
> +	 * would happen if someone added a handle via
> +	 * tpm_buf_append_u32() instead of tpm_buf_append_name()
> +	 */
> +	for (i = 0; i < handles; i++) {
> +		u32 handle = tpm_buf_read_u32(buf, &offset_s);
> +
> +		if (auth->name_h[i] != handle) {
> +			dev_err(&chip->dev, "TPM: handle %d wrong for name\n",
> +				  i);
> +			return;
> +		}
> +	}
> +	/* point offset_s to the start of the sessions */
> +	val = tpm_buf_read_u32(buf, &offset_s);
> +	/* point offset_p to the start of the parameters */
> +	offset_p = offset_s + val;
> +	for (i = 1; offset_s < offset_p; i++) {
> +		u32 handle = tpm_buf_read_u32(buf, &offset_s);
> +		u16 len;
> +		u8 a;
> +
> +		/* nonce (already in auth) */
> +		len = tpm_buf_read_u16(buf, &offset_s);
> +		offset_s += len;
> +
> +		a = tpm_buf_read_u8(buf, &offset_s);
> +
> +		len = tpm_buf_read_u16(buf, &offset_s);
> +		if (handle == auth->handle && auth->attrs == a) {
> +			hmac = &buf->data[offset_s];
> +			/*
> +			 * save our session number so we know which
> +			 * session in the response belongs to us
> +			 */
> +			auth->session = i;
> +		}
> +
> +		offset_s += len;
> +	}
> +	if (offset_s != offset_p) {
> +		dev_err(&chip->dev, "TPM session length is incorrect\n");
> +		return;
> +	}
> +	if (!hmac) {
> +		dev_err(&chip->dev, "TPM could not find HMAC session\n");
> +		return;
> +	}
> +
> +	/* encrypt before HMAC */
> +	if (auth->attrs & TPM2_SA_DECRYPT) {
> +		u16 len;
> +
> +		/* need key and IV */
> +		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
> +			  + auth->passphrase_len, "CFB", auth->our_nonce,
> +			  auth->tpm_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
> +			  auth->scratch);
> +
> +		len = tpm_buf_read_u16(buf, &offset_p);
> +		aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);
> +		aescfb_encrypt(&auth->aes_ctx, &buf->data[offset_p],
> +			       &buf->data[offset_p], len,
> +			       auth->scratch + AES_KEY_BYTES);
> +		/* reset p to beginning of parameters for HMAC */
> +		offset_p -= 2;
> +	}
> +
> +	sha256_init(&sctx);
> +	/* ordinal is already BE */
> +	sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));
> +	/* add the handle names */
> +	for (i = 0; i < handles; i++) {
> +		enum tpm2_mso_type mso = tpm2_handle_mso(auth->name_h[i]);
> +
> +		if (mso == TPM2_MSO_PERSISTENT ||
> +		    mso == TPM2_MSO_VOLATILE ||
> +		    mso == TPM2_MSO_NVRAM) {
> +			sha256_update(&sctx, auth->name[i],
> +				      name_size(auth->name[i]));
> +		} else {
> +			__be32 h = cpu_to_be32(auth->name_h[i]);
> +
> +			sha256_update(&sctx, (u8 *)&h, 4);
> +		}
> +	}
> +	if (offset_s != tpm_buf_length(buf))
> +		sha256_update(&sctx, &buf->data[offset_s],
> +			      tpm_buf_length(buf) - offset_s);
> +	sha256_final(&sctx, cphash);
> +
> +	/* now calculate the hmac */
> +	tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
> +		       + auth->passphrase_len);
> +	sha256_update(&sctx, cphash, sizeof(cphash));
> +	sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));
> +	sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
> +	sha256_update(&sctx, &auth->attrs, 1);
> +	tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
> +			+ auth->passphrase_len, hmac);
> +}
> +EXPORT_SYMBOL(tpm_buf_fill_hmac_session);
> +
>  static int tpm2_parse_read_public(char *name, struct tpm_buf *buf)
>  {
>  	struct tpm_header *head = (struct tpm_header *)buf->data;
> @@ -406,6 +658,154 @@ void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
>  		memcpy(auth->name[slot], name, name_size(name));
>  }
>  EXPORT_SYMBOL(tpm_buf_append_name);
> +
> +/**
> + * tpm_buf_check_hmac_response() - check the TPM return HMAC for correctness
> + * @chip: the TPM chip structure
> + * @buf: the original command buffer (which now contains the response)
> + * @rc: the return code from tpm_transmit_cmd
> + *
> + * If @rc is non zero, @buf may not contain an actual return, so @rc
> + * is passed through as the return and the session cleaned up and
> + * de-allocated if required (this is required if
> + * TPM2_SA_CONTINUE_SESSION was not specified as a session flag).
> + *
> + * If @rc is zero, the response HMAC is computed against the returned
> + * @buf and matched to the TPM one in the session area.  If there is a
> + * mismatch, an error is logged and -EINVAL returned.
> + *
> + * The reason for this is that the command issue and HMAC check
> + * sequence should look like:
> + *
> + *	rc = tpm_transmit_cmd(...);
> + *	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
> + *	if (rc)
> + *		...
> + *
> + * Which is easily layered into the current contrl flow.
> + *
> + * Returns: 0 on success or an error.
> + */
> +int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,
> +				int rc)
> +{
> +	struct tpm_header *head = (struct tpm_header *)buf->data;
> +	struct tpm2_auth *auth = chip->auth;
> +	off_t offset_s, offset_p;
> +	u8 rphash[SHA256_DIGEST_SIZE];
> +	u32 attrs;
> +	struct sha256_state sctx;
> +	u16 tag = be16_to_cpu(head->tag);
> +	u32 cc = be32_to_cpu(auth->ordinal);
> +	int parm_len, len, i, handles;
> +
> +	if (auth->session >= TPM_HEADER_SIZE) {
> +		WARN(1, "tpm session not filled correctly\n");
> +		goto out;
> +	}
> +
> +	if (rc != 0)
> +		/* pass non success rc through and close the session */
> +		goto out;
> +
> +	rc = -EINVAL;
> +	if (tag != TPM2_ST_SESSIONS) {
> +		dev_err(&chip->dev, "TPM: HMAC response check has no sessions tag\n");
> +		goto out;
> +	}
> +
> +	i = tpm2_find_cc(chip, cc);
> +	if (i < 0)
> +		goto out;
> +	attrs = chip->cc_attrs_tbl[i];
> +	handles = (attrs >> TPM2_CC_ATTR_RHANDLE) & 1;
> +
> +	/* point to area beyond handles */
> +	offset_s = TPM_HEADER_SIZE + handles * 4;
> +	parm_len = tpm_buf_read_u32(buf, &offset_s);
> +	offset_p = offset_s;
> +	offset_s += parm_len;
> +	/* skip over any sessions before ours */
> +	for (i = 0; i < auth->session - 1; i++) {
> +		len = tpm_buf_read_u16(buf, &offset_s);
> +		offset_s += len + 1;
> +		len = tpm_buf_read_u16(buf, &offset_s);
> +		offset_s += len;
> +	}
> +	/* TPM nonce */
> +	len = tpm_buf_read_u16(buf, &offset_s);
> +	if (offset_s + len > tpm_buf_length(buf))
> +		goto out;
> +	if (len != SHA256_DIGEST_SIZE)
> +		goto out;
> +	memcpy(auth->tpm_nonce, &buf->data[offset_s], len);
> +	offset_s += len;
> +	attrs = tpm_buf_read_u8(buf, &offset_s);
> +	len = tpm_buf_read_u16(buf, &offset_s);
> +	if (offset_s + len != tpm_buf_length(buf))
> +		goto out;
> +	if (len != SHA256_DIGEST_SIZE)
> +		goto out;
> +	/*
> +	 * offset_s points to the HMAC. now calculate comparison, beginning
> +	 * with rphash
> +	 */
> +	sha256_init(&sctx);
> +	/* yes, I know this is now zero, but it's what the standard says */
> +	sha256_update(&sctx, (u8 *)&head->return_code,
> +		      sizeof(head->return_code));
> +	/* ordinal is already BE */
> +	sha256_update(&sctx, (u8 *)&auth->ordinal, sizeof(auth->ordinal));
> +	sha256_update(&sctx, &buf->data[offset_p], parm_len);
> +	sha256_final(&sctx, rphash);
> +
> +	/* now calculate the hmac */
> +	tpm2_hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
> +		       + auth->passphrase_len);
> +	sha256_update(&sctx, rphash, sizeof(rphash));
> +	sha256_update(&sctx, auth->tpm_nonce, sizeof(auth->tpm_nonce));
> +	sha256_update(&sctx, auth->our_nonce, sizeof(auth->our_nonce));
> +	sha256_update(&sctx, &auth->attrs, 1);
> +	/* we're done with the rphash, so put our idea of the hmac there */
> +	tpm2_hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
> +			+ auth->passphrase_len, rphash);
> +	if (memcmp(rphash, &buf->data[offset_s], SHA256_DIGEST_SIZE) == 0) {
> +		rc = 0;
> +	} else {
> +		dev_err(&chip->dev, "TPM: HMAC check failed\n");
> +		goto out;
> +	}
> +
> +	/* now do response decryption */
> +	if (auth->attrs & TPM2_SA_ENCRYPT) {
> +		/* need key and IV */
> +		tpm2_KDFa(auth->session_key, SHA256_DIGEST_SIZE
> +			  + auth->passphrase_len, "CFB", auth->tpm_nonce,
> +			  auth->our_nonce, AES_KEY_BYTES + AES_BLOCK_SIZE,
> +			  auth->scratch);
> +
> +		len = tpm_buf_read_u16(buf, &offset_p);
> +		aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEY_BYTES);
> +		aescfb_decrypt(&auth->aes_ctx, &buf->data[offset_p],
> +			       &buf->data[offset_p], len,
> +			       auth->scratch + AES_KEY_BYTES);
> +	}
> +
> + out:
> +	if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0) {
> +		if (rc)
> +			/* manually close the session if it wasn't consumed */
> +			tpm2_flush_context(chip, auth->handle);
> +		memzero_explicit(auth, sizeof(*auth));
> +	} else {
> +		/* reset for next use  */
> +		auth->session = TPM_HEADER_SIZE;
> +	}
> +
> +	return rc;
> +}
> +EXPORT_SYMBOL(tpm_buf_check_hmac_response);
> +
>  /**
>   * tpm2_end_auth_session() - kill the allocated auth session
>   * @chip: the TPM chip structure
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 31c2065fcd35..dd4d6a6158c4 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -510,8 +510,25 @@ static inline void tpm_buf_append_empty_auth(struct tpm_buf *buf, u32 handle)
>  int tpm2_start_auth_session(struct tpm_chip *chip);
>  void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
>  			 u32 handle, u8 *name);
> +void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
> +				 u8 attributes, u8 *passphrase,
> +				 int passphraselen);
> +static inline void tpm_buf_append_hmac_session_opt(struct tpm_chip *chip,
> +						   struct tpm_buf *buf,
> +						   u8 attributes,
> +						   u8 *passphrase,
> +						   int passphraselen)
> +{
> +	tpm_buf_append_hmac_session(chip, buf, attributes, passphrase,
> +				    passphraselen);
> +}
> +void tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf);
> +int tpm_buf_check_hmac_response(struct tpm_chip *chip, struct tpm_buf *buf,
> +				int rc);
>  void tpm2_end_auth_session(struct tpm_chip *chip);
>  #else
> +#include <asm/unaligned.h>
> +
>  static inline int tpm2_start_auth_session(struct tpm_chip *chip)
>  {
>  	return 0;
> @@ -527,6 +544,58 @@ static inline void tpm_buf_append_name(struct tpm_chip *chip,
>  	/* count the number of handles in the upper bits of flags */
>  	buf->handles++;
>  }
> +static inline void tpm_buf_append_hmac_session(struct tpm_chip *chip,
> +					       struct tpm_buf *buf,
> +					       u8 attributes, u8 *passphrase,
> +					       int passphraselen)
> +{
> +	/* offset tells us where the sessions area begins */
> +	int offset = buf->handles * 4 + TPM_HEADER_SIZE;
> +	u32 len = 9 + passphraselen;
> +
> +	if (tpm_buf_length(buf) != offset) {
> +		/* not the first session so update the existing length */
> +		len += get_unaligned_be32(&buf->data[offset]);
> +		put_unaligned_be32(len, &buf->data[offset]);
> +	} else {
> +		tpm_buf_append_u32(buf, len);
> +	}
> +	/* auth handle */
> +	tpm_buf_append_u32(buf, TPM2_RS_PW);
> +	/* nonce */
> +	tpm_buf_append_u16(buf, 0);
> +	/* attributes */
> +	tpm_buf_append_u8(buf, 0);
> +	/* passphrase */
> +	tpm_buf_append_u16(buf, passphraselen);
> +	tpm_buf_append(buf, passphrase, passphraselen);
> +}
> +static inline void tpm_buf_append_hmac_session_opt(struct tpm_chip *chip,
> +						   struct tpm_buf *buf,
> +						   u8 attributes,
> +						   u8 *passphrase,
> +						   int passphraselen)
> +{
> +	int offset = buf->handles * 4 + TPM_HEADER_SIZE;
> +	struct tpm_header *head = (struct tpm_header *) buf->data;
> +
> +	/*
> +	 * if the only sessions are optional, the command tag
> +	 * must change to TPM2_ST_NO_SESSIONS
> +	 */
> +	if (tpm_buf_length(buf) == offset)
> +		head->tag = cpu_to_be16(TPM2_ST_NO_SESSIONS);
> +}
> +static inline void tpm_buf_fill_hmac_session(struct tpm_chip *chip,
> +					     struct tpm_buf *buf)
> +{
> +}
> +static inline int tpm_buf_check_hmac_response(struct tpm_chip *chip,
> +					      struct tpm_buf *buf,
> +					      int rc)
> +{
> +	return rc;
> +}
>  #endif	/* CONFIG_TCG_TPM2_HMAC */
>  
>  #endif

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 22/22] tpm: disable the TPM if NULL name changes
  2024-04-29 20:28 ` [PATCH v8 22/22] tpm: disable the TPM if NULL name changes James Bottomley
@ 2024-04-29 22:59   ` Jarkko Sakkinen
  2024-04-29 23:34   ` Jarkko Sakkinen
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 22:59 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> Update tpm2_load_context() to return -EINVAL on integrity failures and
> use this as a signal when loading the NULL context that something
> might be wrong.  If the signal fails, check the name of the NULL
> primary against the one stored in the chip data and if there is a
> mismatch disable the TPM because it is likely to have suffered a reset
> attack.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> ---
>  drivers/char/tpm/tpm-chip.c      |  3 ++
>  drivers/char/tpm/tpm2-sessions.c | 77 +++++++++++++++++++++++++-------
>  drivers/char/tpm/tpm2-space.c    |  3 ++
>  include/linux/tpm.h              |  4 +-
>  4 files changed, 70 insertions(+), 17 deletions(-)
>
> diff --git a/drivers/char/tpm/tpm-chip.c b/drivers/char/tpm/tpm-chip.c
> index d93937326b2e..854546000c92 100644
> --- a/drivers/char/tpm/tpm-chip.c
> +++ b/drivers/char/tpm/tpm-chip.c
> @@ -158,6 +158,9 @@ int tpm_try_get_ops(struct tpm_chip *chip)
>  {
>  	int rc = -EIO;
>  
> +	if (chip->flags & TPM_CHIP_FLAG_DISABLE)
> +		return rc;
> +
>  	get_device(&chip->dev);
>  
>  	down_read(&chip->ops_sem);
> diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
> index 3c97d3d5e00e..98819c9a0913 100644
> --- a/drivers/char/tpm/tpm2-sessions.c
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -80,6 +80,9 @@
>  /* maximum number of names the TPM must remember for authorization */
>  #define AUTH_MAX_NAMES	3
>  
> +static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
> +			       u32 *handle, u8 *name);
> +
>  /*
>   * This is the structure that carries all the auth information (like
>   * session handle, nonces, session key and auth) from use to use it is
> @@ -851,6 +854,37 @@ static int tpm2_parse_start_auth_session(struct tpm2_auth *auth,
>  	return 0;
>  }
>  
> +static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)
> +{
> +	int rc;
> +	unsigned int offset = 0; /* dummy offset for null seed context */
> +	u8 name[SHA256_DIGEST_SIZE + 2];
> +
> +	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
> +			       null_key);
> +	if (rc != -EINVAL)
> +		return rc;
> +
> +	/* an integrity failure may mean the TPM has been reset */
> +	dev_err(&chip->dev, "NULL key integrity failure!\n");
> +	/* check the null name against what we know */
> +	tpm2_create_primary(chip, TPM2_RH_NULL, NULL, name);
> +	if (memcmp(name, chip->null_key_name, sizeof(name)) == 0)
> +		/* name unchanged, assume transient integrity failure */
> +		return rc;
> +	/*
> +	 * Fatal TPM failure: the NULL seed has actually changed, so
> +	 * the TPM must have been illegally reset.  All in-kernel TPM
> +	 * operations will fail because the NULL primary can't be
> +	 * loaded to salt the sessions, but disable the TPM anyway so
> +	 * userspace programmes can't be compromised by it.
> +	 */
> +	dev_err(&chip->dev, "NULL name has changed, disabling TPM due to interference\n");
> +	chip->flags |= TPM_CHIP_FLAG_DISABLE;
> +
> +	return rc;
> +}
> +
>  /**
>   * tpm2_start_auth_session() - create a HMAC authentication session with the TPM
>   * @chip: the TPM chip structure to create the session with
> @@ -868,12 +902,9 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
>  	struct tpm_buf buf;
>  	struct tpm2_auth *auth = chip->auth;
>  	int rc;
> -	/* null seed context has no offset, but we must provide one */
> -	unsigned int offset = 0;
> -	u32 nullkey;
> +	u32 null_key;
>  
> -	rc = tpm2_load_context(chip, chip->null_key_context, &offset,
> -			       &nullkey);
> +	rc = tpm2_load_null(chip, &null_key);
>  	if (rc)
>  		goto out;
>  
> @@ -884,7 +915,7 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
>  		goto out;
>  
>  	/* salt key handle */
> -	tpm_buf_append_u32(&buf, nullkey);
> +	tpm_buf_append_u32(&buf, null_key);
>  	/* bind key handle */
>  	tpm_buf_append_u32(&buf, TPM2_RH_NULL);
>  	/* nonce caller */
> @@ -908,7 +939,7 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
>  	tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
>  
>  	rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
> -	tpm2_flush_context(chip, nullkey);
> +	tpm2_flush_context(chip, null_key);
>  
>  	if (rc == TPM2_RC_SUCCESS)
>  		rc = tpm2_parse_start_auth_session(auth, &buf);
> @@ -930,19 +961,25 @@ EXPORT_SYMBOL(tpm2_start_auth_session);
>   * @buf:	The response buffer from the chip
>   * @handle:	pointer to be filled in with the return handle of the primary
>   * @hierarchy:	The hierarchy the primary was created for
> + * @name:	pointer to be filled in with the primary key name
>   *
>   * @returns: 0 on success or a positive TPM or negative standard error
>   */
>  static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
> -				     u32 *handle, u32 hierarchy)
> +				     u32 *handle, u32 hierarchy, u8 *name)
>  {
>  	struct tpm_header *head = (struct tpm_header *)buf->data;
>  	off_t offset_r = TPM_HEADER_SIZE, offset_t;
>  	u16 len = TPM_HEADER_SIZE;
>  	u32 total_len = be32_to_cpu(head->length);
> -	u32 val, param_len;
> +	u32 val, param_len, keyhandle;
> +
> +	keyhandle = tpm_buf_read_u32(buf, &offset_r);
> +	if (handle)
> +		*handle = keyhandle;
> +	else
> +		tpm2_flush_context(chip, keyhandle);
>  
> -	*handle = tpm_buf_read_u32(buf, &offset_r);
>  	param_len = tpm_buf_read_u32(buf, &offset_r);
>  	/*
>  	 * param_len doesn't include the header, but all the other
> @@ -955,9 +992,14 @@ static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
>  		return -EINVAL;
>  	len = tpm_buf_read_u16(buf, &offset_r);
>  	offset_t = offset_r;
> -	/* now we have the public area, compute the name of the object */
> -	put_unaligned_be16(TPM_ALG_SHA256, chip->null_key_name);
> -	sha256(&buf->data[offset_r], len, chip->null_key_name + 2);
> +	if (name) {
> +		/*
> +		 * now we have the public area, compute the name of
> +		 * the object
> +		 */
> +		put_unaligned_be16(TPM_ALG_SHA256, name);
> +		sha256(&buf->data[offset_r], len, name + 2);
> +	}
>  
>  	/* validate the public key */
>  	val = tpm_buf_read_u16(buf, &offset_t);
> @@ -1086,6 +1128,7 @@ static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
>   * @chip:      the TPM chip to create under
>   * @hierarchy: The hierarchy handle to create under
>   * @handle:    The returned volatile handle on success
> + * @name:      The name of the returned key
>   *
>   * For platforms that might not have a persistent primary, this can be
>   * used to create one quickly on the fly (it uses Elliptic Curve not
> @@ -1097,7 +1140,7 @@ static int tpm2_parse_create_primary(struct tpm_chip *chip, struct tpm_buf *buf,
>   * @returns: 0 on success or positive TPM or negative error.
>   */
>  static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
> -			       u32 *handle)
> +			       u32 *handle, u8 *name)
>  {
>  	int rc;
>  	struct tpm_buf buf;
> @@ -1187,7 +1230,8 @@ static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
>  			      "attempting to create NULL primary");
>  
>  	if (rc == TPM2_RC_SUCCESS)
> -		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy);
> +		rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy,
> +					       name);
>  
>  	tpm_buf_destroy(&buf);
>  
> @@ -1199,7 +1243,8 @@ static int tpm2_create_null_primary(struct tpm_chip *chip)
>  	u32 null_key;
>  	int rc;
>  
> -	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key);
> +	rc = tpm2_create_primary(chip, TPM2_RH_NULL, &null_key,
> +				 chip->null_key_name);
>  
>  	if (rc == TPM2_RC_SUCCESS) {
>  		unsigned int offset = 0; /* dummy offset for null key context */
> diff --git a/drivers/char/tpm/tpm2-space.c b/drivers/char/tpm/tpm2-space.c
> index 24479a81c23c..4892d491da8d 100644
> --- a/drivers/char/tpm/tpm2-space.c
> +++ b/drivers/char/tpm/tpm2-space.c
> @@ -105,6 +105,9 @@ int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
>  		*handle = 0;
>  		tpm_buf_destroy(&tbuf);
>  		return -ENOENT;
> +	} else if (tpm2_rc_value(rc) == TPM2_RC_INTEGRITY) {
> +		tpm_buf_destroy(&tbuf);
> +		return -EINVAL;
>  	} else if (rc > 0) {
>  		dev_warn(&chip->dev, "%s: failed with a TPM error 0x%04X\n",
>  			 __func__, rc);
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index dd4d6a6158c4..c17e4efbb2e5 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -248,6 +248,7 @@ enum tpm2_return_codes {
>  	TPM2_RC_SUCCESS		= 0x0000,
>  	TPM2_RC_HASH		= 0x0083, /* RC_FMT1 */
>  	TPM2_RC_HANDLE		= 0x008B,
> +	TPM2_RC_INTEGRITY	= 0x009F,
>  	TPM2_RC_INITIALIZE	= 0x0100, /* RC_VER1 */
>  	TPM2_RC_FAILURE		= 0x0101,
>  	TPM2_RC_DISABLED	= 0x0120,
> @@ -346,6 +347,7 @@ enum tpm_chip_flags {
>  	TPM_CHIP_FLAG_FIRMWARE_UPGRADE		= BIT(7),
>  	TPM_CHIP_FLAG_SUSPENDED			= BIT(8),
>  	TPM_CHIP_FLAG_HWRNG_DISABLED		= BIT(9),
> +	TPM_CHIP_FLAG_DISABLE			= BIT(10),
>  };
>  
>  #define to_tpm_chip(d) container_of(d, struct tpm_chip, dev)
> @@ -447,7 +449,7 @@ static inline bool tpm_is_firmware_upgrade(struct tpm_chip *chip)
>  
>  static inline u32 tpm2_rc_value(u32 rc)
>  {
> -	return (rc & BIT(7)) ? rc & 0xff : rc;
> +	return (rc & BIT(7)) ? rc & 0xbf : rc;

Bit 6 is set for TPM2_RC_INTEGRITY and thus you needed to
mask it out, as it is set given the handle, right? Just
sanity checking that I understand the change.

>  }
>  
>  #if defined(CONFIG_TCG_TPM) || defined(CONFIG_TCG_TPM_MODULE)

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 22/22] tpm: disable the TPM if NULL name changes
  2024-04-29 20:28 ` [PATCH v8 22/22] tpm: disable the TPM if NULL name changes James Bottomley
  2024-04-29 22:59   ` Jarkko Sakkinen
@ 2024-04-29 23:34   ` Jarkko Sakkinen
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 23:34 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> +	if (chip->flags & TPM_CHIP_FLAG_DISABLE)
> +		return rc;
> +

s/DISABLE/ACCESS_DENIED/ as it is more to the point.

Further, tpm_open() should fail right off the bat after ending up to
this situation.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-29 22:26   ` Jarkko Sakkinen
@ 2024-04-29 23:49     ` Jarkko Sakkinen
  2024-04-30 11:18       ` Stefan Berger
  0 siblings, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-29 23:49 UTC (permalink / raw)
  To: Jarkko Sakkinen, James Bottomley, linux-integrity, Stefan Berger
  Cc: keyrings, Ard Biesheuvel

On Tue Apr 30, 2024 at 1:26 AM EEST, Jarkko Sakkinen wrote:
> Right and obviously 3rd option is to send a PR to
> https://gitlab.com/jarkkojs/linux-tpmdd-test.
>
> I.e. patch file goes to patches/qemu (BR2_GLOBAL_PATCH_DIR
> points there).

Stefan, can I do a "zero QEMU changes" negative test for
changing null seed by somehow reseting swtpm? That would
be best possible option (if it is possible).

It does not matter what side-effects it has on swtpm side
as long as the hmac path gets invalidated, as then the
device is rendered as unusable.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-29 23:49     ` Jarkko Sakkinen
@ 2024-04-30 11:18       ` Stefan Berger
  2024-04-30 18:37         ` Jarkko Sakkinen
  0 siblings, 1 reply; 75+ messages in thread
From: Stefan Berger @ 2024-04-30 11:18 UTC (permalink / raw)
  To: Jarkko Sakkinen, James Bottomley, linux-integrity
  Cc: keyrings, Ard Biesheuvel



On 4/29/24 19:49, Jarkko Sakkinen wrote:
> On Tue Apr 30, 2024 at 1:26 AM EEST, Jarkko Sakkinen wrote:
>> Right and obviously 3rd option is to send a PR to
>> https://gitlab.com/jarkkojs/linux-tpmdd-test.
>>
>> I.e. patch file goes to patches/qemu (BR2_GLOBAL_PATCH_DIR
>> points there).
> 
> Stefan, can I do a "zero QEMU changes" negative test for
> changing null seed by somehow reseting swtpm? That would
> be best possible option (if it is possible).

You cannot easily reset swtpm without changing 'something' and resetting 
the NULL seed only works when running TPM2_Startup. You could modify 
some TPM2 command to do what HierarchyStartup does with the nullSeed to 
simulate what you want.

> 
> It does not matter what side-effects it has on swtpm side
> as long as the hmac path gets invalidated, as then the
> device is rendered as unusable.
> 
> BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 14/22] tpm: Add HMAC session start and end functions
  2024-04-29 20:28 ` [PATCH v8 14/22] tpm: Add HMAC session start and end functions James Bottomley
  2024-04-29 22:38   ` Jarkko Sakkinen
@ 2024-04-30 16:49   ` Jarkko Sakkinen
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-30 16:49 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Mon Apr 29, 2024 at 11:28 PM EEST, James Bottomley wrote:
> +	rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
> +	if (rc)
> +		goto out;

Have missed this one. The command code name is truncated, which we have
not done. It should be TPM2_CC_START_AUTH_SESSION.

Spotted this while thinking how to test the interposer scenario.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 11:18       ` Stefan Berger
@ 2024-04-30 18:37         ` Jarkko Sakkinen
  2024-04-30 18:57           ` Stefan Berger
  0 siblings, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-30 18:37 UTC (permalink / raw)
  To: Stefan Berger, James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Tue Apr 30, 2024 at 2:18 PM EEST, Stefan Berger wrote:
>
>
> On 4/29/24 19:49, Jarkko Sakkinen wrote:
> > On Tue Apr 30, 2024 at 1:26 AM EEST, Jarkko Sakkinen wrote:
> >> Right and obviously 3rd option is to send a PR to
> >> https://gitlab.com/jarkkojs/linux-tpmdd-test.
> >>
> >> I.e. patch file goes to patches/qemu (BR2_GLOBAL_PATCH_DIR
> >> points there).
> > 
> > Stefan, can I do a "zero QEMU changes" negative test for
> > changing null seed by somehow reseting swtpm? That would
> > be best possible option (if it is possible).
>
> You cannot easily reset swtpm without changing 'something' and resetting 
> the NULL seed only works when running TPM2_Startup. You could modify 
> some TPM2 command to do what HierarchyStartup does with the nullSeed to 
> simulate what you want.

Hmm... I'm not too eager to modify swtpm itself.

So one hacky option might be to run swtpm using system() in an
interposer program and that program would again create chardev
using cuse.

That program would again have to modify traffic "at some point".

Maybe +1 command after TPM2_StartAuthSession or later?

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 18:37         ` Jarkko Sakkinen
@ 2024-04-30 18:57           ` Stefan Berger
  0 siblings, 0 replies; 75+ messages in thread
From: Stefan Berger @ 2024-04-30 18:57 UTC (permalink / raw)
  To: Jarkko Sakkinen, James Bottomley, linux-integrity
  Cc: keyrings, Ard Biesheuvel



On 4/30/24 14:37, Jarkko Sakkinen wrote:
> On Tue Apr 30, 2024 at 2:18 PM EEST, Stefan Berger wrote:
>>
>>
>> On 4/29/24 19:49, Jarkko Sakkinen wrote:
>>> On Tue Apr 30, 2024 at 1:26 AM EEST, Jarkko Sakkinen wrote:
>>>> Right and obviously 3rd option is to send a PR to
>>>> https://gitlab.com/jarkkojs/linux-tpmdd-test.
>>>>
>>>> I.e. patch file goes to patches/qemu (BR2_GLOBAL_PATCH_DIR
>>>> points there).
>>>
>>> Stefan, can I do a "zero QEMU changes" negative test for
>>> changing null seed by somehow reseting swtpm? That would
>>> be best possible option (if it is possible).
>>
>> You cannot easily reset swtpm without changing 'something' and resetting
>> the NULL seed only works when running TPM2_Startup. You could modify
>> some TPM2 command to do what HierarchyStartup does with the nullSeed to
>> simulate what you want.
> 
> Hmm... I'm not too eager to modify swtpm itself.

You would modify libtpms. You may just want to copy the few relevant 
lines from HierarchyStartup function into another TPM 2 command that 
then resets the null seed and whatever else you need reset as a side 
effect. This sounds simpler to me than what you are proposing with 
system(). Who or what would run system().

> 
> So one hacky option might be to run swtpm using system() in an
> interposer program and that program would again create chardev
> using cuse.
> 
> That program would again have to modify traffic "at some point".
> 
> Maybe +1 command after TPM2_StartAuthSession or later?
> 
> BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-29 22:22 ` [PATCH v8 00/22] add integrity and security to TPM2 transactions Jarkko Sakkinen
  2024-04-29 22:26   ` Jarkko Sakkinen
@ 2024-04-30 19:23   ` James Bottomley
  2024-04-30 21:48     ` Jarkko Sakkinen
  1 sibling, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-04-30 19:23 UTC (permalink / raw)
  To: Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Tue, 2024-04-30 at 01:22 +0300, Jarkko Sakkinen wrote:
> On Mon Apr 29, 2024 at 11:27 PM EEST, James Bottomley wrote:
> > 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/1568031515.6613.31.camel@HansenPartnership.com/
> > 
> > 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
> > v3 rebases the encryption to be against Ard's new library function,
> > the
> > aescfb addition of which appears as patch 1.
> > v4 refreshes Ard's patch, adds kernel doc (including a new patch to
> > add it to the moved tpm-buf functions) updates and rewords some
> > commit
> > logs
> > v5: update to proposed tpm-buf implementation (for ease of use all
> > precursor patches are part of this series, so the actual session
> > HMAC
> > and encryption begins at patch 10) and add review feedback
> > v6: split the original sessions patch into three and change the
> > config
> > variable name
> > v7: Collect reviews and add extra patch to check for and disable
> > the TPM on
> > detecting a reset attack.
> > v8: split KDF out, add tpm_ prefix + other cosmetic updates
> > 
> > James
> > 
> > ---
> > 
> > Ard Biesheuvel (1):
> >   crypto: lib - implement library version of AES in CFB mode
> > 
> > James Bottomley (14):
> >   tpm: Move buffer handling from static inlines to real functions
> >   tpm: add buffer function to point to returned parameters
> >   tpm: export the context save and load commands
> >   tpm: Add NULL primary creation
> >   tpm: Add TCG mandated Key Derivation Functions (KDFs)
> >   tpm: Add HMAC session start and end functions
> >   tpm: Add HMAC session name/handle append
> >   tpm: Add the rest of the session HMAC API
> >   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
> >   tpm: disable the TPM if NULL name changes
> > 
> > Jarkko Sakkinen (7):
> >   tpm: Remove unused tpm_buf_tag()
> >   tpm: Remove tpm_send()
> >   tpm: Update struct tpm_buf documentation comments
> >   tpm: Store the length of the tpm_buf data separately.
> >   tpm: TPM2B formatted buffers
> >   tpm: Add tpm_buf_read_{u8,u16,u32}
> >   KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers
> > 
> >  Documentation/security/tpm/tpm-security.rst |  216 ++++
> >  drivers/char/tpm/Kconfig                    |   14 +
> >  drivers/char/tpm/Makefile                   |    2 +
> >  drivers/char/tpm/tpm-buf.c                  |  251 ++++
> >  drivers/char/tpm/tpm-chip.c                 |    6 +
> >  drivers/char/tpm/tpm-interface.c            |   26 +-
> >  drivers/char/tpm/tpm-sysfs.c                |   18 +
> >  drivers/char/tpm/tpm.h                      |   14 +
> >  drivers/char/tpm/tpm2-cmd.c                 |   53 +-
> >  drivers/char/tpm/tpm2-sessions.c            | 1280
> > +++++++++++++++++++
> >  drivers/char/tpm/tpm2-space.c               |   11 +-
> >  include/crypto/aes.h                        |    5 +
> >  include/keys/trusted_tpm.h                  |    2 -
> >  include/linux/tpm.h                         |  316 +++--
> >  lib/crypto/Kconfig                          |    5 +
> >  lib/crypto/Makefile                         |    3 +
> >  lib/crypto/aescfb.c                         |  257 ++++
> >  security/keys/trusted-keys/trusted_tpm1.c   |   23 +-
> >  security/keys/trusted-keys/trusted_tpm2.c   |  136 +-
> >  19 files changed, 2443 insertions(+), 195 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
> >  create mode 100644 lib/crypto/aescfb.c
> 
> Thanks for the update!
> 
> I think I asked this already earlier but unfortunately could not
> find the corresponding email from lore.

Well, you did, but at that time I didn't have the null name change
detection so:

> 
> Anyway, I've tested this series with QEMU i.e. to the point that
> I know that it does not break anything in the case when things are
> working as expected.
> 
> What I would like to test is the negative case when the null key
> name changes and see what happens.
> 
> I recall that you had some version of QEMU that had ability to test
> this and my latest question on that was what QEMU baseline it was
> expected to be applied over.

Yes, I added patches to qemu to make it talk directly to the mssim TPM
reference implementation

https://github.com/microsoft/ms-tpm-20-ref

so I could be sure I was testing against the reference implementation.
However, they also have the advantage that you can use wireshark to
dump the TPM transactions (ensuring encryption).  You can also tamper
with the TPM state from the outside by connecting to the TPM socket.

For the case you want, you can simulate a reset by killing and
restarting the tpm server (you have to power it up and issue the
startup command manually).  The next TPM command the kernel tries
should see the null name change and react accordingly.

It looks like the current qemu patches fail to apply again, so I just
reposted them against qemu git head:

https://lore.kernel.org/qemu-devel/20240430190855.2811-1-James.Bottomley@HansenPartnership.com/

> Since I could not find the email subthread I neither have the patch
> nor do know the baseline. So if you could help with these details
> then we can move forward.
> 
> I can also work with QEMU Git fork if you have one and point out
> QEMU_OVERRIDE_SRCDIR to the clone.

I only have the patches in a local git repository, but I could push
qemu up onto kernel.org if it would help?

James


^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 19:23   ` James Bottomley
@ 2024-04-30 21:48     ` Jarkko Sakkinen
  2024-04-30 22:31       ` James Bottomley
  0 siblings, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-30 21:48 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Tue Apr 30, 2024 at 10:23 PM EEST, James Bottomley wrote:
> On Tue, 2024-04-30 at 01:22 +0300, Jarkko Sakkinen wrote:
> > On Mon Apr 29, 2024 at 11:27 PM EEST, James Bottomley wrote:
> > > 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/1568031515.6613.31.camel@HansenPartnership.com/
> > > 
> > > 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
> > > v3 rebases the encryption to be against Ard's new library function,
> > > the
> > > aescfb addition of which appears as patch 1.
> > > v4 refreshes Ard's patch, adds kernel doc (including a new patch to
> > > add it to the moved tpm-buf functions) updates and rewords some
> > > commit
> > > logs
> > > v5: update to proposed tpm-buf implementation (for ease of use all
> > > precursor patches are part of this series, so the actual session
> > > HMAC
> > > and encryption begins at patch 10) and add review feedback
> > > v6: split the original sessions patch into three and change the
> > > config
> > > variable name
> > > v7: Collect reviews and add extra patch to check for and disable
> > > the TPM on
> > > detecting a reset attack.
> > > v8: split KDF out, add tpm_ prefix + other cosmetic updates
> > > 
> > > James
> > > 
> > > ---
> > > 
> > > Ard Biesheuvel (1):
> > >   crypto: lib - implement library version of AES in CFB mode
> > > 
> > > James Bottomley (14):
> > >   tpm: Move buffer handling from static inlines to real functions
> > >   tpm: add buffer function to point to returned parameters
> > >   tpm: export the context save and load commands
> > >   tpm: Add NULL primary creation
> > >   tpm: Add TCG mandated Key Derivation Functions (KDFs)
> > >   tpm: Add HMAC session start and end functions
> > >   tpm: Add HMAC session name/handle append
> > >   tpm: Add the rest of the session HMAC API
> > >   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
> > >   tpm: disable the TPM if NULL name changes
> > > 
> > > Jarkko Sakkinen (7):
> > >   tpm: Remove unused tpm_buf_tag()
> > >   tpm: Remove tpm_send()
> > >   tpm: Update struct tpm_buf documentation comments
> > >   tpm: Store the length of the tpm_buf data separately.
> > >   tpm: TPM2B formatted buffers
> > >   tpm: Add tpm_buf_read_{u8,u16,u32}
> > >   KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers
> > > 
> > >  Documentation/security/tpm/tpm-security.rst |  216 ++++
> > >  drivers/char/tpm/Kconfig                    |   14 +
> > >  drivers/char/tpm/Makefile                   |    2 +
> > >  drivers/char/tpm/tpm-buf.c                  |  251 ++++
> > >  drivers/char/tpm/tpm-chip.c                 |    6 +
> > >  drivers/char/tpm/tpm-interface.c            |   26 +-
> > >  drivers/char/tpm/tpm-sysfs.c                |   18 +
> > >  drivers/char/tpm/tpm.h                      |   14 +
> > >  drivers/char/tpm/tpm2-cmd.c                 |   53 +-
> > >  drivers/char/tpm/tpm2-sessions.c            | 1280
> > > +++++++++++++++++++
> > >  drivers/char/tpm/tpm2-space.c               |   11 +-
> > >  include/crypto/aes.h                        |    5 +
> > >  include/keys/trusted_tpm.h                  |    2 -
> > >  include/linux/tpm.h                         |  316 +++--
> > >  lib/crypto/Kconfig                          |    5 +
> > >  lib/crypto/Makefile                         |    3 +
> > >  lib/crypto/aescfb.c                         |  257 ++++
> > >  security/keys/trusted-keys/trusted_tpm1.c   |   23 +-
> > >  security/keys/trusted-keys/trusted_tpm2.c   |  136 +-
> > >  19 files changed, 2443 insertions(+), 195 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
> > >  create mode 100644 lib/crypto/aescfb.c
> > 
> > Thanks for the update!
> > 
> > I think I asked this already earlier but unfortunately could not
> > find the corresponding email from lore.
>
> Well, you did, but at that time I didn't have the null name change
> detection so:
>
> > 
> > Anyway, I've tested this series with QEMU i.e. to the point that
> > I know that it does not break anything in the case when things are
> > working as expected.
> > 
> > What I would like to test is the negative case when the null key
> > name changes and see what happens.
> > 
> > I recall that you had some version of QEMU that had ability to test
> > this and my latest question on that was what QEMU baseline it was
> > expected to be applied over.
>
> Yes, I added patches to qemu to make it talk directly to the mssim TPM
> reference implementation
>
> https://github.com/microsoft/ms-tpm-20-ref
>
> so I could be sure I was testing against the reference implementation.
> However, they also have the advantage that you can use wireshark to
> dump the TPM transactions (ensuring encryption).  You can also tamper
> with the TPM state from the outside by connecting to the TPM socket.
>
> For the case you want, you can simulate a reset by killing and
> restarting the tpm server (you have to power it up and issue the
> startup command manually).  The next TPM command the kernel tries
> should see the null name change and react accordingly.
>
> It looks like the current qemu patches fail to apply again, so I just
> reposted them against qemu git head:
>
> https://lore.kernel.org/qemu-devel/20240430190855.2811-1-James.Bottomley@HansenPartnership.com/
>
> > Since I could not find the email subthread I neither have the patch
> > nor do know the baseline. So if you could help with these details
> > then we can move forward.
> > 
> > I can also work with QEMU Git fork if you have one and point out
> > QEMU_OVERRIDE_SRCDIR to the clone.
>
> I only have the patches in a local git repository, but I could push
> qemu up onto kernel.org if it would help?

That definitely does help. I can point out my build to that repository,
(or actually clone of it).

As said the "valid flow" has been tested multiple times. I guess I can
hold v6.10 PR to next week so there is still time to barely squeeze this
to v6.10.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 21:48     ` Jarkko Sakkinen
@ 2024-04-30 22:31       ` James Bottomley
  2024-04-30 22:46         ` Jarkko Sakkinen
  2024-05-03 23:18         ` Jarkko Sakkinen
  0 siblings, 2 replies; 75+ messages in thread
From: James Bottomley @ 2024-04-30 22:31 UTC (permalink / raw)
  To: Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Wed, 2024-05-01 at 00:48 +0300, Jarkko Sakkinen wrote:
> On Tue Apr 30, 2024 at 10:23 PM EEST, James Bottomley wrote:
> > On Tue, 2024-04-30 at 01:22 +0300, Jarkko Sakkinen wrote:
[...]
> > > Since I could not find the email subthread I neither have the
> > > patch nor do know the baseline. So if you could help with these
> > > details then we can move forward.
> > > 
> > > I can also work with QEMU Git fork if you have one and point out
> > > QEMU_OVERRIDE_SRCDIR to the clone.
> > 
> > I only have the patches in a local git repository, but I could push
> > qemu up onto kernel.org if it would help?
> 
> That definitely does help. I can point out my build to that
> repository, (or actually clone of it).

OK, it's the mssim branch here:

https://git.kernel.org/pub/scm/linux/kernel/git/jejb/qemu.git/log/?h=mssim

It's based on qemu head, but it works for me.

James


^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 22:31       ` James Bottomley
@ 2024-04-30 22:46         ` Jarkko Sakkinen
  2024-04-30 23:10           ` Jarkko Sakkinen
  2024-05-03 23:18         ` Jarkko Sakkinen
  1 sibling, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-30 22:46 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Wed May 1, 2024 at 1:31 AM EEST, James Bottomley wrote:
> On Wed, 2024-05-01 at 00:48 +0300, Jarkko Sakkinen wrote:
> > On Tue Apr 30, 2024 at 10:23 PM EEST, James Bottomley wrote:
> > > On Tue, 2024-04-30 at 01:22 +0300, Jarkko Sakkinen wrote:
> [...]
> > > > Since I could not find the email subthread I neither have the
> > > > patch nor do know the baseline. So if you could help with these
> > > > details then we can move forward.
> > > > 
> > > > I can also work with QEMU Git fork if you have one and point out
> > > > QEMU_OVERRIDE_SRCDIR to the clone.
> > > 
> > > I only have the patches in a local git repository, but I could push
> > > qemu up onto kernel.org if it would help?
> > 
> > That definitely does help. I can point out my build to that
> > repository, (or actually clone of it).
>
> OK, it's the mssim branch here:
>
> https://git.kernel.org/pub/scm/linux/kernel/git/jejb/qemu.git/log/?h=mssim
>
> It's based on qemu head, but it works for me.
>
> James

OK, cool. I'll test this on Thursday as tomorrow is national holiday
in Finland. However, I'll quickly just try it in my host before going
to sleep (if there is any feedback to be given).

I happen to run Tumbleweed nowadays so I can just install ibmswtpm2
package, i.e. should take only a short while.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 22:46         ` Jarkko Sakkinen
@ 2024-04-30 23:10           ` Jarkko Sakkinen
  0 siblings, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-04-30 23:10 UTC (permalink / raw)
  To: Jarkko Sakkinen, James Bottomley, linux-integrity
  Cc: keyrings, Ard Biesheuvel

On Wed May 1, 2024 at 1:46 AM EEST, Jarkko Sakkinen wrote:
> On Wed May 1, 2024 at 1:31 AM EEST, James Bottomley wrote:
> > On Wed, 2024-05-01 at 00:48 +0300, Jarkko Sakkinen wrote:
> > > On Tue Apr 30, 2024 at 10:23 PM EEST, James Bottomley wrote:
> > > > On Tue, 2024-04-30 at 01:22 +0300, Jarkko Sakkinen wrote:
> > [...]
> > > > > Since I could not find the email subthread I neither have the
> > > > > patch nor do know the baseline. So if you could help with these
> > > > > details then we can move forward.
> > > > > 
> > > > > I can also work with QEMU Git fork if you have one and point out
> > > > > QEMU_OVERRIDE_SRCDIR to the clone.
> > > > 
> > > > I only have the patches in a local git repository, but I could push
> > > > qemu up onto kernel.org if it would help?
> > > 
> > > That definitely does help. I can point out my build to that
> > > repository, (or actually clone of it).
> >
> > OK, it's the mssim branch here:
> >
> > https://git.kernel.org/pub/scm/linux/kernel/git/jejb/qemu.git/log/?h=mssim
> >
> > It's based on qemu head, but it works for me.
> >
> > James
>
> OK, cool. I'll test this on Thursday as tomorrow is national holiday
> in Finland. However, I'll quickly just try it in my host before going
> to sleep (if there is any feedback to be given).
>
> I happen to run Tumbleweed nowadays so I can just install ibmswtpm2
> package, i.e. should take only a short while.

OK, so I got to the point that I can startup a VM with mssim so I'll
do the "final test" Thursday :-)

I have no time to review the qemu patches but you could add my
tested-by if you want to those.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 00/22] add integrity and security to TPM2 transactions
  2024-04-30 22:31       ` James Bottomley
  2024-04-30 22:46         ` Jarkko Sakkinen
@ 2024-05-03 23:18         ` Jarkko Sakkinen
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-03 23:18 UTC (permalink / raw)
  To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel

On Wed May 1, 2024 at 1:31 AM EEST, James Bottomley wrote:
> On Wed, 2024-05-01 at 00:48 +0300, Jarkko Sakkinen wrote:
> > On Tue Apr 30, 2024 at 10:23 PM EEST, James Bottomley wrote:
> > > On Tue, 2024-04-30 at 01:22 +0300, Jarkko Sakkinen wrote:
> [...]
> > > > Since I could not find the email subthread I neither have the
> > > > patch nor do know the baseline. So if you could help with these
> > > > details then we can move forward.
> > > > 
> > > > I can also work with QEMU Git fork if you have one and point out
> > > > QEMU_OVERRIDE_SRCDIR to the clone.
> > > 
> > > I only have the patches in a local git repository, but I could push
> > > qemu up onto kernel.org if it would help?
> > 
> > That definitely does help. I can point out my build to that
> > repository, (or actually clone of it).
>
> OK, it's the mssim branch here:
>
> https://git.kernel.org/pub/scm/linux/kernel/git/jejb/qemu.git/log/?h=mssim
>
> It's based on qemu head, but it works for me.

OK so

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Tested-by: Jarkko Sakkinen <jarkko@kernel.org>

National holiday mixed up this week a bit and I've been preparing also
abstract to ethprague (https://ethprague.com/) which I need to put out
during weekend, thus the delays.

Pretty good timing BTW also considering latest developments in systemd.
Let's stay put for any emerging issues with this through the release
cycle.

If possible, CC me to QEMU patch set iterations. I'll pick these during
the weekend.

Thanks for the good work (and patience in the review cycles)! Awesome
achievement.

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-04-29 20:28 ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() James Bottomley
@ 2024-05-17  0:25   ` Nícolas F. R. A. Prado
  2024-05-17  1:59     ` James Bottomley
  0 siblings, 1 reply; 75+ messages in thread
From: Nícolas F. R. A. Prado @ 2024-05-17  0:25 UTC (permalink / raw)
  To: James Bottomley
  Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel,
	regressions, kernel

On Mon, Apr 29, 2024 at 04:28:07PM -0400, James Bottomley wrote:
> If some entity is snooping the TPM bus, they can see the random
> numbers we're extracting from the TPM and do prediction attacks
> against their consumers.  Foil this attack by using response
> encryption to prevent the attacker from seeing the random sequence.
> 
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
> 
> ---
> v7: add review
> ---
>  drivers/char/tpm/tpm2-cmd.c | 21 +++++++++++++++++----
>  1 file changed, 17 insertions(+), 4 deletions(-)
> 
> diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
> index a53a843294ed..0cdf892ec2a7 100644
> --- a/drivers/char/tpm/tpm2-cmd.c
> +++ b/drivers/char/tpm/tpm2-cmd.c
> @@ -292,25 +292,35 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
>  	if (!num_bytes || max > TPM_MAX_RNG_DATA)
>  		return -EINVAL;
>  
> -	err = tpm_buf_init(&buf, 0, 0);
> +	err = tpm2_start_auth_session(chip);
>  	if (err)
>  		return err;
>  
> +	err = tpm_buf_init(&buf, 0, 0);
> +	if (err) {
> +		tpm2_end_auth_session(chip);
> +		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(chip, &buf, TPM2_SA_ENCRYPT
> +						| TPM2_SA_CONTINUE_SESSION,
> +						NULL, 0);
>  		tpm_buf_append_u16(&buf, num_bytes);
> +		tpm_buf_fill_hmac_session(chip, &buf);
>  		err = tpm_transmit_cmd(chip, &buf,
>  				       offsetof(struct tpm2_get_random_out,
>  						buffer),
>  				       "attempting get random");
> +		err = tpm_buf_check_hmac_response(chip, &buf, 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 +
> @@ -327,9 +337,12 @@ 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(chip);
> +
>  	return total ? total : -EIO;
>  out:
>  	tpm_buf_destroy(&buf);
> +	tpm2_end_auth_session(chip);
>  	return err;
>  }
>  
> -- 
> 2.35.3
> 

Hi,

KernelCI has identified a new warning and I tracked it down to this commit. It
was observed on the following platforms:
* mt8183-kukui-jacuzzi-juniper-sku16
* sc7180-trogdor-kingoftown
(but probably affects all platforms that have a tpm driver with async probe)

The warning is the following:

[    2.017338] ------------[ cut here ]------------
[    2.025521] WARNING: CPU: 0 PID: 72 at kernel/module/kmod.c:144 __request_module+0x188/0x1f4
[    2.039508] Modules linked in:
[    2.046447] CPU: 0 PID: 72 Comm: kworker/u34:3 Not tainted 6.9.0 #1
[    2.046455] Hardware name: Google juniper sku16 board (DT)
[    2.046460] Workqueue: async async_run_entry_fn
[    2.060094]
[    2.060097] pstate: 00000005 (nzcv daif -PAN -UAO -TCO -DIT -SSBS BTYPE=--)
[    2.091758] pc : __request_module+0x188/0x1f4
[    2.096114] lr : __request_module+0x180/0x1f4
[    2.100468] sp : ffff80008088b400
[    2.103777] x29: ffff80008088b400 x28: 0000000000281ae0 x27: ffffa13fd366e0d2
[    2.110915] x26: 0000000000000000 x25: ffff2387008f33c0 x24: 00000000ffffffff
[    2.118053] x23: 000000000000200f x22: ffffa13fd0ed49de x21: 0000000000000001
[    2.125190] x20: 0000000000000000 x19: ffffa13fd23f0be0 x18: 0000000000000014
[    2.132327] x17: 00000000fbdae5e3 x16: 000000005bcbb9f8 x15: 000000008700f694
[    2.139463] x14: 0000000000000001 x13: ffff80008088b850 x12: 0000000000000000
[    2.146600] x11: 00000000f8f4a4bb x10: fffffffffdd186ae x9 : 0000000000000004
[    2.153736] x8 : ffff2387008f33c0 x7 : 3135616873286361 x6 : 0c0406065b07370f
[    2.160873] x5 : 0f37075b0606040c x4 : 0000000000000000 x3 : 0000000000000000
[    2.168009] x2 : ffffa13fd0ed49de x1 : ffffa13fcfcc4768 x0 : 0000000000000001
[    2.175146] Call trace:
[    2.177587]  __request_module+0x188/0x1f4
[    2.181596]  crypto_alg_mod_lookup+0x178/0x21c
[    2.186042]  crypto_alloc_tfm_node+0x58/0x114
[    2.190396]  crypto_alloc_shash+0x24/0x30
[    2.194404]  drbg_init_hash_kernel+0x28/0xdc
[    2.198673]  drbg_kcapi_seed+0x21c/0x420
[    2.202593]  crypto_rng_reset+0x84/0xb4
[    2.206425]  crypto_get_default_rng+0xa4/0xd8
[    2.210779]  ecc_gen_privkey+0x58/0xd0
[    2.214526]  ecdh_set_secret+0x90/0x198
[    2.218360]  tpm_buf_append_salt+0x164/0x2dc
[    2.222632]  tpm2_start_auth_session+0xc8/0x29c
[    2.227162]  tpm2_get_random+0x44/0x204
[    2.230996]  tpm_get_random+0x74/0x90
[    2.234655]  tpm_hwrng_read+0x24/0x30
[    2.238314]  add_early_randomness+0x68/0x118
[    2.242584]  hwrng_register+0x16c/0x218
[    2.246418]  tpm_chip_register+0xf0/0x2cc
[    2.248143] cros-ec-spi spi2.0: SPI transfer timed out
[    2.250419]  tpm_tis_core_init+0x494/0x7e0
[    2.255552] spi_master spi2: failed to transfer one message from queue
[    2.259623]  tpm_tis_spi_init+0x54/0x70
[    2.259629]  cr50_spi_probe+0xf4/0x27c
[    2.266145] spi_master spi2: noqueue transfer failed
[    2.269961]  tpm_tis_spi_driver_probe+0x34/0x64
[    2.273704] cros-ec-spi spi2.0: spi transfer failed: -110
[    2.278647]  spi_probe+0x84/0xe4
[    2.291799]  really_probe+0xbc/0x2a0
[    2.295373]  __driver_probe_device+0x78/0x12c
[    2.299725]  driver_probe_device+0xdc/0x160
[    2.303903]  __device_attach_driver+0xb8/0x134
[    2.308342]  bus_for_each_drv+0x84/0xe0
[    2.312174]  __device_attach_async_helper+0xac/0xd0
[    2.317051]  async_run_entry_fn+0x34/0xe0
[    2.321058]  process_one_work+0x150/0x294
[    2.325068]  worker_thread+0x304/0x408
[    2.328816]  kthread+0x118/0x11c
[    2.332045]  ret_from_fork+0x10/0x20
[    2.335621] ---[ end trace 0000000000000000 ]---

Which is generated in __request_module() here:

	/*
	 * We don't allow synchronous module loading from async.  Module
	 * init may invoke async_synchronize_full() which will end up
	 * waiting for this task which already is waiting for the module
	 * loading to complete, leading to a deadlock.
	 */
	WARN_ON_ONCE(wait && current_is_async());

As the comment says this could lead to a deadlock so it seemed worthwhile to
report and get fixed.

The tpm_tis_spi driver probes asynchronously,

	.probe_type = PROBE_PREFER_ASYNCHRONOUS,

and as part of its probe registers the tpm device which ultimately leads to a
module being requested synchronously in crypto_larval_lookup():

	request_module("crypto-%s-all", name);

and that triggers the warning.

#regzbot introduced: 1b6d7f9eb150
#regzbot title: __request_module warning: sync module loading from async tpm driver probe

Thanks,
Nícolas

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17  0:25   ` Nícolas F. R. A. Prado
@ 2024-05-17  1:59     ` James Bottomley
  2024-05-17  7:20       ` Ard Biesheuvel
  0 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-05-17  1:59 UTC (permalink / raw)
  To: Nícolas F. R. A. Prado
  Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel,
	regressions, kernel

On Thu, 2024-05-16 at 20:25 -0400, Nícolas F. R. A. Prado wrote:
> On Mon, Apr 29, 2024 at 04:28:07PM -0400, James Bottomley wrote:
> > If some entity is snooping the TPM bus, they can see the random
> > numbers we're extracting from the TPM and do prediction attacks
> > against their consumers.  Foil this attack by using response
> > encryption to prevent the attacker from seeing the random sequence.
> > 
> > Signed-off-by: James Bottomley
> > <James.Bottomley@HansenPartnership.com>
> > Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
> > 
> > ---
> > v7: add review
> > ---
> >  drivers/char/tpm/tpm2-cmd.c | 21 +++++++++++++++++----
> >  1 file changed, 17 insertions(+), 4 deletions(-)
> > 
> > diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-
> > cmd.c
> > index a53a843294ed..0cdf892ec2a7 100644
> > --- a/drivers/char/tpm/tpm2-cmd.c
> > +++ b/drivers/char/tpm/tpm2-cmd.c
> > @@ -292,25 +292,35 @@ int tpm2_get_random(struct tpm_chip *chip, u8
> > *dest, size_t max)
> >         if (!num_bytes || max > TPM_MAX_RNG_DATA)
> >                 return -EINVAL;
> >  
> > -       err = tpm_buf_init(&buf, 0, 0);
> > +       err = tpm2_start_auth_session(chip);
> >         if (err)
> >                 return err;
> >  
> > +       err = tpm_buf_init(&buf, 0, 0);
> > +       if (err) {
> > +               tpm2_end_auth_session(chip);
> > +               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(chip, &buf,
> > TPM2_SA_ENCRYPT
> > +                                               |
> > TPM2_SA_CONTINUE_SESSION,
> > +                                               NULL, 0);
> >                 tpm_buf_append_u16(&buf, num_bytes);
> > +               tpm_buf_fill_hmac_session(chip, &buf);
> >                 err = tpm_transmit_cmd(chip, &buf,
> >                                        offsetof(struct
> > tpm2_get_random_out,
> >                                                 buffer),
> >                                        "attempting get random");
> > +               err = tpm_buf_check_hmac_response(chip, &buf, 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 +
> > @@ -327,9 +337,12 @@ 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(chip);
> > +
> >         return total ? total : -EIO;
> >  out:
> >         tpm_buf_destroy(&buf);
> > +       tpm2_end_auth_session(chip);
> >         return err;
> >  }
> >  
> > -- 
> > 2.35.3
> > 
> 
> Hi,
> 
> KernelCI has identified a new warning and I tracked it down to this
> commit. It
> was observed on the following platforms:
> * mt8183-kukui-jacuzzi-juniper-sku16
> * sc7180-trogdor-kingoftown
> (but probably affects all platforms that have a tpm driver with async
> probe)
> 
> The warning is the following:
> 
> [    2.017338] ------------[ cut here ]------------
> [    2.025521] WARNING: CPU: 0 PID: 72 at kernel/module/kmod.c:144
> __request_module+0x188/0x1f4
> [    2.039508] Modules linked in:
> [    2.046447] CPU: 0 PID: 72 Comm: kworker/u34:3 Not tainted 6.9.0
> #1
> [    2.046455] Hardware name: Google juniper sku16 board (DT)
> [    2.046460] Workqueue: async async_run_entry_fn
> [    2.060094]
> [    2.060097] pstate: 00000005 (nzcv daif -PAN -UAO -TCO -DIT -SSBS
> BTYPE=--)
> [    2.091758] pc : __request_module+0x188/0x1f4
> [    2.096114] lr : __request_module+0x180/0x1f4
> [    2.100468] sp : ffff80008088b400
> [    2.103777] x29: ffff80008088b400 x28: 0000000000281ae0 x27:
> ffffa13fd366e0d2
> [    2.110915] x26: 0000000000000000 x25: ffff2387008f33c0 x24:
> 00000000ffffffff
> [    2.118053] x23: 000000000000200f x22: ffffa13fd0ed49de x21:
> 0000000000000001
> [    2.125190] x20: 0000000000000000 x19: ffffa13fd23f0be0 x18:
> 0000000000000014
> [    2.132327] x17: 00000000fbdae5e3 x16: 000000005bcbb9f8 x15:
> 000000008700f694
> [    2.139463] x14: 0000000000000001 x13: ffff80008088b850 x12:
> 0000000000000000
> [    2.146600] x11: 00000000f8f4a4bb x10: fffffffffdd186ae x9 :
> 0000000000000004
> [    2.153736] x8 : ffff2387008f33c0 x7 : 3135616873286361 x6 :
> 0c0406065b07370f
> [    2.160873] x5 : 0f37075b0606040c x4 : 0000000000000000 x3 :
> 0000000000000000
> [    2.168009] x2 : ffffa13fd0ed49de x1 : ffffa13fcfcc4768 x0 :
> 0000000000000001
> [    2.175146] Call trace:
> [    2.177587]  __request_module+0x188/0x1f4
> [    2.181596]  crypto_alg_mod_lookup+0x178/0x21c
> [    2.186042]  crypto_alloc_tfm_node+0x58/0x114
> [    2.190396]  crypto_alloc_shash+0x24/0x30
> [    2.194404]  drbg_init_hash_kernel+0x28/0xdc
> [    2.198673]  drbg_kcapi_seed+0x21c/0x420
> [    2.202593]  crypto_rng_reset+0x84/0xb4
> [    2.206425]  crypto_get_default_rng+0xa4/0xd8
> [    2.210779]  ecc_gen_privkey+0x58/0xd0
> [    2.214526]  ecdh_set_secret+0x90/0x198
> [    2.218360]  tpm_buf_append_salt+0x164/0x2dc

This looks like a misconfiguration.  The kernel is trying to load the
ecdh module, but it should have been selected as built in by this in
drivers/char/tpm/Kconfig:

config TCG_TPM2_HMAC
        bool "Use HMAC and encrypted transactions on the TPM bus"
        default y
        select CRYPTO_ECDH
        select CRYPTO_LIB_AESCFB
        select CRYPTO_LIB_SHA256

Can you check what the status of CONFIG_CRYPTO_ECHD is for your build?

Regards,

James


^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17  1:59     ` James Bottomley
@ 2024-05-17  7:20       ` Ard Biesheuvel
  2024-05-17  8:26         ` Jarkko Sakkinen
  2024-05-17 13:35         ` James Bottomley
  0 siblings, 2 replies; 75+ messages in thread
From: Ard Biesheuvel @ 2024-05-17  7:20 UTC (permalink / raw)
  To: James Bottomley, Linux Crypto Mailing List, Herbert Xu
  Cc: Nícolas F. R. A. Prado, linux-integrity, Jarkko Sakkinen,
	keyrings, regressions, kernel

On Fri, 17 May 2024 at 03:59, James Bottomley
<James.Bottomley@hansenpartnership.com> wrote:
>
> On Thu, 2024-05-16 at 20:25 -0400, Nícolas F. R. A. Prado wrote:
...
> > KernelCI has identified a new warning and I tracked it down to this
> > commit. It
> > was observed on the following platforms:
> > * mt8183-kukui-jacuzzi-juniper-sku16
> > * sc7180-trogdor-kingoftown
> > (but probably affects all platforms that have a tpm driver with async
> > probe)
> >
> > [    2.175146] Call trace:
> > [    2.177587]  __request_module+0x188/0x1f4
> > [    2.181596]  crypto_alg_mod_lookup+0x178/0x21c
> > [    2.186042]  crypto_alloc_tfm_node+0x58/0x114
> > [    2.190396]  crypto_alloc_shash+0x24/0x30
> > [    2.194404]  drbg_init_hash_kernel+0x28/0xdc
> > [    2.198673]  drbg_kcapi_seed+0x21c/0x420
> > [    2.202593]  crypto_rng_reset+0x84/0xb4
> > [    2.206425]  crypto_get_default_rng+0xa4/0xd8
> > [    2.210779]  ecc_gen_privkey+0x58/0xd0
> > [    2.214526]  ecdh_set_secret+0x90/0x198
> > [    2.218360]  tpm_buf_append_salt+0x164/0x2dc
>
> This looks like a misconfiguration.  The kernel is trying to load the
> ecdh module, but it should have been selected as built in by this in
> drivers/char/tpm/Kconfig:
>
> config TCG_TPM2_HMAC
>         bool "Use HMAC and encrypted transactions on the TPM bus"
>         default y
>         select CRYPTO_ECDH
>         select CRYPTO_LIB_AESCFB
>         select CRYPTO_LIB_SHA256
>

The module request is not for ECDH itself but for the DRBG it attempts
to use to generate the secret.

Given that CRYPTO_ECDH does not strictly require a DRBG in principle,
but does in this particular case, I think it makes sense to select
CRYPTO_DRBG here (or depend on it being builtin), rather than updating
the Kconfig rules for CRYPTO_ECDH itself.

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17  7:20       ` Ard Biesheuvel
@ 2024-05-17  8:26         ` Jarkko Sakkinen
  2024-05-17 13:35         ` James Bottomley
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-17  8:26 UTC (permalink / raw)
  To: Ard Biesheuvel, James Bottomley, Linux Crypto Mailing List, Herbert Xu
  Cc: Nícolas F. R. A. Prado, linux-integrity, keyrings,
	regressions, kernel

On Fri May 17, 2024 at 10:20 AM EEST, Ard Biesheuvel wrote:
> On Fri, 17 May 2024 at 03:59, James Bottomley
> <James.Bottomley@hansenpartnership.com> wrote:
> >
> > On Thu, 2024-05-16 at 20:25 -0400, Nícolas F. R. A. Prado wrote:
> ...
> > > KernelCI has identified a new warning and I tracked it down to this
> > > commit. It
> > > was observed on the following platforms:
> > > * mt8183-kukui-jacuzzi-juniper-sku16
> > > * sc7180-trogdor-kingoftown
> > > (but probably affects all platforms that have a tpm driver with async
> > > probe)
> > >
> > > [    2.175146] Call trace:
> > > [    2.177587]  __request_module+0x188/0x1f4
> > > [    2.181596]  crypto_alg_mod_lookup+0x178/0x21c
> > > [    2.186042]  crypto_alloc_tfm_node+0x58/0x114
> > > [    2.190396]  crypto_alloc_shash+0x24/0x30
> > > [    2.194404]  drbg_init_hash_kernel+0x28/0xdc
> > > [    2.198673]  drbg_kcapi_seed+0x21c/0x420
> > > [    2.202593]  crypto_rng_reset+0x84/0xb4
> > > [    2.206425]  crypto_get_default_rng+0xa4/0xd8
> > > [    2.210779]  ecc_gen_privkey+0x58/0xd0
> > > [    2.214526]  ecdh_set_secret+0x90/0x198
> > > [    2.218360]  tpm_buf_append_salt+0x164/0x2dc
> >
> > This looks like a misconfiguration.  The kernel is trying to load the
> > ecdh module, but it should have been selected as built in by this in
> > drivers/char/tpm/Kconfig:
> >
> > config TCG_TPM2_HMAC
> >         bool "Use HMAC and encrypted transactions on the TPM bus"
> >         default y
> >         select CRYPTO_ECDH
> >         select CRYPTO_LIB_AESCFB
> >         select CRYPTO_LIB_SHA256
> >
>
> The module request is not for ECDH itself but for the DRBG it attempts
> to use to generate the secret.
>
> Given that CRYPTO_ECDH does not strictly require a DRBG in principle,
> but does in this particular case, I think it makes sense to select
> CRYPTO_DRBG here (or depend on it being builtin), rather than updating
> the Kconfig rules for CRYPTO_ECDH itself.

I can spin a new PR if James can make a fix.

All previous 4 PR's for 6.10 were applied to Linus' tree so my queue
is empty. Need to have both fixes and stable-tags to save my bandwidth.

Maybe for transcript just two first lines denoting that it was
__request_module() will do. That and adding CONFIG_DRBG will take
it away should be enough for the full disclosure, right?

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17  7:20       ` Ard Biesheuvel
  2024-05-17  8:26         ` Jarkko Sakkinen
@ 2024-05-17 13:35         ` James Bottomley
  2024-05-17 13:43           ` Ard Biesheuvel
  1 sibling, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-05-17 13:35 UTC (permalink / raw)
  To: Ard Biesheuvel, Linux Crypto Mailing List, Herbert Xu
  Cc: Nícolas F. R. A. Prado, linux-integrity, Jarkko Sakkinen,
	keyrings, regressions, kernel

On Fri, 2024-05-17 at 09:20 +0200, Ard Biesheuvel wrote:
> On Fri, 17 May 2024 at 03:59, James Bottomley
> <James.Bottomley@hansenpartnership.com> wrote:
> > 
> > On Thu, 2024-05-16 at 20:25 -0400, Nícolas F. R. A. Prado wrote:
> ...
> > > KernelCI has identified a new warning and I tracked it down to
> > > this
> > > commit. It
> > > was observed on the following platforms:
> > > * mt8183-kukui-jacuzzi-juniper-sku16
> > > * sc7180-trogdor-kingoftown
> > > (but probably affects all platforms that have a tpm driver with
> > > async
> > > probe)
> > > 
> > > [    2.175146] Call trace:
> > > [    2.177587]  __request_module+0x188/0x1f4
> > > [    2.181596]  crypto_alg_mod_lookup+0x178/0x21c
> > > [    2.186042]  crypto_alloc_tfm_node+0x58/0x114
> > > [    2.190396]  crypto_alloc_shash+0x24/0x30
> > > [    2.194404]  drbg_init_hash_kernel+0x28/0xdc
> > > [    2.198673]  drbg_kcapi_seed+0x21c/0x420
> > > [    2.202593]  crypto_rng_reset+0x84/0xb4
> > > [    2.206425]  crypto_get_default_rng+0xa4/0xd8
> > > [    2.210779]  ecc_gen_privkey+0x58/0xd0
> > > [    2.214526]  ecdh_set_secret+0x90/0x198
> > > [    2.218360]  tpm_buf_append_salt+0x164/0x2dc
> > 
> > This looks like a misconfiguration.  The kernel is trying to load
> > the
> > ecdh module, but it should have been selected as built in by this
> > in
> > drivers/char/tpm/Kconfig:
> > 
> > config TCG_TPM2_HMAC
> >         bool "Use HMAC and encrypted transactions on the TPM bus"
> >         default y
> >         select CRYPTO_ECDH
> >         select CRYPTO_LIB_AESCFB
> >         select CRYPTO_LIB_SHA256
> > 
> 
> The module request is not for ECDH itself but for the DRBG it
> attempts
> to use to generate the secret.
> 
> Given that CRYPTO_ECDH does not strictly require a DRBG in principle,
> but does in this particular case, I think it makes sense to select
> CRYPTO_DRBG here (or depend on it being builtin), rather than
> updating the Kconfig rules for CRYPTO_ECDH itself.

Thanks for the analysis.  If I look at how CRYPTO_ECC does it, that
selects CRYPTO_RNG_DEFAULT which pulls in CRYPTO_DRBG, so the fix would
be the attached.  Does that look right to you Ard?  And does it work
Nicolas?

James

---8>8>8><8<8<8---

From 8c60ffd959eaa65627aca6596c35bb9cbfd9bee6 Mon Sep 17 00:00:00 2001
From: James Bottomley <James.Bottomley@HansenPartnership.com>
Date: Fri, 17 May 2024 06:29:31 -0700
Subject: [PATCH] tpm: Fix sessions cryptography requirement for Random Numbers
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The ECDH code in tpm2-sessions.c requires an initial random number
generator to generate the key pair.  If the configuration doesn't have
CONFIG_RNG_DEFAULT, it will try to pull this in as a module (which is
impossible for the early kernel boot where the TPM starts).  Fix this
by selecting the required RNG.

Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/Kconfig | 1 +
 1 file changed, 1 insertion(+)

diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
index 4f83ee7021d0..12065eddb922 100644
--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -31,6 +31,7 @@ config TCG_TPM2_HMAC
 	bool "Use HMAC and encrypted transactions on the TPM bus"
 	default y
 	select CRYPTO_ECDH
+	select CRYTPO_RNG_DEFAULT
 	select CRYPTO_LIB_AESCFB
 	select CRYPTO_LIB_SHA256
 	help
-- 
2.35.3



^ permalink raw reply related	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17 13:35         ` James Bottomley
@ 2024-05-17 13:43           ` Ard Biesheuvel
  2024-05-17 14:25             ` James Bottomley
  0 siblings, 1 reply; 75+ messages in thread
From: Ard Biesheuvel @ 2024-05-17 13:43 UTC (permalink / raw)
  To: James Bottomley
  Cc: Linux Crypto Mailing List, Herbert Xu,
	Nícolas F. R. A. Prado, linux-integrity, Jarkko Sakkinen,
	keyrings, regressions, kernel

On Fri, 17 May 2024 at 15:35, James Bottomley
<James.Bottomley@hansenpartnership.com> wrote:
>
> On Fri, 2024-05-17 at 09:20 +0200, Ard Biesheuvel wrote:
> > On Fri, 17 May 2024 at 03:59, James Bottomley
> > <James.Bottomley@hansenpartnership.com> wrote:
> > >
> > > On Thu, 2024-05-16 at 20:25 -0400, Nícolas F. R. A. Prado wrote:
> > ...
> > > > KernelCI has identified a new warning and I tracked it down to
> > > > this
> > > > commit. It
> > > > was observed on the following platforms:
> > > > * mt8183-kukui-jacuzzi-juniper-sku16
> > > > * sc7180-trogdor-kingoftown
> > > > (but probably affects all platforms that have a tpm driver with
> > > > async
> > > > probe)
> > > >
> > > > [    2.175146] Call trace:
> > > > [    2.177587]  __request_module+0x188/0x1f4
> > > > [    2.181596]  crypto_alg_mod_lookup+0x178/0x21c
> > > > [    2.186042]  crypto_alloc_tfm_node+0x58/0x114
> > > > [    2.190396]  crypto_alloc_shash+0x24/0x30
> > > > [    2.194404]  drbg_init_hash_kernel+0x28/0xdc
> > > > [    2.198673]  drbg_kcapi_seed+0x21c/0x420
> > > > [    2.202593]  crypto_rng_reset+0x84/0xb4
> > > > [    2.206425]  crypto_get_default_rng+0xa4/0xd8
> > > > [    2.210779]  ecc_gen_privkey+0x58/0xd0
> > > > [    2.214526]  ecdh_set_secret+0x90/0x198
> > > > [    2.218360]  tpm_buf_append_salt+0x164/0x2dc
> > >
> > > This looks like a misconfiguration.  The kernel is trying to load
> > > the
> > > ecdh module, but it should have been selected as built in by this
> > > in
> > > drivers/char/tpm/Kconfig:
> > >
> > > config TCG_TPM2_HMAC
> > >         bool "Use HMAC and encrypted transactions on the TPM bus"
> > >         default y
> > >         select CRYPTO_ECDH
> > >         select CRYPTO_LIB_AESCFB
> > >         select CRYPTO_LIB_SHA256
> > >
> >
> > The module request is not for ECDH itself but for the DRBG it
> > attempts
> > to use to generate the secret.
> >
> > Given that CRYPTO_ECDH does not strictly require a DRBG in principle,
> > but does in this particular case, I think it makes sense to select
> > CRYPTO_DRBG here (or depend on it being builtin), rather than
> > updating the Kconfig rules for CRYPTO_ECDH itself.
>
> Thanks for the analysis.  If I look at how CRYPTO_ECC does it, that
> selects CRYPTO_RNG_DEFAULT which pulls in CRYPTO_DRBG, so the fix would
> be the attached.  Does that look right to you Ard?

No it doesn't - it's CRYPTO_RNG_DEFAULT not CRYTPO_RNG_DEFAULT :-)

With that fixed,

Acked-by: Ard Biesheuvel <ardb@kernel.org>



> And does it work
> Nicolas?
>
> James
>
> ---8>8>8><8<8<8---
>
> From 8c60ffd959eaa65627aca6596c35bb9cbfd9bee6 Mon Sep 17 00:00:00 2001
> From: James Bottomley <James.Bottomley@HansenPartnership.com>
> Date: Fri, 17 May 2024 06:29:31 -0700
> Subject: [PATCH] tpm: Fix sessions cryptography requirement for Random Numbers
> MIME-Version: 1.0
> Content-Type: text/plain; charset=UTF-8
> Content-Transfer-Encoding: 8bit
>
> The ECDH code in tpm2-sessions.c requires an initial random number
> generator to generate the key pair.  If the configuration doesn't have
> CONFIG_RNG_DEFAULT, it will try to pull this in as a module (which is
> impossible for the early kernel boot where the TPM starts).  Fix this
> by selecting the required RNG.
>
> Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> ---
>  drivers/char/tpm/Kconfig | 1 +
>  1 file changed, 1 insertion(+)
>
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index 4f83ee7021d0..12065eddb922 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -31,6 +31,7 @@ config TCG_TPM2_HMAC
>         bool "Use HMAC and encrypted transactions on the TPM bus"
>         default y
>         select CRYPTO_ECDH
> +       select CRYTPO_RNG_DEFAULT
>         select CRYPTO_LIB_AESCFB
>         select CRYPTO_LIB_SHA256
>         help
> --
> 2.35.3
>
>

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17 13:43           ` Ard Biesheuvel
@ 2024-05-17 14:25             ` James Bottomley
  2024-05-17 16:22               ` Nícolas F. R. A. Prado
  0 siblings, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-05-17 14:25 UTC (permalink / raw)
  To: Ard Biesheuvel
  Cc: Linux Crypto Mailing List, Herbert Xu,
	Nícolas F. R. A. Prado, linux-integrity, Jarkko Sakkinen,
	keyrings, regressions, kernel

On Fri, 2024-05-17 at 15:43 +0200, Ard Biesheuvel wrote:
> On Fri, 17 May 2024 at 15:35, James Bottomley
> <James.Bottomley@hansenpartnership.com> wrote:
[...]
> > Thanks for the analysis.  If I look at how CRYPTO_ECC does it, that
> > selects CRYPTO_RNG_DEFAULT which pulls in CRYPTO_DRBG, so the fix
> > would be the attached.  Does that look right to you Ard?
> 
> No it doesn't - it's CRYPTO_RNG_DEFAULT not CRYTPO_RNG_DEFAULT :-)
> 
> With that fixed,
> 
> Acked-by: Ard Biesheuvel <ardb@kernel.org>

Erm, oops, sorry about that; so attached is the update.

James

---8>8>8><8<8<8---

From 2ac337a33e6416ef806e2c692b9239d193e8468f Mon Sep 17 00:00:00 2001
From: James Bottomley <James.Bottomley@HansenPartnership.com>
Date: Fri, 17 May 2024 06:29:31 -0700
Subject: [PATCH] tpm: Fix sessions cryptography requirement for Random Numbers
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The ECDH code in tpm2-sessions.c requires an initial random number
generator to generate the key pair.  If the configuration doesn't have
CONFIG_RNG_DEFAULT, it will try to pull this in as a module (which is
impossible for the early kernel boot where the TPM starts).  Fix this
by selecting the required RNG.

Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
Acked-by: Ard Biesheuvel <ardb@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
 drivers/char/tpm/Kconfig | 1 +
 1 file changed, 1 insertion(+)

diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
index 4f83ee7021d0..ecdd3db4be2b 100644
--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -31,6 +31,7 @@ config TCG_TPM2_HMAC
 	bool "Use HMAC and encrypted transactions on the TPM bus"
 	default y
 	select CRYPTO_ECDH
+	select CRYPTO_RNG_DEFAULT
 	select CRYPTO_LIB_AESCFB
 	select CRYPTO_LIB_SHA256
 	help
-- 
2.35.3



^ permalink raw reply related	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17 14:25             ` James Bottomley
@ 2024-05-17 16:22               ` Nícolas F. R. A. Prado
  2024-05-17 16:48                 ` Jarkko Sakkinen
  0 siblings, 1 reply; 75+ messages in thread
From: Nícolas F. R. A. Prado @ 2024-05-17 16:22 UTC (permalink / raw)
  To: James Bottomley
  Cc: Ard Biesheuvel, Linux Crypto Mailing List, Herbert Xu,
	linux-integrity, Jarkko Sakkinen, keyrings, regressions, kernel

On Fri, May 17, 2024 at 07:25:40AM -0700, James Bottomley wrote:
> On Fri, 2024-05-17 at 15:43 +0200, Ard Biesheuvel wrote:
> > On Fri, 17 May 2024 at 15:35, James Bottomley
> > <James.Bottomley@hansenpartnership.com> wrote:
> [...]
> > > Thanks for the analysis.  If I look at how CRYPTO_ECC does it, that
> > > selects CRYPTO_RNG_DEFAULT which pulls in CRYPTO_DRBG, so the fix
> > > would be the attached.  Does that look right to you Ard?
> > 
> > No it doesn't - it's CRYPTO_RNG_DEFAULT not CRYTPO_RNG_DEFAULT :-)
> > 
> > With that fixed,
> > 
> > Acked-by: Ard Biesheuvel <ardb@kernel.org>
> 
> Erm, oops, sorry about that; so attached is the update.
> 
> James
> 
> ---8>8>8><8<8<8---
> 
> From 2ac337a33e6416ef806e2c692b9239d193e8468f Mon Sep 17 00:00:00 2001
> From: James Bottomley <James.Bottomley@HansenPartnership.com>
> Date: Fri, 17 May 2024 06:29:31 -0700
> Subject: [PATCH] tpm: Fix sessions cryptography requirement for Random Numbers
> MIME-Version: 1.0
> Content-Type: text/plain; charset=UTF-8
> Content-Transfer-Encoding: 8bit
> 
> The ECDH code in tpm2-sessions.c requires an initial random number
> generator to generate the key pair.  If the configuration doesn't have
> CONFIG_RNG_DEFAULT, it will try to pull this in as a module (which is
> impossible for the early kernel boot where the TPM starts).  Fix this
> by selecting the required RNG.
> 
> Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
> Acked-by: Ard Biesheuvel <ardb@kernel.org>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> ---
>  drivers/char/tpm/Kconfig | 1 +
>  1 file changed, 1 insertion(+)
> 
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index 4f83ee7021d0..ecdd3db4be2b 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -31,6 +31,7 @@ config TCG_TPM2_HMAC
>  	bool "Use HMAC and encrypted transactions on the TPM bus"
>  	default y
>  	select CRYPTO_ECDH
> +	select CRYPTO_RNG_DEFAULT
>  	select CRYPTO_LIB_AESCFB
>  	select CRYPTO_LIB_SHA256
>  	help
> -- 
> 2.35.3
> 
> 

Hi James,

thanks for the patch. But I actually already had that config enabled builtin. I
also had ECDH and DRBG which have been suggested previously:

	CONFIG_CRYPTO_RNG_DEFAULT=y

	CONFIG_CRYPTO_DRBG_MENU=y
	CONFIG_CRYPTO_DRBG_HMAC=y
	# CONFIG_CRYPTO_DRBG_HASH is not set
	# CONFIG_CRYPTO_DRBG_CTR is not set
	CONFIG_CRYPTO_DRBG=y

	CONFIG_CRYPTO_ECDH=y

I've pasted my full config here: http://0x0.st/XPN_.txt

Adding a debug print I see that the module that the code tries to load is
"crypto-hmac(sha512)". I would have expected to see 

	MODULE_ALIAS_CRYPTO("hmac(sha512)");

in crypto/drbg.c, but I don't see it anywhere in the tree. Maybe it is missing?

Thanks,
Nícolas

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17 16:22               ` Nícolas F. R. A. Prado
@ 2024-05-17 16:48                 ` Jarkko Sakkinen
  2024-05-18  4:31                   ` Eric Biggers
  0 siblings, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-17 16:48 UTC (permalink / raw)
  To: Nícolas F. R. A. Prado, James Bottomley
  Cc: Ard Biesheuvel, Linux Crypto Mailing List, Herbert Xu,
	linux-integrity, keyrings, regressions, kernel

On Fri May 17, 2024 at 7:22 PM EEST, Nícolas F. R. A. Prado wrote:
> On Fri, May 17, 2024 at 07:25:40AM -0700, James Bottomley wrote:
> > On Fri, 2024-05-17 at 15:43 +0200, Ard Biesheuvel wrote:
> > > On Fri, 17 May 2024 at 15:35, James Bottomley
> > > <James.Bottomley@hansenpartnership.com> wrote:
> > [...]
> > > > Thanks for the analysis.  If I look at how CRYPTO_ECC does it, that
> > > > selects CRYPTO_RNG_DEFAULT which pulls in CRYPTO_DRBG, so the fix
> > > > would be the attached.  Does that look right to you Ard?
> > > 
> > > No it doesn't - it's CRYPTO_RNG_DEFAULT not CRYTPO_RNG_DEFAULT :-)
> > > 
> > > With that fixed,
> > > 
> > > Acked-by: Ard Biesheuvel <ardb@kernel.org>
> > 
> > Erm, oops, sorry about that; so attached is the update.
> > 
> > James
> > 
> > ---8>8>8><8<8<8---
> > 
> > From 2ac337a33e6416ef806e2c692b9239d193e8468f Mon Sep 17 00:00:00 2001
> > From: James Bottomley <James.Bottomley@HansenPartnership.com>
> > Date: Fri, 17 May 2024 06:29:31 -0700
> > Subject: [PATCH] tpm: Fix sessions cryptography requirement for Random Numbers
> > MIME-Version: 1.0
> > Content-Type: text/plain; charset=UTF-8
> > Content-Transfer-Encoding: 8bit
> > 
> > The ECDH code in tpm2-sessions.c requires an initial random number
> > generator to generate the key pair.  If the configuration doesn't have
> > CONFIG_RNG_DEFAULT, it will try to pull this in as a module (which is
> > impossible for the early kernel boot where the TPM starts).  Fix this
> > by selecting the required RNG.
> > 
> > Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> > Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
> > Acked-by: Ard Biesheuvel <ardb@kernel.org>
> > Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> > ---
> >  drivers/char/tpm/Kconfig | 1 +
> >  1 file changed, 1 insertion(+)
> > 
> > diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> > index 4f83ee7021d0..ecdd3db4be2b 100644
> > --- a/drivers/char/tpm/Kconfig
> > +++ b/drivers/char/tpm/Kconfig
> > @@ -31,6 +31,7 @@ config TCG_TPM2_HMAC
> >  	bool "Use HMAC and encrypted transactions on the TPM bus"
> >  	default y
> >  	select CRYPTO_ECDH
> > +	select CRYPTO_RNG_DEFAULT
> >  	select CRYPTO_LIB_AESCFB
> >  	select CRYPTO_LIB_SHA256
> >  	help
> > -- 
> > 2.35.3
> > 
> > 
>
> Hi James,
>
> thanks for the patch. But I actually already had that config enabled builtin. I
> also had ECDH and DRBG which have been suggested previously:
>
> 	CONFIG_CRYPTO_RNG_DEFAULT=y
>
> 	CONFIG_CRYPTO_DRBG_MENU=y
> 	CONFIG_CRYPTO_DRBG_HMAC=y
> 	# CONFIG_CRYPTO_DRBG_HASH is not set
> 	# CONFIG_CRYPTO_DRBG_CTR is not set
> 	CONFIG_CRYPTO_DRBG=y
>
> 	CONFIG_CRYPTO_ECDH=y
>
> I've pasted my full config here: http://0x0.st/XPN_.txt
>
> Adding a debug print I see that the module that the code tries to load is
> "crypto-hmac(sha512)". I would have expected to see 
>
> 	MODULE_ALIAS_CRYPTO("hmac(sha512)");
>
> in crypto/drbg.c, but I don't see it anywhere in the tree. Maybe it is missing?

1. Bug fixes need to be submitted as described in
   https://www.kernel.org/doc/html/latest/process/submitting-patches.html
2. The patch is missing the transcript:
   https://lore.kernel.org/linux-integrity/D1BRZ60B9O5S.3NAT20QPQE6KH@kernel.org/

There's nothing to review at this point.

>
> Thanks,
> Nícolas

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-17 16:48                 ` Jarkko Sakkinen
@ 2024-05-18  4:31                   ` Eric Biggers
  2024-05-18  7:03                     ` [PATCH] crypto: api - Do not load modules until algapi is ready Herbert Xu
  2024-05-18 10:56                     ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() Jarkko Sakkinen
  0 siblings, 2 replies; 75+ messages in thread
From: Eric Biggers @ 2024-05-18  4:31 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Nícolas F. R. A. Prado, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, Herbert Xu, linux-integrity, keyrings,
	regressions, kernel

On Fri, May 17, 2024 at 07:48:48PM +0300, Jarkko Sakkinen wrote:
> On Fri May 17, 2024 at 7:22 PM EEST, Nícolas F. R. A. Prado wrote:
> > On Fri, May 17, 2024 at 07:25:40AM -0700, James Bottomley wrote:
> > > On Fri, 2024-05-17 at 15:43 +0200, Ard Biesheuvel wrote:
> > > > On Fri, 17 May 2024 at 15:35, James Bottomley
> > > > <James.Bottomley@hansenpartnership.com> wrote:
> > > [...]
> > > > > Thanks for the analysis.  If I look at how CRYPTO_ECC does it, that
> > > > > selects CRYPTO_RNG_DEFAULT which pulls in CRYPTO_DRBG, so the fix
> > > > > would be the attached.  Does that look right to you Ard?
> > > > 
> > > > No it doesn't - it's CRYPTO_RNG_DEFAULT not CRYTPO_RNG_DEFAULT :-)
> > > > 
> > > > With that fixed,
> > > > 
> > > > Acked-by: Ard Biesheuvel <ardb@kernel.org>
> > > 
> > > Erm, oops, sorry about that; so attached is the update.
> > > 
> > > James
> > > 
> > > ---8>8>8><8<8<8---
> > > 
> > > From 2ac337a33e6416ef806e2c692b9239d193e8468f Mon Sep 17 00:00:00 2001
> > > From: James Bottomley <James.Bottomley@HansenPartnership.com>
> > > Date: Fri, 17 May 2024 06:29:31 -0700
> > > Subject: [PATCH] tpm: Fix sessions cryptography requirement for Random Numbers
> > > MIME-Version: 1.0
> > > Content-Type: text/plain; charset=UTF-8
> > > Content-Transfer-Encoding: 8bit
> > > 
> > > The ECDH code in tpm2-sessions.c requires an initial random number
> > > generator to generate the key pair.  If the configuration doesn't have
> > > CONFIG_RNG_DEFAULT, it will try to pull this in as a module (which is
> > > impossible for the early kernel boot where the TPM starts).  Fix this
> > > by selecting the required RNG.
> > > 
> > > Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> > > Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
> > > Acked-by: Ard Biesheuvel <ardb@kernel.org>
> > > Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> > > ---
> > >  drivers/char/tpm/Kconfig | 1 +
> > >  1 file changed, 1 insertion(+)
> > > 
> > > diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> > > index 4f83ee7021d0..ecdd3db4be2b 100644
> > > --- a/drivers/char/tpm/Kconfig
> > > +++ b/drivers/char/tpm/Kconfig
> > > @@ -31,6 +31,7 @@ config TCG_TPM2_HMAC
> > >  	bool "Use HMAC and encrypted transactions on the TPM bus"
> > >  	default y
> > >  	select CRYPTO_ECDH
> > > +	select CRYPTO_RNG_DEFAULT
> > >  	select CRYPTO_LIB_AESCFB
> > >  	select CRYPTO_LIB_SHA256
> > >  	help
> > > -- 
> > > 2.35.3
> > > 
> > > 
> >
> > Hi James,
> >
> > thanks for the patch. But I actually already had that config enabled builtin. I
> > also had ECDH and DRBG which have been suggested previously:
> >
> > 	CONFIG_CRYPTO_RNG_DEFAULT=y
> >
> > 	CONFIG_CRYPTO_DRBG_MENU=y
> > 	CONFIG_CRYPTO_DRBG_HMAC=y
> > 	# CONFIG_CRYPTO_DRBG_HASH is not set
> > 	# CONFIG_CRYPTO_DRBG_CTR is not set
> > 	CONFIG_CRYPTO_DRBG=y
> >
> > 	CONFIG_CRYPTO_ECDH=y
> >
> > I've pasted my full config here: http://0x0.st/XPN_.txt
> >
> > Adding a debug print I see that the module that the code tries to load is
> > "crypto-hmac(sha512)". I would have expected to see 
> >
> > 	MODULE_ALIAS_CRYPTO("hmac(sha512)");
> >
> > in crypto/drbg.c, but I don't see it anywhere in the tree. Maybe it is missing?
> 

This is "normal" behavior when the crypto API instantiates a template:

    1. drbg.c asks for "hmac(sha512)"

    2. The crypto API looks for a direct implementation of "hmac(sha512)".
       This includes requesting a module with alias "crypto-hmac(sha512)".

    3. If none is found, the "hmac" template is instantiated instead.

There are two possible fixes for the bug.  Either fix ecc_gen_privkey() to just
use get_random_bytes() instead of the weird crypto API RNG, or make
drbg_init_hash_kernel() pass the CRYPTO_NOLOAD flag to crypto_alloc_shash().

Or if the TPM driver could be changed to not need to generate an ECC private key
at probe time, that would also avoid this problem.

- Eric

^ permalink raw reply	[flat|nested] 75+ messages in thread

* [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18  4:31                   ` Eric Biggers
@ 2024-05-18  7:03                     ` Herbert Xu
  2024-05-18 11:04                       ` Jarkko Sakkinen
  2024-05-20 15:49                       ` Nícolas F. R. A. Prado
  2024-05-18 10:56                     ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() Jarkko Sakkinen
  1 sibling, 2 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-18  7:03 UTC (permalink / raw)
  To: Eric Biggers
  Cc: Jarkko Sakkinen, Nícolas F. R. A. Prado, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel

On Fri, May 17, 2024 at 09:31:15PM -0700, Eric Biggers wrote:
>
> This is "normal" behavior when the crypto API instantiates a template:
> 
>     1. drbg.c asks for "hmac(sha512)"
> 
>     2. The crypto API looks for a direct implementation of "hmac(sha512)".
>        This includes requesting a module with alias "crypto-hmac(sha512)".
> 
>     3. If none is found, the "hmac" template is instantiated instead.
> 
> There are two possible fixes for the bug.  Either fix ecc_gen_privkey() to just
> use get_random_bytes() instead of the weird crypto API RNG, or make
> drbg_init_hash_kernel() pass the CRYPTO_NOLOAD flag to crypto_alloc_shash().
> 
> Or if the TPM driver could be changed to not need to generate an ECC private key
> at probe time, that would also avoid this problem.

Thanks for diagnosing the problem.  This is easy to fix though,
we could simply reuse the static branch that was created for
boot-time self-testing:

---8<---
When the Crypto API is built into the kernel, it may be invoked
during system initialisation before modules can be loaded.  Ensure
that it doesn't load modules if this is the case by checking
crypto_boot_test_finished().

Add a call to wait_for_device_probe so that the drivers that may
call into the Crypto API have finished probing.

Reported-by: Nícolas F. R. A. Prado" <nfraprado@collabora.com>
Reported-by: Eric Biggers <ebiggers@kernel.org>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>

diff --git a/crypto/algapi.c b/crypto/algapi.c
index 85bc279b4233..c018bcbd1f46 100644
--- a/crypto/algapi.c
+++ b/crypto/algapi.c
@@ -7,6 +7,7 @@
 
 #include <crypto/algapi.h>
 #include <crypto/internal/simd.h>
+#include <linux/device/driver.h>
 #include <linux/err.h>
 #include <linux/errno.h>
 #include <linux/fips.h>
@@ -1056,9 +1057,12 @@ EXPORT_SYMBOL_GPL(crypto_type_has_alg);
 
 static void __init crypto_start_tests(void)
 {
-	if (IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS))
+	if (!IS_BUILTIN(CONFIG_CRYPTO_ALGAPI))
 		return;
 
+	if (IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS))
+		goto test_done;
+
 	for (;;) {
 		struct crypto_larval *larval = NULL;
 		struct crypto_alg *q;
@@ -1092,6 +1096,8 @@ static void __init crypto_start_tests(void)
 		crypto_wait_for_test(larval);
 	}
 
+test_done:
+	wait_for_device_probe();
 	set_crypto_boot_test_finished();
 }
 
diff --git a/crypto/api.c b/crypto/api.c
index 6aa5a3b4ed5e..5c970af04ba9 100644
--- a/crypto/api.c
+++ b/crypto/api.c
@@ -31,9 +31,8 @@ EXPORT_SYMBOL_GPL(crypto_alg_sem);
 BLOCKING_NOTIFIER_HEAD(crypto_chain);
 EXPORT_SYMBOL_GPL(crypto_chain);
 
-#ifndef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
+#if IS_BUILTIN(CONFIG_CRYPTO_ALGAPI)
 DEFINE_STATIC_KEY_FALSE(__crypto_boot_test_finished);
-EXPORT_SYMBOL_GPL(__crypto_boot_test_finished);
 #endif
 
 static struct crypto_alg *crypto_larval_wait(struct crypto_alg *alg);
@@ -280,7 +279,7 @@ static struct crypto_alg *crypto_larval_lookup(const char *name, u32 type,
 	mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
 
 	alg = crypto_alg_lookup(name, type, mask);
-	if (!alg && !(mask & CRYPTO_NOLOAD)) {
+	if (crypto_boot_test_finished() && !alg && !(mask & CRYPTO_NOLOAD)) {
 		request_module("crypto-%s", name);
 
 		if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
diff --git a/crypto/internal.h b/crypto/internal.h
index 63e59240d5fb..d27166a92eca 100644
--- a/crypto/internal.h
+++ b/crypto/internal.h
@@ -66,7 +66,7 @@ extern struct blocking_notifier_head crypto_chain;
 
 int alg_test(const char *driver, const char *alg, u32 type, u32 mask);
 
-#ifdef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
+#if !IS_BUILTIN(CONFIG_CRYPTO_ALGAPI)
 static inline bool crypto_boot_test_finished(void)
 {
 	return true;
@@ -84,7 +84,7 @@ static inline void set_crypto_boot_test_finished(void)
 {
 	static_branch_enable(&__crypto_boot_test_finished);
 }
-#endif /* !CONFIG_CRYPTO_MANAGER_DISABLE_TESTS */
+#endif /* !IS_BUILTIN(CONFIG_CRYPTO_ALGAPI) */
 
 #ifdef CONFIG_PROC_FS
 void __init crypto_init_proc(void);
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply related	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-18  4:31                   ` Eric Biggers
  2024-05-18  7:03                     ` [PATCH] crypto: api - Do not load modules until algapi is ready Herbert Xu
@ 2024-05-18 10:56                     ` Jarkko Sakkinen
  2024-05-18 12:31                       ` Herbert Xu
  1 sibling, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-18 10:56 UTC (permalink / raw)
  To: Eric Biggers
  Cc: Nícolas F. R. A. Prado, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, Herbert Xu, linux-integrity, keyrings,
	regressions, kernel

On Sat May 18, 2024 at 7:31 AM EEST, Eric Biggers wrote:
> This is "normal" behavior when the crypto API instantiates a template:
>
>     1. drbg.c asks for "hmac(sha512)"
>
>     2. The crypto API looks for a direct implementation of "hmac(sha512)".
>        This includes requesting a module with alias "crypto-hmac(sha512)".
>
>     3. If none is found, the "hmac" template is instantiated instead.
>
> There are two possible fixes for the bug.  Either fix ecc_gen_privkey() to just
> use get_random_bytes() instead of the weird crypto API RNG, or make
> drbg_init_hash_kernel() pass the CRYPTO_NOLOAD flag to crypto_alloc_shash().
>
> Or if the TPM driver could be changed to not need to generate an ECC private key
> at probe time, that would also avoid this problem.

Issues:

- IMA extends PCR's. This requires encrypted communications path.
- HWRNG uses auth session (see tpm2_get_radom()).
- TPM trusted keys

Null key is required before any other legit use in initialization.

Even something like 

--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -36,6 +36,8 @@ config TCG_TPM2_HMAC
        bool "Use HMAC and encrypted transactions on the TPM bus"
        default y
+       select CRYPTO_DRBG
        select CRYPTO_ECDH
+       select CRYPTO_HMAC
+       select CRYPTO_SHA512
        select CRYPTO_LIB_AESCFB
        select CRYPTO_LIB_SHA256
        help

would be more decent.

>
> - Eric

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18  7:03                     ` [PATCH] crypto: api - Do not load modules until algapi is ready Herbert Xu
@ 2024-05-18 11:04                       ` Jarkko Sakkinen
  2024-05-18 12:32                         ` Herbert Xu
  2024-05-20 15:49                       ` Nícolas F. R. A. Prado
  1 sibling, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-18 11:04 UTC (permalink / raw)
  To: Herbert Xu, Eric Biggers
  Cc: Nícolas F. R. A. Prado, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel

On Sat May 18, 2024 at 10:03 AM EEST, Herbert Xu wrote:
> When the Crypto API is built into the kernel, it may be invoked
> during system initialisation before modules can be loaded.  Ensure
> that it doesn't load modules if this is the case by checking
> crypto_boot_test_finished().
>
> Add a call to wait_for_device_probe so that the drivers that may
> call into the Crypto API have finished probing.
>
> Reported-by: Nícolas F. R. A. Prado" <nfraprado@collabora.com>
> Reported-by: Eric Biggers <ebiggers@kernel.org>
> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>

Right does this mean for TPM driver that a crypto API invocation not
having everthing needed loaded will block until this is not the case?

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random()
  2024-05-18 10:56                     ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() Jarkko Sakkinen
@ 2024-05-18 12:31                       ` Herbert Xu
  0 siblings, 0 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-18 12:31 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Eric Biggers, Nícolas F. R. A. Prado, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel

On Sat, May 18, 2024 at 01:56:44PM +0300, Jarkko Sakkinen wrote:
>
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -36,6 +36,8 @@ config TCG_TPM2_HMAC
>         bool "Use HMAC and encrypted transactions on the TPM bus"
>         default y
> +       select CRYPTO_DRBG
>         select CRYPTO_ECDH
> +       select CRYPTO_HMAC
> +       select CRYPTO_SHA512
>         select CRYPTO_LIB_AESCFB
>         select CRYPTO_LIB_SHA256
>         help

This isn't necessary because ECDH selects ECC which already
selects the DRBG and all the required algorithms.

You can verify this with the failing .config file as it has
everything needed built into the kernel (which is in fact
where the problem is).

Cheers,
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18 11:04                       ` Jarkko Sakkinen
@ 2024-05-18 12:32                         ` Herbert Xu
  2024-05-18 13:03                           ` Jarkko Sakkinen
  2024-05-18 13:07                           ` James Bottomley
  0 siblings, 2 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-18 12:32 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Eric Biggers, Nícolas F. R. A. Prado, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel

On Sat, May 18, 2024 at 02:04:18PM +0300, Jarkko Sakkinen wrote:
>
> Right does this mean for TPM driver that a crypto API invocation not
> having everthing needed loaded will block until this is not the case?

All this does is disable module loading by the Crypto API (because
there is no point and it may deadlock) until such a point where
all/most drivers have finished loading.

So if the algorithm is missing (which shouldn't happen because of
Kconfig selects), then it will simply fail.

Cheers,
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18 12:32                         ` Herbert Xu
@ 2024-05-18 13:03                           ` Jarkko Sakkinen
  2024-05-18 13:07                           ` James Bottomley
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-18 13:03 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Eric Biggers, Nícolas F. R. A. Prado, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel

On Sat May 18, 2024 at 3:32 PM EEST, Herbert Xu wrote:
> On Sat, May 18, 2024 at 02:04:18PM +0300, Jarkko Sakkinen wrote:
> >
> > Right does this mean for TPM driver that a crypto API invocation not
> > having everthing needed loaded will block until this is not the case?
>
> All this does is disable module loading by the Crypto API (because
> there is no point and it may deadlock) until such a point where
> all/most drivers have finished loading.
>
> So if the algorithm is missing (which shouldn't happen because of
> Kconfig selects), then it will simply fail.
>
> Cheers,

Ok, you can add

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18 12:32                         ` Herbert Xu
  2024-05-18 13:03                           ` Jarkko Sakkinen
@ 2024-05-18 13:07                           ` James Bottomley
  2024-05-19  4:19                             ` Herbert Xu
  1 sibling, 1 reply; 75+ messages in thread
From: James Bottomley @ 2024-05-18 13:07 UTC (permalink / raw)
  To: Herbert Xu, Jarkko Sakkinen
  Cc: Eric Biggers, Nícolas F. R. A. Prado, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel

On May 18, 2024 5:32:56 AM PDT, Herbert Xu <herbert@gondor.apana.org.au> wrote:
>On Sat, May 18, 2024 at 02:04:18PM +0300, Jarkko Sakkinen wrote:
>>
>> Right does this mean for TPM driver that a crypto API invocation not
>> having everthing needed loaded will block until this is not the case?
>
>All this does is disable module loading by the Crypto API (because
>there is no point and it may deadlock) until such a point where
>all/most drivers have finished loading.
>
>So if the algorithm is missing (which shouldn't happen because of
>Kconfig selects), then it will simply fail.

I have a curiosity question: if Eric is right and it's looking for an optional hmac accelerator module, why don't I see this?  The only real config difference between what I tested and what Nicholas did is he's arm and I'm x86.

James

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18 13:07                           ` James Bottomley
@ 2024-05-19  4:19                             ` Herbert Xu
  0 siblings, 0 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-19  4:19 UTC (permalink / raw)
  To: James Bottomley
  Cc: Jarkko Sakkinen, Eric Biggers, Nícolas F. R. A. Prado,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel

On Sat, May 18, 2024 at 06:07:39AM -0700, James Bottomley wrote:
>
> I have a curiosity question: if Eric is right and it's looking for an optional hmac accelerator module, why don't I see this?  The only real config difference between what I tested and what Nicholas did is he's arm and I'm x86.

It depends on your kernel config.  Perhaps you didn't build the
TPM driver into the kernel?

It's not an issue with an optional algorithm that's not included.

It's the fact the Crypto API tries to load a module for any
algorithm that requires instantiation (anything with "()" in its
name).

Cheers,
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [PATCH] crypto: api - Do not load modules until algapi is ready
  2024-05-18  7:03                     ` [PATCH] crypto: api - Do not load modules until algapi is ready Herbert Xu
  2024-05-18 11:04                       ` Jarkko Sakkinen
@ 2024-05-20 15:49                       ` Nícolas F. R. A. Prado
  2024-05-21  2:53                         ` [v2 PATCH] crypto: api - Do not load modules if called by async probing Herbert Xu
  1 sibling, 1 reply; 75+ messages in thread
From: Nícolas F. R. A. Prado @ 2024-05-20 15:49 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Eric Biggers, Jarkko Sakkinen, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel

On Sat, May 18, 2024 at 03:03:51PM +0800, Herbert Xu wrote:
> On Fri, May 17, 2024 at 09:31:15PM -0700, Eric Biggers wrote:
> >
> > This is "normal" behavior when the crypto API instantiates a template:
> > 
> >     1. drbg.c asks for "hmac(sha512)"
> > 
> >     2. The crypto API looks for a direct implementation of "hmac(sha512)".
> >        This includes requesting a module with alias "crypto-hmac(sha512)".
> > 
> >     3. If none is found, the "hmac" template is instantiated instead.
> > 
> > There are two possible fixes for the bug.  Either fix ecc_gen_privkey() to just
> > use get_random_bytes() instead of the weird crypto API RNG, or make
> > drbg_init_hash_kernel() pass the CRYPTO_NOLOAD flag to crypto_alloc_shash().
> > 
> > Or if the TPM driver could be changed to not need to generate an ECC private key
> > at probe time, that would also avoid this problem.
> 
> Thanks for diagnosing the problem.  This is easy to fix though,
> we could simply reuse the static branch that was created for
> boot-time self-testing:
> 
> ---8<---
> When the Crypto API is built into the kernel, it may be invoked
> during system initialisation before modules can be loaded.  Ensure
> that it doesn't load modules if this is the case by checking
> crypto_boot_test_finished().
> 
> Add a call to wait_for_device_probe so that the drivers that may
> call into the Crypto API have finished probing.
> 
> Reported-by: Nícolas F. R. A. Prado" <nfraprado@collabora.com>
> Reported-by: Eric Biggers <ebiggers@kernel.org>
> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
> 
> diff --git a/crypto/algapi.c b/crypto/algapi.c
> index 85bc279b4233..c018bcbd1f46 100644
> --- a/crypto/algapi.c
> +++ b/crypto/algapi.c
> @@ -7,6 +7,7 @@
>  
>  #include <crypto/algapi.h>
>  #include <crypto/internal/simd.h>
> +#include <linux/device/driver.h>
>  #include <linux/err.h>
>  #include <linux/errno.h>
>  #include <linux/fips.h>
> @@ -1056,9 +1057,12 @@ EXPORT_SYMBOL_GPL(crypto_type_has_alg);
>  
>  static void __init crypto_start_tests(void)
>  {
> -	if (IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS))
> +	if (!IS_BUILTIN(CONFIG_CRYPTO_ALGAPI))
>  		return;
>  
> +	if (IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS))
> +		goto test_done;
> +
>  	for (;;) {
>  		struct crypto_larval *larval = NULL;
>  		struct crypto_alg *q;
> @@ -1092,6 +1096,8 @@ static void __init crypto_start_tests(void)
>  		crypto_wait_for_test(larval);
>  	}
>  
> +test_done:
> +	wait_for_device_probe();
>  	set_crypto_boot_test_finished();
>  }
>  
> diff --git a/crypto/api.c b/crypto/api.c
> index 6aa5a3b4ed5e..5c970af04ba9 100644
> --- a/crypto/api.c
> +++ b/crypto/api.c
> @@ -31,9 +31,8 @@ EXPORT_SYMBOL_GPL(crypto_alg_sem);
>  BLOCKING_NOTIFIER_HEAD(crypto_chain);
>  EXPORT_SYMBOL_GPL(crypto_chain);
>  
> -#ifndef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
> +#if IS_BUILTIN(CONFIG_CRYPTO_ALGAPI)
>  DEFINE_STATIC_KEY_FALSE(__crypto_boot_test_finished);
> -EXPORT_SYMBOL_GPL(__crypto_boot_test_finished);
>  #endif
>  
>  static struct crypto_alg *crypto_larval_wait(struct crypto_alg *alg);
> @@ -280,7 +279,7 @@ static struct crypto_alg *crypto_larval_lookup(const char *name, u32 type,
>  	mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
>  
>  	alg = crypto_alg_lookup(name, type, mask);
> -	if (!alg && !(mask & CRYPTO_NOLOAD)) {
> +	if (crypto_boot_test_finished() && !alg && !(mask & CRYPTO_NOLOAD)) {
>  		request_module("crypto-%s", name);
>  
>  		if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
> diff --git a/crypto/internal.h b/crypto/internal.h
> index 63e59240d5fb..d27166a92eca 100644
> --- a/crypto/internal.h
> +++ b/crypto/internal.h
> @@ -66,7 +66,7 @@ extern struct blocking_notifier_head crypto_chain;
>  
>  int alg_test(const char *driver, const char *alg, u32 type, u32 mask);
>  
> -#ifdef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
> +#if !IS_BUILTIN(CONFIG_CRYPTO_ALGAPI)
>  static inline bool crypto_boot_test_finished(void)
>  {
>  	return true;
> @@ -84,7 +84,7 @@ static inline void set_crypto_boot_test_finished(void)
>  {
>  	static_branch_enable(&__crypto_boot_test_finished);
>  }
> -#endif /* !CONFIG_CRYPTO_MANAGER_DISABLE_TESTS */
> +#endif /* !IS_BUILTIN(CONFIG_CRYPTO_ALGAPI) */
>  
>  #ifdef CONFIG_PROC_FS
>  void __init crypto_init_proc(void);
> -- 

Hi Herbert,

Unfortunately this patch didn't work either. The warning is still there
unchanged.

The warning is triggered by a driver that probes asynchronously registering a
TPM device, which ends up requesting a module to be loaded synchronously. So I
don't think waiting would even help here. I believe one possible solution would
be to request the module asynchronously and defer probe. Not ideal but I think
would work.

Alternatively, could the initialization code that loads this module
(hmac(sha512)) be run synchronously before the TPM device is registered? Or is
it device specific?

PS: the wait_for_device_probe() call in the patch didn't actually wait for
anything in this case since when the crypto tests code ran there weren't any
probes in progress

Thanks,
Nícolas

^ permalink raw reply	[flat|nested] 75+ messages in thread

* [v2 PATCH] crypto: api - Do not load modules if called by async probing
  2024-05-20 15:49                       ` Nícolas F. R. A. Prado
@ 2024-05-21  2:53                         ` Herbert Xu
  2024-05-21 19:37                           ` Nícolas F. R. A. Prado
  0 siblings, 1 reply; 75+ messages in thread
From: Herbert Xu @ 2024-05-21  2:53 UTC (permalink / raw)
  To: Nícolas F. R. A. Prado
  Cc: Eric Biggers, Jarkko Sakkinen, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel, Linus Torvalds, Tejun Heo,
	Linux Kernel Mailing List

On Mon, May 20, 2024 at 11:49:56AM -0400, Nícolas F. R. A. Prado wrote:
>
> Unfortunately this patch didn't work either. The warning is still there
> unchanged.

OK perhaps we can do it by calling current_is_async ourselves.
But this is really a nasty hack because it basically defeats
the whole point of loading optional algorithm by module.

Linus/Tejun, is it time perhaps to remove the warning introduced
by commit 0fdff3ec6d87856cdcc99e69cf42143fdd6c56b4 since it's
been ten years since the warning caused a real problem?

For the Crypto API, if it is called by some random driver via the
async context, this warning stops us from loading any modules
without printing a nasty warning that isn't relevant as the Crypto
API never calls async_synchronize_full.

---8<---
Do not call request_module if this is the case or a warning will
be printed.

Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
Reported-by: Eric Biggers <ebiggers@kernel.org>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
---
 crypto/api.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/crypto/api.c b/crypto/api.c
index 22556907b3bc..7c4b9f86c1ad 100644
--- a/crypto/api.c
+++ b/crypto/api.c
@@ -10,6 +10,7 @@
  * and Nettle, by Niels Möller.
  */
 
+#include <linux/async.h>
 #include <linux/err.h>
 #include <linux/errno.h>
 #include <linux/jump_label.h>
@@ -280,7 +281,8 @@ static struct crypto_alg *crypto_larval_lookup(const char *name, u32 type,
 	mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
 
 	alg = crypto_alg_lookup(name, type, mask);
-	if (!alg && !(mask & CRYPTO_NOLOAD)) {
+	if (!alg && !(mask & CRYPTO_NOLOAD) &&
+	    (!IS_BUILTIN(CONFIG_CRYPTO) || !current_is_async())) {
 		request_module("crypto-%s", name);
 
 		if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
-- 
2.39.2

-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply related	[flat|nested] 75+ messages in thread

* Re: [v2 PATCH] crypto: api - Do not load modules if called by async probing
  2024-05-21  2:53                         ` [v2 PATCH] crypto: api - Do not load modules if called by async probing Herbert Xu
@ 2024-05-21 19:37                           ` Nícolas F. R. A. Prado
  2024-05-22  5:37                             ` [v3 PATCH] hwrng: core - Remove add_early_randomness Herbert Xu
  0 siblings, 1 reply; 75+ messages in thread
From: Nícolas F. R. A. Prado @ 2024-05-21 19:37 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Eric Biggers, Jarkko Sakkinen, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel, Linus Torvalds, Tejun Heo,
	Linux Kernel Mailing List

On Tue, May 21, 2024 at 10:53:18AM +0800, Herbert Xu wrote:
> On Mon, May 20, 2024 at 11:49:56AM -0400, Nícolas F. R. A. Prado wrote:
> >
> > Unfortunately this patch didn't work either. The warning is still there
> > unchanged.
> 
> OK perhaps we can do it by calling current_is_async ourselves.
> But this is really a nasty hack because it basically defeats
> the whole point of loading optional algorithm by module.
> 
> Linus/Tejun, is it time perhaps to remove the warning introduced
> by commit 0fdff3ec6d87856cdcc99e69cf42143fdd6c56b4 since it's
> been ten years since the warning caused a real problem?
> 
> For the Crypto API, if it is called by some random driver via the
> async context, this warning stops us from loading any modules
> without printing a nasty warning that isn't relevant as the Crypto
> API never calls async_synchronize_full.
> 
> ---8<---
> Do not call request_module if this is the case or a warning will
> be printed.
> 
> Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> Reported-by: Eric Biggers <ebiggers@kernel.org>
> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
> ---
>  crypto/api.c | 4 +++-
>  1 file changed, 3 insertions(+), 1 deletion(-)
> 
> diff --git a/crypto/api.c b/crypto/api.c
> index 22556907b3bc..7c4b9f86c1ad 100644
> --- a/crypto/api.c
> +++ b/crypto/api.c
> @@ -10,6 +10,7 @@
>   * and Nettle, by Niels Möller.
>   */
>  
> +#include <linux/async.h>
>  #include <linux/err.h>
>  #include <linux/errno.h>
>  #include <linux/jump_label.h>
> @@ -280,7 +281,8 @@ static struct crypto_alg *crypto_larval_lookup(const char *name, u32 type,
>  	mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD);
>  
>  	alg = crypto_alg_lookup(name, type, mask);
> -	if (!alg && !(mask & CRYPTO_NOLOAD)) {
> +	if (!alg && !(mask & CRYPTO_NOLOAD) &&
> +	    (!IS_BUILTIN(CONFIG_CRYPTO) || !current_is_async())) {
>  		request_module("crypto-%s", name);
>  
>  		if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask &
> -- 
> 2.39.2

FWIW this patch fixes the warning. So feel free to add

Tested-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>

if you choose to apply this patch (I'm happy to help test other patches too). In
any case, please also add the following trailers so the regression gets closed
automatically in regzbot:

Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
Link: https://lore.kernel.org/r/119dc5ed-f159-41be-9dda-1a056f29888d@notapiano/

Thanks,
Nícolas

^ permalink raw reply	[flat|nested] 75+ messages in thread

* [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-21 19:37                           ` Nícolas F. R. A. Prado
@ 2024-05-22  5:37                             ` Herbert Xu
  2024-05-22 11:51                               ` Jarkko Sakkinen
                                                 ` (2 more replies)
  0 siblings, 3 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-22  5:37 UTC (permalink / raw)
  To: Nícolas F. R. A. Prado
  Cc: Eric Biggers, Jarkko Sakkinen, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel, Linus Torvalds, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook

On Tue, May 21, 2024 at 03:37:16PM -0400, Nícolas F. R. A. Prado wrote:
>
> FWIW this patch fixes the warning. So feel free to add
> 
> Tested-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>

Could you please test this patch instead?

---8<---
A potential deadlock was reported with the config file at

https://web.archive.org/web/20240522052129/https://0x0.st/XPN_.txt

In this particular configuration, the deadlock doesn't exist because
the warning triggered at a point before modules were even available.
However, the deadlock can be real because any module loaded would
invoke async_synchronize_full.

The issue is spurious for software crypto algorithms which aren't
themselves involved in async probing.  However, it would be hard to
avoid for a PCI crypto driver using async probing.

In this particular call trace, the problem is easily avoided because
the only reason the module is being requested during probing is the
add_early_randomness call in the hwrng core.  This feature is
vestigial since there is now a kernel thread dedicated to doing
exactly this.

So remove add_early_randomness as it is no longer needed.

Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
Reported-by: Eric Biggers <ebiggers@kernel.org>
Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
Link: https://lore.kernel.org/r/119dc5ed-f159-41be-9dda-1a056f29888d@notapiano/
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>

diff --git a/drivers/char/hw_random/core.c b/drivers/char/hw_random/core.c
index f5c71a617a99..4084df65c9fa 100644
--- a/drivers/char/hw_random/core.c
+++ b/drivers/char/hw_random/core.c
@@ -64,19 +64,6 @@ static size_t rng_buffer_size(void)
 	return RNG_BUFFER_SIZE;
 }
 
-static void add_early_randomness(struct hwrng *rng)
-{
-	int bytes_read;
-
-	mutex_lock(&reading_mutex);
-	bytes_read = rng_get_data(rng, rng_fillbuf, 32, 0);
-	mutex_unlock(&reading_mutex);
-	if (bytes_read > 0) {
-		size_t entropy = bytes_read * 8 * rng->quality / 1024;
-		add_hwgenerator_randomness(rng_fillbuf, bytes_read, entropy, false);
-	}
-}
-
 static inline void cleanup_rng(struct kref *kref)
 {
 	struct hwrng *rng = container_of(kref, struct hwrng, ref);
@@ -340,13 +327,12 @@ static ssize_t rng_current_store(struct device *dev,
 				 const char *buf, size_t len)
 {
 	int err;
-	struct hwrng *rng, *old_rng, *new_rng;
+	struct hwrng *rng, *new_rng;
 
 	err = mutex_lock_interruptible(&rng_mutex);
 	if (err)
 		return -ERESTARTSYS;
 
-	old_rng = current_rng;
 	if (sysfs_streq(buf, "")) {
 		err = enable_best_rng();
 	} else {
@@ -362,11 +348,8 @@ static ssize_t rng_current_store(struct device *dev,
 	new_rng = get_current_rng_nolock();
 	mutex_unlock(&rng_mutex);
 
-	if (new_rng) {
-		if (new_rng != old_rng)
-			add_early_randomness(new_rng);
+	if (new_rng)
 		put_rng(new_rng);
-	}
 
 	return err ? : len;
 }
@@ -544,7 +527,6 @@ int hwrng_register(struct hwrng *rng)
 {
 	int err = -EINVAL;
 	struct hwrng *tmp;
-	bool is_new_current = false;
 
 	if (!rng->name || (!rng->data_read && !rng->read))
 		goto out;
@@ -573,25 +555,8 @@ int hwrng_register(struct hwrng *rng)
 		err = set_current_rng(rng);
 		if (err)
 			goto out_unlock;
-		/* to use current_rng in add_early_randomness() we need
-		 * to take a ref
-		 */
-		is_new_current = true;
-		kref_get(&rng->ref);
 	}
 	mutex_unlock(&rng_mutex);
-	if (is_new_current || !rng->init) {
-		/*
-		 * Use a new device's input to add some randomness to
-		 * the system.  If this rng device isn't going to be
-		 * used right away, its init function hasn't been
-		 * called yet by set_current_rng(); so only use the
-		 * randomness from devices that don't need an init callback
-		 */
-		add_early_randomness(rng);
-	}
-	if (is_new_current)
-		put_rng(rng);
 	return 0;
 out_unlock:
 	mutex_unlock(&rng_mutex);
@@ -602,12 +567,11 @@ EXPORT_SYMBOL_GPL(hwrng_register);
 
 void hwrng_unregister(struct hwrng *rng)
 {
-	struct hwrng *old_rng, *new_rng;
+	struct hwrng *new_rng;
 	int err;
 
 	mutex_lock(&rng_mutex);
 
-	old_rng = current_rng;
 	list_del(&rng->list);
 	complete_all(&rng->dying);
 	if (current_rng == rng) {
@@ -626,11 +590,8 @@ void hwrng_unregister(struct hwrng *rng)
 	} else
 		mutex_unlock(&rng_mutex);
 
-	if (new_rng) {
-		if (old_rng != new_rng)
-			add_early_randomness(new_rng);
+	if (new_rng)
 		put_rng(new_rng);
-	}
 
 	wait_for_completion(&rng->cleanup_done);
 }
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply related	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-22  5:37                             ` [v3 PATCH] hwrng: core - Remove add_early_randomness Herbert Xu
@ 2024-05-22 11:51                               ` Jarkko Sakkinen
  2024-05-23  4:50                                 ` Herbert Xu
  2024-05-22 19:19                               ` Nícolas F. R. A. Prado
  2024-05-22 22:53                               ` Linus Torvalds
  2 siblings, 1 reply; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-22 11:51 UTC (permalink / raw)
  To: Herbert Xu, Nícolas F. R. A. Prado
  Cc: Eric Biggers, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel, Linus Torvalds, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook

On Wed May 22, 2024 at 8:37 AM EEST, Herbert Xu wrote:
> On Tue, May 21, 2024 at 03:37:16PM -0400, Nícolas F. R. A. Prado wrote:
> >
> > FWIW this patch fixes the warning. So feel free to add
> > 
> > Tested-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
>
> Could you please test this patch instead?
>
> ---8<---
> A potential deadlock was reported with the config file at
>
> https://web.archive.org/web/20240522052129/https://0x0.st/XPN_.txt
>
> In this particular configuration, the deadlock doesn't exist because
> the warning triggered at a point before modules were even available.
> However, the deadlock can be real because any module loaded would
> invoke async_synchronize_full.
>
> The issue is spurious for software crypto algorithms which aren't
> themselves involved in async probing.  However, it would be hard to
> avoid for a PCI crypto driver using async probing.
>
> In this particular call trace, the problem is easily avoided because
> the only reason the module is being requested during probing is the
> add_early_randomness call in the hwrng core.  This feature is
> vestigial since there is now a kernel thread dedicated to doing
> exactly this.
>
> So remove add_early_randomness as it is no longer needed.

"vestigial" did not know that word before ;-) Something learned.

What is the kthread doing this currently?

>
> Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> Reported-by: Eric Biggers <ebiggers@kernel.org>
> Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
> Link: https://lore.kernel.org/r/119dc5ed-f159-41be-9dda-1a056f29888d@notapiano/
> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
>
> diff --git a/drivers/char/hw_random/core.c b/drivers/char/hw_random/core.c
> index f5c71a617a99..4084df65c9fa 100644
> --- a/drivers/char/hw_random/core.c
> +++ b/drivers/char/hw_random/core.c
> @@ -64,19 +64,6 @@ static size_t rng_buffer_size(void)
>  	return RNG_BUFFER_SIZE;
>  }
>  
> -static void add_early_randomness(struct hwrng *rng)
> -{
> -	int bytes_read;
> -
> -	mutex_lock(&reading_mutex);
> -	bytes_read = rng_get_data(rng, rng_fillbuf, 32, 0);
> -	mutex_unlock(&reading_mutex);
> -	if (bytes_read > 0) {
> -		size_t entropy = bytes_read * 8 * rng->quality / 1024;
> -		add_hwgenerator_randomness(rng_fillbuf, bytes_read, entropy, false);
> -	}
> -}
> -
>  static inline void cleanup_rng(struct kref *kref)
>  {
>  	struct hwrng *rng = container_of(kref, struct hwrng, ref);
> @@ -340,13 +327,12 @@ static ssize_t rng_current_store(struct device *dev,
>  				 const char *buf, size_t len)
>  {
>  	int err;
> -	struct hwrng *rng, *old_rng, *new_rng;
> +	struct hwrng *rng, *new_rng;
>  
>  	err = mutex_lock_interruptible(&rng_mutex);
>  	if (err)
>  		return -ERESTARTSYS;
>  
> -	old_rng = current_rng;
>  	if (sysfs_streq(buf, "")) {
>  		err = enable_best_rng();
>  	} else {
> @@ -362,11 +348,8 @@ static ssize_t rng_current_store(struct device *dev,
>  	new_rng = get_current_rng_nolock();
>  	mutex_unlock(&rng_mutex);
>  
> -	if (new_rng) {
> -		if (new_rng != old_rng)
> -			add_early_randomness(new_rng);
> +	if (new_rng)
>  		put_rng(new_rng);
> -	}
>  
>  	return err ? : len;
>  }
> @@ -544,7 +527,6 @@ int hwrng_register(struct hwrng *rng)
>  {
>  	int err = -EINVAL;
>  	struct hwrng *tmp;
> -	bool is_new_current = false;
>  
>  	if (!rng->name || (!rng->data_read && !rng->read))
>  		goto out;
> @@ -573,25 +555,8 @@ int hwrng_register(struct hwrng *rng)
>  		err = set_current_rng(rng);
>  		if (err)
>  			goto out_unlock;
> -		/* to use current_rng in add_early_randomness() we need
> -		 * to take a ref
> -		 */
> -		is_new_current = true;
> -		kref_get(&rng->ref);
>  	}
>  	mutex_unlock(&rng_mutex);
> -	if (is_new_current || !rng->init) {
> -		/*
> -		 * Use a new device's input to add some randomness to
> -		 * the system.  If this rng device isn't going to be
> -		 * used right away, its init function hasn't been
> -		 * called yet by set_current_rng(); so only use the
> -		 * randomness from devices that don't need an init callback
> -		 */
> -		add_early_randomness(rng);
> -	}
> -	if (is_new_current)
> -		put_rng(rng);
>  	return 0;
>  out_unlock:
>  	mutex_unlock(&rng_mutex);
> @@ -602,12 +567,11 @@ EXPORT_SYMBOL_GPL(hwrng_register);
>  
>  void hwrng_unregister(struct hwrng *rng)
>  {
> -	struct hwrng *old_rng, *new_rng;
> +	struct hwrng *new_rng;
>  	int err;
>  
>  	mutex_lock(&rng_mutex);
>  
> -	old_rng = current_rng;
>  	list_del(&rng->list);
>  	complete_all(&rng->dying);
>  	if (current_rng == rng) {
> @@ -626,11 +590,8 @@ void hwrng_unregister(struct hwrng *rng)
>  	} else
>  		mutex_unlock(&rng_mutex);
>  
> -	if (new_rng) {
> -		if (old_rng != new_rng)
> -			add_early_randomness(new_rng);
> +	if (new_rng)
>  		put_rng(new_rng);
> -	}
>  
>  	wait_for_completion(&rng->cleanup_done);
>  }

I have no doubts that such thread would not exist, so:

Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-22  5:37                             ` [v3 PATCH] hwrng: core - Remove add_early_randomness Herbert Xu
  2024-05-22 11:51                               ` Jarkko Sakkinen
@ 2024-05-22 19:19                               ` Nícolas F. R. A. Prado
  2024-05-22 22:53                               ` Linus Torvalds
  2 siblings, 0 replies; 75+ messages in thread
From: Nícolas F. R. A. Prado @ 2024-05-22 19:19 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Eric Biggers, Jarkko Sakkinen, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel, Linus Torvalds, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook

On Wed, May 22, 2024 at 01:37:54PM +0800, Herbert Xu wrote:
> On Tue, May 21, 2024 at 03:37:16PM -0400, Nícolas F. R. A. Prado wrote:
> >
> > FWIW this patch fixes the warning. So feel free to add
> > 
> > Tested-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> 
> Could you please test this patch instead?
> 
> ---8<---
> A potential deadlock was reported with the config file at
> 
> https://web.archive.org/web/20240522052129/https://0x0.st/XPN_.txt
> 
> In this particular configuration, the deadlock doesn't exist because
> the warning triggered at a point before modules were even available.
> However, the deadlock can be real because any module loaded would
> invoke async_synchronize_full.
> 
> The issue is spurious for software crypto algorithms which aren't
> themselves involved in async probing.  However, it would be hard to
> avoid for a PCI crypto driver using async probing.
> 
> In this particular call trace, the problem is easily avoided because
> the only reason the module is being requested during probing is the
> add_early_randomness call in the hwrng core.  This feature is
> vestigial since there is now a kernel thread dedicated to doing
> exactly this.
> 
> So remove add_early_randomness as it is no longer needed.
> 
> Reported-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>
> Reported-by: Eric Biggers <ebiggers@kernel.org>
> Fixes: 1b6d7f9eb150 ("tpm: add session encryption protection to tpm2_get_random()")
> Link: https://lore.kernel.org/r/119dc5ed-f159-41be-9dda-1a056f29888d@notapiano/
> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>

This patch also fixes the warning.

Tested-by: Nícolas F. R. A. Prado <nfraprado@collabora.com>

Thanks,
Nícolas

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-22  5:37                             ` [v3 PATCH] hwrng: core - Remove add_early_randomness Herbert Xu
  2024-05-22 11:51                               ` Jarkko Sakkinen
  2024-05-22 19:19                               ` Nícolas F. R. A. Prado
@ 2024-05-22 22:53                               ` Linus Torvalds
  2024-05-23  4:49                                 ` Herbert Xu
  2 siblings, 1 reply; 75+ messages in thread
From: Linus Torvalds @ 2024-05-22 22:53 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Nícolas F. R. A. Prado, Eric Biggers, Jarkko Sakkinen,
	James Bottomley, Ard Biesheuvel, Linux Crypto Mailing List,
	linux-integrity, keyrings, regressions, kernel, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook

On Tue, 21 May 2024 at 22:38, Herbert Xu <herbert@gondor.apana.org.au> wrote:
>
> In this particular configuration, the deadlock doesn't exist because
> the warning triggered at a point before modules were even available.
> However, the deadlock can be real because any module loaded would
> invoke async_synchronize_full.

I think this crapectomy is good regardless of any deadlock - the
"register this driver" should not just blindly call back into the
driver.

That said, looking at the code in question, there are other oddities
going on. Even the "we found a favorite new rng" case looks rather
strange. The thread we use - nice and asynchronous - seems to sleep
only if the randomness source is emptied.

What if you have a really good source of hw randomness? That looks
like a busy loop to me, but hopefully I'm missing something obvious.

So I think this hw_random code has other serious issues, and I get the
feeling there might be more code that needs looking at..

              Linus

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-22 22:53                               ` Linus Torvalds
@ 2024-05-23  4:49                                 ` Herbert Xu
  2024-05-23  9:53                                   ` Jarkko Sakkinen
  2024-05-23 10:40                                   ` Torsten Duwe
  0 siblings, 2 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-23  4:49 UTC (permalink / raw)
  To: Linus Torvalds
  Cc: Nícolas F. R. A. Prado, Eric Biggers, Jarkko Sakkinen,
	James Bottomley, Ard Biesheuvel, Linux Crypto Mailing List,
	linux-integrity, keyrings, regressions, kernel, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook, Torsten Duwe,
	H. Peter Anvin, Theodore Ts'o, Jason A. Donenfeld

On Wed, May 22, 2024 at 03:53:23PM -0700, Linus Torvalds wrote:
> 
> That said, looking at the code in question, there are other oddities
> going on. Even the "we found a favorite new rng" case looks rather
> strange. The thread we use - nice and asynchronous - seems to sleep
> only if the randomness source is emptied.
> 
> What if you have a really good source of hw randomness? That looks
> like a busy loop to me, but hopefully I'm missing something obvious.

Yes that does look strange.  So I dug up the original patch at

	https://lore.kernel.org/all/20140317165012.GC1763@lst.de/

and therein lies the answer.  It's relying on random.c to push back
when the amount of new entropy exceeds what it needs.  IOW we will
sleep via add_hwgenerator_randomness when random.c decides that
enough is enough.  In fact the rate is much less now compared to
when the patch was first applied.

Cheers,
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-22 11:51                               ` Jarkko Sakkinen
@ 2024-05-23  4:50                                 ` Herbert Xu
  0 siblings, 0 replies; 75+ messages in thread
From: Herbert Xu @ 2024-05-23  4:50 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Nícolas F. R. A. Prado, Eric Biggers, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel, Linus Torvalds, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook

On Wed, May 22, 2024 at 02:51:36PM +0300, Jarkko Sakkinen wrote:
>
> What is the kthread doing this currently?

It's hwrng_fillfn.

Cheers,
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-23  4:49                                 ` Herbert Xu
@ 2024-05-23  9:53                                   ` Jarkko Sakkinen
  2024-05-23  9:58                                     ` Herbert Xu
  2024-05-23 10:02                                     ` Jarkko Sakkinen
  2024-05-23 10:40                                   ` Torsten Duwe
  1 sibling, 2 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-23  9:53 UTC (permalink / raw)
  To: Herbert Xu, Linus Torvalds
  Cc: Nícolas F. R. A. Prado, Eric Biggers, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook, Torsten Duwe,
	H. Peter Anvin, Theodore Ts'o, Jason A. Donenfeld

On Thu May 23, 2024 at 7:49 AM EEST, Herbert Xu wrote:
> On Wed, May 22, 2024 at 03:53:23PM -0700, Linus Torvalds wrote:
> > 
> > That said, looking at the code in question, there are other oddities
> > going on. Even the "we found a favorite new rng" case looks rather
> > strange. The thread we use - nice and asynchronous - seems to sleep
> > only if the randomness source is emptied.
> > 
> > What if you have a really good source of hw randomness? That looks
> > like a busy loop to me, but hopefully I'm missing something obvious.
>
> Yes that does look strange.  So I dug up the original patch at
>
> 	https://lore.kernel.org/all/20140317165012.GC1763@lst.de/
>
> and therein lies the answer.  It's relying on random.c to push back
> when the amount of new entropy exceeds what it needs.  IOW we will
> sleep via add_hwgenerator_randomness when random.c decides that
> enough is enough.  In fact the rate is much less now compared to
> when the patch was first applied.

Just throwing something because came to mind, not a serious suggestion.

In crypto_larval_lookup I see statements like this:

	request_module("crypto-%s", name);

You could potentially bake up a section/table to vmlinux which would
have entries like:

	"module name", 1/0

'1' would mean built-in. Then for early randomness use only stuff
that is built-in.

Came to mind from arch/x86/realmode for which I baked in a table
for relocation (this was a collaborative work with H. Peter Anvin
in 2012 to make trampoline code relocatable but is still a legit
example to do such shenanigans in a subystem).

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-23  9:53                                   ` Jarkko Sakkinen
@ 2024-05-23  9:58                                     ` Herbert Xu
  2024-05-23 10:07                                       ` Jarkko Sakkinen
  2024-05-23 10:02                                     ` Jarkko Sakkinen
  1 sibling, 1 reply; 75+ messages in thread
From: Herbert Xu @ 2024-05-23  9:58 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Linus Torvalds, Nícolas F. R. A. Prado, Eric Biggers,
	James Bottomley, Ard Biesheuvel, Linux Crypto Mailing List,
	linux-integrity, keyrings, regressions, kernel, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook, Torsten Duwe,
	H. Peter Anvin, Theodore Ts'o, Jason A. Donenfeld

On Thu, May 23, 2024 at 12:53:04PM +0300, Jarkko Sakkinen wrote:
>
> Just throwing something because came to mind, not a serious suggestion.
> 
> In crypto_larval_lookup I see statements like this:
> 
> 	request_module("crypto-%s", name);
> 
> You could potentially bake up a section/table to vmlinux which would
> have entries like:
> 
> 	"module name", 1/0
> 
> '1' would mean built-in. Then for early randomness use only stuff
> that is built-in.

This early random stuff is obsolete not just because we have a
kernel thread doing the same thing, but moreover random.c itself
has been modified so that it is no longer starved of entropy on
startup.  There is no reason to feed any early randomness.

Cheers,
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-23  9:53                                   ` Jarkko Sakkinen
  2024-05-23  9:58                                     ` Herbert Xu
@ 2024-05-23 10:02                                     ` Jarkko Sakkinen
  1 sibling, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-23 10:02 UTC (permalink / raw)
  To: Jarkko Sakkinen, Herbert Xu, Linus Torvalds
  Cc: Nícolas F. R. A. Prado, Eric Biggers, James Bottomley,
	Ard Biesheuvel, Linux Crypto Mailing List, linux-integrity,
	keyrings, regressions, kernel, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook, Torsten Duwe,
	H. Peter Anvin, Theodore Ts'o, Jason A. Donenfeld

On Thu May 23, 2024 at 12:53 PM EEST, Jarkko Sakkinen wrote:
> On Thu May 23, 2024 at 7:49 AM EEST, Herbert Xu wrote:
> > On Wed, May 22, 2024 at 03:53:23PM -0700, Linus Torvalds wrote:
> > > 
> > > That said, looking at the code in question, there are other oddities
> > > going on. Even the "we found a favorite new rng" case looks rather
> > > strange. The thread we use - nice and asynchronous - seems to sleep
> > > only if the randomness source is emptied.
> > > 
> > > What if you have a really good source of hw randomness? That looks
> > > like a busy loop to me, but hopefully I'm missing something obvious.
> >
> > Yes that does look strange.  So I dug up the original patch at
> >
> > 	https://lore.kernel.org/all/20140317165012.GC1763@lst.de/
> >
> > and therein lies the answer.  It's relying on random.c to push back
> > when the amount of new entropy exceeds what it needs.  IOW we will
> > sleep via add_hwgenerator_randomness when random.c decides that
> > enough is enough.  In fact the rate is much less now compared to
> > when the patch was first applied.
>
> Just throwing something because came to mind, not a serious suggestion.
>
> In crypto_larval_lookup I see statements like this:
>
> 	request_module("crypto-%s", name);
>
> You could potentially bake up a section/table to vmlinux which would
> have entries like:
>
> 	"module name", 1/0
>
> '1' would mean built-in. Then for early randomness use only stuff
> that is built-in.
>
> Came to mind from arch/x86/realmode for which I baked in a table
> for relocation (this was a collaborative work with H. Peter Anvin
> in 2012 to make trampoline code relocatable but is still a legit
> example to do such shenanigans in a subystem).

This could be even parameter in __request_module() itself e.g.

int __request_module(bool wait, bool builtin_only, const char *fmt, ...);

And would not matter which initcall layer we are running at.

BR, Jarkko


^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-23  9:58                                     ` Herbert Xu
@ 2024-05-23 10:07                                       ` Jarkko Sakkinen
  0 siblings, 0 replies; 75+ messages in thread
From: Jarkko Sakkinen @ 2024-05-23 10:07 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Linus Torvalds, Nícolas F. R. A. Prado, Eric Biggers,
	James Bottomley, Ard Biesheuvel, Linux Crypto Mailing List,
	linux-integrity, keyrings, regressions, kernel, Tejun Heo,
	Linux Kernel Mailing List, Kees Cook, Torsten Duwe,
	H. Peter Anvin, Theodore Ts'o, Jason A. Donenfeld

On Thu May 23, 2024 at 12:58 PM EEST, Herbert Xu wrote:
> On Thu, May 23, 2024 at 12:53:04PM +0300, Jarkko Sakkinen wrote:
> >
> > Just throwing something because came to mind, not a serious suggestion.
> > 
> > In crypto_larval_lookup I see statements like this:
> > 
> > 	request_module("crypto-%s", name);
> > 
> > You could potentially bake up a section/table to vmlinux which would
> > have entries like:
> > 
> > 	"module name", 1/0
> > 
> > '1' would mean built-in. Then for early randomness use only stuff
> > that is built-in.
>
> This early random stuff is obsolete not just because we have a
> kernel thread doing the same thing, but moreover random.c itself
> has been modified so that it is no longer starved of entropy on
> startup.  There is no reason to feed any early randomness.

As a feature that would still sometimes nice to have. I've
sometimes wished there was "lsmod -b" or similar to display
built-in stuff ;-)

So overally I think it was good to have at least documented
here... 

BR, Jarkko

^ permalink raw reply	[flat|nested] 75+ messages in thread

* Re: [v3 PATCH] hwrng: core - Remove add_early_randomness
  2024-05-23  4:49                                 ` Herbert Xu
  2024-05-23  9:53                                   ` Jarkko Sakkinen
@ 2024-05-23 10:40                                   ` Torsten Duwe
  1 sibling, 0 replies; 75+ messages in thread
From: Torsten Duwe @ 2024-05-23 10:40 UTC (permalink / raw)
  To: Herbert Xu
  Cc: Linus Torvalds, Nícolas F. R. A. Prado, Eric Biggers,
	Jarkko Sakkinen, James Bottomley, Ard Biesheuvel,
	Linux Crypto Mailing List, linux-integrity, keyrings,
	regressions, kernel, Tejun Heo, Linux Kernel Mailing List,
	Kees Cook, H. Peter Anvin, Theodore Ts'o, Jason A. Donenfeld

On Thu, 23 May 2024 12:49:50 +0800
Herbert Xu <herbert@gondor.apana.org.au> wrote:

> On Wed, May 22, 2024 at 03:53:23PM -0700, Linus Torvalds wrote:
> > 
> > That said, looking at the code in question, there are other oddities
> > going on. Even the "we found a favorite new rng" case looks rather
> > strange. The thread we use - nice and asynchronous - seems to sleep
> > only if the randomness source is emptied.
> > 
> > What if you have a really good source of hw randomness? That looks
> > like a busy loop to me, but hopefully I'm missing something obvious.
> 
> Yes that does look strange.  So I dug up the original patch at
> 
> 	https://lore.kernel.org/all/20140317165012.GC1763@lst.de/
> 
> and therein lies the answer.  It's relying on random.c to push back
> when the amount of new entropy exceeds what it needs.  IOW we will
> sleep via add_hwgenerator_randomness when random.c decides that
> enough is enough.

Yes, I thought that this was the obvious choice, the lesser evil. If it
just discarded the excess and returned immediately I had expected some
kernel threads to spin constantly.

>  In fact the rate is much less now compared to
> when the patch was first applied.

You mean the rate of required entropy? Doesn't that make things worse?
Maybe redesign the API to use a pull scheme? RNGs register at the
randomness facility with a callback that can be used when there is a
need for fresh entropy?

	Torsten


^ permalink raw reply	[flat|nested] 75+ messages in thread

end of thread, other threads:[~2024-05-23 10:41 UTC | newest]

Thread overview: 75+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2024-04-29 20:27 [PATCH v8 00/22] add integrity and security to TPM2 transactions James Bottomley
2024-04-29 20:27 ` [PATCH v8 01/22] tpm: Remove unused tpm_buf_tag() James Bottomley
2024-04-29 20:27 ` [PATCH v8 02/22] tpm: Remove tpm_send() James Bottomley
2024-04-29 20:27 ` [PATCH v8 03/22] tpm: Move buffer handling from static inlines to real functions James Bottomley
2024-04-29 20:27 ` [PATCH v8 04/22] tpm: Update struct tpm_buf documentation comments James Bottomley
2024-04-29 20:27 ` [PATCH v8 05/22] tpm: Store the length of the tpm_buf data separately James Bottomley
2024-04-29 20:27 ` [PATCH v8 06/22] tpm: TPM2B formatted buffers James Bottomley
2024-04-29 20:27 ` [PATCH v8 07/22] tpm: Add tpm_buf_read_{u8,u16,u32} James Bottomley
2024-04-29 20:27 ` [PATCH v8 08/22] KEYS: trusted: tpm2: Use struct tpm_buf for sized buffers James Bottomley
2024-04-29 20:27 ` [PATCH v8 09/22] crypto: lib - implement library version of AES in CFB mode James Bottomley
2024-04-29 20:27 ` [PATCH v8 10/22] tpm: add buffer function to point to returned parameters James Bottomley
2024-04-29 20:28 ` [PATCH v8 11/22] tpm: export the context save and load commands James Bottomley
2024-04-29 20:28 ` [PATCH v8 12/22] tpm: Add NULL primary creation James Bottomley
2024-04-29 22:37   ` Jarkko Sakkinen
2024-04-29 20:28 ` [PATCH v8 13/22] tpm: Add TCG mandated Key Derivation Functions (KDFs) James Bottomley
2024-04-29 22:37   ` Jarkko Sakkinen
2024-04-29 20:28 ` [PATCH v8 14/22] tpm: Add HMAC session start and end functions James Bottomley
2024-04-29 22:38   ` Jarkko Sakkinen
2024-04-30 16:49   ` Jarkko Sakkinen
2024-04-29 20:28 ` [PATCH v8 15/22] tpm: Add HMAC session name/handle append James Bottomley
2024-04-29 22:38   ` Jarkko Sakkinen
2024-04-29 20:28 ` [PATCH v8 16/22] tpm: Add the rest of the session HMAC API James Bottomley
2024-04-29 22:39   ` Jarkko Sakkinen
2024-04-29 20:28 ` [PATCH v8 17/22] tpm: add hmac checks to tpm2_pcr_extend() James Bottomley
2024-04-29 20:28 ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() James Bottomley
2024-05-17  0:25   ` Nícolas F. R. A. Prado
2024-05-17  1:59     ` James Bottomley
2024-05-17  7:20       ` Ard Biesheuvel
2024-05-17  8:26         ` Jarkko Sakkinen
2024-05-17 13:35         ` James Bottomley
2024-05-17 13:43           ` Ard Biesheuvel
2024-05-17 14:25             ` James Bottomley
2024-05-17 16:22               ` Nícolas F. R. A. Prado
2024-05-17 16:48                 ` Jarkko Sakkinen
2024-05-18  4:31                   ` Eric Biggers
2024-05-18  7:03                     ` [PATCH] crypto: api - Do not load modules until algapi is ready Herbert Xu
2024-05-18 11:04                       ` Jarkko Sakkinen
2024-05-18 12:32                         ` Herbert Xu
2024-05-18 13:03                           ` Jarkko Sakkinen
2024-05-18 13:07                           ` James Bottomley
2024-05-19  4:19                             ` Herbert Xu
2024-05-20 15:49                       ` Nícolas F. R. A. Prado
2024-05-21  2:53                         ` [v2 PATCH] crypto: api - Do not load modules if called by async probing Herbert Xu
2024-05-21 19:37                           ` Nícolas F. R. A. Prado
2024-05-22  5:37                             ` [v3 PATCH] hwrng: core - Remove add_early_randomness Herbert Xu
2024-05-22 11:51                               ` Jarkko Sakkinen
2024-05-23  4:50                                 ` Herbert Xu
2024-05-22 19:19                               ` Nícolas F. R. A. Prado
2024-05-22 22:53                               ` Linus Torvalds
2024-05-23  4:49                                 ` Herbert Xu
2024-05-23  9:53                                   ` Jarkko Sakkinen
2024-05-23  9:58                                     ` Herbert Xu
2024-05-23 10:07                                       ` Jarkko Sakkinen
2024-05-23 10:02                                     ` Jarkko Sakkinen
2024-05-23 10:40                                   ` Torsten Duwe
2024-05-18 10:56                     ` [PATCH v8 18/22] tpm: add session encryption protection to tpm2_get_random() Jarkko Sakkinen
2024-05-18 12:31                       ` Herbert Xu
2024-04-29 20:28 ` [PATCH v8 19/22] KEYS: trusted: Add session encryption protection to the seal/unseal path James Bottomley
2024-04-29 20:28 ` [PATCH v8 20/22] tpm: add the null key name as a sysfs export James Bottomley
2024-04-29 20:28 ` [PATCH v8 21/22] Documentation: add tpm-security.rst James Bottomley
2024-04-29 20:28 ` [PATCH v8 22/22] tpm: disable the TPM if NULL name changes James Bottomley
2024-04-29 22:59   ` Jarkko Sakkinen
2024-04-29 23:34   ` Jarkko Sakkinen
2024-04-29 22:22 ` [PATCH v8 00/22] add integrity and security to TPM2 transactions Jarkko Sakkinen
2024-04-29 22:26   ` Jarkko Sakkinen
2024-04-29 23:49     ` Jarkko Sakkinen
2024-04-30 11:18       ` Stefan Berger
2024-04-30 18:37         ` Jarkko Sakkinen
2024-04-30 18:57           ` Stefan Berger
2024-04-30 19:23   ` James Bottomley
2024-04-30 21:48     ` Jarkko Sakkinen
2024-04-30 22:31       ` James Bottomley
2024-04-30 22:46         ` Jarkko Sakkinen
2024-04-30 23:10           ` Jarkko Sakkinen
2024-05-03 23:18         ` Jarkko Sakkinen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).