* [PATCH v4 01/13] crypto: lib - implement library version of AES in CFB mode
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-23 3:34 ` Jarkko Sakkinen
2023-04-03 21:39 ` [PATCH v4 02/13] tpm: move buffer handling from static inlines to real functions James Bottomley
` (15 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 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>
Link: https://lore.kernel.org/all/20230216201410.15010-1-James.Bottomley@HansenPartnership.com/
Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
---
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 6ec2d4543d9c..33213a01aab1 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] 62+ messages in thread* Re: [PATCH v4 01/13] crypto: lib - implement library version of AES in CFB mode
2023-04-03 21:39 ` [PATCH v4 01/13] crypto: lib - implement library version of AES in CFB mode James Bottomley
@ 2023-04-23 3:34 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 3:34 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> 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>
> Link: https://lore.kernel.org/all/20230216201410.15010-1-James.Bottomley@HansenPartnership.com/
> Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
> ---
> 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 6ec2d4543d9c..33213a01aab1 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
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 02/13] tpm: move buffer handling from static inlines to real functions
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
2023-04-03 21:39 ` [PATCH v4 01/13] crypto: lib - implement library version of AES in CFB mode James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-23 3:36 ` Jarkko Sakkinen
2023-04-03 21:39 ` [PATCH v4 03/13] tpm: add kernel doc to buffer handling functions James Bottomley
` (14 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 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>
---
v3: make tpm_buf_tag static
v4: remove space after spdx tag
---
drivers/char/tpm/Makefile | 1 +
drivers/char/tpm/tpm-buf.c | 87 ++++++++++++++++++++++++++++++++++++++
include/linux/tpm.h | 86 ++++---------------------------------
3 files changed, 97 insertions(+), 77 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..baa4866d53a9
--- /dev/null
+++ b/drivers/char/tpm/tpm-buf.c
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Handing for tpm_buf structures to facilitate the building of commands
+ */
+
+#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 4dc97b9f65fb..9c9b5760b412 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -323,84 +323,16 @@ struct tpm2_hash {
unsigned int tpm_id;
};
-static inline void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
-{
- struct tpm_header *head = (struct tpm_header *)buf->data;
-
- head->tag = cpu_to_be16(tag);
- head->length = cpu_to_be32(sizeof(*head));
- head->ordinal = cpu_to_be32(ordinal);
-}
-
-static inline int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
-{
- buf->data = (u8 *)__get_free_page(GFP_KERNEL);
- if (!buf->data)
- return -ENOMEM;
-
- buf->flags = 0;
- tpm_buf_reset(buf, tag, ordinal);
- return 0;
-}
-
-static inline void tpm_buf_destroy(struct tpm_buf *buf)
-{
- free_page((unsigned long)buf->data);
-}
-
-static inline u32 tpm_buf_length(struct tpm_buf *buf)
-{
- struct tpm_header *head = (struct tpm_header *)buf->data;
-
- return be32_to_cpu(head->length);
-}
-
-static inline u16 tpm_buf_tag(struct tpm_buf *buf)
-{
- struct tpm_header *head = (struct tpm_header *)buf->data;
-
- return be16_to_cpu(head->tag);
-}
-
-static inline void tpm_buf_append(struct tpm_buf *buf,
- const unsigned char *new_data,
- unsigned int new_len)
-{
- struct tpm_header *head = (struct tpm_header *)buf->data;
- u32 len = tpm_buf_length(buf);
-
- /* Return silently if overflow has already happened. */
- if (buf->flags & TPM_BUF_OVERFLOW)
- return;
-
- if ((len + new_len) > PAGE_SIZE) {
- WARN(1, "tpm_buf: overflow\n");
- buf->flags |= TPM_BUF_OVERFLOW;
- return;
- }
- memcpy(&buf->data[len], new_data, new_len);
- head->length = cpu_to_be32(len + new_len);
-}
-
-static inline void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value)
-{
- tpm_buf_append(buf, &value, 1);
-}
-
-static inline void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
-{
- __be16 value2 = cpu_to_be16(value);
-
- tpm_buf_append(buf, (u8 *) &value2, 2);
-}
-
-static inline void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
-{
- __be32 value2 = cpu_to_be32(value);
-
- tpm_buf_append(buf, (u8 *) &value2, 4);
-}
+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] 62+ messages in thread* Re: [PATCH v4 02/13] tpm: move buffer handling from static inlines to real functions
2023-04-03 21:39 ` [PATCH v4 02/13] tpm: move buffer handling from static inlines to real functions James Bottomley
@ 2023-04-23 3:36 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 3:36 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> 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>
>
> ---
> v3: make tpm_buf_tag static
> v4: remove space after spdx tag
> ---
> drivers/char/tpm/Makefile | 1 +
> drivers/char/tpm/tpm-buf.c | 87 ++++++++++++++++++++++++++++++++++++++
> include/linux/tpm.h | 86 ++++---------------------------------
> 3 files changed, 97 insertions(+), 77 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..baa4866d53a9
> --- /dev/null
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -0,0 +1,87 @@
> +// SPDX-License-Identifier: GPL-2.0
> +/*
> + * Handing for tpm_buf structures to facilitate the building of commands
> + */
> +
> +#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 4dc97b9f65fb..9c9b5760b412 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -323,84 +323,16 @@ struct tpm2_hash {
> unsigned int tpm_id;
> };
>
> -static inline void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
> -{
> - struct tpm_header *head = (struct tpm_header *)buf->data;
> -
> - head->tag = cpu_to_be16(tag);
> - head->length = cpu_to_be32(sizeof(*head));
> - head->ordinal = cpu_to_be32(ordinal);
> -}
> -
> -static inline int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> -{
> - buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> - if (!buf->data)
> - return -ENOMEM;
> -
> - buf->flags = 0;
> - tpm_buf_reset(buf, tag, ordinal);
> - return 0;
> -}
> -
> -static inline void tpm_buf_destroy(struct tpm_buf *buf)
> -{
> - free_page((unsigned long)buf->data);
> -}
> -
> -static inline u32 tpm_buf_length(struct tpm_buf *buf)
> -{
> - struct tpm_header *head = (struct tpm_header *)buf->data;
> -
> - return be32_to_cpu(head->length);
> -}
> -
> -static inline u16 tpm_buf_tag(struct tpm_buf *buf)
> -{
> - struct tpm_header *head = (struct tpm_header *)buf->data;
> -
> - return be16_to_cpu(head->tag);
> -}
> -
> -static inline void tpm_buf_append(struct tpm_buf *buf,
> - const unsigned char *new_data,
> - unsigned int new_len)
> -{
> - struct tpm_header *head = (struct tpm_header *)buf->data;
> - u32 len = tpm_buf_length(buf);
> -
> - /* Return silently if overflow has already happened. */
> - if (buf->flags & TPM_BUF_OVERFLOW)
> - return;
> -
> - if ((len + new_len) > PAGE_SIZE) {
> - WARN(1, "tpm_buf: overflow\n");
> - buf->flags |= TPM_BUF_OVERFLOW;
> - return;
> - }
>
> - memcpy(&buf->data[len], new_data, new_len);
> - head->length = cpu_to_be32(len + new_len);
> -}
> -
> -static inline void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value)
> -{
> - tpm_buf_append(buf, &value, 1);
> -}
> -
> -static inline void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
> -{
> - __be16 value2 = cpu_to_be16(value);
> -
> - tpm_buf_append(buf, (u8 *) &value2, 2);
> -}
> -
> -static inline void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
> -{
> - __be32 value2 = cpu_to_be32(value);
> -
> - tpm_buf_append(buf, (u8 *) &value2, 4);
> -}
> +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
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 03/13] tpm: add kernel doc to buffer handling functions
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
2023-04-03 21:39 ` [PATCH v4 01/13] crypto: lib - implement library version of AES in CFB mode James Bottomley
2023-04-03 21:39 ` [PATCH v4 02/13] tpm: move buffer handling from static inlines to real functions James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-23 3:40 ` Jarkko Sakkinen
2023-04-03 21:39 ` [PATCH v4 04/13] tpm: add buffer handling for TPM2B types James Bottomley
` (13 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 UTC (permalink / raw)
To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
drivers/char/tpm/tpm-buf.c | 65 ++++++++++++++++++++++++++++++++++++++
1 file changed, 65 insertions(+)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index baa4866d53a9..3351db515e6b 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -6,6 +6,16 @@
#include <linux/module.h>
#include <linux/tpm.h>
+/**
+ * tpm_buf_init - initialize a TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @tag: command tag
+ * @ordinal: command ordinal
+ *
+ * Allocates a 4k buffer to hold the command structure.
+ *
+ * @return: 0 on success or -ENOMEM
+ */
int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
{
buf->data = (u8 *)__get_free_page(GFP_KERNEL);
@@ -18,6 +28,16 @@ int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
}
EXPORT_SYMBOL_GPL(tpm_buf_init);
+/**
+ * tpm_buf_reset - reset an initialized TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @tag: command tag
+ * @ordinal: command ordinal
+ *
+ * Repurposes an already allocated @buf for a new command.
+ * Identical to calling tpm_buf_destroy/tpm_buf_init except it keeps
+ * the 4k allocated page and cannot fail.
+ */
void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
{
struct tpm_header *head = (struct tpm_header *) buf->data;
@@ -28,12 +48,24 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
}
EXPORT_SYMBOL_GPL(tpm_buf_reset);
+/**
+ * tpm_buf_destroy - destroy an initialized TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ *
+ * Frees the memory allocated to @buf.
+ */
void tpm_buf_destroy(struct tpm_buf *buf)
{
free_page((unsigned long)buf->data);
}
EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+/**
+ * tpm_buf_length - get the current length of a TPM command
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ *
+ * @return: the current length of the @buf.
+ */
u32 tpm_buf_length(struct tpm_buf *buf)
{
struct tpm_header *head = (struct tpm_header *)buf->data;
@@ -42,6 +74,15 @@ u32 tpm_buf_length(struct tpm_buf *buf)
}
EXPORT_SYMBOL_GPL(tpm_buf_length);
+/**
+ * tpm_buf_append - append data to an initialized TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @new_data: pointer to the added data
+ * @new_len: length of the added data
+ *
+ * Appends @new_data to the end of the current @buf and updates the
+ * length.
+ */
void tpm_buf_append(struct tpm_buf *buf,
const unsigned char *new_data,
unsigned int new_len)
@@ -64,12 +105,28 @@ void tpm_buf_append(struct tpm_buf *buf,
}
EXPORT_SYMBOL_GPL(tpm_buf_append);
+/**
+ * tpm_buf_append_u8 - append u8 data to an initialized TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @value: the value of the data to append
+ *
+ * Appends @value as a byte to the end of the current @buf and updates
+ * the length.
+ */
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);
+/**
+ * tpm_buf_append_u16 - append u16 data to an initialized TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @value: the value of the data to append
+ *
+ * Appends @value as a big endian short to the end of the current @buf
+ * and updates the length.
+ */
void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
{
__be16 value2 = cpu_to_be16(value);
@@ -78,6 +135,14 @@ void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
}
EXPORT_SYMBOL_GPL(tpm_buf_append_u16);
+/**
+ * tpm_buf_append_u32 - append u32 data to an initialized TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @value: the value of the data to append
+ *
+ * Appends @value as a big endian word to the end of the current @buf
+ * and updates the length.
+ */
void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
{
__be32 value2 = cpu_to_be32(value);
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* Re: [PATCH v4 03/13] tpm: add kernel doc to buffer handling functions
2023-04-03 21:39 ` [PATCH v4 03/13] tpm: add kernel doc to buffer handling functions James Bottomley
@ 2023-04-23 3:40 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 3:40 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> ---
> drivers/char/tpm/tpm-buf.c | 65 ++++++++++++++++++++++++++++++++++++++
> 1 file changed, 65 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index baa4866d53a9..3351db515e6b 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -6,6 +6,16 @@
> #include <linux/module.h>
> #include <linux/tpm.h>
>
> +/**
> + * tpm_buf_init - initialize a TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @tag: command tag
> + * @ordinal: command ordinal
> + *
> + * Allocates a 4k buffer to hold the command structure.
> + *
> + * @return: 0 on success or -ENOMEM
> + */
> int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> {
> buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> @@ -18,6 +28,16 @@ int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_init);
>
> +/**
> + * tpm_buf_reset - reset an initialized TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @tag: command tag
> + * @ordinal: command ordinal
> + *
> + * Repurposes an already allocated @buf for a new command.
> + * Identical to calling tpm_buf_destroy/tpm_buf_init except it keeps
> + * the 4k allocated page and cannot fail.
> + */
> void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
> {
> struct tpm_header *head = (struct tpm_header *) buf->data;
> @@ -28,12 +48,24 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_reset);
>
> +/**
> + * tpm_buf_destroy - destroy an initialized TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + *
> + * Frees the memory allocated to @buf.
> + */
> void tpm_buf_destroy(struct tpm_buf *buf)
> {
> free_page((unsigned long)buf->data);
> }
> EXPORT_SYMBOL_GPL(tpm_buf_destroy);
>
> +/**
> + * tpm_buf_length - get the current length of a TPM command
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + *
> + * @return: the current length of the @buf.
> + */
> u32 tpm_buf_length(struct tpm_buf *buf)
> {
> struct tpm_header *head = (struct tpm_header *)buf->data;
> @@ -42,6 +74,15 @@ u32 tpm_buf_length(struct tpm_buf *buf)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_length);
>
> +/**
> + * tpm_buf_append - append data to an initialized TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @new_data: pointer to the added data
> + * @new_len: length of the added data
> + *
> + * Appends @new_data to the end of the current @buf and updates the
> + * length.
> + */
> void tpm_buf_append(struct tpm_buf *buf,
> const unsigned char *new_data,
> unsigned int new_len)
> @@ -64,12 +105,28 @@ void tpm_buf_append(struct tpm_buf *buf,
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append);
>
> +/**
> + * tpm_buf_append_u8 - append u8 data to an initialized TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @value: the value of the data to append
> + *
> + * Appends @value as a byte to the end of the current @buf and updates
> + * the length.
> + */
> 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);
>
> +/**
> + * tpm_buf_append_u16 - append u16 data to an initialized TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @value: the value of the data to append
> + *
> + * Appends @value as a big endian short to the end of the current @buf
> + * and updates the length.
> + */
> void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
> {
> __be16 value2 = cpu_to_be16(value);
> @@ -78,6 +135,14 @@ void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append_u16);
>
> +/**
> + * tpm_buf_append_u32 - append u32 data to an initialized TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @value: the value of the data to append
> + *
> + * Appends @value as a big endian word to the end of the current @buf
> + * and updates the length.
> + */
> void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
> {
> __be32 value2 = cpu_to_be32(value);
> --
> 2.35.3
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 04/13] tpm: add buffer handling for TPM2B types
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (2 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 03/13] tpm: add kernel doc to buffer handling functions James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-23 4:12 ` Jarkko Sakkinen
2023-05-02 15:43 ` Stefan Berger
2023-04-03 21:39 ` [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing James Bottomley
` (12 subsequent siblings)
16 siblings, 2 replies; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 UTC (permalink / raw)
To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
Most complex TPM commands require appending TPM2B buffers to the
command body. TPM2B types are variable size arrays, making it
difficult to represent them as structures. Introduce primitives to
build them up using in place buffer append operations.
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
v4: add kernel doc
---
drivers/char/tpm/tpm-buf.c | 109 ++++++++++++++++++++++++++++++++-----
include/linux/tpm.h | 3 +
2 files changed, 97 insertions(+), 15 deletions(-)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 3351db515e6b..b7e42fb6266c 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -6,27 +6,16 @@
#include <linux/module.h>
#include <linux/tpm.h>
-/**
- * tpm_buf_init - initialize a TPM command buffer
- * @buf: pointer to a tpm_buf structure (usually on stack)
- * @tag: command tag
- * @ordinal: command ordinal
- *
- * Allocates a 4k buffer to hold the command structure.
- *
- * @return: 0 on success or -ENOMEM
- */
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static int __tpm_buf_init(struct tpm_buf *buf)
{
buf->data = (u8 *)__get_free_page(GFP_KERNEL);
if (!buf->data)
return -ENOMEM;
buf->flags = 0;
- tpm_buf_reset(buf, tag, ordinal);
+
return 0;
}
-EXPORT_SYMBOL_GPL(tpm_buf_init);
/**
* tpm_buf_reset - reset an initialized TPM command buffer
@@ -48,6 +37,58 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
}
EXPORT_SYMBOL_GPL(tpm_buf_reset);
+/**
+ * tpm_buf_init - initialize a TPM command buffer
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ * @tag: command tag
+ * @ordinal: command ordinal
+ *
+ * Allocates a 4k buffer to hold the command structure.
+ *
+ * @return: 0 on success or -ENOMEM
+ */
+int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+{
+ int rc;
+
+ rc = __tpm_buf_init(buf);
+ if (rc)
+ return rc;
+
+ tpm_buf_reset(buf, tag, ordinal);
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
+
+/**
+ * tpm_buf_init_2b - initialize a TPM command buffer for 2B data
+ * @buf: pointer to a tpm_buf structure (usually on stack)
+ *
+ * TPM commands are often composed of sets of TPM2B data. This
+ * function initializes a tpm_buf (@buf) as a holder of TPM2B data,
+ * which allows all the current tpm2_buf_appendX functions to work on it.
+ *
+ * @return: 0 on success or -ENOMEM
+ */
+int tpm_buf_init_2b(struct tpm_buf *buf)
+{
+ struct tpm_header *head;
+ int rc;
+
+ rc = __tpm_buf_init(buf);
+ if (rc)
+ return rc;
+
+ head = (struct tpm_header *) buf->data;
+
+ head->length = cpu_to_be32(sizeof(*head));
+
+ buf->flags = TPM_BUF_2B;
+ return 0;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init_2b);
+
/**
* tpm_buf_destroy - destroy an initialized TPM command buffer
* @buf: pointer to a tpm_buf structure (usually on stack)
@@ -60,6 +101,13 @@ void tpm_buf_destroy(struct tpm_buf *buf)
}
EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+static void *tpm_buf_data(struct tpm_buf *buf)
+{
+ if (buf->flags & TPM_BUF_2B)
+ return buf->data + TPM_HEADER_SIZE;
+ return buf->data;
+}
+
/**
* tpm_buf_length - get the current length of a TPM command
* @buf: pointer to a tpm_buf structure (usually on stack)
@@ -69,8 +117,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
u32 tpm_buf_length(struct tpm_buf *buf)
{
struct tpm_header *head = (struct tpm_header *)buf->data;
+ u32 len;
- return be32_to_cpu(head->length);
+ len = be32_to_cpu(head->length);
+ if (buf->flags & TPM_BUF_2B)
+ len -= sizeof(*head);
+ return len;
}
EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -88,7 +140,7 @@ void tpm_buf_append(struct tpm_buf *buf,
unsigned int new_len)
{
struct tpm_header *head = (struct tpm_header *) buf->data;
- u32 len = tpm_buf_length(buf);
+ u32 len = be32_to_cpu(head->length);
/* Return silently if overflow has already happened. */
if (buf->flags & TPM_BUF_OVERFLOW)
@@ -150,3 +202,30 @@ void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
tpm_buf_append(buf, (u8 *) &value2, 4);
}
EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
+
+static void tpm_buf_reset_int(struct tpm_buf *buf)
+{
+ struct tpm_header *head;
+
+ head = (struct tpm_header *)buf->data;
+ head->length = cpu_to_be32(sizeof(*head));
+}
+
+/**
+ * tpm_buf_append_2b - append TPM2B data to an initialized TPM command buffer
+ * @tpm2b: pointer to a tpm_buf structure containing the TPM2B data.
+ *
+ * Appends @tpm2b as a correct TPM2B structure (big endian short
+ * length) followed by data of that length. @tpm2b is then emptied to
+ * allow reuse.
+ */
+void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
+{
+ u16 len = tpm_buf_length(tpm2b);
+
+ tpm_buf_append_u16(buf, len);
+ tpm_buf_append(buf, tpm_buf_data(tpm2b), len);
+ /* clear the buf for reuse */
+ tpm_buf_reset_int(tpm2b);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 9c9b5760b412..76d495cb5b08 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -301,6 +301,7 @@ struct tpm_header {
enum tpm_buf_flags {
TPM_BUF_OVERFLOW = BIT(0),
+ TPM_BUF_2B = BIT(1),
};
struct tpm_buf {
@@ -325,6 +326,7 @@ struct tpm2_hash {
int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
+int tpm_buf_init_2b(struct tpm_buf *buf);
void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
void tpm_buf_destroy(struct tpm_buf *buf);
u32 tpm_buf_length(struct tpm_buf *buf);
@@ -333,6 +335,7 @@ void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
+void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
/*
* Check if TPM device is in the firmware upgrade mode.
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* Re: [PATCH v4 04/13] tpm: add buffer handling for TPM2B types
2023-04-03 21:39 ` [PATCH v4 04/13] tpm: add buffer handling for TPM2B types James Bottomley
@ 2023-04-23 4:12 ` Jarkko Sakkinen
2023-05-02 15:43 ` Stefan Berger
1 sibling, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 4:12 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> Most complex TPM commands require appending TPM2B buffers to the
> command body. TPM2B types are variable size arrays, making it
> difficult to represent them as structures. Introduce primitives to
"TPM2B is a buffer defined 16-bit size field followed by the blob."
Just state what it is, as "variable sized array" is ambiguous
terminology.
> build them up using in place buffer append operations.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
> v4: add kernel doc
> ---
> drivers/char/tpm/tpm-buf.c | 109 ++++++++++++++++++++++++++++++++-----
> include/linux/tpm.h | 3 +
> 2 files changed, 97 insertions(+), 15 deletions(-)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index 3351db515e6b..b7e42fb6266c 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -6,27 +6,16 @@
> #include <linux/module.h>
> #include <linux/tpm.h>
>
> -/**
> - * tpm_buf_init - initialize a TPM command buffer
> - * @buf: pointer to a tpm_buf structure (usually on stack)
> - * @tag: command tag
> - * @ordinal: command ordinal
> - *
> - * Allocates a 4k buffer to hold the command structure.
> - *
> - * @return: 0 on success or -ENOMEM
> - */
> -int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> +static int __tpm_buf_init(struct tpm_buf *buf)
> {
> buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> if (!buf->data)
> return -ENOMEM;
>
> buf->flags = 0;
> - tpm_buf_reset(buf, tag, ordinal);
> +
> return 0;
> }
> -EXPORT_SYMBOL_GPL(tpm_buf_init);
>
> /**
> * tpm_buf_reset - reset an initialized TPM command buffer
> @@ -48,6 +37,58 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_reset);
>
> +/**
> + * tpm_buf_init - initialize a TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @tag: command tag
> + * @ordinal: command ordinal
> + *
> + * Allocates a 4k buffer to hold the command structure.
> + *
> + * @return: 0 on success or -ENOMEM
> + */
> +int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> +{
> + int rc;
> +
> + rc = __tpm_buf_init(buf);
> + if (rc)
> + return rc;
> +
> + tpm_buf_reset(buf, tag, ordinal);
> +
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(tpm_buf_init);
> +
> +/**
> + * tpm_buf_init_2b - initialize a TPM command buffer for 2B data
> + *
> + * TPM commands are often composed of sets of TPM2B data. This
Two undescriptive terms used for the same thing:
* 2B data
* TPM2B data
I'd pick only one, and something that is understable by common sense
instead of this gibberish.
I'd suggest along the lines of:
/*
* tpm_buf_init_data - initialize a TPM data buffer
*
* TPM2 protocol uses data buffers (TPM2B_*) to carry blobs of different types.
* Each buffer starts with 16-bit unsigned integer defining the size of the
* blob that follows it.
* ...
> + * function initializes a tpm_buf (@buf) as a holder of TPM2B data,
> + * which allows all the current tpm2_buf_appendX functions to work on it.
I don't understand what I'm reading, i.e. what literally happens
when something is initialized as a holder of something else...
Please make this understandable.
> + *
> + * @return: 0 on success or -ENOMEM
> + */
> +int tpm_buf_init_2b(struct tpm_buf *buf)
> +{
> + struct tpm_header *head;
> + int rc;
> +
> + rc = __tpm_buf_init(buf);
> + if (rc)
> + return rc;
> +
> + head = (struct tpm_header *) buf->data;
> +
I'd remove this empty line.
i
> + head->length = cpu_to_be32(sizeof(*head));
> +
I'd remove this empty line.
I'm missing (not described here or in the commit message) how
can you use command header here? AFAIK, header for TPM2B_*
is 16-bit number.
Please document if something weird is done. I don't understand
this.
> + buf->flags = TPM_BUF_2B;
empty line here
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(tpm_buf_init_2b);
> +
> /**
> * tpm_buf_destroy - destroy an initialized TPM command buffer
> * @buf: pointer to a tpm_buf structure (usually on stack)
> @@ -60,6 +101,13 @@ void tpm_buf_destroy(struct tpm_buf *buf)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_destroy);
>
> +static void *tpm_buf_data(struct tpm_buf *buf)
> +{
> + if (buf->flags & TPM_BUF_2B)
> + return buf->data + TPM_HEADER_SIZE;
empty line here
> + return buf->data;
> +}
> +
> /**
> * tpm_buf_length - get the current length of a TPM command
> * @buf: pointer to a tpm_buf structure (usually on stack)
> @@ -69,8 +117,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
> u32 tpm_buf_length(struct tpm_buf *buf)
> {
> struct tpm_header *head = (struct tpm_header *)buf->data;
> + u32 len;
>
> - return be32_to_cpu(head->length);
> + len = be32_to_cpu(head->length);
> + if (buf->flags & TPM_BUF_2B)
> + len -= sizeof(*head);
empty line here
> + return len;
> }
> EXPORT_SYMBOL_GPL(tpm_buf_length);
>
> @@ -88,7 +140,7 @@ void tpm_buf_append(struct tpm_buf *buf,
> unsigned int new_len)
> {
> struct tpm_header *head = (struct tpm_header *) buf->data;
> - u32 len = tpm_buf_length(buf);
> + u32 len = be32_to_cpu(head->length);
>
> /* Return silently if overflow has already happened. */
> if (buf->flags & TPM_BUF_OVERFLOW)
> @@ -150,3 +202,30 @@ void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
> tpm_buf_append(buf, (u8 *) &value2, 4);
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
> +
> +static void tpm_buf_reset_int(struct tpm_buf *buf)
> +{
> + struct tpm_header *head;
> +
> + head = (struct tpm_header *)buf->data;
> + head->length = cpu_to_be32(sizeof(*head));
> +}
> +
> +/**
> + * tpm_buf_append_2b - append TPM2B data to an initialized TPM command buffer
> + * @tpm2b: pointer to a tpm_buf structure containing the TPM2B data.
> + *
> + * Appends @tpm2b as a correct TPM2B structure (big endian short
> + * length) followed by data of that length. @tpm2b is then emptied to
> + * allow reuse.
> + */
> +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> +{
> + u16 len = tpm_buf_length(tpm2b);
> +
> + tpm_buf_append_u16(buf, len);
> + tpm_buf_append(buf, tpm_buf_data(tpm2b), len);
> + /* clear the buf for reuse */
> + tpm_buf_reset_int(tpm2b);
> +}
> +EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 9c9b5760b412..76d495cb5b08 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -301,6 +301,7 @@ struct tpm_header {
>
> enum tpm_buf_flags {
> TPM_BUF_OVERFLOW = BIT(0),
> + TPM_BUF_2B = BIT(1),
> };
>
> struct tpm_buf {
> @@ -325,6 +326,7 @@ struct tpm2_hash {
>
>
> int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
> +int tpm_buf_init_2b(struct tpm_buf *buf);
> void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
> void tpm_buf_destroy(struct tpm_buf *buf);
> u32 tpm_buf_length(struct tpm_buf *buf);
> @@ -333,6 +335,7 @@ void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
> void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
> void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
> void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
> +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
>
> /*
> * Check if TPM device is in the firmware upgrade mode.
> --
> 2.35.3
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 04/13] tpm: add buffer handling for TPM2B types
2023-04-03 21:39 ` [PATCH v4 04/13] tpm: add buffer handling for TPM2B types James Bottomley
2023-04-23 4:12 ` Jarkko Sakkinen
@ 2023-05-02 15:43 ` Stefan Berger
2023-05-03 11:29 ` Jarkko Sakkinen
1 sibling, 1 reply; 62+ messages in thread
From: Stefan Berger @ 2023-05-02 15:43 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On 4/3/23 17:39, James Bottomley wrote:
> Most complex TPM commands require appending TPM2B buffers to the
> command body. TPM2B types are variable size arrays, making it
> difficult to represent them as structures. Introduce primitives to
> build them up using in place buffer append operations.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
> v4: add kernel doc
> ---
> drivers/char/tpm/tpm-buf.c | 109 ++++++++++++++++++++++++++++++++-----
> include/linux/tpm.h | 3 +
> 2 files changed, 97 insertions(+), 15 deletions(-)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index 3351db515e6b..b7e42fb6266c 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -6,27 +6,16 @@
> #include <linux/module.h>
> #include <linux/tpm.h>
>
> -/**
> - * tpm_buf_init - initialize a TPM command buffer
> - * @buf: pointer to a tpm_buf structure (usually on stack)
> - * @tag: command tag
> - * @ordinal: command ordinal
> - *
> - * Allocates a 4k buffer to hold the command structure.
> - *
> - * @return: 0 on success or -ENOMEM
> - */
> -int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> +static int __tpm_buf_init(struct tpm_buf *buf)
> {
> buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> if (!buf->data)
> return -ENOMEM;
>
> buf->flags = 0;
> - tpm_buf_reset(buf, tag, ordinal);
> +
> return 0;
> }
> -EXPORT_SYMBOL_GPL(tpm_buf_init);
>
> /**
> * tpm_buf_reset - reset an initialized TPM command buffer
> @@ -48,6 +37,58 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_reset);
>
> +/**
> + * tpm_buf_init - initialize a TPM command buffer
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + * @tag: command tag
> + * @ordinal: command ordinal
> + *
> + * Allocates a 4k buffer to hold the command structure.
> + *
> + * @return: 0 on success or -ENOMEM
> + */
> +int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
> +{
> + int rc;
> +
> + rc = __tpm_buf_init(buf);
> + if (rc)
> + return rc;
> +
> + tpm_buf_reset(buf, tag, ordinal);
> +
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(tpm_buf_init);
> +
> +/**
> + * tpm_buf_init_2b - initialize a TPM command buffer for 2B data
> + * @buf: pointer to a tpm_buf structure (usually on stack)
> + *
> + * TPM commands are often composed of sets of TPM2B data. This
> + * function initializes a tpm_buf (@buf) as a holder of TPM2B data,
> + * which allows all the current tpm2_buf_appendX functions to work on it.
> + *
> + * @return: 0 on success or -ENOMEM
> + */
> +int tpm_buf_init_2b(struct tpm_buf *buf)
> +{
> + struct tpm_header *head;
> + int rc;
> +
> + rc = __tpm_buf_init(buf);
> + if (rc)
> + return rc;
> +
> + head = (struct tpm_header *) buf->data;
> +
> + head->length = cpu_to_be32(sizeof(*head));
just tpm_buf_init(buf) and then set the flag below?
> +
> + buf->flags = TPM_BUF_2B;
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(tpm_buf_init_2b);
> +
> /**
> * tpm_buf_destroy - destroy an initialized TPM command buffer
> * @buf: pointer to a tpm_buf structure (usually on stack)
> @@ -60,6 +101,13 @@ void tpm_buf_destroy(struct tpm_buf *buf)
> }
> EXPORT_SYMBOL_GPL(tpm_buf_destroy);
>
> +static void *tpm_buf_data(struct tpm_buf *buf)
> +{
> + if (buf->flags & TPM_BUF_2B)
> + return buf->data + TPM_HEADER_SIZE;
> + return buf->data;
> +}
> +
> /**
> * tpm_buf_length - get the current length of a TPM command
> * @buf: pointer to a tpm_buf structure (usually on stack)
> @@ -69,8 +117,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
> u32 tpm_buf_length(struct tpm_buf *buf)
> {
> struct tpm_header *head = (struct tpm_header *)buf->data;
> + u32 len;
>
> - return be32_to_cpu(head->length);
> + len = be32_to_cpu(head->length);
> + if (buf->flags & TPM_BUF_2B)
> + len -= sizeof(*head);
> + return len;
> }
> EXPORT_SYMBOL_GPL(tpm_buf_length);
>
> @@ -88,7 +140,7 @@ void tpm_buf_append(struct tpm_buf *buf,
> unsigned int new_len)
> {
> struct tpm_header *head = (struct tpm_header *) buf->data;
> - u32 len = tpm_buf_length(buf);
> + u32 len = be32_to_cpu(head->length);
>
> /* Return silently if overflow has already happened. */
> if (buf->flags & TPM_BUF_OVERFLOW)
> @@ -150,3 +202,30 @@ void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
> tpm_buf_append(buf, (u8 *) &value2, 4);
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
> +
> +static void tpm_buf_reset_int(struct tpm_buf *buf)
> +{
> + struct tpm_header *head;
> +
> + head = (struct tpm_header *)buf->data;
> + head->length = cpu_to_be32(sizeof(*head));
tpm_buf_reset(buf, 0, 0);
in tpm_buf_reset() it seem there should be this:
buf->flags &= ~TPM_BUF_OVERFLOW;
> +}
> +
> +/**
> + * tpm_buf_append_2b - append TPM2B data to an initialized TPM command buffer
> + * @tpm2b: pointer to a tpm_buf structure containing the TPM2B data.
> + *
> + * Appends @tpm2b as a correct TPM2B structure (big endian short
> + * length) followed by data of that length. @tpm2b is then emptied to
> + * allow reuse.
> + */
> +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> +{
> + u16 len = tpm_buf_length(tpm2b);
> +
if (tpm2b->flags & TPM_BUF_OVERFLOW) {
buf->flags |= TPM_BUF_OVERFLOW;
return;
}
> + tpm_buf_append_u16(buf, len);
> + tpm_buf_append(buf, tpm_buf_data(tpm2b), len);
> + /* clear the buf for reuse */
> + tpm_buf_reset_int(tpm2b);
> +}
> +EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 9c9b5760b412..76d495cb5b08 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -301,6 +301,7 @@ struct tpm_header {
>
> enum tpm_buf_flags {
> TPM_BUF_OVERFLOW = BIT(0),
> + TPM_BUF_2B = BIT(1),
> };
>
> struct tpm_buf {
> @@ -325,6 +326,7 @@ struct tpm2_hash {
>
>
> int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
> +int tpm_buf_init_2b(struct tpm_buf *buf);
> void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
> void tpm_buf_destroy(struct tpm_buf *buf);
> u32 tpm_buf_length(struct tpm_buf *buf);
> @@ -333,6 +335,7 @@ void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
> void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
> void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
> void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
> +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
>
> /*
> * Check if TPM device is in the firmware upgrade mode.
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 04/13] tpm: add buffer handling for TPM2B types
2023-05-02 15:43 ` Stefan Berger
@ 2023-05-03 11:29 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-05-03 11:29 UTC (permalink / raw)
To: Stefan Berger, James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue May 2, 2023 at 6:43 PM EEST, Stefan Berger wrote:
> > +void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> > +{
> > + u16 len = tpm_buf_length(tpm2b);
> > +
>
> if (tpm2b->flags & TPM_BUF_OVERFLOW) {
> buf->flags |= TPM_BUF_OVERFLOW;
> return;
> }
>
> > + tpm_buf_append_u16(buf, len);
> > + tpm_buf_append(buf, tpm_buf_data(tpm2b), len);
>
>
> > + /* clear the buf for reuse */
> > + tpm_buf_reset_int(tpm2b);
This should only append. Unpredictable side-effect like this, will
add by factors to the time spent maintaining all this.
For any extra steps, do them in the call site.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (3 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 04/13] tpm: add buffer handling for TPM2B types James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-23 4:14 ` Jarkko Sakkinen
` (2 more replies)
2023-04-03 21:39 ` [PATCH v4 06/13] tpm: add buffer function to point to returned parameters James Bottomley
` (11 subsequent siblings)
16 siblings, 3 replies; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 UTC (permalink / raw)
To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
Extracting values from returned TPM buffers can be hard. Add cursor
based (moving poiner) functions that make it easier to extract TPM
returned values from a buffer.
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
v4: add kernel doc and reword commit
---
drivers/char/tpm/tpm-buf.c | 48 ++++++++++++++++++++++++++++++++++++++
include/linux/tpm.h | 3 +++
2 files changed, 51 insertions(+)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index b7e42fb6266c..da0f6e725c3f 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -6,6 +6,8 @@
#include <linux/module.h>
#include <linux/tpm.h>
+#include <asm/unaligned.h>
+
static int __tpm_buf_init(struct tpm_buf *buf)
{
buf->data = (u8 *)__get_free_page(GFP_KERNEL);
@@ -229,3 +231,49 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
tpm_buf_reset_int(tpm2b);
}
EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
+
+/* functions for unmarshalling data and moving the cursor */
+
+/**
+ * tpm_get_inc_u8 - read a u8 and move pointer beyond it
+ * @ptr: pointer to pointer
+ *
+ * @return: value read
+ */
+u8 tpm_get_inc_u8(const u8 **ptr)
+{
+ return *((*ptr)++);
+}
+EXPORT_SYMBOL_GPL(tpm_get_inc_u8);
+
+/**
+ * tpm_get_inc_u16 - read a u16 and move pointer beyond it
+ * @ptr: pointer to pointer
+ *
+ * @return: value read (converted from big endian)
+ */
+u16 tpm_get_inc_u16(const u8 **ptr)
+{
+ u16 val;
+
+ val = get_unaligned_be16(*ptr);
+ *ptr += sizeof(val);
+ return val;
+}
+EXPORT_SYMBOL_GPL(tpm_get_inc_u16);
+
+/**
+ * tpm_get_inc_u32 - read a u32 and move pointer beyond it
+ * @ptr: pointer to pointer
+ *
+ * @return: value read (converted from big endian)
+ */
+u32 tpm_get_inc_u32(const u8 **ptr)
+{
+ u32 val;
+
+ val = get_unaligned_be32(*ptr);
+ *ptr += sizeof(val);
+ return val;
+}
+EXPORT_SYMBOL_GPL(tpm_get_inc_u32);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 76d495cb5b08..845eadfed715 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -336,6 +336,9 @@ void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
+u8 tpm_get_inc_u8(const u8 **ptr);
+u16 tpm_get_inc_u16(const u8 **ptr);
+u32 tpm_get_inc_u32(const u8 **ptr);
/*
* Check if TPM device is in the firmware upgrade mode.
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* Re: [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing
2023-04-03 21:39 ` [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing James Bottomley
@ 2023-04-23 4:14 ` Jarkko Sakkinen
2023-05-02 13:54 ` Stefan Berger
2023-08-22 11:15 ` Jarkko Sakkinen
2 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 4:14 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> Extracting values from returned TPM buffers can be hard. Add cursor
> based (moving poiner) functions that make it easier to extract TPM
> returned values from a buffer.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
> v4: add kernel doc and reword commit
> ---
> drivers/char/tpm/tpm-buf.c | 48 ++++++++++++++++++++++++++++++++++++++
> include/linux/tpm.h | 3 +++
> 2 files changed, 51 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index b7e42fb6266c..da0f6e725c3f 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -6,6 +6,8 @@
> #include <linux/module.h>
> #include <linux/tpm.h>
>
> +#include <asm/unaligned.h>
> +
> static int __tpm_buf_init(struct tpm_buf *buf)
> {
> buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> @@ -229,3 +231,49 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> tpm_buf_reset_int(tpm2b);
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
> +
> +/* functions for unmarshalling data and moving the cursor */
> +
> +/**
> + * tpm_get_inc_u8 - read a u8 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read
> + */
> +u8 tpm_get_inc_u8(const u8 **ptr)
> +{
> + return *((*ptr)++);
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u8);
> +
> +/**
> + * tpm_get_inc_u16 - read a u16 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read (converted from big endian)
> + */
> +u16 tpm_get_inc_u16(const u8 **ptr)
> +{
> + u16 val;
> +
> + val = get_unaligned_be16(*ptr);
> + *ptr += sizeof(val);
> + return val;
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u16);
> +
> +/**
> + * tpm_get_inc_u32 - read a u32 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read (converted from big endian)
> + */
> +u32 tpm_get_inc_u32(const u8 **ptr)
> +{
> + u32 val;
> +
> + val = get_unaligned_be32(*ptr);
> + *ptr += sizeof(val);
> + return val;
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u32);
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 76d495cb5b08..845eadfed715 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -336,6 +336,9 @@ void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
> void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
> void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
> void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
> +u8 tpm_get_inc_u8(const u8 **ptr);
> +u16 tpm_get_inc_u16(const u8 **ptr);
> +u32 tpm_get_inc_u32(const u8 **ptr);
>
> /*
> * Check if TPM device is in the firmware upgrade mode.
> --
> 2.35.3
Why not just inline functions?
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing
2023-04-03 21:39 ` [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing James Bottomley
2023-04-23 4:14 ` Jarkko Sakkinen
@ 2023-05-02 13:54 ` Stefan Berger
2023-08-22 11:15 ` Jarkko Sakkinen
2 siblings, 0 replies; 62+ messages in thread
From: Stefan Berger @ 2023-05-02 13:54 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On 4/3/23 17:39, James Bottomley wrote:
> Extracting values from returned TPM buffers can be hard. Add cursor
> based (moving poiner) functions that make it easier to extract TPM
s/poiner/pointer
> returned values from a buffer.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
>
> ---
> v4: add kernel doc and reword commit
> ---
> drivers/char/tpm/tpm-buf.c | 48 ++++++++++++++++++++++++++++++++++++++
> include/linux/tpm.h | 3 +++
> 2 files changed, 51 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index b7e42fb6266c..da0f6e725c3f 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -6,6 +6,8 @@
> #include <linux/module.h>
> #include <linux/tpm.h>
>
> +#include <asm/unaligned.h>
> +
> static int __tpm_buf_init(struct tpm_buf *buf)
> {
> buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> @@ -229,3 +231,49 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> tpm_buf_reset_int(tpm2b);
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
> +
> +/* functions for unmarshalling data and moving the cursor */
> +
> +/**
> + * tpm_get_inc_u8 - read a u8 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read
> + */
> +u8 tpm_get_inc_u8(const u8 **ptr)
> +{
> + return *((*ptr)++);
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u8);
> +
> +/**
> + * tpm_get_inc_u16 - read a u16 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read (converted from big endian)
> + */
> +u16 tpm_get_inc_u16(const u8 **ptr)
> +{
> + u16 val;
> +
> + val = get_unaligned_be16(*ptr);
> + *ptr += sizeof(val);
> + return val;
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u16);
> +
> +/**
> + * tpm_get_inc_u32 - read a u32 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read (converted from big endian)
> + */
> +u32 tpm_get_inc_u32(const u8 **ptr)
> +{
> + u32 val;
> +
> + val = get_unaligned_be32(*ptr);
> + *ptr += sizeof(val);
> + return val;
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u32);
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index 76d495cb5b08..845eadfed715 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -336,6 +336,9 @@ void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
> void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
> void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
> void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
> +u8 tpm_get_inc_u8(const u8 **ptr);
> +u16 tpm_get_inc_u16(const u8 **ptr);
> +u32 tpm_get_inc_u32(const u8 **ptr);
>
> /*
> * Check if TPM device is in the firmware upgrade mode.
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing
2023-04-03 21:39 ` [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing James Bottomley
2023-04-23 4:14 ` Jarkko Sakkinen
2023-05-02 13:54 ` Stefan Berger
@ 2023-08-22 11:15 ` Jarkko Sakkinen
2023-08-22 13:51 ` Jarkko Sakkinen
2 siblings, 1 reply; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-08-22 11:15 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> Extracting values from returned TPM buffers can be hard. Add cursor
> based (moving poiner) functions that make it easier to extract TPM
> returned values from a buffer.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
> v4: add kernel doc and reword commit
> ---
> drivers/char/tpm/tpm-buf.c | 48 ++++++++++++++++++++++++++++++++++++++
> include/linux/tpm.h | 3 +++
> 2 files changed, 51 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index b7e42fb6266c..da0f6e725c3f 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -6,6 +6,8 @@
> #include <linux/module.h>
> #include <linux/tpm.h>
>
> +#include <asm/unaligned.h>
> +
> static int __tpm_buf_init(struct tpm_buf *buf)
> {
> buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> @@ -229,3 +231,49 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> tpm_buf_reset_int(tpm2b);
> }
> EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
> +
> +/* functions for unmarshalling data and moving the cursor */
> +
> +/**
> + * tpm_get_inc_u8 - read a u8 and move pointer beyond it
> + * @ptr: pointer to pointer
> + *
> + * @return: value read
> + */
> +u8 tpm_get_inc_u8(const u8 **ptr)
> +{
> + return *((*ptr)++);
> +}
> +EXPORT_SYMBOL_GPL(tpm_get_inc_u8);
No overflow check, and these should be static inlines.
Please consider this:
/**
* tpm_buf_read_u8() - Read a byte from a TPM buffer
* @buf: &tpm_buf instance
* @offset: offset within the consumed part of the buffer
*/
static inline int tpm_buf_read_u8(const struct tpm_buf *buf, offs_t *offset)
{
if (*offset++ >= buf->length)
return -EINVAL;
return buf->data[*offset - 1];
}
Depends on:
https://lore.kernel.org/linux-integrity/20230821033630.1039527-1-jarkko@kernel.org/
No motivation for weird cursor concept, when the reality is just
a read from a buffer.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing
2023-08-22 11:15 ` Jarkko Sakkinen
@ 2023-08-22 13:51 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-08-22 13:51 UTC (permalink / raw)
To: Jarkko Sakkinen, James Bottomley, linux-integrity
Cc: keyrings, Ard Biesheuvel
On Tue Aug 22, 2023 at 2:15 PM EEST, Jarkko Sakkinen wrote:
> On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> > Extracting values from returned TPM buffers can be hard. Add cursor
> > based (moving poiner) functions that make it easier to extract TPM
> > returned values from a buffer.
> >
> > Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> >
> > ---
> > v4: add kernel doc and reword commit
> > ---
> > drivers/char/tpm/tpm-buf.c | 48 ++++++++++++++++++++++++++++++++++++++
> > include/linux/tpm.h | 3 +++
> > 2 files changed, 51 insertions(+)
> >
> > diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> > index b7e42fb6266c..da0f6e725c3f 100644
> > --- a/drivers/char/tpm/tpm-buf.c
> > +++ b/drivers/char/tpm/tpm-buf.c
> > @@ -6,6 +6,8 @@
> > #include <linux/module.h>
> > #include <linux/tpm.h>
> >
> > +#include <asm/unaligned.h>
> > +
> > static int __tpm_buf_init(struct tpm_buf *buf)
> > {
> > buf->data = (u8 *)__get_free_page(GFP_KERNEL);
> > @@ -229,3 +231,49 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
> > tpm_buf_reset_int(tpm2b);
> > }
> > EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
> > +
> > +/* functions for unmarshalling data and moving the cursor */
> > +
> > +/**
> > + * tpm_get_inc_u8 - read a u8 and move pointer beyond it
> > + * @ptr: pointer to pointer
> > + *
> > + * @return: value read
> > + */
> > +u8 tpm_get_inc_u8(const u8 **ptr)
> > +{
> > + return *((*ptr)++);
> > +}
> > +EXPORT_SYMBOL_GPL(tpm_get_inc_u8);
>
> No overflow check, and these should be static inlines.
>
> Please consider this:
>
> /**
> * tpm_buf_read_u8() - Read a byte from a TPM buffer
> * @buf: &tpm_buf instance
> * @offset: offset within the consumed part of the buffer
> */
> static inline int tpm_buf_read_u8(const struct tpm_buf *buf, offs_t *offset)
> {
> if (*offset++ >= buf->length)
Oops, this increases pointer location, not value, sorry (should be (*offset)++).
> return -EINVAL;
>
> return buf->data[*offset - 1];
> }
Actually probably best would be if you would add first (in order to
have all the logic in a single location):
/**
* tpm_buf_read() - Read from a TPM buffer
* @buf: &tpm_buf instance
* @count: the number of bytes to read
* @offset: offset within the buffer
* @output: the output buffer
*/
int tpm_buf_read(const struct tpm_buf *buf, size_t count, offs_t *offset, void *output)
{
if (*(offset + count) >= buf->length)
return -EINVAL;
memcpy(output, &buf->data[*offset], count);
*offset += count;
] return 0;
}
EXPORT_SYMBOL_GPL(tpm_buf_read);
For instance:
static inline static int tpm_buf_read_u16(const struct tpm_buf *buf, offs_t *offset)
{
u16 value;
int ret;
ret = tpm_buf_read(buf, sizeof(u16), offset, &value);
return ret ? ret : be16_to_cpu(value);
}
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 06/13] tpm: add buffer function to point to returned parameters
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (4 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 05/13] tpm: add cursor based buffer functions for response parsing James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-05-02 14:09 ` Stefan Berger
2023-04-03 21:39 ` [PATCH v4 07/13] tpm: export the context save and load commands James Bottomley
` (10 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 UTC (permalink / raw)
To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
Introducing encryption sessions changes where the return parameters
are located in the buffer because if a return session is present
they're 4 bytes beyond the header with those 4 bytes showing the
parameter length. If there is no return session, then they're in the
usual place immediately after the header. The tpm_buf_parameters()
encapsulates this calculation and should be used everywhere
&buf.data[TPM_HEADER_SIZE] is used now.
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
---
v4: add kdoc
---
drivers/char/tpm/tpm-buf.c | 27 +++++++++++++++++++++++++++
include/linux/tpm.h | 2 ++
2 files changed, 29 insertions(+)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index da0f6e725c3f..d107321bcdff 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -277,3 +277,30 @@ u32 tpm_get_inc_u32(const u8 **ptr)
return val;
}
EXPORT_SYMBOL_GPL(tpm_get_inc_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 parameters area of the tpm_buf
+ * @buf: tpm_buf to use
+ *
+ * Where the parameters are located depends on the tag of a TPM
+ * command. 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 845eadfed715..d2fea2afd37c 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -340,6 +340,8 @@ u8 tpm_get_inc_u8(const u8 **ptr);
u16 tpm_get_inc_u16(const u8 **ptr);
u32 tpm_get_inc_u32(const u8 **ptr);
+u8 *tpm_buf_parameters(struct tpm_buf *buf);
+
/*
* Check if TPM device is in the firmware upgrade mode.
*/
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* Re: [PATCH v4 06/13] tpm: add buffer function to point to returned parameters
2023-04-03 21:39 ` [PATCH v4 06/13] tpm: add buffer function to point to returned parameters James Bottomley
@ 2023-05-02 14:09 ` Stefan Berger
2023-05-03 11:31 ` Jarkko Sakkinen
0 siblings, 1 reply; 62+ messages in thread
From: Stefan Berger @ 2023-05-02 14:09 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On 4/3/23 17:39, James Bottomley wrote:
> Introducing encryption sessions changes where the return parameters
> are located in the buffer because if a return session is present
> they're 4 bytes beyond the header with those 4 bytes showing the
> parameter length. If there is no return session, then they're in the
> usual place immediately after the header. The tpm_buf_parameters()
> encapsulates this calculation and should be used everywhere
> &buf.data[TPM_HEADER_SIZE] is used now.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
>
> ---
> v4: add kdoc
> ---
> drivers/char/tpm/tpm-buf.c | 27 +++++++++++++++++++++++++++
> include/linux/tpm.h | 2 ++
> 2 files changed, 29 insertions(+)
>
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index da0f6e725c3f..d107321bcdff 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -277,3 +277,30 @@ u32 tpm_get_inc_u32(const u8 **ptr)
> return val;
> }
> EXPORT_SYMBOL_GPL(tpm_get_inc_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 parameters area of the tpm_buf
in a TPM response
> + * @buf: tpm_buf to use
> + *
> + * Where the parameters are located depends on the tag of a TPM
> + * command. Evaluate this and return a pointer to the first byte of
> + * the parameters area.
I would also describe here what the non-obvious 4 bytes are that you are skipping over in case of TPM2_ST_SESSIONS.
With this:
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
> + *
> + * @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 845eadfed715..d2fea2afd37c 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -340,6 +340,8 @@ u8 tpm_get_inc_u8(const u8 **ptr);
> u16 tpm_get_inc_u16(const u8 **ptr);
> u32 tpm_get_inc_u32(const u8 **ptr);
>
> +u8 *tpm_buf_parameters(struct tpm_buf *buf);
> +
> /*
> * Check if TPM device is in the firmware upgrade mode.
> */
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 06/13] tpm: add buffer function to point to returned parameters
2023-05-02 14:09 ` Stefan Berger
@ 2023-05-03 11:31 ` Jarkko Sakkinen
2023-06-06 2:09 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-05-03 11:31 UTC (permalink / raw)
To: Stefan Berger, James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue May 2, 2023 at 5:09 PM EEST, Stefan Berger wrote:
>
>
> On 4/3/23 17:39, James Bottomley wrote:
> > Introducing encryption sessions changes where the return parameters
s/Introducing/Introduce/
Commit messages should always be in the imperative form.
> > are located in the buffer because if a return session is present
> > they're 4 bytes beyond the header with those 4 bytes showing the
> > parameter length. If there is no return session, then they're in the
> > usual place immediately after the header. The tpm_buf_parameters()
> > encapsulates this calculation and should be used everywhere
> > &buf.data[TPM_HEADER_SIZE] is used now.
> >
> > Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> >
> > ---
> > v4: add kdoc
> > ---
> > drivers/char/tpm/tpm-buf.c | 27 +++++++++++++++++++++++++++
> > include/linux/tpm.h | 2 ++
> > 2 files changed, 29 insertions(+)
> >
> > diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> > index da0f6e725c3f..d107321bcdff 100644
> > --- a/drivers/char/tpm/tpm-buf.c
> > +++ b/drivers/char/tpm/tpm-buf.c
> > @@ -277,3 +277,30 @@ u32 tpm_get_inc_u32(const u8 **ptr)
> > return val;
> > }
> > EXPORT_SYMBOL_GPL(tpm_get_inc_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 parameters area of the tpm_buf
>
> in a TPM response
>
>
> > + * @buf: tpm_buf to use
> > + *
> > + * Where the parameters are located depends on the tag of a TPM
> > + * command. Evaluate this and return a pointer to the first byte of
> > + * the parameters area.
>
> I would also describe here what the non-obvious 4 bytes are that you are skipping over in case of TPM2_ST_SESSIONS.
>
> With this:
>
> Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
>
> > + *
> > + * @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 845eadfed715..d2fea2afd37c 100644
> > --- a/include/linux/tpm.h
> > +++ b/include/linux/tpm.h
> > @@ -340,6 +340,8 @@ u8 tpm_get_inc_u8(const u8 **ptr);
> > u16 tpm_get_inc_u16(const u8 **ptr);
> > u32 tpm_get_inc_u32(const u8 **ptr);
> >
> > +u8 *tpm_buf_parameters(struct tpm_buf *buf);
> > +
> > /*
> > * Check if TPM device is in the firmware upgrade mode.
> > */
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 06/13] tpm: add buffer function to point to returned parameters
2023-05-03 11:31 ` Jarkko Sakkinen
@ 2023-06-06 2:09 ` James Bottomley
2023-06-06 15:34 ` Jarkko Sakkinen
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-06-06 2:09 UTC (permalink / raw)
To: Jarkko Sakkinen, Stefan Berger, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Wed, 2023-05-03 at 14:31 +0300, Jarkko Sakkinen wrote:
> On Tue May 2, 2023 at 5:09 PM EEST, Stefan Berger wrote:
> >
> >
> > On 4/3/23 17:39, James Bottomley wrote:
> > > Introducing encryption sessions changes where the return
> > > parameters
>
> s/Introducing/Introduce/
>
> Commit messages should always be in the imperative form.
"Introducing" in this sentence is a gerund (verb used as a noun); it
can't be changed to an imperative because it's not being used as a
direct verb in the sentence (that honour goes to "changes", which also
can't be made imperative because the gerund is the subject). I can
reword it like this if you want the sentence to begin with an
imperative (and get rid of the gerund before Linus bites my head off
again for using obscure grammatical constructions):
"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."
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 06/13] tpm: add buffer function to point to returned parameters
2023-06-06 2:09 ` James Bottomley
@ 2023-06-06 15:34 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-06-06 15:34 UTC (permalink / raw)
To: James Bottomley, Stefan Berger, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Tue Jun 6, 2023 at 5:09 AM EEST, James Bottomley wrote:
> On Wed, 2023-05-03 at 14:31 +0300, Jarkko Sakkinen wrote:
> > On Tue May 2, 2023 at 5:09 PM EEST, Stefan Berger wrote:
> > >
> > >
> > > On 4/3/23 17:39, James Bottomley wrote:
> > > > Introducing encryption sessions changes where the return
> > > > parameters
> >
> > s/Introducing/Introduce/
> >
> > Commit messages should always be in the imperative form.
>
> "Introducing" in this sentence is a gerund (verb used as a noun); it
> can't be changed to an imperative because it's not being used as a
> direct verb in the sentence (that honour goes to "changes", which also
> can't be made imperative because the gerund is the subject). I can
> reword it like this if you want the sentence to begin with an
> imperative (and get rid of the gerund before Linus bites my head off
> again for using obscure grammatical constructions):
>
> "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."
I'm planning to write a small (RFC) patch set just for the tpm_buf
portion because it is the part that does not work for me. What builds
on top of that looks decent, or will converge to decent.
I have some ideas that have building up in my head so I'll just dump
that as source code and see if that works for you (or not).
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 07/13] tpm: export the context save and load commands
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (5 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 06/13] tpm: add buffer function to point to returned parameters James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-05-02 14:12 ` Stefan Berger
2023-04-03 21:39 ` [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code James Bottomley
` (9 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 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>
---
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 830014a26609..00a06e3ba892 100644
--- a/drivers/char/tpm/tpm.h
+++ b/drivers/char/tpm/tpm.h
@@ -310,6 +310,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 ffb35f0154c1..d77ee4af9d65 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] 62+ messages in thread* Re: [PATCH v4 07/13] tpm: export the context save and load commands
2023-04-03 21:39 ` [PATCH v4 07/13] tpm: export the context save and load commands James Bottomley
@ 2023-05-02 14:12 ` Stefan Berger
0 siblings, 0 replies; 62+ messages in thread
From: Stefan Berger @ 2023-05-02 14:12 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On 4/3/23 17:39, James Bottomley wrote:
> 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>
> ---
> 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 830014a26609..00a06e3ba892 100644
> --- a/drivers/char/tpm/tpm.h
> +++ b/drivers/char/tpm/tpm.h
> @@ -310,6 +310,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 ffb35f0154c1..d77ee4af9d65 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;
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (6 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 07/13] tpm: export the context save and load commands James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-04 1:49 ` kernel test robot
` (2 more replies)
2023-04-03 21:39 ` [PATCH v4 09/13] tpm: add hmac checks to tpm2_pcr_extend() James Bottomley
` (8 subsequent siblings)
16 siblings, 3 replies; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 UTC (permalink / raw)
To: linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
Add true session based HMAC authentication plus parameter decryption
and response encryption using AES. The basic design is to segregate
all the nasty crypto, hash and hmac code into tpm2-sessions.c and
export a usable API. The API first of all starts off by gaining a
session with
tpm2_start_auth_session()
Which initiates a session with the TPM and allocates an opaque
tpm2_auth structure to handle the session parameters. Then the use is
simply:
* tpm_buf_append_name() in place of the tpm_buf_append_u32 for the
handles
* tpm_buf_append_hmac_session() where tpm2_append_auth() would go
* tpm_buf_fill_hmac_session() called after the entire command buffer
is finished but before tpm_transmit_cmd() is called which computes
the correct HMAC and places it in the command at the correct
location.
Finally, after tpm_transmit_cmd() is called,
tpm_buf_check_hmac_response() is called to check that the returned
HMAC matched and collect the new state for the next use of the
session, if any.
The features of the session is controlled by the session attributes
set in tpm_buf_append_hmac_session(). If TPM2_SA_CONTINUE_SESSION is
not specified, the session will be flushed and the tpm2_auth structure
freed in tpm_buf_check_hmac_response(); otherwise the session may be
used again. Parameter encryption is specified by or'ing the flag
TPM2_SA_DECRYPT and response encryption by or'ing the flag
TPM2_SA_ENCRYPT. the various encryptions will be taken care of by
tpm_buf_fill_hmac_session() and tpm_buf_check_hmac_response()
respectively.
To get all of this to work securely, the Kernel needs a primary key to
encrypt the session salt to, so an EC key from the NULL seed is
derived and its context saved in the tpm_chip structure. The context
is loaded on demand into an available volatile handle when
tpm_start_auth_session() is called, but is flushed before that
function exits to conserve handles.
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
---
v2: fix memory leaks from smatch; adjust for name hash size
v3: make tpm2_make_null_primary static
v4: use crypto library functions
---
drivers/char/tpm/Kconfig | 13 +
drivers/char/tpm/Makefile | 1 +
drivers/char/tpm/tpm-buf.c | 1 +
drivers/char/tpm/tpm-chip.c | 3 +
drivers/char/tpm/tpm.h | 10 +
drivers/char/tpm/tpm2-cmd.c | 5 +
drivers/char/tpm/tpm2-sessions.c | 1158 ++++++++++++++++++++++++++++++
include/linux/tpm.h | 165 +++++
8 files changed, 1356 insertions(+)
create mode 100644 drivers/char/tpm/tpm2-sessions.c
diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
index 927088b2c3d3..8af3afc48511 100644
--- a/drivers/char/tpm/Kconfig
+++ b/drivers/char/tpm/Kconfig
@@ -27,6 +27,19 @@ menuconfig TCG_TPM
if TCG_TPM
+config TPM_BUS_SECURITY
+ bool "Use secure 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 tamper resistent scheme
+ for communicating with the TPM to prevent or detect bus
+ snooping and iterposer attacks like TPM Genie. Saying Y here
+ adds some encryption overhead to all kernel to TPM
+ transactions.
+
config HW_RANDOM_TPM
bool "TPM HW Random Number Generator support"
depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m)
diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile
index ad3594e383e1..10dc214aa093 100644
--- a/drivers/char/tpm/Makefile
+++ b/drivers/char/tpm/Makefile
@@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o
tpm-y += eventlog/tpm2.o
tpm-y += tpm-buf.o
+tpm-$(CONFIG_TPM_BUS_SECURITY) += tpm2-sessions.o
tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
tpm-$(CONFIG_EFI) += eventlog/efi.o
tpm-$(CONFIG_OF) += eventlog/of.o
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index d107321bcdff..2127fc5e51e2 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -36,6 +36,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 0601e6e5e326..7e654776514a 100644
--- a/drivers/char/tpm/tpm-chip.c
+++ b/drivers/char/tpm/tpm-chip.c
@@ -270,6 +270,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_TPM_BUS_SECURITY
+ kfree(chip->auth);
+#endif
kfree(chip);
}
diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
index 00a06e3ba892..3ce53e47b600 100644
--- a/drivers/char/tpm/tpm.h
+++ b/drivers/char/tpm/tpm.h
@@ -319,4 +319,14 @@ void tpm_bios_log_setup(struct tpm_chip *chip);
void tpm_bios_log_teardown(struct tpm_chip *chip);
int tpm_dev_common_init(void);
void tpm_dev_common_exit(void);
+
+#ifdef CONFIG_TPM_BUS_SECURITY
+int tpm2_sessions_init(struct tpm_chip *chip);
+#else
+static inline int tpm2_sessions_init(struct tpm_chip *chip)
+{
+ return 0;
+}
+#endif
+
#endif
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..7f5cc826c8d5
--- /dev/null
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -0,0 +1,1158 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
+ *
+ * Cryptographic helper routines for handling TPM2 sessions for
+ * authorization HMAC and request response encryption.
+ *
+ * The idea is to ensure that every TPM command is HMAC protected by a
+ * session, meaning in-flight tampering would be detected and in
+ * addition all sensitive inputs and responses should be encrypted.
+ *
+ * The basic way this works is to use a TPM feature called salted
+ * sessions where a random secret used in session construction is
+ * encrypted to the public part of a known TPM key. The problem is we
+ * have no known keys, so initially a primary Elliptic Curve key is
+ * derived from the NULL seed (we use EC because most TPMs generate
+ * these keys much faster than RSA ones). The curve used is NIST_P256
+ * because that's now mandated to be present in 'TCG TPM v2.0
+ * Provisioning Guidance'
+ *
+ * Threat problems: the initial TPM2_CreatePrimary is not (and cannot
+ * be) session protected, so a clever Man in the Middle could return a
+ * public key they control to this command and from there intercept
+ * and decode all subsequent session based transactions. The kernel
+ * cannot mitigate this threat but, after boot, userspace can get
+ * proof this has not happened by asking the TPM to certify the NULL
+ * key. This certification would chain back to the TPM Endorsement
+ * Certificate and prove the NULL seed primary had not been tampered
+ * with and thus all sessions must have been cryptographically secure.
+ * To assist with this, the initial NULL seed public key name is made
+ * available in a sysfs file.
+ *
+ * Use of these functions:
+ *
+ * The design is all the crypto, hash and hmac gunk is confined in this
+ * file and never needs to be seen even by the kernel internal user. To
+ * the user there's an init function tpm2_sessions_init() that needs to
+ * be called once per TPM which generates the NULL seed primary key.
+ *
+ * Then there are six usage functions:
+ *
+ * tpm2_start_auth_session() which allocates the opaque auth structure
+ * and gets a session from the TPM. This must be called before
+ * any of the following functions. The session is protected by a
+ * session_key which is derived from a random salt value
+ * encrypted to the NULL seed.
+ * tpm2_end_auth_session() kills the session and frees the resources.
+ * Under normal operation this function is done by
+ * tpm_buf_check_hmac_response(), so this is only to be used on
+ * error legs where the latter is not executed.
+ * tpm_buf_append_name() to add a handle to the buffer. This must be
+ * used in place of the usual tpm_buf_append_u32() for adding
+ * handles because handles have to be processed specially when
+ * calculating the HMAC. In particular, for NV, volatile and
+ * permanent objects you now need to provide the name.
+ * tpm_buf_append_hmac_session() which appends the hmac session to the
+ * buf in the same way tpm_buf_append_auth does().
+ * tpm_buf_fill_hmac_session() This calculates the correct hash and
+ * places it in the buffer. It must be called after the complete
+ * command buffer is finalized so it can fill in the correct HMAC
+ * based on the parameters.
+ * tpm_buf_check_hmac_response() which checks the session response in
+ * the buffer and calculates what it should be. If there's a
+ * mismatch it will log a warning and return an error. If
+ * tpm_buf_append_hmac_session() did not specify
+ * TPM_SA_CONTINUE_SESSION then the session will be closed (if it
+ * hasn't been consumed) and the auth structure freed.
+ */
+
+#include "tpm.h"
+
+#include <linux/random.h>
+#include <linux/scatterlist.h>
+
+#include <asm/unaligned.h>
+
+#include <crypto/aes.h>
+#include <crypto/kpp.h>
+#include <crypto/ecdh.h>
+#include <crypto/hash.h>
+#include <crypto/hmac.h>
+
+/* if you change to AES256, you only need change this */
+#define AES_KEYBYTES AES_KEYSIZE_128
+
+#define AES_KEYBITS (AES_KEYBYTES*8)
+#define AUTH_MAX_NAMES 3
+
+/*
+ * This is the structure that carries all the auth information (like
+ * session handle, nonces, session key and auth) from use to use it is
+ * designed to be opaque to anything outside.
+ */
+struct tpm2_auth {
+ u32 handle;
+ /*
+ * This has two meanings: before tpm_buf_fill_hmac_session()
+ * it marks the offset in the buffer of the start of the
+ * sessions (i.e. after all the handles). Once the buffer has
+ * been filled it markes the session number of our auth
+ * session so we can find it again in the response buffer.
+ *
+ * The two cases are distinguished because the first offset
+ * must always be greater than TPM_HEADER_SIZE and the second
+ * must be less than or equal to 5.
+ */
+ u32 session;
+ /*
+ * the size here is variable and set by the size of our_nonce
+ * which must be between 16 and the name hash length. we set
+ * the maximum sha256 size for the greatest protection
+ */
+ u8 our_nonce[SHA256_DIGEST_SIZE];
+ u8 tpm_nonce[SHA256_DIGEST_SIZE];
+ /*
+ * the salt is only used across the session command/response
+ * after that it can be used as a scratch area
+ */
+ union {
+ u8 salt[EC_PT_SZ];
+ /* scratch for key + IV */
+ u8 scratch[AES_KEYBYTES + AES_BLOCK_SIZE];
+ };
+ /*
+ * the session key and passphrase are the same size as the
+ * name digest (sha256 again). The session key is constant
+ * for the use of the session and the passphrase can change
+ * with every invocation.
+ *
+ * Note: these fields must be adjacent and in this order
+ * because several HMAC/KDF schemes use the combination of the
+ * session_key and passphrase.
+ */
+ u8 session_key[SHA256_DIGEST_SIZE];
+ u8 passphrase[SHA256_DIGEST_SIZE];
+ int passphraselen;
+ struct crypto_aes_ctx aes_ctx;
+ /* saved session attributes */
+ u8 attrs;
+ __be32 ordinal;
+ /* 3 names of handles: name_h is handle, name is name of handle */
+ u32 name_h[AUTH_MAX_NAMES];
+ u8 name[AUTH_MAX_NAMES][2 + 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
+ * on every operation, so we weld the hmac init and final functions in
+ * here to give it the same usage characteristics as a regular hash
+ */
+static void hmac_init(struct sha256_state *sctx, u8 *key, int keylen)
+{
+ u8 pad[SHA256_BLOCK_SIZE];
+ int i;
+
+ sha256_init(sctx);
+ for (i = 0; i < sizeof(pad); i++) {
+ if (i < keylen)
+ pad[i] = key[i];
+ else
+ pad[i] = 0;
+ pad[i] ^= HMAC_IPAD_VALUE;
+ }
+ sha256_update(sctx, pad, sizeof(pad));
+}
+
+static void hmac_final(struct sha256_state *sctx, u8 *key, int keylen, u8 *out)
+{
+ u8 pad[SHA256_BLOCK_SIZE];
+ int i;
+
+ for (i = 0; i < sizeof(pad); i++) {
+ if (i < keylen)
+ pad[i] = key[i];
+ else
+ pad[i] = 0;
+ pad[i] ^= HMAC_OPAD_VALUE;
+ }
+
+ /* collect the final hash; use out as temporary storage */
+ 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 KDFa. Note output is in bytes not bits.
+ */
+static void KDFa(u8 *key, int keylen, const char *label, u8 *u,
+ u8 *v, int bytes, u8 *out)
+{
+ u32 counter;
+ const __be32 bits = cpu_to_be32(bytes * 8);
+
+ for (counter = 1; bytes > 0; bytes -= SHA256_DIGEST_SIZE, counter++,
+ out += SHA256_DIGEST_SIZE) {
+ struct sha256_state sctx;
+ __be32 c = cpu_to_be32(counter);
+
+ hmac_init(&sctx, key, keylen);
+ 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));
+ hmac_final(&sctx, key, keylen, out);
+ }
+}
+
+/*
+ * Somewhat of a bastardization of the real KDFe. We're assuming
+ * we're working with known point sizes for the input parameters and
+ * the hash algorithm is fixed at sha256. Because we know that the
+ * point size is 32 bytes like the hash size, there's no need to loop
+ * in this KDF.
+ */
+static void KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
+ u8 *keyout)
+{
+ 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, keyout);
+}
+
+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->ec_point_x, EC_PT_SZ);
+ sg_set_buf(&s[1], chip->ec_point_y, EC_PT_SZ);
+ kpp_request_set_input(req, s, EC_PT_SZ*2);
+ sg_init_one(d, 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
+ */
+ KDFe(chip->auth->salt, "SECRET", x, chip->ec_point_x, chip->auth->salt);
+ out:
+ 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)
+ * @passphraselen: The length of the session authority (0 if none)
+ *
+ * This fills in a session structure in the TPM command buffer, except
+ * for the HMAC which cannot be computed until the command buffer is
+ * complete. The type of session is controlled by the @attributes,
+ * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
+ * session won't terminate after tpm_buf_check_hmac_response(),
+ * TPM2_SA_DECRYPT which means this buffers first parameter should be
+ * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
+ * response buffer's first parameter needs to be decrypted (confusing,
+ * but the defines are written from the point of view of the TPM).
+ *
+ * Any session appended by this command must be finalized by calling
+ * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
+ * and the TPM will reject the command.
+ *
+ * As with most tpm_buf operations, success is assumed because failure
+ * will be caused by an incorrect programming model and indicated by a
+ * kernel message.
+ */
+void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
+ u8 attributes, u8 *passphrase,
+ int passphraselen)
+{
+ 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 && passphraselen > 0
+ && passphrase[passphraselen - 1] == '\0')
+ passphraselen--;
+
+ auth->attrs = attributes;
+ auth->passphraselen = passphraselen;
+ if (passphraselen)
+ memcpy(auth->passphrase, passphrase, passphraselen);
+
+ if (auth->session != tpm_buf_length(buf)) {
+ /* we're not the first session */
+ len = get_unaligned_be32(&buf->data[auth->session]);
+ if (4 + len + auth->session != tpm_buf_length(buf)) {
+ WARN(1, "session length mismatch, cannot append");
+ return;
+ }
+
+ /* add our new session */
+ len += 9 + 2 * SHA256_DIGEST_SIZE;
+ put_unaligned_be32(len, &buf->data[auth->session]);
+ } else {
+ tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
+ }
+
+ /* random number for our nonce */
+ get_random_bytes(nonce, sizeof(nonce));
+ memcpy(auth->our_nonce, nonce, sizeof(nonce));
+ tpm_buf_append_u32(buf, auth->handle);
+ /* our new nonce */
+ tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
+ tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
+ tpm_buf_append_u8(buf, auth->attrs);
+ /* and put a placeholder for the hmac */
+ tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
+ tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
+}
+EXPORT_SYMBOL(tpm_buf_append_hmac_session);
+
+/**
+ * tpm_buf_fill_hmac_session() - finalize the session HMAC
+ * @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;
+ const u8 *s, *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);
+
+ s = &buf->data[TPM_HEADER_SIZE];
+ /*
+ * just check the names, it's easy to make mistakes. This
+ * would happen if someone added a handle via
+ * tpm_buf_append_u32() instead of tpm_buf_append_name()
+ */
+ for (i = 0; i < handles; i++) {
+ u32 handle = tpm_get_inc_u32(&s);
+
+ if (auth->name_h[i] != handle) {
+ dev_err(&chip->dev, "TPM: handle %d wrong for name\n",
+ i);
+ return;
+ }
+ }
+ /* point s to the start of the sessions */
+ val = tpm_get_inc_u32(&s);
+ /* point p to the start of the parameters */
+ p = s + val;
+ for (i = 1; s < p; i++) {
+ u32 handle = tpm_get_inc_u32(&s);
+ u16 len;
+ u8 a;
+
+ /* nonce (already in auth) */
+ len = tpm_get_inc_u16(&s);
+ s += len;
+
+ a = *s++;
+
+ len = tpm_get_inc_u16(&s);
+ if (handle == auth->handle && auth->attrs == a) {
+ hmac = (u8 *)s;
+ /*
+ * save our session number so we know which
+ * session in the response belongs to us
+ */
+ auth->session = i;
+ }
+
+ s += len;
+ }
+ if (s != p) {
+ dev_err(&chip->dev, "TPM session length is incorrect\n");
+ return;
+ }
+ if (!hmac) {
+ dev_err(&chip->dev, "TPM could not find HMAC session\n");
+ return;
+ }
+
+ /* encrypt before HMAC */
+ if (auth->attrs & TPM2_SA_DECRYPT) {
+ u16 len;
+
+ /* need key and IV */
+ KDFa(auth->session_key, SHA256_DIGEST_SIZE
+ + auth->passphraselen, "CFB", auth->our_nonce,
+ auth->tpm_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
+ auth->scratch);
+
+ len = tpm_get_inc_u16(&p);
+ aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEYBYTES);
+ aescfb_encrypt(&auth->aes_ctx, (u8 *)p, p, len,
+ auth->scratch + AES_KEYBYTES);
+ /* reset p to beginning of parameters for HMAC */
+ 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++) {
+ u8 mso = auth->name_h[i] >> 24;
+
+ if (mso == 0x81 || mso == 0x80 || mso == 0x01) {
+ 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 (buf->data - s != tpm_buf_length(buf))
+ sha256_update(&sctx, s, buf->data + tpm_buf_length(buf) - s);
+ sha256_final(&sctx, cphash);
+
+ /* now calculate the hmac */
+ hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
+ + auth->passphraselen);
+ 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);
+ hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
+ + auth->passphraselen, hmac);
+}
+EXPORT_SYMBOL(tpm_buf_fill_hmac_session);
+
+static int parse_read_public(char *name, const u8 *data)
+{
+ struct tpm_header *head = (struct tpm_header *)data;
+ u32 tot_len = be32_to_cpu(head->length);
+ u32 val;
+
+ data += TPM_HEADER_SIZE;
+ /* we're starting after the header so adjust the length */
+ tot_len -= TPM_HEADER_SIZE;
+
+ /* skip public */
+ val = tpm_get_inc_u16(&data);
+ if (val > tot_len)
+ return -EINVAL;
+ data += val;
+ /* name */
+ val = tpm_get_inc_u16(&data);
+ if (val != name_size(data))
+ return -EINVAL;
+ memcpy(name, data, name_size(data));
+ /* forget the rest */
+ return 0;
+}
+
+static int tpm2_readpublic(struct tpm_chip *chip, u32 handle, char *name)
+{
+ struct tpm_buf buf;
+ int rc;
+
+ rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
+ if (rc)
+ return rc;
+
+ tpm_buf_append_u32(&buf, handle);
+ rc = tpm_transmit_cmd(chip, &buf, 0, "read public");
+ if (rc == TPM2_RC_SUCCESS)
+ rc = parse_read_public(name, buf.data);
+
+ tpm_buf_destroy(&buf);
+
+ return rc;
+}
+
+/**
+ * tpm_buf_append_name() - add a handle area to the buffer
+ * @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 simly
+ * the actual 4 byte handle or an empty buf (in these cases @name
+ * should be NULL) but for volatile objects, permanent objects and NV
+ * areas, the name is defined as the hash (according to the name
+ * algorithm which should be set to sha256) of the public area to
+ * which the two byte algorithm id has been appended. For these
+ * objects, the @name pointer should point to this. If a name is
+ * required but @name is NULL, then TPM2_ReadPublic() will be called
+ * on the handle to obtain the name.
+ *
+ * As with most tpm_buf operations, success is assumed because failure
+ * will be caused by an incorrect programming model and indicated by a
+ * kernel message.
+ */
+void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
+ u32 handle, u8 *name)
+{
+ int slot;
+ u8 mso = handle >> 24;
+ struct tpm2_auth *auth = chip->auth;
+
+ 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 == 0x81 || mso == 0x80 || mso == 0x01) {
+ if (!name)
+ tpm2_readpublic(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);
+
+/**
+ * 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;
+ const u8 *s, *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 */
+ s = &buf->data[TPM_HEADER_SIZE + handles * 4];
+ parm_len = tpm_get_inc_u32(&s);
+ p = s;
+ s += parm_len;
+ /* skip over any sessions before ours */
+ for (i = 0; i < auth->session - 1; i++) {
+ len = tpm_get_inc_u16(&s);
+ s += len + 1;
+ len = tpm_get_inc_u16(&s);
+ s += len;
+ }
+ /* TPM nonce */
+ len = tpm_get_inc_u16(&s);
+ if (s - buf->data + len > tpm_buf_length(buf))
+ goto out;
+ if (len != SHA256_DIGEST_SIZE)
+ goto out;
+ memcpy(auth->tpm_nonce, s, len);
+ s += len;
+ attrs = *s++;
+ len = tpm_get_inc_u16(&s);
+ if (s - buf->data + len != tpm_buf_length(buf))
+ goto out;
+ if (len != SHA256_DIGEST_SIZE)
+ goto out;
+ /*
+ * s points to the HMAC. now calculate comparison, beginning
+ * with rphash
+ */
+ 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, p, parm_len);
+ sha256_final(&sctx, rphash);
+
+ /* now calculate the hmac */
+ hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
+ + auth->passphraselen);
+ 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 */
+ hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
+ + auth->passphraselen, rphash);
+ if (memcmp(rphash, 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 */
+ KDFa(auth->session_key, SHA256_DIGEST_SIZE
+ + auth->passphraselen, "CFB", auth->tpm_nonce,
+ auth->our_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
+ auth->scratch);
+
+ len = tpm_get_inc_u16(&p);
+ aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEYBYTES);
+ aescfb_decrypt(&auth->aes_ctx, (u8 *)p, p, len,
+ auth->scratch + AES_KEYBYTES);
+ }
+
+ out:
+ if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0
+ && rc)
+ /* manually close the session if it wasn't consumed */
+ tpm2_flush_context(chip, auth->handle);
+
+ /* 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
+ *
+ * ends the session started by tpm2_start_auth_session and frees all
+ * the resources. Under normal conditions,
+ * tpm_buf_check_hmac_response() will correctly end the session if
+ * required, so this function is only for use in error legs that will
+ * bypass the normal invocation of tpm_buf_check_hmac_respons().
+ */
+void tpm2_end_auth_session(struct tpm_chip *chip)
+{
+ tpm2_flush_context(chip, chip->auth->handle);
+ chip->auth->session = TPM_HEADER_SIZE;
+}
+EXPORT_SYMBOL(tpm2_end_auth_session);
+
+static int parse_start_auth_session(struct tpm2_auth *auth, const u8 *data)
+{
+ struct tpm_header *head = (struct tpm_header *)data;
+ u32 tot_len = be32_to_cpu(head->length);
+ u32 val;
+
+ data += TPM_HEADER_SIZE;
+ /* we're starting after the header so adjust the length */
+ tot_len -= TPM_HEADER_SIZE;
+
+ /* should have handle plus nonce */
+ if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
+ return -EINVAL;
+
+ auth->handle = tpm_get_inc_u32(&data);
+ val = tpm_get_inc_u16(&data);
+ if (val != sizeof(auth->tpm_nonce))
+ return -EINVAL;
+ memcpy(auth->tpm_nonce, data, sizeof(auth->tpm_nonce));
+ /* now compute the session key from the nonces */
+ KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
+ auth->our_nonce, sizeof(auth->session_key), auth->session_key);
+
+ return 0;
+}
+
+/**
+ * tpm2_start_auth_session - create a HMAC authentication session with the TPM
+ * @chip: the TPM chip structure to create the session with
+ *
+ * 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;
+ unsigned int offset = 0; /* dummy offset for null seed context */
+ u32 nullkey;
+
+ rc = tpm2_load_context(chip, chip->tpmkeycontext, &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_KEYBITS);
+ /* symmetric algorithm mode (must be CFB) */
+ tpm_buf_append_u16(&buf, TPM_ALG_CFB);
+ /* hash algorithm for session */
+ tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
+
+ rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
+ tpm2_flush_context(chip, nullkey);
+
+ if (rc == TPM2_RC_SUCCESS)
+ rc = parse_start_auth_session(auth, buf.data);
+
+ tpm_buf_destroy(&buf);
+
+ if (rc)
+ goto out;
+
+ out:
+ return rc;
+}
+EXPORT_SYMBOL(tpm2_start_auth_session);
+
+static int parse_create_primary(struct tpm_chip *chip, u8 *data, u32 *nullkey)
+{
+ struct tpm_header *head = (struct tpm_header *)data;
+ u16 len;
+ u32 tot_len = be32_to_cpu(head->length);
+ u32 val, parm_len;
+ const u8 *resp, *tmp;
+
+ data += TPM_HEADER_SIZE;
+ /* we're starting after the header so adjust the length */
+ tot_len -= TPM_HEADER_SIZE;
+
+ resp = data;
+ *nullkey = tpm_get_inc_u32(&resp);
+ parm_len = tpm_get_inc_u32(&resp);
+ if (parm_len + 8 > tot_len)
+ return -EINVAL;
+ len = tpm_get_inc_u16(&resp);
+ tmp = resp;
+ /* now we have the public area, compute the name of the object */
+ put_unaligned_be16(TPM_ALG_SHA256, chip->tpmkeyname);
+ sha256(resp, len, chip->tpmkeyname + 2);
+
+ /* validate the public key */
+ val = tpm_get_inc_u16(&tmp);
+ /* key type (must be what we asked for) */
+ if (val != TPM_ALG_ECC)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* name algorithm */
+ if (val != TPM_ALG_SHA256)
+ return -EINVAL;
+ val = tpm_get_inc_u32(&tmp);
+ /* object properties */
+ if (val != (TPM2_OA_NO_DA |
+ TPM2_OA_FIXED_TPM |
+ TPM2_OA_FIXED_PARENT |
+ TPM2_OA_SENSITIVE_DATA_ORIGIN |
+ TPM2_OA_USER_WITH_AUTH |
+ TPM2_OA_DECRYPT |
+ TPM2_OA_RESTRICTED))
+ return -EINVAL;
+ /* auth policy (empty) */
+ val = tpm_get_inc_u16(&tmp);
+ if (val != 0)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* symmetric key parameters */
+ if (val != TPM_ALG_AES)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* symmetric key length */
+ if (val != AES_KEYBITS)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* symmetric encryption scheme */
+ if (val != TPM_ALG_CFB)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* signing scheme */
+ if (val != TPM_ALG_NULL)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* ECC Curve */
+ if (val != TPM2_ECC_NIST_P256)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* KDF Scheme */
+ if (val != TPM_ALG_NULL)
+ return -EINVAL;
+ val = tpm_get_inc_u16(&tmp);
+ /* x point */
+ if (val != 32)
+ return -EINVAL;
+ memcpy(chip->ec_point_x, tmp, val);
+ tmp += val;
+ val = tpm_get_inc_u16(&tmp);
+ if (val != 32)
+ return -EINVAL;
+ memcpy(chip->ec_point_y, tmp, val);
+ tmp += val;
+ resp += len;
+ /* should have exactly consumed the tpm2b public structure */
+ if (tmp != resp)
+ return -EINVAL;
+ if (resp - data > parm_len)
+ return -EINVAL;
+ /* creation data (skip) */
+ len = tpm_get_inc_u16(&resp);
+ resp += len;
+ if (resp - data > parm_len)
+ return -EINVAL;
+ /* creation digest (must be sha256) */
+ len = tpm_get_inc_u16(&resp);
+ resp += len;
+ if (len != SHA256_DIGEST_SIZE || resp - data > parm_len)
+ return -EINVAL;
+ /* TPMT_TK_CREATION follows */
+ /* tag, must be TPM_ST_CREATION (0x8021) */
+ val = tpm_get_inc_u16(&resp);
+ if (val != TPM2_ST_CREATION || resp - data > parm_len)
+ return -EINVAL;
+ /* hierarchy (must be NULL) */
+ val = tpm_get_inc_u32(&resp);
+ if (val != TPM2_RH_NULL || resp - data > parm_len)
+ return -EINVAL;
+ /* the ticket digest HMAC (might not be sha256) */
+ len = tpm_get_inc_u16(&resp);
+ resp += len;
+ if (resp - data > parm_len)
+ return -EINVAL;
+ /*
+ * finally we have the name, which is a sha256 digest plus a 2
+ * byte algorithm type
+ */
+ len = tpm_get_inc_u16(&resp);
+ if (resp + len - data != parm_len + 8)
+ return -EINVAL;
+ if (len != SHA256_DIGEST_SIZE + 2)
+ return -EINVAL;
+
+ if (memcmp(chip->tpmkeyname, resp, SHA256_DIGEST_SIZE + 2) != 0) {
+ dev_err(&chip->dev, "NULL Seed name comparison failed\n");
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy, u32 *handle)
+{
+ int rc;
+ struct tpm_buf buf;
+ struct tpm_buf template;
+
+ rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
+ if (rc)
+ return rc;
+
+ rc = tpm_buf_init_2b(&template);
+ if (rc) {
+ tpm_buf_destroy(&buf);
+ return rc;
+ }
+
+ /*
+ * create the template. Note: in order for userspace to
+ * verify the security of the system, it will have to create
+ * and certify this NULL primary, meaning all the template
+ * parameters will have to be identical, so conform exactly to
+ * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
+ * key
+ */
+
+ /* key type */
+ tpm_buf_append_u16(&template, TPM_ALG_ECC);
+ /* name algorithm */
+ tpm_buf_append_u16(&template, TPM_ALG_SHA256);
+ /* object properties */
+ tpm_buf_append_u32(&template, TPM2_OA_NO_DA |
+ TPM2_OA_FIXED_TPM |
+ TPM2_OA_FIXED_PARENT |
+ TPM2_OA_SENSITIVE_DATA_ORIGIN |
+ TPM2_OA_USER_WITH_AUTH |
+ TPM2_OA_DECRYPT |
+ TPM2_OA_RESTRICTED);
+ /* sauth policy (empty) */
+ tpm_buf_append_u16(&template, 0);
+
+ /* BEGIN parameters: key specific; for ECC*/
+ /* symmetric algorithm */
+ tpm_buf_append_u16(&template, TPM_ALG_AES);
+ /* bits for symmetric algorithm */
+ tpm_buf_append_u16(&template, 128);
+ /* algorithm mode (must be CFB) */
+ tpm_buf_append_u16(&template, TPM_ALG_CFB);
+ /* scheme (NULL means any scheme) */
+ tpm_buf_append_u16(&template, TPM_ALG_NULL);
+ /* ECC Curve ID */
+ tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
+ /* KDF Scheme */
+ tpm_buf_append_u16(&template, TPM_ALG_NULL);
+ /* unique: key specific; for ECC it is two points */
+ tpm_buf_append_u16(&template, 0);
+ tpm_buf_append_u16(&template, 0);
+ /* END parameters */
+
+ /* primary handle */
+ tpm_buf_append_u32(&buf, hierarchy);
+ 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_2b(&buf, &template);
+ tpm_buf_destroy(&template);
+ /* outside info (empty) */
+ tpm_buf_append_u16(&buf, 0);
+ /* creation PCR (none) */
+ tpm_buf_append_u32(&buf, 0);
+
+ rc = tpm_transmit_cmd(chip, &buf, 0,
+ "attempting to create NULL primary");
+
+ if (rc == TPM2_RC_SUCCESS)
+ rc = parse_create_primary(chip, buf.data, handle);
+
+ tpm_buf_destroy(&buf);
+
+ return rc;
+}
+
+static int tpm2_create_null_primary(struct tpm_chip *chip)
+{
+ u32 nullkey;
+ int rc;
+
+ rc = tpm2_create_primary(chip, TPM2_RH_NULL, &nullkey);
+
+ if (rc == TPM2_RC_SUCCESS) {
+ unsigned int offset = 0; /* dummy offset for tpmkeycontext */
+
+ rc = tpm2_save_context(chip, nullkey, chip->tpmkeycontext,
+ sizeof(chip->tpmkeycontext), &offset);
+ tpm2_flush_context(chip, nullkey);
+ }
+
+ return rc;
+}
+
+int tpm2_sessions_init(struct tpm_chip *chip)
+{
+ int rc;
+
+ rc = tpm2_create_null_primary(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;
+}
+EXPORT_SYMBOL(tpm2_sessions_init);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index d2fea2afd37c..af3cf219de2b 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -30,17 +30,28 @@
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 {
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 +60,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 +132,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 +200,15 @@ struct tpm_chip {
/* active locality */
int locality;
+
+#ifdef CONFIG_TPM_BUS_SECURITY
+ /* details for communication security via sessions */
+ u8 tpmkeycontext[TPM2_MAX_CONTEXT_SIZE]; /* context for NULL seed */
+ u8 tpmkeyname[TPM2_NAME_SIZE]; /* name of NULL seed */
+ u8 ec_point_x[EC_PT_SZ];
+ u8 ec_point_y[EC_PT_SZ];
+ struct tpm2_auth *auth;
+#endif
};
#define TPM_HEADER_SIZE 10
@@ -194,6 +233,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 */
@@ -231,6 +271,10 @@ enum tpm2_command_codes {
TPM2_CC_CONTEXT_LOAD = 0x0161,
TPM2_CC_CONTEXT_SAVE = 0x0162,
TPM2_CC_FLUSH_CONTEXT = 0x0165,
+ TPM2_CC_POLICY_AUTHVALUE = 0x016B,
+ TPM2_CC_POLICY_COUNTER_TIMER = 0x016D,
+ TPM2_CC_READ_PUBLIC = 0x0173,
+ TPM2_CC_START_AUTH_SESS = 0x0176,
TPM2_CC_VERIFY_SIGNATURE = 0x0177,
TPM2_CC_GET_CAPABILITY = 0x017A,
TPM2_CC_GET_RANDOM = 0x017B,
@@ -243,6 +287,7 @@ enum tpm2_command_codes {
};
enum tpm2_permanent_handles {
+ TPM2_RH_NULL = 0x40000007,
TPM2_RS_PW = 0x40000009,
};
@@ -307,16 +352,30 @@ enum tpm_buf_flags {
struct tpm_buf {
unsigned int flags;
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),
};
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 {
@@ -370,6 +429,15 @@ 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);
+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)
{
@@ -400,5 +468,102 @@ 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
+#ifdef CONFIG_TPM_BUS_SECURITY
+
+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;
+}
+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++;
+}
+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_TPM_BUS_SECURITY */
+
#endif
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-04-03 21:39 ` [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code James Bottomley
@ 2023-04-04 1:49 ` kernel test robot
2023-04-23 5:29 ` Jarkko Sakkinen
2023-11-26 3:39 ` Jarkko Sakkinen
2 siblings, 0 replies; 62+ messages in thread
From: kernel test robot @ 2023-04-04 1:49 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: oe-kbuild-all, Jarkko Sakkinen, keyrings, Ard Biesheuvel
Hi James,
kernel test robot noticed the following build warnings:
[auto build test WARNING on char-misc/char-misc-testing]
[also build test WARNING on char-misc/char-misc-next char-misc/char-misc-linus herbert-cryptodev-2.6/master herbert-crypto-2.6/master linus/master v6.3-rc5 next-20230403]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/James-Bottomley/crypto-lib-implement-library-version-of-AES-in-CFB-mode/20230404-055053
patch link: https://lore.kernel.org/r/20230403214003.32093-9-James.Bottomley%40HansenPartnership.com
patch subject: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
config: sparc-allyesconfig (https://download.01.org/0day-ci/archive/20230404/202304040920.8D4b7ebX-lkp@intel.com/config)
compiler: sparc64-linux-gcc (GCC) 12.1.0
reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/2fbef78e6bdb1d5385ac75a5a5e750fed42e53e2
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review James-Bottomley/crypto-lib-implement-library-version-of-AES-in-CFB-mode/20230404-055053
git checkout 2fbef78e6bdb1d5385ac75a5a5e750fed42e53e2
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=sparc olddefconfig
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross W=1 O=build_dir ARCH=sparc SHELL=/bin/bash drivers/char/tpm/
If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <lkp@intel.com>
| Link: https://lore.kernel.org/oe-kbuild-all/202304040920.8D4b7ebX-lkp@intel.com/
All warnings (new ones prefixed by >>):
>> drivers/char/tpm/tpm2-sessions.c:337: warning: This comment starts with '/**', but isn't a kernel-doc comment. Refer Documentation/doc-guide/kernel-doc.rst
* tpm_buf_append_hmac_session() append a TPM session element
vim +337 drivers/char/tpm/tpm2-sessions.c
335
336 /**
> 337 * tpm_buf_append_hmac_session() append a TPM session element
338 * @chip: the TPM chip structure
339 * @buf: The buffer to be appended
340 * @attributes: The session attributes
341 * @passphrase: The session authority (NULL if none)
342 * @passphraselen: The length of the session authority (0 if none)
343 *
344 * This fills in a session structure in the TPM command buffer, except
345 * for the HMAC which cannot be computed until the command buffer is
346 * complete. The type of session is controlled by the @attributes,
347 * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
348 * session won't terminate after tpm_buf_check_hmac_response(),
349 * TPM2_SA_DECRYPT which means this buffers first parameter should be
350 * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
351 * response buffer's first parameter needs to be decrypted (confusing,
352 * but the defines are written from the point of view of the TPM).
353 *
354 * Any session appended by this command must be finalized by calling
355 * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
356 * and the TPM will reject the command.
357 *
358 * As with most tpm_buf operations, success is assumed because failure
359 * will be caused by an incorrect programming model and indicated by a
360 * kernel message.
361 */
362 void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
363 u8 attributes, u8 *passphrase,
364 int passphraselen)
365 {
366 u8 nonce[SHA256_DIGEST_SIZE];
367 u32 len;
368 struct tpm2_auth *auth = chip->auth;
369
370 /*
371 * The Architecture Guide requires us to strip trailing zeros
372 * before computing the HMAC
373 */
374 while (passphrase && passphraselen > 0
375 && passphrase[passphraselen - 1] == '\0')
376 passphraselen--;
377
378 auth->attrs = attributes;
379 auth->passphraselen = passphraselen;
380 if (passphraselen)
381 memcpy(auth->passphrase, passphrase, passphraselen);
382
383 if (auth->session != tpm_buf_length(buf)) {
384 /* we're not the first session */
385 len = get_unaligned_be32(&buf->data[auth->session]);
386 if (4 + len + auth->session != tpm_buf_length(buf)) {
387 WARN(1, "session length mismatch, cannot append");
388 return;
389 }
390
391 /* add our new session */
392 len += 9 + 2 * SHA256_DIGEST_SIZE;
393 put_unaligned_be32(len, &buf->data[auth->session]);
394 } else {
395 tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
396 }
397
398 /* random number for our nonce */
399 get_random_bytes(nonce, sizeof(nonce));
400 memcpy(auth->our_nonce, nonce, sizeof(nonce));
401 tpm_buf_append_u32(buf, auth->handle);
402 /* our new nonce */
403 tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
404 tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
405 tpm_buf_append_u8(buf, auth->attrs);
406 /* and put a placeholder for the hmac */
407 tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
408 tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
409 }
410 EXPORT_SYMBOL(tpm_buf_append_hmac_session);
411
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-04-03 21:39 ` [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code James Bottomley
2023-04-04 1:49 ` kernel test robot
@ 2023-04-23 5:29 ` Jarkko Sakkinen
2023-11-26 3:39 ` Jarkko Sakkinen
2 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 5:29 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-04-03 at 17:39 -0400, James Bottomley wrote:
> Add true session based HMAC authentication plus parameter decryption
> and response encryption using AES. The basic design is to segregate
> all the nasty crypto, hash and hmac code into tpm2-sessions.c and
> export a usable API. The API first of all starts off by gaining a
> session with
>
> tpm2_start_auth_session()
>
> Which initiates a session with the TPM and allocates an opaque
> tpm2_auth structure to handle the session parameters. Then the use is
> simply:
>
> * tpm_buf_append_name() in place of the tpm_buf_append_u32 for the
> handles
>
> * tpm_buf_append_hmac_session() where tpm2_append_auth() would go
>
> * tpm_buf_fill_hmac_session() called after the entire command buffer
> is finished but before tpm_transmit_cmd() is called which computes
> the correct HMAC and places it in the command at the correct
> location.
>
> Finally, after tpm_transmit_cmd() is called,
> tpm_buf_check_hmac_response() is called to check that the returned
> HMAC matched and collect the new state for the next use of the
> session, if any.
>
> The features of the session is controlled by the session attributes
> set in tpm_buf_append_hmac_session(). If TPM2_SA_CONTINUE_SESSION is
> not specified, the session will be flushed and the tpm2_auth structure
> freed in tpm_buf_check_hmac_response(); otherwise the session may be
> used again. Parameter encryption is specified by or'ing the flag
> TPM2_SA_DECRYPT and response encryption by or'ing the flag
> TPM2_SA_ENCRYPT. the various encryptions will be taken care of by
> tpm_buf_fill_hmac_session() and tpm_buf_check_hmac_response()
> respectively.
>
> To get all of this to work securely, the Kernel needs a primary key to
> encrypt the session salt to, so an EC key from the NULL seed is
> derived and its context saved in the tpm_chip structure. The context
> is loaded on demand into an available volatile handle when
> tpm_start_auth_session() is called, but is flushed before that
> function exits to conserve handles.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
>
> ---
>
> v2: fix memory leaks from smatch; adjust for name hash size
> v3: make tpm2_make_null_primary static
> v4: use crypto library functions
> ---
> drivers/char/tpm/Kconfig | 13 +
> drivers/char/tpm/Makefile | 1 +
> drivers/char/tpm/tpm-buf.c | 1 +
> drivers/char/tpm/tpm-chip.c | 3 +
> drivers/char/tpm/tpm.h | 10 +
> drivers/char/tpm/tpm2-cmd.c | 5 +
> drivers/char/tpm/tpm2-sessions.c | 1158 ++++++++++++++++++++++++++++++
> include/linux/tpm.h | 165 +++++
> 8 files changed, 1356 insertions(+)
> create mode 100644 drivers/char/tpm/tpm2-sessions.c
>
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index 927088b2c3d3..8af3afc48511 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -27,6 +27,19 @@ menuconfig TCG_TPM
>
> if TCG_TPM
>
> +config TPM_BUS_SECURITY
"bus security" means nothing.
> + bool "Use secure transactions on the TPM bus"
Neither does "secure transactions"
> + default y
> + select CRYPTO_ECDH
> + select CRYPTO_LIB_AESCFB
> + select CRYPTO_LIB_SHA256
> + help
> + Setting this causes us to deploy a tamper resistent scheme
> + for communicating with the TPM to prevent or detect bus
> + snooping and iterposer attacks like TPM Genie. Saying Y here
> + adds some encryption overhead to all kernel to TPM
> + transactions.
AFAIK, tamper resistance is part of the physical security. Software
does not provide tamper resistance. Or at least I've not heard that
term used with software before.
Please provide URL to TPM Genie because you can't assume it being
"commmon terminology". Or if you don't want to do that, remove it
from the description as it has on function in kconfig.
From that description it is impossible to say what this *actually*
does, if we assume that the reader is kernel developer/maintainer.
It is just gibberish.
To fix all this maybe to flag could be something like
TCG_TPM_HMAC_ENCRYPTION because it adds layer of protection.
The kconfig description should essentially two things:
1. The HMAC scheme very broadly.
2. Keys generated/used, e.g. it would be nice to know if there
is a protection key for each boot cycle and that kind of stuff.
The current stuff helps no one to understand this feature.
R, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-04-03 21:39 ` [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code James Bottomley
2023-04-04 1:49 ` kernel test robot
2023-04-23 5:29 ` Jarkko Sakkinen
@ 2023-11-26 3:39 ` Jarkko Sakkinen
2023-11-26 3:45 ` Jarkko Sakkinen
2023-11-26 15:05 ` James Bottomley
2 siblings, 2 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-11-26 3:39 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
Revisiting this.
On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> Add true session based HMAC authentication plus parameter decryption
> and response encryption using AES. The basic design is to segregate
"true session based HMAC authentication" sounds like something that
would work in a marketing material but not in this context tbh.
> 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()
"...ssssion with tpm2_start_auth_session(), which initiates a session..."
(sentence structure)
> Which initiates a session with the TPM and allocates an opaque
> tpm2_auth structure to handle the session parameters. Then the use is
> simply:
>
> * tpm_buf_append_name() in place of the tpm_buf_append_u32 for the
> handles
>
> * tpm_buf_append_hmac_session() where tpm2_append_auth() would go
>
> * tpm_buf_fill_hmac_session() called after the entire command buffer
> is finished but before tpm_transmit_cmd() is called which computes
> the correct HMAC and places it in the command at the correct
> location.
>
> Finally, after tpm_transmit_cmd() is called,
> tpm_buf_check_hmac_response() is called to check that the returned
> HMAC matched and collect the new state for the next use of the
> session, if any.
>
> The features of the session is controlled by the session attributes
> set in tpm_buf_append_hmac_session(). If TPM2_SA_CONTINUE_SESSION is
> not specified, the session will be flushed and the tpm2_auth structure
> freed in tpm_buf_check_hmac_response(); otherwise the session may be
> used again. Parameter encryption is specified by or'ing the flag
> TPM2_SA_DECRYPT and response encryption by or'ing the flag
> TPM2_SA_ENCRYPT. the various encryptions will be taken care of by
> tpm_buf_fill_hmac_session() and tpm_buf_check_hmac_response()
> respectively.
>
> To get all of this to work securely, the Kernel needs a primary key to
> encrypt the session salt to, so an EC key from the NULL seed is
> derived and its context saved in the tpm_chip structure. The context
> is loaded on demand into an available volatile handle when
> tpm_start_auth_session() is called, but is flushed before that
> function exits to conserve handles.
>
> Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
>
> ---
One very obvious thing to fix there is the kconfig flag:
1. Its meaning and purpose is not documented to the commit message. What
is it and what is its meaning and purpose.
2. TPM_BUS_SECURITY does not follow the naming convention of other
TPM kconfig flags, and to add, "security" is way way too abstract
word. Something like TCG_TPM_HMAC
It should be renamed as TCG_TPM_
>
> v2: fix memory leaks from smatch; adjust for name hash size
> v3: make tpm2_make_null_primary static
> v4: use crypto library functions
> ---
> drivers/char/tpm/Kconfig | 13 +
> drivers/char/tpm/Makefile | 1 +
> drivers/char/tpm/tpm-buf.c | 1 +
> drivers/char/tpm/tpm-chip.c | 3 +
> drivers/char/tpm/tpm.h | 10 +
> drivers/char/tpm/tpm2-cmd.c | 5 +
> drivers/char/tpm/tpm2-sessions.c | 1158 ++++++++++++++++++++++++++++++
> include/linux/tpm.h | 165 +++++
> 8 files changed, 1356 insertions(+)
> create mode 100644 drivers/char/tpm/tpm2-sessions.c
>
> diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> index 927088b2c3d3..8af3afc48511 100644
> --- a/drivers/char/tpm/Kconfig
> +++ b/drivers/char/tpm/Kconfig
> @@ -27,6 +27,19 @@ menuconfig TCG_TPM
>
> if TCG_TPM
>
> +config TPM_BUS_SECURITY
> + bool "Use secure 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 tamper resistent scheme
> + for communicating with the TPM to prevent or detect bus
> + snooping and iterposer attacks like TPM Genie. Saying Y here
> + adds some encryption overhead to all kernel to TPM
> + transactions.
> +
> config HW_RANDOM_TPM
> bool "TPM HW Random Number Generator support"
> depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m)
> diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile
> index ad3594e383e1..10dc214aa093 100644
> --- a/drivers/char/tpm/Makefile
> +++ b/drivers/char/tpm/Makefile
> @@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o
> tpm-y += eventlog/tpm2.o
> tpm-y += tpm-buf.o
>
> +tpm-$(CONFIG_TPM_BUS_SECURITY) += tpm2-sessions.o
> tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
> tpm-$(CONFIG_EFI) += eventlog/efi.o
> tpm-$(CONFIG_OF) += eventlog/of.o
> diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> index d107321bcdff..2127fc5e51e2 100644
> --- a/drivers/char/tpm/tpm-buf.c
> +++ b/drivers/char/tpm/tpm-buf.c
> @@ -36,6 +36,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 0601e6e5e326..7e654776514a 100644
> --- a/drivers/char/tpm/tpm-chip.c
> +++ b/drivers/char/tpm/tpm-chip.c
> @@ -270,6 +270,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_TPM_BUS_SECURITY
> + kfree(chip->auth);
> +#endif
> kfree(chip);
> }
>
> diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
> index 00a06e3ba892..3ce53e47b600 100644
> --- a/drivers/char/tpm/tpm.h
> +++ b/drivers/char/tpm/tpm.h
> @@ -319,4 +319,14 @@ void tpm_bios_log_setup(struct tpm_chip *chip);
> void tpm_bios_log_teardown(struct tpm_chip *chip);
> int tpm_dev_common_init(void);
> void tpm_dev_common_exit(void);
> +
> +#ifdef CONFIG_TPM_BUS_SECURITY
> +int tpm2_sessions_init(struct tpm_chip *chip);
> +#else
> +static inline int tpm2_sessions_init(struct tpm_chip *chip)
> +{
> + return 0;
> +}
> +#endif
> +
> #endif
> 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..7f5cc826c8d5
> --- /dev/null
> +++ b/drivers/char/tpm/tpm2-sessions.c
> @@ -0,0 +1,1158 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +/*
> + * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
> + *
> + * Cryptographic helper routines for handling TPM2 sessions for
> + * authorization HMAC and request response encryption.
> + *
> + * The idea is to ensure that every TPM command is HMAC protected by a
> + * session, meaning in-flight tampering would be detected and in
> + * addition all sensitive inputs and responses should be encrypted.
> + *
> + * The basic way this works is to use a TPM feature called salted
> + * sessions where a random secret used in session construction is
> + * encrypted to the public part of a known TPM key. The problem is we
> + * have no known keys, so initially a primary Elliptic Curve key is
> + * derived from the NULL seed (we use EC because most TPMs generate
> + * these keys much faster than RSA ones). The curve used is NIST_P256
> + * because that's now mandated to be present in 'TCG TPM v2.0
> + * Provisioning Guidance'
> + *
> + * Threat problems: the initial TPM2_CreatePrimary is not (and cannot
> + * be) session protected, so a clever Man in the Middle could return a
> + * public key they control to this command and from there intercept
> + * and decode all subsequent session based transactions. The kernel
> + * cannot mitigate this threat but, after boot, userspace can get
> + * proof this has not happened by asking the TPM to certify the NULL
> + * key. This certification would chain back to the TPM Endorsement
> + * Certificate and prove the NULL seed primary had not been tampered
> + * with and thus all sessions must have been cryptographically secure.
> + * To assist with this, the initial NULL seed public key name is made
> + * available in a sysfs file.
> + *
> + * Use of these functions:
> + *
> + * The design is all the crypto, hash and hmac gunk is confined in this
> + * file and never needs to be seen even by the kernel internal user. To
> + * the user there's an init function tpm2_sessions_init() that needs to
> + * be called once per TPM which generates the NULL seed primary key.
What is an "init function"? Again, lot of words but not inherent
meaning.
> + *
> + * Then there are six usage functions:
> + *
> + * tpm2_start_auth_session() which allocates the opaque auth structure
> + * and gets a session from the TPM. This must be called before
> + * any of the following functions. The session is protected by a
> + * session_key which is derived from a random salt value
> + * encrypted to the NULL seed.
> + * tpm2_end_auth_session() kills the session and frees the resources.
> + * Under normal operation this function is done by
> + * tpm_buf_check_hmac_response(), so this is only to be used on
> + * error legs where the latter is not executed.
> + * tpm_buf_append_name() to add a handle to the buffer. This must be
> + * used in place of the usual tpm_buf_append_u32() for adding
> + * handles because handles have to be processed specially when
> + * calculating the HMAC. In particular, for NV, volatile and
> + * permanent objects you now need to provide the name.
> + * tpm_buf_append_hmac_session() which appends the hmac session to the
> + * buf in the same way tpm_buf_append_auth does().
> + * tpm_buf_fill_hmac_session() This calculates the correct hash and
> + * places it in the buffer. It must be called after the complete
> + * command buffer is finalized so it can fill in the correct HMAC
> + * based on the parameters.
> + * tpm_buf_check_hmac_response() which checks the session response in
> + * the buffer and calculates what it should be. If there's a
> + * mismatch it will log a warning and return an error. If
> + * tpm_buf_append_hmac_session() did not specify
> + * TPM_SA_CONTINUE_SESSION then the session will be closed (if it
> + * hasn't been consumed) and the auth structure freed.
> + */
> +
> +#include "tpm.h"
> +
> +#include <linux/random.h>
> +#include <linux/scatterlist.h>
> +
> +#include <asm/unaligned.h>
> +
> +#include <crypto/aes.h>
> +#include <crypto/kpp.h>
> +#include <crypto/ecdh.h>
> +#include <crypto/hash.h>
> +#include <crypto/hmac.h>
> +
> +/* if you change to AES256, you only need change this */
> +#define AES_KEYBYTES AES_KEYSIZE_128
> +
> +#define AES_KEYBITS (AES_KEYBYTES*8)
> +#define AUTH_MAX_NAMES 3
> +
> +/*
> + * This is the structure that carries all the auth information (like
> + * session handle, nonces, session key and auth) from use to use it is
> + * designed to be opaque to anything outside.
> + */
> +struct tpm2_auth {
> + u32 handle;
> + /*
> + * This has two meanings: before tpm_buf_fill_hmac_session()
> + * it marks the offset in the buffer of the start of the
> + * sessions (i.e. after all the handles). Once the buffer has
> + * been filled it markes the session number of our auth
> + * session so we can find it again in the response buffer.
> + *
> + * The two cases are distinguished because the first offset
> + * must always be greater than TPM_HEADER_SIZE and the second
> + * must be less than or equal to 5.
> + */
> + u32 session;
> + /*
> + * the size here is variable and set by the size of our_nonce
> + * which must be between 16 and the name hash length. we set
> + * the maximum sha256 size for the greatest protection
> + */
> + u8 our_nonce[SHA256_DIGEST_SIZE];
> + u8 tpm_nonce[SHA256_DIGEST_SIZE];
> + /*
> + * the salt is only used across the session command/response
> + * after that it can be used as a scratch area
> + */
> + union {
> + u8 salt[EC_PT_SZ];
> + /* scratch for key + IV */
> + u8 scratch[AES_KEYBYTES + AES_BLOCK_SIZE];
> + };
> + /*
> + * the session key and passphrase are the same size as the
> + * name digest (sha256 again). The session key is constant
> + * for the use of the session and the passphrase can change
> + * with every invocation.
> + *
> + * Note: these fields must be adjacent and in this order
> + * because several HMAC/KDF schemes use the combination of the
> + * session_key and passphrase.
> + */
> + u8 session_key[SHA256_DIGEST_SIZE];
> + u8 passphrase[SHA256_DIGEST_SIZE];
> + int passphraselen;
> + struct crypto_aes_ctx aes_ctx;
> + /* saved session attributes */
> + u8 attrs;
> + __be32 ordinal;
> + /* 3 names of handles: name_h is handle, name is name of handle */
> + u32 name_h[AUTH_MAX_NAMES];
> + u8 name[AUTH_MAX_NAMES][2 + 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
> + * on every operation, so we weld the hmac init and final functions in
> + * here to give it the same usage characteristics as a regular hash
> + */
> +static void hmac_init(struct sha256_state *sctx, u8 *key, int keylen)
> +{
> + u8 pad[SHA256_BLOCK_SIZE];
> + int i;
> +
> + sha256_init(sctx);
> + for (i = 0; i < sizeof(pad); i++) {
> + if (i < keylen)
> + pad[i] = key[i];
> + else
> + pad[i] = 0;
> + pad[i] ^= HMAC_IPAD_VALUE;
> + }
> + sha256_update(sctx, pad, sizeof(pad));
> +}
> +
> +static void hmac_final(struct sha256_state *sctx, u8 *key, int keylen, u8 *out)
> +{
> + u8 pad[SHA256_BLOCK_SIZE];
> + int i;
> +
> + for (i = 0; i < sizeof(pad); i++) {
> + if (i < keylen)
> + pad[i] = key[i];
> + else
> + pad[i] = 0;
> + pad[i] ^= HMAC_OPAD_VALUE;
> + }
> +
> + /* collect the final hash; use out as temporary storage */
> + 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 KDFa. Note output is in bytes not bits.
> + */
> +static void KDFa(u8 *key, int keylen, const char *label, u8 *u,
> + u8 *v, int bytes, u8 *out)
> +{
> + u32 counter;
> + const __be32 bits = cpu_to_be32(bytes * 8);
> +
> + for (counter = 1; bytes > 0; bytes -= SHA256_DIGEST_SIZE, counter++,
> + out += SHA256_DIGEST_SIZE) {
> + struct sha256_state sctx;
> + __be32 c = cpu_to_be32(counter);
> +
> + hmac_init(&sctx, key, keylen);
> + 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));
> + hmac_final(&sctx, key, keylen, out);
> + }
> +}
> +
> +/*
> + * Somewhat of a bastardization of the real KDFe. We're assuming
> + * we're working with known point sizes for the input parameters and
> + * the hash algorithm is fixed at sha256. Because we know that the
> + * point size is 32 bytes like the hash size, there's no need to loop
> + * in this KDF.
> + */
> +static void KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
> + u8 *keyout)
> +{
> + 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, keyout);
> +}
> +
> +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->ec_point_x, EC_PT_SZ);
> + sg_set_buf(&s[1], chip->ec_point_y, EC_PT_SZ);
> + kpp_request_set_input(req, s, EC_PT_SZ*2);
> + sg_init_one(d, 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
> + */
> + KDFe(chip->auth->salt, "SECRET", x, chip->ec_point_x, chip->auth->salt);
> + out:
> + 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)
> + * @passphraselen: The length of the session authority (0 if none)
> + *
> + * This fills in a session structure in the TPM command buffer, except
> + * for the HMAC which cannot be computed until the command buffer is
> + * complete. The type of session is controlled by the @attributes,
> + * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
> + * session won't terminate after tpm_buf_check_hmac_response(),
> + * TPM2_SA_DECRYPT which means this buffers first parameter should be
> + * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
> + * response buffer's first parameter needs to be decrypted (confusing,
> + * but the defines are written from the point of view of the TPM).
> + *
> + * Any session appended by this command must be finalized by calling
> + * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
> + * and the TPM will reject the command.
> + *
> + * As with most tpm_buf operations, success is assumed because failure
> + * will be caused by an incorrect programming model and indicated by a
> + * kernel message.
> + */
> +void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
> + u8 attributes, u8 *passphrase,
> + int passphraselen)
> +{
> + 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 && passphraselen > 0
> + && passphrase[passphraselen - 1] == '\0')
> + passphraselen--;
> +
> + auth->attrs = attributes;
> + auth->passphraselen = passphraselen;
> + if (passphraselen)
> + memcpy(auth->passphrase, passphrase, passphraselen);
> +
> + if (auth->session != tpm_buf_length(buf)) {
> + /* we're not the first session */
> + len = get_unaligned_be32(&buf->data[auth->session]);
> + if (4 + len + auth->session != tpm_buf_length(buf)) {
> + WARN(1, "session length mismatch, cannot append");
> + return;
> + }
> +
> + /* add our new session */
> + len += 9 + 2 * SHA256_DIGEST_SIZE;
> + put_unaligned_be32(len, &buf->data[auth->session]);
> + } else {
> + tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
> + }
> +
> + /* random number for our nonce */
> + get_random_bytes(nonce, sizeof(nonce));
> + memcpy(auth->our_nonce, nonce, sizeof(nonce));
> + tpm_buf_append_u32(buf, auth->handle);
> + /* our new nonce */
> + tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
> + tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
> + tpm_buf_append_u8(buf, auth->attrs);
> + /* and put a placeholder for the hmac */
> + tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
> + tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
> +}
> +EXPORT_SYMBOL(tpm_buf_append_hmac_session);
> +
> +/**
> + * tpm_buf_fill_hmac_session() - finalize the session HMAC
> + * @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;
> + const u8 *s, *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);
> +
> + s = &buf->data[TPM_HEADER_SIZE];
> + /*
> + * just check the names, it's easy to make mistakes. This
> + * would happen if someone added a handle via
> + * tpm_buf_append_u32() instead of tpm_buf_append_name()
> + */
> + for (i = 0; i < handles; i++) {
> + u32 handle = tpm_get_inc_u32(&s);
> +
> + if (auth->name_h[i] != handle) {
> + dev_err(&chip->dev, "TPM: handle %d wrong for name\n",
> + i);
> + return;
> + }
> + }
> + /* point s to the start of the sessions */
> + val = tpm_get_inc_u32(&s);
> + /* point p to the start of the parameters */
> + p = s + val;
> + for (i = 1; s < p; i++) {
> + u32 handle = tpm_get_inc_u32(&s);
> + u16 len;
> + u8 a;
> +
> + /* nonce (already in auth) */
> + len = tpm_get_inc_u16(&s);
> + s += len;
> +
> + a = *s++;
> +
> + len = tpm_get_inc_u16(&s);
> + if (handle == auth->handle && auth->attrs == a) {
> + hmac = (u8 *)s;
> + /*
> + * save our session number so we know which
> + * session in the response belongs to us
> + */
> + auth->session = i;
> + }
> +
> + s += len;
> + }
> + if (s != p) {
> + dev_err(&chip->dev, "TPM session length is incorrect\n");
> + return;
> + }
> + if (!hmac) {
> + dev_err(&chip->dev, "TPM could not find HMAC session\n");
> + return;
> + }
> +
> + /* encrypt before HMAC */
> + if (auth->attrs & TPM2_SA_DECRYPT) {
> + u16 len;
> +
> + /* need key and IV */
> + KDFa(auth->session_key, SHA256_DIGEST_SIZE
> + + auth->passphraselen, "CFB", auth->our_nonce,
> + auth->tpm_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
> + auth->scratch);
> +
> + len = tpm_get_inc_u16(&p);
> + aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEYBYTES);
> + aescfb_encrypt(&auth->aes_ctx, (u8 *)p, p, len,
> + auth->scratch + AES_KEYBYTES);
> + /* reset p to beginning of parameters for HMAC */
> + 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++) {
> + u8 mso = auth->name_h[i] >> 24;
> +
> + if (mso == 0x81 || mso == 0x80 || mso == 0x01) {
> + 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 (buf->data - s != tpm_buf_length(buf))
> + sha256_update(&sctx, s, buf->data + tpm_buf_length(buf) - s);
> + sha256_final(&sctx, cphash);
> +
> + /* now calculate the hmac */
> + hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
> + + auth->passphraselen);
> + 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);
> + hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
> + + auth->passphraselen, hmac);
> +}
> +EXPORT_SYMBOL(tpm_buf_fill_hmac_session);
> +
> +static int parse_read_public(char *name, const u8 *data)
> +{
> + struct tpm_header *head = (struct tpm_header *)data;
> + u32 tot_len = be32_to_cpu(head->length);
> + u32 val;
> +
> + data += TPM_HEADER_SIZE;
> + /* we're starting after the header so adjust the length */
> + tot_len -= TPM_HEADER_SIZE;
> +
> + /* skip public */
> + val = tpm_get_inc_u16(&data);
> + if (val > tot_len)
> + return -EINVAL;
> + data += val;
> + /* name */
> + val = tpm_get_inc_u16(&data);
> + if (val != name_size(data))
> + return -EINVAL;
> + memcpy(name, data, name_size(data));
> + /* forget the rest */
> + return 0;
> +}
> +
> +static int tpm2_readpublic(struct tpm_chip *chip, u32 handle, char *name)
> +{
> + struct tpm_buf buf;
> + int rc;
> +
> + rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
> + if (rc)
> + return rc;
> +
> + tpm_buf_append_u32(&buf, handle);
> + rc = tpm_transmit_cmd(chip, &buf, 0, "read public");
> + if (rc == TPM2_RC_SUCCESS)
> + rc = parse_read_public(name, buf.data);
> +
> + tpm_buf_destroy(&buf);
> +
> + return rc;
> +}
> +
> +/**
> + * tpm_buf_append_name() - add a handle area to the buffer
> + * @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 simly
> + * the actual 4 byte handle or an empty buf (in these cases @name
> + * should be NULL) but for volatile objects, permanent objects and NV
> + * areas, the name is defined as the hash (according to the name
> + * algorithm which should be set to sha256) of the public area to
> + * which the two byte algorithm id has been appended. For these
> + * objects, the @name pointer should point to this. If a name is
> + * required but @name is NULL, then TPM2_ReadPublic() will be called
> + * on the handle to obtain the name.
> + *
> + * As with most tpm_buf operations, success is assumed because failure
> + * will be caused by an incorrect programming model and indicated by a
> + * kernel message.
> + */
> +void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
> + u32 handle, u8 *name)
> +{
> + int slot;
> + u8 mso = handle >> 24;
> + struct tpm2_auth *auth = chip->auth;
> +
> + 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 == 0x81 || mso == 0x80 || mso == 0x01) {
> + if (!name)
> + tpm2_readpublic(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);
> +
> +/**
> + * 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;
> + const u8 *s, *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 */
> + s = &buf->data[TPM_HEADER_SIZE + handles * 4];
> + parm_len = tpm_get_inc_u32(&s);
> + p = s;
> + s += parm_len;
> + /* skip over any sessions before ours */
> + for (i = 0; i < auth->session - 1; i++) {
> + len = tpm_get_inc_u16(&s);
> + s += len + 1;
> + len = tpm_get_inc_u16(&s);
> + s += len;
> + }
> + /* TPM nonce */
> + len = tpm_get_inc_u16(&s);
> + if (s - buf->data + len > tpm_buf_length(buf))
> + goto out;
> + if (len != SHA256_DIGEST_SIZE)
> + goto out;
> + memcpy(auth->tpm_nonce, s, len);
> + s += len;
> + attrs = *s++;
> + len = tpm_get_inc_u16(&s);
> + if (s - buf->data + len != tpm_buf_length(buf))
> + goto out;
> + if (len != SHA256_DIGEST_SIZE)
> + goto out;
> + /*
> + * s points to the HMAC. now calculate comparison, beginning
> + * with rphash
> + */
> + 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, p, parm_len);
> + sha256_final(&sctx, rphash);
> +
> + /* now calculate the hmac */
> + hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
> + + auth->passphraselen);
> + 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 */
> + hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
> + + auth->passphraselen, rphash);
> + if (memcmp(rphash, 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 */
> + KDFa(auth->session_key, SHA256_DIGEST_SIZE
> + + auth->passphraselen, "CFB", auth->tpm_nonce,
> + auth->our_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
> + auth->scratch);
> +
> + len = tpm_get_inc_u16(&p);
> + aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEYBYTES);
> + aescfb_decrypt(&auth->aes_ctx, (u8 *)p, p, len,
> + auth->scratch + AES_KEYBYTES);
> + }
> +
> + out:
> + if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0
> + && rc)
> + /* manually close the session if it wasn't consumed */
> + tpm2_flush_context(chip, auth->handle);
> +
> + /* 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
> + *
> + * ends the session started by tpm2_start_auth_session and frees all
> + * the resources. Under normal conditions,
> + * tpm_buf_check_hmac_response() will correctly end the session if
> + * required, so this function is only for use in error legs that will
> + * bypass the normal invocation of tpm_buf_check_hmac_respons().
> + */
> +void tpm2_end_auth_session(struct tpm_chip *chip)
> +{
> + tpm2_flush_context(chip, chip->auth->handle);
> + chip->auth->session = TPM_HEADER_SIZE;
> +}
> +EXPORT_SYMBOL(tpm2_end_auth_session);
> +
> +static int parse_start_auth_session(struct tpm2_auth *auth, const u8 *data)
> +{
> + struct tpm_header *head = (struct tpm_header *)data;
> + u32 tot_len = be32_to_cpu(head->length);
> + u32 val;
> +
> + data += TPM_HEADER_SIZE;
> + /* we're starting after the header so adjust the length */
> + tot_len -= TPM_HEADER_SIZE;
> +
> + /* should have handle plus nonce */
> + if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
> + return -EINVAL;
> +
> + auth->handle = tpm_get_inc_u32(&data);
> + val = tpm_get_inc_u16(&data);
> + if (val != sizeof(auth->tpm_nonce))
> + return -EINVAL;
> + memcpy(auth->tpm_nonce, data, sizeof(auth->tpm_nonce));
> + /* now compute the session key from the nonces */
> + KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
> + auth->our_nonce, sizeof(auth->session_key), auth->session_key);
> +
> + return 0;
> +}
> +
> +/**
> + * tpm2_start_auth_session - create a HMAC authentication session with the TPM
> + * @chip: the TPM chip structure to create the session with
> + *
> + * 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;
> + unsigned int offset = 0; /* dummy offset for null seed context */
> + u32 nullkey;
> +
> + rc = tpm2_load_context(chip, chip->tpmkeycontext, &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_KEYBITS);
> + /* symmetric algorithm mode (must be CFB) */
> + tpm_buf_append_u16(&buf, TPM_ALG_CFB);
> + /* hash algorithm for session */
> + tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
> +
> + rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
> + tpm2_flush_context(chip, nullkey);
> +
> + if (rc == TPM2_RC_SUCCESS)
> + rc = parse_start_auth_session(auth, buf.data);
> +
> + tpm_buf_destroy(&buf);
> +
> + if (rc)
> + goto out;
> +
> + out:
> + return rc;
> +}
> +EXPORT_SYMBOL(tpm2_start_auth_session);
> +
> +static int parse_create_primary(struct tpm_chip *chip, u8 *data, u32 *nullkey)
> +{
> + struct tpm_header *head = (struct tpm_header *)data;
> + u16 len;
> + u32 tot_len = be32_to_cpu(head->length);
> + u32 val, parm_len;
> + const u8 *resp, *tmp;
> +
> + data += TPM_HEADER_SIZE;
> + /* we're starting after the header so adjust the length */
> + tot_len -= TPM_HEADER_SIZE;
> +
> + resp = data;
> + *nullkey = tpm_get_inc_u32(&resp);
> + parm_len = tpm_get_inc_u32(&resp);
> + if (parm_len + 8 > tot_len)
> + return -EINVAL;
> + len = tpm_get_inc_u16(&resp);
> + tmp = resp;
> + /* now we have the public area, compute the name of the object */
> + put_unaligned_be16(TPM_ALG_SHA256, chip->tpmkeyname);
> + sha256(resp, len, chip->tpmkeyname + 2);
> +
> + /* validate the public key */
> + val = tpm_get_inc_u16(&tmp);
> + /* key type (must be what we asked for) */
> + if (val != TPM_ALG_ECC)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* name algorithm */
> + if (val != TPM_ALG_SHA256)
> + return -EINVAL;
> + val = tpm_get_inc_u32(&tmp);
> + /* object properties */
> + if (val != (TPM2_OA_NO_DA |
> + TPM2_OA_FIXED_TPM |
> + TPM2_OA_FIXED_PARENT |
> + TPM2_OA_SENSITIVE_DATA_ORIGIN |
> + TPM2_OA_USER_WITH_AUTH |
> + TPM2_OA_DECRYPT |
> + TPM2_OA_RESTRICTED))
> + return -EINVAL;
> + /* auth policy (empty) */
> + val = tpm_get_inc_u16(&tmp);
> + if (val != 0)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* symmetric key parameters */
> + if (val != TPM_ALG_AES)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* symmetric key length */
> + if (val != AES_KEYBITS)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* symmetric encryption scheme */
> + if (val != TPM_ALG_CFB)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* signing scheme */
> + if (val != TPM_ALG_NULL)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* ECC Curve */
> + if (val != TPM2_ECC_NIST_P256)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* KDF Scheme */
> + if (val != TPM_ALG_NULL)
> + return -EINVAL;
> + val = tpm_get_inc_u16(&tmp);
> + /* x point */
> + if (val != 32)
> + return -EINVAL;
> + memcpy(chip->ec_point_x, tmp, val);
> + tmp += val;
> + val = tpm_get_inc_u16(&tmp);
> + if (val != 32)
> + return -EINVAL;
> + memcpy(chip->ec_point_y, tmp, val);
> + tmp += val;
> + resp += len;
> + /* should have exactly consumed the tpm2b public structure */
> + if (tmp != resp)
> + return -EINVAL;
> + if (resp - data > parm_len)
> + return -EINVAL;
> + /* creation data (skip) */
> + len = tpm_get_inc_u16(&resp);
> + resp += len;
> + if (resp - data > parm_len)
> + return -EINVAL;
> + /* creation digest (must be sha256) */
> + len = tpm_get_inc_u16(&resp);
> + resp += len;
> + if (len != SHA256_DIGEST_SIZE || resp - data > parm_len)
> + return -EINVAL;
> + /* TPMT_TK_CREATION follows */
> + /* tag, must be TPM_ST_CREATION (0x8021) */
> + val = tpm_get_inc_u16(&resp);
> + if (val != TPM2_ST_CREATION || resp - data > parm_len)
> + return -EINVAL;
> + /* hierarchy (must be NULL) */
> + val = tpm_get_inc_u32(&resp);
> + if (val != TPM2_RH_NULL || resp - data > parm_len)
> + return -EINVAL;
> + /* the ticket digest HMAC (might not be sha256) */
> + len = tpm_get_inc_u16(&resp);
> + resp += len;
> + if (resp - data > parm_len)
> + return -EINVAL;
> + /*
> + * finally we have the name, which is a sha256 digest plus a 2
> + * byte algorithm type
> + */
> + len = tpm_get_inc_u16(&resp);
> + if (resp + len - data != parm_len + 8)
> + return -EINVAL;
> + if (len != SHA256_DIGEST_SIZE + 2)
> + return -EINVAL;
> +
> + if (memcmp(chip->tpmkeyname, resp, SHA256_DIGEST_SIZE + 2) != 0) {
> + dev_err(&chip->dev, "NULL Seed name comparison failed\n");
> + return -EINVAL;
> + }
> +
> + return 0;
> +}
> +
> +static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy, u32 *handle)
> +{
> + int rc;
> + struct tpm_buf buf;
> + struct tpm_buf template;
> +
> + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
> + if (rc)
> + return rc;
> +
> + rc = tpm_buf_init_2b(&template);
> + if (rc) {
> + tpm_buf_destroy(&buf);
> + return rc;
> + }
> +
> + /*
> + * create the template. Note: in order for userspace to
> + * verify the security of the system, it will have to create
> + * and certify this NULL primary, meaning all the template
> + * parameters will have to be identical, so conform exactly to
> + * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
> + * key
> + */
> +
> + /* key type */
> + tpm_buf_append_u16(&template, TPM_ALG_ECC);
> + /* name algorithm */
> + tpm_buf_append_u16(&template, TPM_ALG_SHA256);
> + /* object properties */
> + tpm_buf_append_u32(&template, TPM2_OA_NO_DA |
> + TPM2_OA_FIXED_TPM |
> + TPM2_OA_FIXED_PARENT |
> + TPM2_OA_SENSITIVE_DATA_ORIGIN |
> + TPM2_OA_USER_WITH_AUTH |
> + TPM2_OA_DECRYPT |
> + TPM2_OA_RESTRICTED);
> + /* sauth policy (empty) */
> + tpm_buf_append_u16(&template, 0);
> +
> + /* BEGIN parameters: key specific; for ECC*/
> + /* symmetric algorithm */
> + tpm_buf_append_u16(&template, TPM_ALG_AES);
> + /* bits for symmetric algorithm */
> + tpm_buf_append_u16(&template, 128);
> + /* algorithm mode (must be CFB) */
> + tpm_buf_append_u16(&template, TPM_ALG_CFB);
> + /* scheme (NULL means any scheme) */
> + tpm_buf_append_u16(&template, TPM_ALG_NULL);
> + /* ECC Curve ID */
> + tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
> + /* KDF Scheme */
> + tpm_buf_append_u16(&template, TPM_ALG_NULL);
> + /* unique: key specific; for ECC it is two points */
> + tpm_buf_append_u16(&template, 0);
> + tpm_buf_append_u16(&template, 0);
> + /* END parameters */
> +
> + /* primary handle */
> + tpm_buf_append_u32(&buf, hierarchy);
> + 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_2b(&buf, &template);
> + tpm_buf_destroy(&template);
> + /* outside info (empty) */
> + tpm_buf_append_u16(&buf, 0);
> + /* creation PCR (none) */
> + tpm_buf_append_u32(&buf, 0);
> +
> + rc = tpm_transmit_cmd(chip, &buf, 0,
> + "attempting to create NULL primary");
> +
> + if (rc == TPM2_RC_SUCCESS)
> + rc = parse_create_primary(chip, buf.data, handle);
> +
> + tpm_buf_destroy(&buf);
> +
> + return rc;
> +}
> +
> +static int tpm2_create_null_primary(struct tpm_chip *chip)
> +{
> + u32 nullkey;
> + int rc;
> +
> + rc = tpm2_create_primary(chip, TPM2_RH_NULL, &nullkey);
> +
> + if (rc == TPM2_RC_SUCCESS) {
> + unsigned int offset = 0; /* dummy offset for tpmkeycontext */
> +
> + rc = tpm2_save_context(chip, nullkey, chip->tpmkeycontext,
> + sizeof(chip->tpmkeycontext), &offset);
> + tpm2_flush_context(chip, nullkey);
> + }
> +
> + return rc;
> +}
> +
> +int tpm2_sessions_init(struct tpm_chip *chip)
Neithe here is an explanation what is an "init function".
> +{
> + int rc;
> +
> + rc = tpm2_create_null_primary(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;
> +}
> +EXPORT_SYMBOL(tpm2_sessions_init);
> diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> index d2fea2afd37c..af3cf219de2b 100644
> --- a/include/linux/tpm.h
> +++ b/include/linux/tpm.h
> @@ -30,17 +30,28 @@
> 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 {
> 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 +60,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 +132,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 +200,15 @@ struct tpm_chip {
>
> /* active locality */
> int locality;
> +
> +#ifdef CONFIG_TPM_BUS_SECURITY
> + /* details for communication security via sessions */
> + u8 tpmkeycontext[TPM2_MAX_CONTEXT_SIZE]; /* context for NULL seed */
> + u8 tpmkeyname[TPM2_NAME_SIZE]; /* name of NULL seed */
> + u8 ec_point_x[EC_PT_SZ];
> + u8 ec_point_y[EC_PT_SZ];
> + struct tpm2_auth *auth;
> +#endif
> };
>
> #define TPM_HEADER_SIZE 10
> @@ -194,6 +233,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 */
> @@ -231,6 +271,10 @@ enum tpm2_command_codes {
> TPM2_CC_CONTEXT_LOAD = 0x0161,
> TPM2_CC_CONTEXT_SAVE = 0x0162,
> TPM2_CC_FLUSH_CONTEXT = 0x0165,
> + TPM2_CC_POLICY_AUTHVALUE = 0x016B,
> + TPM2_CC_POLICY_COUNTER_TIMER = 0x016D,
> + TPM2_CC_READ_PUBLIC = 0x0173,
> + TPM2_CC_START_AUTH_SESS = 0x0176,
> TPM2_CC_VERIFY_SIGNATURE = 0x0177,
> TPM2_CC_GET_CAPABILITY = 0x017A,
> TPM2_CC_GET_RANDOM = 0x017B,
> @@ -243,6 +287,7 @@ enum tpm2_command_codes {
> };
>
> enum tpm2_permanent_handles {
> + TPM2_RH_NULL = 0x40000007,
> TPM2_RS_PW = 0x40000009,
> };
>
> @@ -307,16 +352,30 @@ enum tpm_buf_flags {
> struct tpm_buf {
> unsigned int flags;
> 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),
> };
>
> 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 {
> @@ -370,6 +429,15 @@ 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);
> +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)
> {
> @@ -400,5 +468,102 @@ 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
> +#ifdef CONFIG_TPM_BUS_SECURITY
> +
> +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;
> +}
> +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++;
> +}
> +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_TPM_BUS_SECURITY */
> +
> #endif
Most the code looks overally decent, except reverse christmas tree
declarations would be nice to have. Getting this patch right is
probably the most critical and rest is pretty easy after that.
Thus the focus.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-11-26 3:39 ` Jarkko Sakkinen
@ 2023-11-26 3:45 ` Jarkko Sakkinen
2023-11-26 15:07 ` James Bottomley
2023-11-26 15:05 ` James Bottomley
1 sibling, 1 reply; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-11-26 3:45 UTC (permalink / raw)
To: Jarkko Sakkinen, James Bottomley, linux-integrity
Cc: keyrings, Ard Biesheuvel
On Sun Nov 26, 2023 at 5:39 AM EET, Jarkko Sakkinen wrote:
> Revisiting this.
>
> On Tue Apr 4, 2023 at 12:39 AM EEST, James Bottomley wrote:
> > Add true session based HMAC authentication plus parameter decryption
> > and response encryption using AES. The basic design is to segregate
>
> "true session based HMAC authentication" sounds like something that
> would work in a marketing material but not in this context tbh.
>
> > 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()
>
> "...ssssion with tpm2_start_auth_session(), which initiates a session..."
> (sentence structure)
>
> > Which initiates a session with the TPM and allocates an opaque
> > tpm2_auth structure to handle the session parameters. Then the use is
> > simply:
> >
> > * tpm_buf_append_name() in place of the tpm_buf_append_u32 for the
> > handles
> >
> > * tpm_buf_append_hmac_session() where tpm2_append_auth() would go
> >
> > * tpm_buf_fill_hmac_session() called after the entire command buffer
> > is finished but before tpm_transmit_cmd() is called which computes
> > the correct HMAC and places it in the command at the correct
> > location.
> >
> > Finally, after tpm_transmit_cmd() is called,
> > tpm_buf_check_hmac_response() is called to check that the returned
> > HMAC matched and collect the new state for the next use of the
> > session, if any.
> >
> > The features of the session is controlled by the session attributes
> > set in tpm_buf_append_hmac_session(). If TPM2_SA_CONTINUE_SESSION is
> > not specified, the session will be flushed and the tpm2_auth structure
> > freed in tpm_buf_check_hmac_response(); otherwise the session may be
> > used again. Parameter encryption is specified by or'ing the flag
> > TPM2_SA_DECRYPT and response encryption by or'ing the flag
> > TPM2_SA_ENCRYPT. the various encryptions will be taken care of by
> > tpm_buf_fill_hmac_session() and tpm_buf_check_hmac_response()
> > respectively.
> >
> > To get all of this to work securely, the Kernel needs a primary key to
> > encrypt the session salt to, so an EC key from the NULL seed is
> > derived and its context saved in the tpm_chip structure. The context
> > is loaded on demand into an available volatile handle when
> > tpm_start_auth_session() is called, but is flushed before that
> > function exits to conserve handles.
> >
> > Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
> > Reviewed-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> # crypto API parts
> >
> > ---
>
> One very obvious thing to fix there is the kconfig flag:
>
> 1. Its meaning and purpose is not documented to the commit message. What
> is it and what is its meaning and purpose.
> 2. TPM_BUS_SECURITY does not follow the naming convention of other
> TPM kconfig flags, and to add, "security" is way way too abstract
> word. Something like TCG_TPM_HMAC
>
> It should be renamed as TCG_TPM_
>
> >
> > v2: fix memory leaks from smatch; adjust for name hash size
> > v3: make tpm2_make_null_primary static
> > v4: use crypto library functions
> > ---
> > drivers/char/tpm/Kconfig | 13 +
> > drivers/char/tpm/Makefile | 1 +
> > drivers/char/tpm/tpm-buf.c | 1 +
> > drivers/char/tpm/tpm-chip.c | 3 +
> > drivers/char/tpm/tpm.h | 10 +
> > drivers/char/tpm/tpm2-cmd.c | 5 +
> > drivers/char/tpm/tpm2-sessions.c | 1158 ++++++++++++++++++++++++++++++
> > include/linux/tpm.h | 165 +++++
> > 8 files changed, 1356 insertions(+)
> > create mode 100644 drivers/char/tpm/tpm2-sessions.c
> >
> > diff --git a/drivers/char/tpm/Kconfig b/drivers/char/tpm/Kconfig
> > index 927088b2c3d3..8af3afc48511 100644
> > --- a/drivers/char/tpm/Kconfig
> > +++ b/drivers/char/tpm/Kconfig
> > @@ -27,6 +27,19 @@ menuconfig TCG_TPM
> >
> > if TCG_TPM
> >
> > +config TPM_BUS_SECURITY
> > + bool "Use secure 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 tamper resistent scheme
> > + for communicating with the TPM to prevent or detect bus
> > + snooping and iterposer attacks like TPM Genie. Saying Y here
> > + adds some encryption overhead to all kernel to TPM
> > + transactions.
> > +
> > config HW_RANDOM_TPM
> > bool "TPM HW Random Number Generator support"
> > depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m)
> > diff --git a/drivers/char/tpm/Makefile b/drivers/char/tpm/Makefile
> > index ad3594e383e1..10dc214aa093 100644
> > --- a/drivers/char/tpm/Makefile
> > +++ b/drivers/char/tpm/Makefile
> > @@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o
> > tpm-y += eventlog/tpm2.o
> > tpm-y += tpm-buf.o
> >
> > +tpm-$(CONFIG_TPM_BUS_SECURITY) += tpm2-sessions.o
> > tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
> > tpm-$(CONFIG_EFI) += eventlog/efi.o
> > tpm-$(CONFIG_OF) += eventlog/of.o
> > diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
> > index d107321bcdff..2127fc5e51e2 100644
> > --- a/drivers/char/tpm/tpm-buf.c
> > +++ b/drivers/char/tpm/tpm-buf.c
> > @@ -36,6 +36,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 0601e6e5e326..7e654776514a 100644
> > --- a/drivers/char/tpm/tpm-chip.c
> > +++ b/drivers/char/tpm/tpm-chip.c
> > @@ -270,6 +270,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_TPM_BUS_SECURITY
> > + kfree(chip->auth);
> > +#endif
> > kfree(chip);
> > }
> >
> > diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
> > index 00a06e3ba892..3ce53e47b600 100644
> > --- a/drivers/char/tpm/tpm.h
> > +++ b/drivers/char/tpm/tpm.h
> > @@ -319,4 +319,14 @@ void tpm_bios_log_setup(struct tpm_chip *chip);
> > void tpm_bios_log_teardown(struct tpm_chip *chip);
> > int tpm_dev_common_init(void);
> > void tpm_dev_common_exit(void);
> > +
> > +#ifdef CONFIG_TPM_BUS_SECURITY
> > +int tpm2_sessions_init(struct tpm_chip *chip);
> > +#else
> > +static inline int tpm2_sessions_init(struct tpm_chip *chip)
> > +{
> > + return 0;
> > +}
> > +#endif
> > +
> > #endif
> > 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..7f5cc826c8d5
> > --- /dev/null
> > +++ b/drivers/char/tpm/tpm2-sessions.c
> > @@ -0,0 +1,1158 @@
> > +// SPDX-License-Identifier: GPL-2.0
> > +
> > +/*
> > + * Copyright (C) 2018 James.Bottomley@HansenPartnership.com
> > + *
> > + * Cryptographic helper routines for handling TPM2 sessions for
> > + * authorization HMAC and request response encryption.
> > + *
> > + * The idea is to ensure that every TPM command is HMAC protected by a
> > + * session, meaning in-flight tampering would be detected and in
> > + * addition all sensitive inputs and responses should be encrypted.
> > + *
> > + * The basic way this works is to use a TPM feature called salted
> > + * sessions where a random secret used in session construction is
> > + * encrypted to the public part of a known TPM key. The problem is we
> > + * have no known keys, so initially a primary Elliptic Curve key is
> > + * derived from the NULL seed (we use EC because most TPMs generate
> > + * these keys much faster than RSA ones). The curve used is NIST_P256
> > + * because that's now mandated to be present in 'TCG TPM v2.0
> > + * Provisioning Guidance'
> > + *
> > + * Threat problems: the initial TPM2_CreatePrimary is not (and cannot
> > + * be) session protected, so a clever Man in the Middle could return a
> > + * public key they control to this command and from there intercept
> > + * and decode all subsequent session based transactions. The kernel
> > + * cannot mitigate this threat but, after boot, userspace can get
> > + * proof this has not happened by asking the TPM to certify the NULL
> > + * key. This certification would chain back to the TPM Endorsement
> > + * Certificate and prove the NULL seed primary had not been tampered
> > + * with and thus all sessions must have been cryptographically secure.
> > + * To assist with this, the initial NULL seed public key name is made
> > + * available in a sysfs file.
> > + *
> > + * Use of these functions:
> > + *
> > + * The design is all the crypto, hash and hmac gunk is confined in this
> > + * file and never needs to be seen even by the kernel internal user. To
> > + * the user there's an init function tpm2_sessions_init() that needs to
> > + * be called once per TPM which generates the NULL seed primary key.
>
> What is an "init function"? Again, lot of words but not inherent
> meaning.
>
> > + *
> > + * Then there are six usage functions:
> > + *
> > + * tpm2_start_auth_session() which allocates the opaque auth structure
> > + * and gets a session from the TPM. This must be called before
> > + * any of the following functions. The session is protected by a
> > + * session_key which is derived from a random salt value
> > + * encrypted to the NULL seed.
> > + * tpm2_end_auth_session() kills the session and frees the resources.
> > + * Under normal operation this function is done by
> > + * tpm_buf_check_hmac_response(), so this is only to be used on
> > + * error legs where the latter is not executed.
> > + * tpm_buf_append_name() to add a handle to the buffer. This must be
> > + * used in place of the usual tpm_buf_append_u32() for adding
> > + * handles because handles have to be processed specially when
> > + * calculating the HMAC. In particular, for NV, volatile and
> > + * permanent objects you now need to provide the name.
> > + * tpm_buf_append_hmac_session() which appends the hmac session to the
> > + * buf in the same way tpm_buf_append_auth does().
> > + * tpm_buf_fill_hmac_session() This calculates the correct hash and
> > + * places it in the buffer. It must be called after the complete
> > + * command buffer is finalized so it can fill in the correct HMAC
> > + * based on the parameters.
> > + * tpm_buf_check_hmac_response() which checks the session response in
> > + * the buffer and calculates what it should be. If there's a
> > + * mismatch it will log a warning and return an error. If
> > + * tpm_buf_append_hmac_session() did not specify
> > + * TPM_SA_CONTINUE_SESSION then the session will be closed (if it
> > + * hasn't been consumed) and the auth structure freed.
> > + */
> > +
> > +#include "tpm.h"
> > +
> > +#include <linux/random.h>
> > +#include <linux/scatterlist.h>
> > +
> > +#include <asm/unaligned.h>
> > +
> > +#include <crypto/aes.h>
> > +#include <crypto/kpp.h>
> > +#include <crypto/ecdh.h>
> > +#include <crypto/hash.h>
> > +#include <crypto/hmac.h>
> > +
> > +/* if you change to AES256, you only need change this */
> > +#define AES_KEYBYTES AES_KEYSIZE_128
> > +
> > +#define AES_KEYBITS (AES_KEYBYTES*8)
> > +#define AUTH_MAX_NAMES 3
> > +
> > +/*
> > + * This is the structure that carries all the auth information (like
> > + * session handle, nonces, session key and auth) from use to use it is
> > + * designed to be opaque to anything outside.
> > + */
> > +struct tpm2_auth {
> > + u32 handle;
> > + /*
> > + * This has two meanings: before tpm_buf_fill_hmac_session()
> > + * it marks the offset in the buffer of the start of the
> > + * sessions (i.e. after all the handles). Once the buffer has
> > + * been filled it markes the session number of our auth
> > + * session so we can find it again in the response buffer.
> > + *
> > + * The two cases are distinguished because the first offset
> > + * must always be greater than TPM_HEADER_SIZE and the second
> > + * must be less than or equal to 5.
> > + */
> > + u32 session;
> > + /*
> > + * the size here is variable and set by the size of our_nonce
> > + * which must be between 16 and the name hash length. we set
> > + * the maximum sha256 size for the greatest protection
> > + */
> > + u8 our_nonce[SHA256_DIGEST_SIZE];
> > + u8 tpm_nonce[SHA256_DIGEST_SIZE];
> > + /*
> > + * the salt is only used across the session command/response
> > + * after that it can be used as a scratch area
> > + */
> > + union {
> > + u8 salt[EC_PT_SZ];
> > + /* scratch for key + IV */
> > + u8 scratch[AES_KEYBYTES + AES_BLOCK_SIZE];
> > + };
> > + /*
> > + * the session key and passphrase are the same size as the
> > + * name digest (sha256 again). The session key is constant
> > + * for the use of the session and the passphrase can change
> > + * with every invocation.
> > + *
> > + * Note: these fields must be adjacent and in this order
> > + * because several HMAC/KDF schemes use the combination of the
> > + * session_key and passphrase.
> > + */
> > + u8 session_key[SHA256_DIGEST_SIZE];
> > + u8 passphrase[SHA256_DIGEST_SIZE];
> > + int passphraselen;
> > + struct crypto_aes_ctx aes_ctx;
> > + /* saved session attributes */
> > + u8 attrs;
> > + __be32 ordinal;
> > + /* 3 names of handles: name_h is handle, name is name of handle */
> > + u32 name_h[AUTH_MAX_NAMES];
> > + u8 name[AUTH_MAX_NAMES][2 + 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
> > + * on every operation, so we weld the hmac init and final functions in
> > + * here to give it the same usage characteristics as a regular hash
> > + */
> > +static void hmac_init(struct sha256_state *sctx, u8 *key, int keylen)
> > +{
> > + u8 pad[SHA256_BLOCK_SIZE];
> > + int i;
> > +
> > + sha256_init(sctx);
> > + for (i = 0; i < sizeof(pad); i++) {
> > + if (i < keylen)
> > + pad[i] = key[i];
> > + else
> > + pad[i] = 0;
> > + pad[i] ^= HMAC_IPAD_VALUE;
> > + }
> > + sha256_update(sctx, pad, sizeof(pad));
> > +}
> > +
> > +static void hmac_final(struct sha256_state *sctx, u8 *key, int keylen, u8 *out)
> > +{
> > + u8 pad[SHA256_BLOCK_SIZE];
> > + int i;
> > +
> > + for (i = 0; i < sizeof(pad); i++) {
> > + if (i < keylen)
> > + pad[i] = key[i];
> > + else
> > + pad[i] = 0;
> > + pad[i] ^= HMAC_OPAD_VALUE;
> > + }
> > +
> > + /* collect the final hash; use out as temporary storage */
> > + 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 KDFa. Note output is in bytes not bits.
> > + */
> > +static void KDFa(u8 *key, int keylen, const char *label, u8 *u,
> > + u8 *v, int bytes, u8 *out)
> > +{
> > + u32 counter;
> > + const __be32 bits = cpu_to_be32(bytes * 8);
> > +
> > + for (counter = 1; bytes > 0; bytes -= SHA256_DIGEST_SIZE, counter++,
> > + out += SHA256_DIGEST_SIZE) {
> > + struct sha256_state sctx;
> > + __be32 c = cpu_to_be32(counter);
> > +
> > + hmac_init(&sctx, key, keylen);
> > + 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));
> > + hmac_final(&sctx, key, keylen, out);
> > + }
> > +}
> > +
> > +/*
> > + * Somewhat of a bastardization of the real KDFe. We're assuming
> > + * we're working with known point sizes for the input parameters and
> > + * the hash algorithm is fixed at sha256. Because we know that the
> > + * point size is 32 bytes like the hash size, there's no need to loop
> > + * in this KDF.
> > + */
> > +static void KDFe(u8 z[EC_PT_SZ], const char *str, u8 *pt_u, u8 *pt_v,
> > + u8 *keyout)
> > +{
> > + 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, keyout);
> > +}
> > +
> > +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->ec_point_x, EC_PT_SZ);
> > + sg_set_buf(&s[1], chip->ec_point_y, EC_PT_SZ);
> > + kpp_request_set_input(req, s, EC_PT_SZ*2);
> > + sg_init_one(d, 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
> > + */
> > + KDFe(chip->auth->salt, "SECRET", x, chip->ec_point_x, chip->auth->salt);
> > + out:
> > + 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)
> > + * @passphraselen: The length of the session authority (0 if none)
> > + *
> > + * This fills in a session structure in the TPM command buffer, except
> > + * for the HMAC which cannot be computed until the command buffer is
> > + * complete. The type of session is controlled by the @attributes,
> > + * the main ones of which are TPM2_SA_CONTINUE_SESSION which means the
> > + * session won't terminate after tpm_buf_check_hmac_response(),
> > + * TPM2_SA_DECRYPT which means this buffers first parameter should be
> > + * encrypted with a session key and TPM2_SA_ENCRYPT, which means the
> > + * response buffer's first parameter needs to be decrypted (confusing,
> > + * but the defines are written from the point of view of the TPM).
> > + *
> > + * Any session appended by this command must be finalized by calling
> > + * tpm_buf_fill_hmac_session() otherwise the HMAC will be incorrect
> > + * and the TPM will reject the command.
> > + *
> > + * As with most tpm_buf operations, success is assumed because failure
> > + * will be caused by an incorrect programming model and indicated by a
> > + * kernel message.
> > + */
> > +void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
> > + u8 attributes, u8 *passphrase,
> > + int passphraselen)
> > +{
> > + 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 && passphraselen > 0
> > + && passphrase[passphraselen - 1] == '\0')
> > + passphraselen--;
> > +
> > + auth->attrs = attributes;
> > + auth->passphraselen = passphraselen;
> > + if (passphraselen)
> > + memcpy(auth->passphrase, passphrase, passphraselen);
> > +
> > + if (auth->session != tpm_buf_length(buf)) {
> > + /* we're not the first session */
> > + len = get_unaligned_be32(&buf->data[auth->session]);
> > + if (4 + len + auth->session != tpm_buf_length(buf)) {
> > + WARN(1, "session length mismatch, cannot append");
> > + return;
> > + }
> > +
> > + /* add our new session */
> > + len += 9 + 2 * SHA256_DIGEST_SIZE;
> > + put_unaligned_be32(len, &buf->data[auth->session]);
> > + } else {
> > + tpm_buf_append_u32(buf, 9 + 2 * SHA256_DIGEST_SIZE);
> > + }
> > +
> > + /* random number for our nonce */
> > + get_random_bytes(nonce, sizeof(nonce));
> > + memcpy(auth->our_nonce, nonce, sizeof(nonce));
> > + tpm_buf_append_u32(buf, auth->handle);
> > + /* our new nonce */
> > + tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
> > + tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
> > + tpm_buf_append_u8(buf, auth->attrs);
> > + /* and put a placeholder for the hmac */
> > + tpm_buf_append_u16(buf, SHA256_DIGEST_SIZE);
> > + tpm_buf_append(buf, nonce, SHA256_DIGEST_SIZE);
> > +}
> > +EXPORT_SYMBOL(tpm_buf_append_hmac_session);
> > +
> > +/**
> > + * tpm_buf_fill_hmac_session() - finalize the session HMAC
> > + * @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;
> > + const u8 *s, *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);
> > +
> > + s = &buf->data[TPM_HEADER_SIZE];
> > + /*
> > + * just check the names, it's easy to make mistakes. This
> > + * would happen if someone added a handle via
> > + * tpm_buf_append_u32() instead of tpm_buf_append_name()
> > + */
> > + for (i = 0; i < handles; i++) {
> > + u32 handle = tpm_get_inc_u32(&s);
> > +
> > + if (auth->name_h[i] != handle) {
> > + dev_err(&chip->dev, "TPM: handle %d wrong for name\n",
> > + i);
> > + return;
> > + }
> > + }
> > + /* point s to the start of the sessions */
> > + val = tpm_get_inc_u32(&s);
> > + /* point p to the start of the parameters */
> > + p = s + val;
> > + for (i = 1; s < p; i++) {
> > + u32 handle = tpm_get_inc_u32(&s);
> > + u16 len;
> > + u8 a;
> > +
> > + /* nonce (already in auth) */
> > + len = tpm_get_inc_u16(&s);
> > + s += len;
> > +
> > + a = *s++;
> > +
> > + len = tpm_get_inc_u16(&s);
> > + if (handle == auth->handle && auth->attrs == a) {
> > + hmac = (u8 *)s;
> > + /*
> > + * save our session number so we know which
> > + * session in the response belongs to us
> > + */
> > + auth->session = i;
> > + }
> > +
> > + s += len;
> > + }
> > + if (s != p) {
> > + dev_err(&chip->dev, "TPM session length is incorrect\n");
> > + return;
> > + }
> > + if (!hmac) {
> > + dev_err(&chip->dev, "TPM could not find HMAC session\n");
> > + return;
> > + }
> > +
> > + /* encrypt before HMAC */
> > + if (auth->attrs & TPM2_SA_DECRYPT) {
> > + u16 len;
> > +
> > + /* need key and IV */
> > + KDFa(auth->session_key, SHA256_DIGEST_SIZE
> > + + auth->passphraselen, "CFB", auth->our_nonce,
> > + auth->tpm_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
> > + auth->scratch);
> > +
> > + len = tpm_get_inc_u16(&p);
> > + aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEYBYTES);
> > + aescfb_encrypt(&auth->aes_ctx, (u8 *)p, p, len,
> > + auth->scratch + AES_KEYBYTES);
> > + /* reset p to beginning of parameters for HMAC */
> > + 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++) {
> > + u8 mso = auth->name_h[i] >> 24;
> > +
> > + if (mso == 0x81 || mso == 0x80 || mso == 0x01) {
> > + 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 (buf->data - s != tpm_buf_length(buf))
> > + sha256_update(&sctx, s, buf->data + tpm_buf_length(buf) - s);
> > + sha256_final(&sctx, cphash);
> > +
> > + /* now calculate the hmac */
> > + hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
> > + + auth->passphraselen);
> > + 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);
> > + hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
> > + + auth->passphraselen, hmac);
> > +}
> > +EXPORT_SYMBOL(tpm_buf_fill_hmac_session);
> > +
> > +static int parse_read_public(char *name, const u8 *data)
> > +{
> > + struct tpm_header *head = (struct tpm_header *)data;
> > + u32 tot_len = be32_to_cpu(head->length);
> > + u32 val;
> > +
> > + data += TPM_HEADER_SIZE;
> > + /* we're starting after the header so adjust the length */
> > + tot_len -= TPM_HEADER_SIZE;
> > +
> > + /* skip public */
> > + val = tpm_get_inc_u16(&data);
> > + if (val > tot_len)
> > + return -EINVAL;
> > + data += val;
> > + /* name */
> > + val = tpm_get_inc_u16(&data);
> > + if (val != name_size(data))
> > + return -EINVAL;
> > + memcpy(name, data, name_size(data));
> > + /* forget the rest */
> > + return 0;
> > +}
> > +
> > +static int tpm2_readpublic(struct tpm_chip *chip, u32 handle, char *name)
> > +{
> > + struct tpm_buf buf;
> > + int rc;
> > +
> > + rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
> > + if (rc)
> > + return rc;
> > +
> > + tpm_buf_append_u32(&buf, handle);
> > + rc = tpm_transmit_cmd(chip, &buf, 0, "read public");
> > + if (rc == TPM2_RC_SUCCESS)
> > + rc = parse_read_public(name, buf.data);
> > +
> > + tpm_buf_destroy(&buf);
> > +
> > + return rc;
> > +}
> > +
> > +/**
> > + * tpm_buf_append_name() - add a handle area to the buffer
> > + * @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 simly
> > + * the actual 4 byte handle or an empty buf (in these cases @name
> > + * should be NULL) but for volatile objects, permanent objects and NV
> > + * areas, the name is defined as the hash (according to the name
> > + * algorithm which should be set to sha256) of the public area to
> > + * which the two byte algorithm id has been appended. For these
> > + * objects, the @name pointer should point to this. If a name is
> > + * required but @name is NULL, then TPM2_ReadPublic() will be called
> > + * on the handle to obtain the name.
> > + *
> > + * As with most tpm_buf operations, success is assumed because failure
> > + * will be caused by an incorrect programming model and indicated by a
> > + * kernel message.
> > + */
> > +void tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
> > + u32 handle, u8 *name)
> > +{
> > + int slot;
> > + u8 mso = handle >> 24;
> > + struct tpm2_auth *auth = chip->auth;
> > +
> > + 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 == 0x81 || mso == 0x80 || mso == 0x01) {
> > + if (!name)
> > + tpm2_readpublic(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);
> > +
> > +/**
> > + * 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;
> > + const u8 *s, *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 */
> > + s = &buf->data[TPM_HEADER_SIZE + handles * 4];
> > + parm_len = tpm_get_inc_u32(&s);
> > + p = s;
> > + s += parm_len;
> > + /* skip over any sessions before ours */
> > + for (i = 0; i < auth->session - 1; i++) {
> > + len = tpm_get_inc_u16(&s);
> > + s += len + 1;
> > + len = tpm_get_inc_u16(&s);
> > + s += len;
> > + }
> > + /* TPM nonce */
> > + len = tpm_get_inc_u16(&s);
> > + if (s - buf->data + len > tpm_buf_length(buf))
> > + goto out;
> > + if (len != SHA256_DIGEST_SIZE)
> > + goto out;
> > + memcpy(auth->tpm_nonce, s, len);
> > + s += len;
> > + attrs = *s++;
> > + len = tpm_get_inc_u16(&s);
> > + if (s - buf->data + len != tpm_buf_length(buf))
> > + goto out;
> > + if (len != SHA256_DIGEST_SIZE)
> > + goto out;
> > + /*
> > + * s points to the HMAC. now calculate comparison, beginning
> > + * with rphash
> > + */
> > + 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, p, parm_len);
> > + sha256_final(&sctx, rphash);
> > +
> > + /* now calculate the hmac */
> > + hmac_init(&sctx, auth->session_key, sizeof(auth->session_key)
> > + + auth->passphraselen);
> > + 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 */
> > + hmac_final(&sctx, auth->session_key, sizeof(auth->session_key)
> > + + auth->passphraselen, rphash);
> > + if (memcmp(rphash, 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 */
> > + KDFa(auth->session_key, SHA256_DIGEST_SIZE
> > + + auth->passphraselen, "CFB", auth->tpm_nonce,
> > + auth->our_nonce, AES_KEYBYTES + AES_BLOCK_SIZE,
> > + auth->scratch);
> > +
> > + len = tpm_get_inc_u16(&p);
> > + aes_expandkey(&auth->aes_ctx, auth->scratch, AES_KEYBYTES);
> > + aescfb_decrypt(&auth->aes_ctx, (u8 *)p, p, len,
> > + auth->scratch + AES_KEYBYTES);
> > + }
> > +
> > + out:
> > + if ((auth->attrs & TPM2_SA_CONTINUE_SESSION) == 0
> > + && rc)
> > + /* manually close the session if it wasn't consumed */
> > + tpm2_flush_context(chip, auth->handle);
> > +
> > + /* 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
> > + *
> > + * ends the session started by tpm2_start_auth_session and frees all
> > + * the resources. Under normal conditions,
> > + * tpm_buf_check_hmac_response() will correctly end the session if
> > + * required, so this function is only for use in error legs that will
> > + * bypass the normal invocation of tpm_buf_check_hmac_respons().
> > + */
> > +void tpm2_end_auth_session(struct tpm_chip *chip)
> > +{
> > + tpm2_flush_context(chip, chip->auth->handle);
> > + chip->auth->session = TPM_HEADER_SIZE;
> > +}
> > +EXPORT_SYMBOL(tpm2_end_auth_session);
> > +
> > +static int parse_start_auth_session(struct tpm2_auth *auth, const u8 *data)
> > +{
> > + struct tpm_header *head = (struct tpm_header *)data;
> > + u32 tot_len = be32_to_cpu(head->length);
> > + u32 val;
> > +
> > + data += TPM_HEADER_SIZE;
> > + /* we're starting after the header so adjust the length */
> > + tot_len -= TPM_HEADER_SIZE;
> > +
> > + /* should have handle plus nonce */
> > + if (tot_len != 4 + 2 + sizeof(auth->tpm_nonce))
> > + return -EINVAL;
> > +
> > + auth->handle = tpm_get_inc_u32(&data);
> > + val = tpm_get_inc_u16(&data);
> > + if (val != sizeof(auth->tpm_nonce))
> > + return -EINVAL;
> > + memcpy(auth->tpm_nonce, data, sizeof(auth->tpm_nonce));
> > + /* now compute the session key from the nonces */
> > + KDFa(auth->salt, sizeof(auth->salt), "ATH", auth->tpm_nonce,
> > + auth->our_nonce, sizeof(auth->session_key), auth->session_key);
> > +
> > + return 0;
> > +}
> > +
> > +/**
> > + * tpm2_start_auth_session - create a HMAC authentication session with the TPM
> > + * @chip: the TPM chip structure to create the session with
> > + *
> > + * 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;
> > + unsigned int offset = 0; /* dummy offset for null seed context */
> > + u32 nullkey;
> > +
> > + rc = tpm2_load_context(chip, chip->tpmkeycontext, &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_KEYBITS);
> > + /* symmetric algorithm mode (must be CFB) */
> > + tpm_buf_append_u16(&buf, TPM_ALG_CFB);
> > + /* hash algorithm for session */
> > + tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
> > +
> > + rc = tpm_transmit_cmd(chip, &buf, 0, "start auth session");
> > + tpm2_flush_context(chip, nullkey);
> > +
> > + if (rc == TPM2_RC_SUCCESS)
> > + rc = parse_start_auth_session(auth, buf.data);
> > +
> > + tpm_buf_destroy(&buf);
> > +
> > + if (rc)
> > + goto out;
> > +
> > + out:
> > + return rc;
> > +}
> > +EXPORT_SYMBOL(tpm2_start_auth_session);
> > +
> > +static int parse_create_primary(struct tpm_chip *chip, u8 *data, u32 *nullkey)
> > +{
> > + struct tpm_header *head = (struct tpm_header *)data;
> > + u16 len;
> > + u32 tot_len = be32_to_cpu(head->length);
> > + u32 val, parm_len;
> > + const u8 *resp, *tmp;
> > +
> > + data += TPM_HEADER_SIZE;
> > + /* we're starting after the header so adjust the length */
> > + tot_len -= TPM_HEADER_SIZE;
> > +
> > + resp = data;
> > + *nullkey = tpm_get_inc_u32(&resp);
> > + parm_len = tpm_get_inc_u32(&resp);
> > + if (parm_len + 8 > tot_len)
> > + return -EINVAL;
> > + len = tpm_get_inc_u16(&resp);
> > + tmp = resp;
> > + /* now we have the public area, compute the name of the object */
> > + put_unaligned_be16(TPM_ALG_SHA256, chip->tpmkeyname);
> > + sha256(resp, len, chip->tpmkeyname + 2);
> > +
> > + /* validate the public key */
> > + val = tpm_get_inc_u16(&tmp);
> > + /* key type (must be what we asked for) */
> > + if (val != TPM_ALG_ECC)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* name algorithm */
> > + if (val != TPM_ALG_SHA256)
> > + return -EINVAL;
> > + val = tpm_get_inc_u32(&tmp);
> > + /* object properties */
> > + if (val != (TPM2_OA_NO_DA |
> > + TPM2_OA_FIXED_TPM |
> > + TPM2_OA_FIXED_PARENT |
> > + TPM2_OA_SENSITIVE_DATA_ORIGIN |
> > + TPM2_OA_USER_WITH_AUTH |
> > + TPM2_OA_DECRYPT |
> > + TPM2_OA_RESTRICTED))
> > + return -EINVAL;
> > + /* auth policy (empty) */
> > + val = tpm_get_inc_u16(&tmp);
> > + if (val != 0)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* symmetric key parameters */
> > + if (val != TPM_ALG_AES)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* symmetric key length */
> > + if (val != AES_KEYBITS)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* symmetric encryption scheme */
> > + if (val != TPM_ALG_CFB)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* signing scheme */
> > + if (val != TPM_ALG_NULL)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* ECC Curve */
> > + if (val != TPM2_ECC_NIST_P256)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* KDF Scheme */
> > + if (val != TPM_ALG_NULL)
> > + return -EINVAL;
> > + val = tpm_get_inc_u16(&tmp);
> > + /* x point */
> > + if (val != 32)
> > + return -EINVAL;
> > + memcpy(chip->ec_point_x, tmp, val);
> > + tmp += val;
> > + val = tpm_get_inc_u16(&tmp);
> > + if (val != 32)
> > + return -EINVAL;
> > + memcpy(chip->ec_point_y, tmp, val);
> > + tmp += val;
> > + resp += len;
> > + /* should have exactly consumed the tpm2b public structure */
> > + if (tmp != resp)
> > + return -EINVAL;
> > + if (resp - data > parm_len)
> > + return -EINVAL;
> > + /* creation data (skip) */
> > + len = tpm_get_inc_u16(&resp);
> > + resp += len;
> > + if (resp - data > parm_len)
> > + return -EINVAL;
> > + /* creation digest (must be sha256) */
> > + len = tpm_get_inc_u16(&resp);
> > + resp += len;
> > + if (len != SHA256_DIGEST_SIZE || resp - data > parm_len)
> > + return -EINVAL;
> > + /* TPMT_TK_CREATION follows */
> > + /* tag, must be TPM_ST_CREATION (0x8021) */
> > + val = tpm_get_inc_u16(&resp);
> > + if (val != TPM2_ST_CREATION || resp - data > parm_len)
> > + return -EINVAL;
> > + /* hierarchy (must be NULL) */
> > + val = tpm_get_inc_u32(&resp);
> > + if (val != TPM2_RH_NULL || resp - data > parm_len)
> > + return -EINVAL;
> > + /* the ticket digest HMAC (might not be sha256) */
> > + len = tpm_get_inc_u16(&resp);
> > + resp += len;
> > + if (resp - data > parm_len)
> > + return -EINVAL;
> > + /*
> > + * finally we have the name, which is a sha256 digest plus a 2
> > + * byte algorithm type
> > + */
> > + len = tpm_get_inc_u16(&resp);
> > + if (resp + len - data != parm_len + 8)
> > + return -EINVAL;
> > + if (len != SHA256_DIGEST_SIZE + 2)
> > + return -EINVAL;
> > +
> > + if (memcmp(chip->tpmkeyname, resp, SHA256_DIGEST_SIZE + 2) != 0) {
> > + dev_err(&chip->dev, "NULL Seed name comparison failed\n");
> > + return -EINVAL;
> > + }
> > +
> > + return 0;
> > +}
> > +
> > +static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy, u32 *handle)
> > +{
> > + int rc;
> > + struct tpm_buf buf;
> > + struct tpm_buf template;
> > +
> > + rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
> > + if (rc)
> > + return rc;
> > +
> > + rc = tpm_buf_init_2b(&template);
> > + if (rc) {
> > + tpm_buf_destroy(&buf);
> > + return rc;
> > + }
> > +
> > + /*
> > + * create the template. Note: in order for userspace to
> > + * verify the security of the system, it will have to create
> > + * and certify this NULL primary, meaning all the template
> > + * parameters will have to be identical, so conform exactly to
> > + * the TCG TPM v2.0 Provisioning Guidance for the SRK ECC
> > + * key
> > + */
> > +
> > + /* key type */
> > + tpm_buf_append_u16(&template, TPM_ALG_ECC);
> > + /* name algorithm */
> > + tpm_buf_append_u16(&template, TPM_ALG_SHA256);
> > + /* object properties */
> > + tpm_buf_append_u32(&template, TPM2_OA_NO_DA |
> > + TPM2_OA_FIXED_TPM |
> > + TPM2_OA_FIXED_PARENT |
> > + TPM2_OA_SENSITIVE_DATA_ORIGIN |
> > + TPM2_OA_USER_WITH_AUTH |
> > + TPM2_OA_DECRYPT |
> > + TPM2_OA_RESTRICTED);
> > + /* sauth policy (empty) */
> > + tpm_buf_append_u16(&template, 0);
> > +
> > + /* BEGIN parameters: key specific; for ECC*/
> > + /* symmetric algorithm */
> > + tpm_buf_append_u16(&template, TPM_ALG_AES);
> > + /* bits for symmetric algorithm */
> > + tpm_buf_append_u16(&template, 128);
> > + /* algorithm mode (must be CFB) */
> > + tpm_buf_append_u16(&template, TPM_ALG_CFB);
> > + /* scheme (NULL means any scheme) */
> > + tpm_buf_append_u16(&template, TPM_ALG_NULL);
> > + /* ECC Curve ID */
> > + tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
> > + /* KDF Scheme */
> > + tpm_buf_append_u16(&template, TPM_ALG_NULL);
> > + /* unique: key specific; for ECC it is two points */
> > + tpm_buf_append_u16(&template, 0);
> > + tpm_buf_append_u16(&template, 0);
> > + /* END parameters */
> > +
> > + /* primary handle */
> > + tpm_buf_append_u32(&buf, hierarchy);
> > + 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_2b(&buf, &template);
> > + tpm_buf_destroy(&template);
> > + /* outside info (empty) */
> > + tpm_buf_append_u16(&buf, 0);
> > + /* creation PCR (none) */
> > + tpm_buf_append_u32(&buf, 0);
> > +
> > + rc = tpm_transmit_cmd(chip, &buf, 0,
> > + "attempting to create NULL primary");
> > +
> > + if (rc == TPM2_RC_SUCCESS)
> > + rc = parse_create_primary(chip, buf.data, handle);
> > +
> > + tpm_buf_destroy(&buf);
> > +
> > + return rc;
> > +}
> > +
> > +static int tpm2_create_null_primary(struct tpm_chip *chip)
> > +{
> > + u32 nullkey;
> > + int rc;
> > +
> > + rc = tpm2_create_primary(chip, TPM2_RH_NULL, &nullkey);
> > +
> > + if (rc == TPM2_RC_SUCCESS) {
> > + unsigned int offset = 0; /* dummy offset for tpmkeycontext */
> > +
> > + rc = tpm2_save_context(chip, nullkey, chip->tpmkeycontext,
> > + sizeof(chip->tpmkeycontext), &offset);
> > + tpm2_flush_context(chip, nullkey);
> > + }
> > +
> > + return rc;
> > +}
> > +
> > +int tpm2_sessions_init(struct tpm_chip *chip)
>
> Neithe here is an explanation what is an "init function".
>
> > +{
> > + int rc;
> > +
> > + rc = tpm2_create_null_primary(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;
> > +}
> > +EXPORT_SYMBOL(tpm2_sessions_init);
> > diff --git a/include/linux/tpm.h b/include/linux/tpm.h
> > index d2fea2afd37c..af3cf219de2b 100644
> > --- a/include/linux/tpm.h
> > +++ b/include/linux/tpm.h
> > @@ -30,17 +30,28 @@
> > 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 {
> > 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 +60,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 +132,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 +200,15 @@ struct tpm_chip {
> >
> > /* active locality */
> > int locality;
> > +
> > +#ifdef CONFIG_TPM_BUS_SECURITY
> > + /* details for communication security via sessions */
> > + u8 tpmkeycontext[TPM2_MAX_CONTEXT_SIZE]; /* context for NULL seed */
> > + u8 tpmkeyname[TPM2_NAME_SIZE]; /* name of NULL seed */
> > + u8 ec_point_x[EC_PT_SZ];
> > + u8 ec_point_y[EC_PT_SZ];
> > + struct tpm2_auth *auth;
> > +#endif
> > };
> >
> > #define TPM_HEADER_SIZE 10
> > @@ -194,6 +233,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 */
> > @@ -231,6 +271,10 @@ enum tpm2_command_codes {
> > TPM2_CC_CONTEXT_LOAD = 0x0161,
> > TPM2_CC_CONTEXT_SAVE = 0x0162,
> > TPM2_CC_FLUSH_CONTEXT = 0x0165,
> > + TPM2_CC_POLICY_AUTHVALUE = 0x016B,
> > + TPM2_CC_POLICY_COUNTER_TIMER = 0x016D,
> > + TPM2_CC_READ_PUBLIC = 0x0173,
> > + TPM2_CC_START_AUTH_SESS = 0x0176,
> > TPM2_CC_VERIFY_SIGNATURE = 0x0177,
> > TPM2_CC_GET_CAPABILITY = 0x017A,
> > TPM2_CC_GET_RANDOM = 0x017B,
> > @@ -243,6 +287,7 @@ enum tpm2_command_codes {
> > };
> >
> > enum tpm2_permanent_handles {
> > + TPM2_RH_NULL = 0x40000007,
> > TPM2_RS_PW = 0x40000009,
> > };
> >
> > @@ -307,16 +352,30 @@ enum tpm_buf_flags {
> > struct tpm_buf {
> > unsigned int flags;
> > 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),
> > };
> >
> > 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 {
> > @@ -370,6 +429,15 @@ 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);
> > +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)
> > {
> > @@ -400,5 +468,102 @@ 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
> > +#ifdef CONFIG_TPM_BUS_SECURITY
> > +
> > +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;
> > +}
> > +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++;
> > +}
> > +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_TPM_BUS_SECURITY */
> > +
> > #endif
>
> Most the code looks overally decent, except reverse christmas tree
> declarations would be nice to have. Getting this patch right is
> probably the most critical and rest is pretty easy after that.
> Thus the focus.
I'll consider picking the tail, editing minimally and sending a new
version with the hmac patches. I.e. change the config flag name and
stuff like that.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-11-26 3:45 ` Jarkko Sakkinen
@ 2023-11-26 15:07 ` James Bottomley
0 siblings, 0 replies; 62+ messages in thread
From: James Bottomley @ 2023-11-26 15:07 UTC (permalink / raw)
To: Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel
Could you please trim your replies. In long patches like this not
doing so makes for a huge fishing expedition
On Sun, 2023-11-26 at 05:45 +0200, Jarkko Sakkinen wrote:
[...]
> > Most the code looks overally decent, except reverse christmas tree
> > declarations would be nice to have. Getting this patch right is
> > probably the most critical and rest is pretty easy after that.
> > Thus the focus.
>
> I'll consider picking the tail, editing minimally and sending a new
> version with the hmac patches. I.e. change the config flag name and
> stuff like that.
I already have it converted ... that's how I found the bugs I reported,
but I need a stable base for a repost.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-11-26 3:39 ` Jarkko Sakkinen
2023-11-26 3:45 ` Jarkko Sakkinen
@ 2023-11-26 15:05 ` James Bottomley
2023-12-04 2:29 ` Jarkko Sakkinen
1 sibling, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-11-26 15:05 UTC (permalink / raw)
To: Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel, Mimi Zohar
On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> One very obvious thing to fix there is the kconfig flag:
>
> 1. Its meaning and purpose is not documented to the commit message.
> What
> is it and what is its meaning and purpose.
> 2. TPM_BUS_SECURITY does not follow the naming convention of other
> TPM kconfig flags, and to add, "security" is way way too abstract
> word. Something like TCG_TPM_HMAC
>
> It should be renamed as TCG_TPM_
One question is do we still need this? Since my tree has moved ahead,
I also need the HMAC code for policy on keys and the primary code for
permanent parents. The only real performance concern is for PCR
extension (no-one really cares about the speed of unseal or random), so
a different possible way of doing this is simply to CONFIG that one
operation.
Regards,
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-11-26 15:05 ` James Bottomley
@ 2023-12-04 2:29 ` Jarkko Sakkinen
2023-12-04 12:35 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-12-04 2:29 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel, Mimi Zohar
On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > One very obvious thing to fix there is the kconfig flag:
> >
> > 1. Its meaning and purpose is not documented to the commit message.
> > What
> > is it and what is its meaning and purpose.
> > 2. TPM_BUS_SECURITY does not follow the naming convention of other
> > TPM kconfig flags, and to add, "security" is way way too abstract
> > word. Something like TCG_TPM_HMAC
> >
> > It should be renamed as TCG_TPM_
>
> One question is do we still need this? Since my tree has moved ahead,
> I also need the HMAC code for policy on keys and the primary code for
> permanent parents. The only real performance concern is for PCR
> extension (no-one really cares about the speed of unseal or random), so
> a different possible way of doing this is simply to CONFIG that one
> operation.
I think so.
Major distributions have started to ship with TPM2 sealed hardware drive
encryption, based on LVM/LUKS2 partitioning setup. It is convenient enough
that at least I prefer it over encrypted passphrase.
Having this feature would add defence in depth to that. I could definitely
see distributions adapting also to HMAC because now there is already too
legit uses cases (ignoring the people who just enjoy configuring obscure
things).
So motivation has rised by a factor now, i.e. it makes sense now more as
a "product" and not just research topic, given the use in the workstation,
in addition to the data center.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 2:29 ` Jarkko Sakkinen
@ 2023-12-04 12:35 ` James Bottomley
2023-12-04 13:43 ` Mimi Zohar
2023-12-04 22:46 ` Jarkko Sakkinen
0 siblings, 2 replies; 62+ messages in thread
From: James Bottomley @ 2023-12-04 12:35 UTC (permalink / raw)
To: Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel, Mimi Zohar
On Mon, 2023-12-04 at 04:29 +0200, Jarkko Sakkinen wrote:
> On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> > On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > > One very obvious thing to fix there is the kconfig flag:
> > >
> > > 1. Its meaning and purpose is not documented to the commit
> > > message. What is it and what is its meaning and purpose.
> > > 2. TPM_BUS_SECURITY does not follow the naming convention of
> > > other TPM kconfig flags, and to add, "security" is way way too
> > > abstract word. Something like TCG_TPM_HMAC
> > >
> > > It should be renamed as TCG_TPM_
> >
> > One question is do we still need this? Since my tree has moved
> > ahead, I also need the HMAC code for policy on keys and the primary
> > code for permanent parents. The only real performance concern is
> > for PCR extension (no-one really cares about the speed of unseal or
> > random), so a different possible way of doing this is simply to
> > CONFIG that one operation.
>
> I think so.
>
> Major distributions have started to ship with TPM2 sealed hardware
> drive encryption, based on LVM/LUKS2 partitioning setup. It is
> convenient enough that at least I prefer it over encrypted
> passphrase.
>
> Having this feature would add defence in depth to that. I could
> definitely see distributions adapting also to HMAC because now there
> is already too legit uses cases (ignoring the people who just enjoy
> configuring obscure things).
>
> So motivation has rised by a factor now, i.e. it makes sense now more
> as a "product" and not just research topic, given the use in the
> workstation, in addition to the data center.
Sorry, miscommunication. By "this" I meant the config option not the
entire HMAC code. The proposal without it would be unconditionally
compile tpm2-sessions.c and do HMAC/encryption on random and
seal/unseal but gate the PCR HMAC via a compile or runtime option so as
not to degrade IMA performance if performance were preferable to
security.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 12:35 ` James Bottomley
@ 2023-12-04 13:43 ` Mimi Zohar
2023-12-04 13:53 ` James Bottomley
2023-12-04 22:58 ` Jarkko Sakkinen
2023-12-04 22:46 ` Jarkko Sakkinen
1 sibling, 2 replies; 62+ messages in thread
From: Mimi Zohar @ 2023-12-04 13:43 UTC (permalink / raw)
To: James Bottomley, Jarkko Sakkinen, linux-integrity
Cc: keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 07:35 -0500, James Bottomley wrote:
> On Mon, 2023-12-04 at 04:29 +0200, Jarkko Sakkinen wrote:
> > On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> > > On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > > > One very obvious thing to fix there is the kconfig flag:
> > > >
> > > > 1. Its meaning and purpose is not documented to the commit
> > > > message. What is it and what is its meaning and purpose.
> > > > 2. TPM_BUS_SECURITY does not follow the naming convention of
> > > > other TPM kconfig flags, and to add, "security" is way way too
> > > > abstract word. Something like TCG_TPM_HMAC
> > > >
> > > > It should be renamed as TCG_TPM_
> > >
> > > One question is do we still need this? Since my tree has moved
> > > ahead, I also need the HMAC code for policy on keys and the primary
> > > code for permanent parents. The only real performance concern is
> > > for PCR extension (no-one really cares about the speed of unseal or
> > > random), so a different possible way of doing this is simply to
> > > CONFIG that one operation.
> >
> > I think so.
> >
> > Major distributions have started to ship with TPM2 sealed hardware
> > drive encryption, based on LVM/LUKS2 partitioning setup. It is
> > convenient enough that at least I prefer it over encrypted
> > passphrase.
> >
> > Having this feature would add defence in depth to that. I could
> > definitely see distributions adapting also to HMAC because now there
> > is already too legit uses cases (ignoring the people who just enjoy
> > configuring obscure things).
> >
> > So motivation has rised by a factor now, i.e. it makes sense now more
> > as a "product" and not just research topic, given the use in the
> > workstation, in addition to the data center.
>
> Sorry, miscommunication. By "this" I meant the config option not the
> entire HMAC code. The proposal without it would be unconditionally
> compile tpm2-sessions.c and do HMAC/encryption on random and
> seal/unseal but gate the PCR HMAC via a compile or runtime option so as
> not to degrade IMA performance if performance were preferable to
> security.
Is there a way of not degrading IMA performance without disabling HMAC
encryption/decryption?
Mimi
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 13:43 ` Mimi Zohar
@ 2023-12-04 13:53 ` James Bottomley
2023-12-04 13:59 ` Mimi Zohar
2023-12-04 22:58 ` Jarkko Sakkinen
1 sibling, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-12-04 13:53 UTC (permalink / raw)
To: Mimi Zohar, Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 08:43 -0500, Mimi Zohar wrote:
> On Mon, 2023-12-04 at 07:35 -0500, James Bottomley wrote:
> > On Mon, 2023-12-04 at 04:29 +0200, Jarkko Sakkinen wrote:
> > > On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> > > > On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > > > > One very obvious thing to fix there is the kconfig flag:
> > > > >
> > > > > 1. Its meaning and purpose is not documented to the commit
> > > > > message. What is it and what is its meaning and purpose.
> > > > > 2. TPM_BUS_SECURITY does not follow the naming convention of
> > > > > other TPM kconfig flags, and to add, "security" is way way
> > > > > too abstract word. Something like TCG_TPM_HMAC
> > > > >
> > > > > It should be renamed as TCG_TPM_
> > > >
> > > > One question is do we still need this? Since my tree has moved
> > > > ahead, I also need the HMAC code for policy on keys and the
> > > > primary code for permanent parents. The only real performance
> > > > concern is for PCR extension (no-one really cares about the
> > > > speed of unseal or random), so a different possible way of
> > > > doing this is simply to CONFIG that one operation.
> > >
> > > I think so.
> > >
> > > Major distributions have started to ship with TPM2 sealed
> > > hardware drive encryption, based on LVM/LUKS2 partitioning setup.
> > > It is convenient enough that at least I prefer it over encrypted
> > > passphrase.
> > >
> > > Having this feature would add defence in depth to that. I could
> > > definitely see distributions adapting also to HMAC because now
> > > there is already too legit uses cases (ignoring the people who
> > > just enjoy configuring obscure things).
> > >
> > > So motivation has rised by a factor now, i.e. it makes sense now
> > > more as a "product" and not just research topic, given the use in
> > > the workstation, in addition to the data center.
> >
> > Sorry, miscommunication. By "this" I meant the config option not
> > the entire HMAC code. The proposal without it would be
> > unconditionally compile tpm2-sessions.c and do HMAC/encryption on
> > random and seal/unseal but gate the PCR HMAC via a compile or
> > runtime option so as not to degrade IMA performance if performance
> > were preferable to security.
>
> Is there a way of not degrading IMA performance without disabling
> HMAC encryption/decryption?
Well, perhaps we should measure it. My operating assumption, since
extend is a simple hash, is that most of the latency of extend is
actually in the LPC (or i2c or whatever) bus round trip. To do HMAC,
you have to have a session, which adds an extra command and thus
doubles the round trip.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 13:53 ` James Bottomley
@ 2023-12-04 13:59 ` Mimi Zohar
2023-12-04 14:02 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: Mimi Zohar @ 2023-12-04 13:59 UTC (permalink / raw)
To: James Bottomley, Jarkko Sakkinen, linux-integrity
Cc: keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 08:53 -0500, James Bottomley wrote:
> On Mon, 2023-12-04 at 08:43 -0500, Mimi Zohar wrote:
> > On Mon, 2023-12-04 at 07:35 -0500, James Bottomley wrote:
> > > On Mon, 2023-12-04 at 04:29 +0200, Jarkko Sakkinen wrote:
> > > > On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> > > > > On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > > > > > One very obvious thing to fix there is the kconfig flag:
> > > > > >
> > > > > > 1. Its meaning and purpose is not documented to the commit
> > > > > > message. What is it and what is its meaning and purpose.
> > > > > > 2. TPM_BUS_SECURITY does not follow the naming convention of
> > > > > > other TPM kconfig flags, and to add, "security" is way way
> > > > > > too abstract word. Something like TCG_TPM_HMAC
> > > > > >
> > > > > > It should be renamed as TCG_TPM_
> > > > >
> > > > > One question is do we still need this? Since my tree has moved
> > > > > ahead, I also need the HMAC code for policy on keys and the
> > > > > primary code for permanent parents. The only real performance
> > > > > concern is for PCR extension (no-one really cares about the
> > > > > speed of unseal or random), so a different possible way of
> > > > > doing this is simply to CONFIG that one operation.
> > > >
> > > > I think so.
> > > >
> > > > Major distributions have started to ship with TPM2 sealed
> > > > hardware drive encryption, based on LVM/LUKS2 partitioning setup.
> > > > It is convenient enough that at least I prefer it over encrypted
> > > > passphrase.
> > > >
> > > > Having this feature would add defence in depth to that. I could
> > > > definitely see distributions adapting also to HMAC because now
> > > > there is already too legit uses cases (ignoring the people who
> > > > just enjoy configuring obscure things).
> > > >
> > > > So motivation has rised by a factor now, i.e. it makes sense now
> > > > more as a "product" and not just research topic, given the use in
> > > > the workstation, in addition to the data center.
> > >
> > > Sorry, miscommunication. By "this" I meant the config option not
> > > the entire HMAC code. The proposal without it would be
> > > unconditionally compile tpm2-sessions.c and do HMAC/encryption on
> > > random and seal/unseal but gate the PCR HMAC via a compile or
> > > runtime option so as not to degrade IMA performance if performance
> > > were preferable to security.
> >
> > Is there a way of not degrading IMA performance without disabling
> > HMAC encryption/decryption?
>
> Well, perhaps we should measure it. My operating assumption, since
> extend is a simple hash, is that most of the latency of extend is
> actually in the LPC (or i2c or whatever) bus round trip. To do HMAC,
> you have to have a session, which adds an extra command and thus
> doubles the round trip.
Agreed getting some statistics would be beneficial. Instead of
creating a session for each IMA extend, would it be possible to estable
a session once and re-use it?
Mimi
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 13:59 ` Mimi Zohar
@ 2023-12-04 14:02 ` James Bottomley
2023-12-04 14:10 ` Mimi Zohar
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-12-04 14:02 UTC (permalink / raw)
To: Mimi Zohar, Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 08:59 -0500, Mimi Zohar wrote:
> On Mon, 2023-12-04 at 08:53 -0500, James Bottomley wrote:
> > On Mon, 2023-12-04 at 08:43 -0500, Mimi Zohar wrote:
[...]
> > > Is there a way of not degrading IMA performance without disabling
> > > HMAC encryption/decryption?
> >
> > Well, perhaps we should measure it. My operating assumption, since
> > extend is a simple hash, is that most of the latency of extend is
> > actually in the LPC (or i2c or whatever) bus round trip. To do
> > HMAC, you have to have a session, which adds an extra command and
> > thus doubles the round trip.
>
> Agreed getting some statistics would be beneficial. Instead of
> creating a session for each IMA extend, would it be possible to
> estable a session once and re-use it?
Not really. Sessions are fairly cheap to establish, so there's not
much work the TPM has to do, so context save/restore would still have
the same doubling of the bus round trip. Keeping a session permanently
in the TPM would avoid the second round trip but be visible to all the
users and highly undesirable (would impact the number of sessions they
could create).
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 14:02 ` James Bottomley
@ 2023-12-04 14:10 ` Mimi Zohar
2023-12-04 14:23 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: Mimi Zohar @ 2023-12-04 14:10 UTC (permalink / raw)
To: James Bottomley, Jarkko Sakkinen, linux-integrity
Cc: keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 09:02 -0500, James Bottomley wrote:
> On Mon, 2023-12-04 at 08:59 -0500, Mimi Zohar wrote:
> > On Mon, 2023-12-04 at 08:53 -0500, James Bottomley wrote:
> > > On Mon, 2023-12-04 at 08:43 -0500, Mimi Zohar wrote:
> [...]
> > > > Is there a way of not degrading IMA performance without disabling
> > > > HMAC encryption/decryption?
> > >
> > > Well, perhaps we should measure it. My operating assumption, since
> > > extend is a simple hash, is that most of the latency of extend is
> > > actually in the LPC (or i2c or whatever) bus round trip. To do
> > > HMAC, you have to have a session, which adds an extra command and
> > > thus doubles the round trip.
> >
> > Agreed getting some statistics would be beneficial. Instead of
> > creating a session for each IMA extend, would it be possible to
> > estable a session once and re-use it?
>
> Not really. Sessions are fairly cheap to establish, so there's not
> much work the TPM has to do, so context save/restore would still have
> the same doubling of the bus round trip. Keeping a session permanently
> in the TPM would avoid the second round trip but be visible to all the
> users and highly undesirable (would impact the number of sessions they
> could create).
Ignoring the "highly undersirable" aspsect, is there a way of limiting
visibility (and of course usage) of the "session permanently in the
TPM" to just IMA?
Mimi
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 14:10 ` Mimi Zohar
@ 2023-12-04 14:23 ` James Bottomley
0 siblings, 0 replies; 62+ messages in thread
From: James Bottomley @ 2023-12-04 14:23 UTC (permalink / raw)
To: Mimi Zohar, Jarkko Sakkinen, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 09:10 -0500, Mimi Zohar wrote:
> On Mon, 2023-12-04 at 09:02 -0500, James Bottomley wrote:
> > On Mon, 2023-12-04 at 08:59 -0500, Mimi Zohar wrote:
> > > On Mon, 2023-12-04 at 08:53 -0500, James Bottomley wrote:
> > > > On Mon, 2023-12-04 at 08:43 -0500, Mimi Zohar wrote:
> > [...]
> > > > > Is there a way of not degrading IMA performance without
> > > > > disabling
> > > > > HMAC encryption/decryption?
> > > >
> > > > Well, perhaps we should measure it. My operating assumption,
> > > > since extend is a simple hash, is that most of the latency of
> > > > extend is actually in the LPC (or i2c or whatever) bus round
> > > > trip. To do HMAC, you have to have a session, which adds an
> > > > extra command and thus doubles the round trip.
> > >
> > > Agreed getting some statistics would be beneficial. Instead of
> > > creating a session for each IMA extend, would it be possible to
> > > estable a session once and re-use it?
> >
> > Not really. Sessions are fairly cheap to establish, so there's not
> > much work the TPM has to do, so context save/restore would still
> > have the same doubling of the bus round trip. Keeping a session
> > permanently in the TPM would avoid the second round trip but be
> > visible to all the users and highly undesirable (would impact the
> > number of sessions they could create).
>
> Ignoring the "highly undersirable" aspsect, is there a way of
> limiting visibility (and of course usage) of the "session permanently
> in the TPM" to just IMA?
In theory, yes, but we'd have to filter the session area of every
command plus inspect commands which take sessions as parameters.
That's a lot of work which would have to be done by an infrastructure
that doesn't fully exist (we already snoop the sessions in tpm space
handling, so we can filter the session areas there; we'd have to add
filtering on commands which take sessions). But nothing can really get
around the problem that commands can take three sessions and on most
TPMs that's also the maximum size of the session volatile area, so we'd
break any user space application that uses more than two sessions.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 13:43 ` Mimi Zohar
2023-12-04 13:53 ` James Bottomley
@ 2023-12-04 22:58 ` Jarkko Sakkinen
1 sibling, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-12-04 22:58 UTC (permalink / raw)
To: Mimi Zohar, James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon Dec 4, 2023 at 3:43 PM EET, Mimi Zohar wrote:
> On Mon, 2023-12-04 at 07:35 -0500, James Bottomley wrote:
> > On Mon, 2023-12-04 at 04:29 +0200, Jarkko Sakkinen wrote:
> > > On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> > > > On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > > > > One very obvious thing to fix there is the kconfig flag:
> > > > >
> > > > > 1. Its meaning and purpose is not documented to the commit
> > > > > message. What is it and what is its meaning and purpose.
> > > > > 2. TPM_BUS_SECURITY does not follow the naming convention of
> > > > > other TPM kconfig flags, and to add, "security" is way way too
> > > > > abstract word. Something like TCG_TPM_HMAC
> > > > >
> > > > > It should be renamed as TCG_TPM_
> > > >
> > > > One question is do we still need this? Since my tree has moved
> > > > ahead, I also need the HMAC code for policy on keys and the primary
> > > > code for permanent parents. The only real performance concern is
> > > > for PCR extension (no-one really cares about the speed of unseal or
> > > > random), so a different possible way of doing this is simply to
> > > > CONFIG that one operation.
> > >
> > > I think so.
> > >
> > > Major distributions have started to ship with TPM2 sealed hardware
> > > drive encryption, based on LVM/LUKS2 partitioning setup. It is
> > > convenient enough that at least I prefer it over encrypted
> > > passphrase.
> > >
> > > Having this feature would add defence in depth to that. I could
> > > definitely see distributions adapting also to HMAC because now there
> > > is already too legit uses cases (ignoring the people who just enjoy
> > > configuring obscure things).
> > >
> > > So motivation has rised by a factor now, i.e. it makes sense now more
> > > as a "product" and not just research topic, given the use in the
> > > workstation, in addition to the data center.
> >
> > Sorry, miscommunication. By "this" I meant the config option not the
> > entire HMAC code. The proposal without it would be unconditionally
> > compile tpm2-sessions.c and do HMAC/encryption on random and
> > seal/unseal but gate the PCR HMAC via a compile or runtime option so as
> > not to degrade IMA performance if performance were preferable to
> > security.
>
> Is there a way of not degrading IMA performance without disabling HMAC
> encryption/decryption?
Whether or not IMA needs HMAC channel to guard its properties, it has to
use it if the whole feature is enabled in the first place.
In a nutshell this patch set has two features:
A. HMAC channel
B. Intrusion detection
Further, B depends on A because corrupted seed from the null hierarchy
is the mechanism how possible interposers are detected.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code
2023-12-04 12:35 ` James Bottomley
2023-12-04 13:43 ` Mimi Zohar
@ 2023-12-04 22:46 ` Jarkko Sakkinen
1 sibling, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-12-04 22:46 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel, Mimi Zohar
On Mon Dec 4, 2023 at 2:35 PM EET, James Bottomley wrote:
> On Mon, 2023-12-04 at 04:29 +0200, Jarkko Sakkinen wrote:
> > On Sun Nov 26, 2023 at 5:05 PM EET, James Bottomley wrote:
> > > On Sun, 2023-11-26 at 05:39 +0200, Jarkko Sakkinen wrote:
> > > > One very obvious thing to fix there is the kconfig flag:
> > > >
> > > > 1. Its meaning and purpose is not documented to the commit
> > > > message. What is it and what is its meaning and purpose.
> > > > 2. TPM_BUS_SECURITY does not follow the naming convention of
> > > > other TPM kconfig flags, and to add, "security" is way way too
> > > > abstract word. Something like TCG_TPM_HMAC
> > > >
> > > > It should be renamed as TCG_TPM_
> > >
> > > One question is do we still need this? Since my tree has moved
> > > ahead, I also need the HMAC code for policy on keys and the primary
> > > code for permanent parents. The only real performance concern is
> > > for PCR extension (no-one really cares about the speed of unseal or
> > > random), so a different possible way of doing this is simply to
> > > CONFIG that one operation.
> >
> > I think so.
> >
> > Major distributions have started to ship with TPM2 sealed hardware
> > drive encryption, based on LVM/LUKS2 partitioning setup. It is
> > convenient enough that at least I prefer it over encrypted
> > passphrase.
> >
> > Having this feature would add defence in depth to that. I could
> > definitely see distributions adapting also to HMAC because now there
> > is already too legit uses cases (ignoring the people who just enjoy
> > configuring obscure things).
> >
> > So motivation has rised by a factor now, i.e. it makes sense now more
> > as a "product" and not just research topic, given the use in the
> > workstation, in addition to the data center.
>
> Sorry, miscommunication. By "this" I meant the config option not the
> entire HMAC code. The proposal without it would be unconditionally
> compile tpm2-sessions.c and do HMAC/encryption on random and
> seal/unseal but gate the PCR HMAC via a compile or runtime option so as
> not to degrade IMA performance if performance were preferable to
> security.
>
> James
Ok, well, at this point I would default-n and distributions can make
their policy.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 09/13] tpm: add hmac checks to tpm2_pcr_extend()
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (7 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 08/13] tpm: Add full HMAC and encrypt/decrypt session handling code James Bottomley
@ 2023-04-03 21:39 ` James Bottomley
2023-04-23 5:32 ` Jarkko Sakkinen
2023-04-03 21:40 ` [PATCH v4 10/13] tpm: add session encryption protection to tpm2_get_random() James Bottomley
` (7 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:39 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>
---
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] 62+ messages in thread* Re: [PATCH v4 09/13] tpm: add hmac checks to tpm2_pcr_extend()
2023-04-03 21:39 ` [PATCH v4 09/13] tpm: add hmac checks to tpm2_pcr_extend() James Bottomley
@ 2023-04-23 5:32 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 5:32 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-04-03 at 17:39 -0400, James Bottomley wrote:
> 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>
What the heck is "check"?
The code change adds hmac pipeline for the command.
I get the code change but the description is misleading as this
does more than just add a check.
> ---
> 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);
>
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 10/13] tpm: add session encryption protection to tpm2_get_random()
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (8 preceding siblings ...)
2023-04-03 21:39 ` [PATCH v4 09/13] tpm: add hmac checks to tpm2_pcr_extend() James Bottomley
@ 2023-04-03 21:40 ` James Bottomley
2023-04-03 21:40 ` [PATCH v4 11/13] KEYS: trusted: Add session encryption protection to the seal/unseal path James Bottomley
` (6 subsequent siblings)
16 siblings, 0 replies; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:40 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>
---
drivers/char/tpm/tpm2-cmd.c | 20 ++++++++++++++++----
1 file changed, 16 insertions(+), 4 deletions(-)
diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index a53a843294ed..acc944591b91 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,6 +337,8 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
} while (retries-- && total < max);
tpm_buf_destroy(&buf);
+ tpm2_end_auth_session(chip);
+
return total ? total : -EIO;
out:
tpm_buf_destroy(&buf);
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* [PATCH v4 11/13] KEYS: trusted: Add session encryption protection to the seal/unseal path
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (9 preceding siblings ...)
2023-04-03 21:40 ` [PATCH v4 10/13] tpm: add session encryption protection to tpm2_get_random() James Bottomley
@ 2023-04-03 21:40 ` James Bottomley
2023-04-03 21:40 ` [PATCH v4 12/13] tpm: add the null key name as a sysfs export James Bottomley
` (5 subsequent siblings)
16 siblings, 0 replies; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:40 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>
---
v2: fix unseal with policy and password
v3: fix session memory leak
---
security/keys/trusted-keys/trusted_tpm2.c | 82 ++++++++++++++++-------
1 file changed, 58 insertions(+), 24 deletions(-)
diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index 2b2c8eb258d5..4790aa7a1e0f 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -252,18 +252,19 @@ 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;
}
- 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(&buf, 4 + options->blobauth_len + payload->key_len);
@@ -305,10 +306,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;
@@ -340,6 +344,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
else
payload->blob_len = blob_len;
+out_put:
tpm_put_ops(chip);
return rc;
}
@@ -409,25 +414,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]);
@@ -465,20 +476,43 @@ 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, TPM_DIGEST_SIZE);
+ } else {
+ /*
+ * FIXME: The policy session was generated outside the
+ * kernel so we don't known the nonce and thus can't
+ * calculate a HMAC on it. Therefore, the user can
+ * only really use TPM2_PolicyPassword and we must
+ * send down the plain text password, which could be
+ * intercepted. We can still encrypt the returned
+ * key, but that's small comfort since the interposer
+ * could repeat our actions with the exfiltrated
+ * password.
+ */
+ tpm2_buf_append_auth(&buf, options->policyhandle,
+ NULL /* nonce */, 0, 0,
+ options->blobauth, options->blobauth_len);
+ tpm_buf_append_hmac_session_opt(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] 62+ messages in thread* [PATCH v4 12/13] tpm: add the null key name as a sysfs export
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (10 preceding siblings ...)
2023-04-03 21:40 ` [PATCH v4 11/13] KEYS: trusted: Add session encryption protection to the seal/unseal path James Bottomley
@ 2023-04-03 21:40 ` James Bottomley
2023-04-23 5:38 ` Jarkko Sakkinen
2023-04-03 21:40 ` [PATCH v4 13/13] Documentation: add tpm-security.rst James Bottomley
` (4 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:40 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>
---
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..403dffea4ea6 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_TPM_BUS_SECURITY
+static ssize_t null_name_show(struct device *dev, struct device_attribute *attr,
+ char *buf)
+{
+ struct tpm_chip *chip = to_tpm_chip(dev);
+ int size = TPM2_NAME_SIZE;
+
+ bin2hex(buf, chip->tpmkeyname, size);
+ size *= 2;
+ buf[size++] = '\n';
+ return size;
+}
+static DEVICE_ATTR_RO(null_name);
+#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_TPM_BUS_SECURITY
+ &dev_attr_null_name.attr,
+#endif
NULL
};
--
2.35.3
^ permalink raw reply related [flat|nested] 62+ messages in thread* Re: [PATCH v4 12/13] tpm: add the null key name as a sysfs export
2023-04-03 21:40 ` [PATCH v4 12/13] tpm: add the null key name as a sysfs export James Bottomley
@ 2023-04-23 5:38 ` Jarkko Sakkinen
0 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 5:38 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-04-03 at 17:40 -0400, James Bottomley wrote:
> 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.
How would you do this in practice with the help of this file?
The current description does not make a case to have this file, unless
it is supported by an usage example to do what you claim above.
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread
* [PATCH v4 13/13] Documentation: add tpm-security.rst
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (11 preceding siblings ...)
2023-04-03 21:40 ` [PATCH v4 12/13] tpm: add the null key name as a sysfs export James Bottomley
@ 2023-04-03 21:40 ` James Bottomley
2023-04-04 18:43 ` [PATCH v4 00/13] add integrity and security to TPM2 transactions William Roberts
` (3 subsequent siblings)
16 siblings, 0 replies; 62+ messages in thread
From: James Bottomley @ 2023-04-03 21:40 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>
---
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] 62+ messages in thread* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (12 preceding siblings ...)
2023-04-03 21:40 ` [PATCH v4 13/13] Documentation: add tpm-security.rst James Bottomley
@ 2023-04-04 18:43 ` William Roberts
2023-04-04 19:18 ` James Bottomley
2023-04-05 18:39 ` William Roberts
` (2 subsequent siblings)
16 siblings, 1 reply; 62+ messages in thread
From: William Roberts @ 2023-04-04 18:43 UTC (permalink / raw)
To: James Bottomley
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Mon, Apr 3, 2023 at 4:44 PM James Bottomley
<James.Bottomley@hansenpartnership.com> 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
>
I fixed systemd, see the relevant PRS:
- https://github.com/systemd/systemd/pulls?q=is%3Apr+is%3Aclosed+author%3Awilliamcroberts
They had some support where they would create a primary key on each
boot and just trust it, eventually
we:
1. Added a bind key as a stop gap
2. strengthened passwords for the bind key
3. Added verification of the tpm key to a trusted public blob and used
the persistent SRK.
I could drop the bind key now if the SRK is present as it's not
needed, but it shouldn't hurt anything.
The big issue is the period of 1 to 2 where a weak pin could be
cracked offline. This occurs in
version 252 but the salt was merged in 253 and using SRK is on main.
> 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.
Ahh I was wondering how you were going to bootstrap trust using the
NULL hierarchy.
>
> 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
>
> James
>
> ---
>
> Ard Biesheuvel (1):
> crypto: lib - implement library version of AES in CFB mode
>
> James Bottomley (12):
> tpm: move buffer handling from static inlines to real functions
> tpm: add kernel doc to buffer handling functions
> tpm: add buffer handling for TPM2B types
> tpm: add cursor based buffer functions for response parsing
> tpm: add buffer function to point to returned parameters
> tpm: export the context save and load commands
> tpm: Add full HMAC and encrypt/decrypt session handling code
> tpm: add hmac checks to tpm2_pcr_extend()
> tpm: add session encryption protection to tpm2_get_random()
> KEYS: trusted: Add session encryption protection to the seal/unseal
> path
> tpm: add the null key name as a sysfs export
> Documentation: add tpm-security.rst
>
> Documentation/security/tpm/tpm-security.rst | 216 ++++
> drivers/char/tpm/Kconfig | 13 +
> drivers/char/tpm/Makefile | 2 +
> drivers/char/tpm/tpm-buf.c | 307 +++++
> drivers/char/tpm/tpm-chip.c | 3 +
> drivers/char/tpm/tpm-sysfs.c | 18 +
> drivers/char/tpm/tpm.h | 14 +
> drivers/char/tpm/tpm2-cmd.c | 52 +-
> drivers/char/tpm/tpm2-sessions.c | 1158 +++++++++++++++++++
> drivers/char/tpm/tpm2-space.c | 8 +-
> include/crypto/aes.h | 5 +
> include/linux/tpm.h | 257 ++--
> lib/crypto/Kconfig | 5 +
> lib/crypto/Makefile | 3 +
> lib/crypto/aescfb.c | 257 ++++
> security/keys/trusted-keys/trusted_tpm2.c | 82 +-
> 16 files changed, 2275 insertions(+), 125 deletions(-)
> create mode 100644 Documentation/security/tpm/tpm-security.rst
> create mode 100644 drivers/char/tpm/tpm-buf.c
> create mode 100644 drivers/char/tpm/tpm2-sessions.c
> create mode 100644 lib/crypto/aescfb.c
>
> --
> 2.35.3
>
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-04 18:43 ` [PATCH v4 00/13] add integrity and security to TPM2 transactions William Roberts
@ 2023-04-04 19:18 ` James Bottomley
2023-04-04 19:42 ` William Roberts
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-04 19:18 UTC (permalink / raw)
To: William Roberts
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Tue, 2023-04-04 at 13:43 -0500, William Roberts wrote:
[...]
> > 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.
>
> Ahh I was wondering how you were going to bootstrap trust using the
> NULL hierarchy.
Well, actually, I changed my mind on the details of this one: the make
credential/activate credential round trip is a huge faff given that
there's no privacy issue. I think what we should do is simply store
the name of a known signing EK on first install (using the standard P-
256 derivation of the EK template but with TPMA_OBJECT_SIGN
additionally set). Then you can use the signing EK to certify the NULL
key directly and merely check the signing EK name against the stored
value to prove everything is correct.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-04 19:18 ` James Bottomley
@ 2023-04-04 19:42 ` William Roberts
2023-04-04 20:19 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: William Roberts @ 2023-04-04 19:42 UTC (permalink / raw)
To: James Bottomley
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Tue, Apr 4, 2023 at 2:18 PM James Bottomley
<James.Bottomley@hansenpartnership.com> wrote:
>
> On Tue, 2023-04-04 at 13:43 -0500, William Roberts wrote:
> [...]
> > > 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.
> >
> > Ahh I was wondering how you were going to bootstrap trust using the
> > NULL hierarchy.
>
> Well, actually, I changed my mind on the details of this one: the make
> credential/activate credential round trip is a huge faff given that
> there's no privacy issue. I think what we should do is simply store
> the name of a known signing EK on first install (using the standard P-
> 256 derivation of the EK template but with TPMA_OBJECT_SIGN
> additionally set). Then you can use the signing EK to certify the NULL
> key directly and merely check the signing EK name against the stored
> value to prove everything is correct.
>
Yeah that model is much simpler. My guess is that on install it would
persist this
"Signing EK" to a specific address that is different from the typical
EK Address?
Any particular reason for using the Endorsement Hierarchy outside of
the lifespan of the seed only changing on revocation of the Manufacturers Cert?
Ie why not Owner Hierarchy?
> James
>
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-04 19:42 ` William Roberts
@ 2023-04-04 20:19 ` James Bottomley
2023-04-04 21:10 ` William Roberts
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-04 20:19 UTC (permalink / raw)
To: William Roberts
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Tue, 2023-04-04 at 14:42 -0500, William Roberts wrote:
> On Tue, Apr 4, 2023 at 2:18 PM James Bottomley
> <James.Bottomley@hansenpartnership.com> wrote:
> >
> > On Tue, 2023-04-04 at 13:43 -0500, William Roberts wrote:
> > [...]
> > > > 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.
> > >
> > > Ahh I was wondering how you were going to bootstrap trust using
> > > the NULL hierarchy.
> >
> > Well, actually, I changed my mind on the details of this one: the
> > make credential/activate credential round trip is a huge faff given
> > that there's no privacy issue. I think what we should do is simply
> > store the name of a known signing EK on first install (using the
> > standard P-256 derivation of the EK template but with
> > TPMA_OBJECT_SIGN additionally set). Then you can use the signing
> > EK to certify the NULL key directly and merely check the signing EK
> > name against the stored value to prove everything is correct.
> >
>
> Yeah that model is much simpler. My guess is that on install it would
> persist this "Signing EK" to a specific address that is different
> from the typical EK Address?
Actually, since this is used to prove trust in the TPM, we can't have
the TPM store it; it's going to have to be somewhere in the root
filesystem, like /etc. Ideally it would be in the immutable part of
/etc so it is write once on install.
> Any particular reason for using the Endorsement Hierarchy outside of
> the lifespan of the seed only changing on revocation of the
> Manufacturers Cert? Ie why not Owner Hierarchy?
That's it really: it's the longest lived key of all those the TPM has.
If I'm deriving it once on install and keeping it immutable until
reinstall, I don't want tpm_clear upsetting the apple cart.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-04 20:19 ` James Bottomley
@ 2023-04-04 21:10 ` William Roberts
2023-04-04 21:33 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: William Roberts @ 2023-04-04 21:10 UTC (permalink / raw)
To: James Bottomley
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Tue, Apr 4, 2023 at 3:19 PM James Bottomley
<James.Bottomley@hansenpartnership.com> wrote:
>
> On Tue, 2023-04-04 at 14:42 -0500, William Roberts wrote:
> > On Tue, Apr 4, 2023 at 2:18 PM James Bottomley
> > <James.Bottomley@hansenpartnership.com> wrote:
> > >
> > > On Tue, 2023-04-04 at 13:43 -0500, William Roberts wrote:
> > > [...]
> > > > > 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.
> > > >
> > > > Ahh I was wondering how you were going to bootstrap trust using
> > > > the NULL hierarchy.
> > >
> > > Well, actually, I changed my mind on the details of this one: the
> > > make credential/activate credential round trip is a huge faff given
> > > that there's no privacy issue. I think what we should do is simply
> > > store the name of a known signing EK on first install (using the
> > > standard P-256 derivation of the EK template but with
> > > TPMA_OBJECT_SIGN additionally set). Then you can use the signing
> > > EK to certify the NULL key directly and merely check the signing EK
> > > name against the stored value to prove everything is correct.
> > >
> >
> > Yeah that model is much simpler. My guess is that on install it would
> > persist this "Signing EK" to a specific address that is different
> > from the typical EK Address?
>
> Actually, since this is used to prove trust in the TPM, we can't have
> the TPM store it;
Hmm, I think we miscommunicated here. At some point you need to call
TPM2_CreatePrimary
with the "Signing EK" template which would require Endorsement
Hierarchy (EH) Auth. So I would
imagine this key would be persistend to avoid needing it all the time?
Then the use of
TPM2_Certify using the "EK Signing" key would also need EH Auth since
AuthPolicy is coupled to EH Auth
via PolicySecret. I'm just thinking every time these commands are
invoked, especially if this is used
during boot, where EH Auth would be coming from or am I missing something?
> it's going to have to be somewhere in the root
> filesystem, like /etc. Ideally it would be in the immutable part of
> /etc so it is write once on install.
>
I'm assuming this would be the template or name of the "Signing EK"?
In systemd we just shove the name (Actually a serialized ESYS_TR) of
the SRK into
the LUKS data and ESAPI handles the check in session establishment.
> > Any particular reason for using the Endorsement Hierarchy outside of
> > the lifespan of the seed only changing on revocation of the
> > Manufacturers Cert? Ie why not Owner Hierarchy?
>
> That's it really: it's the longest lived key of all those the TPM has.
> If I'm deriving it once on install and keeping it immutable until
> reinstall, I don't want tpm_clear upsetting the apple cart.
>
> James
>
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-04 21:10 ` William Roberts
@ 2023-04-04 21:33 ` James Bottomley
2023-04-04 21:44 ` William Roberts
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-04 21:33 UTC (permalink / raw)
To: William Roberts
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Tue, 2023-04-04 at 16:10 -0500, William Roberts wrote:
> On Tue, Apr 4, 2023 at 3:19 PM James Bottomley
> <James.Bottomley@hansenpartnership.com> wrote:
> >
> > On Tue, 2023-04-04 at 14:42 -0500, William Roberts wrote:
> > > On Tue, Apr 4, 2023 at 2:18 PM James Bottomley
> > > <James.Bottomley@hansenpartnership.com> wrote:
> > > >
> > > > On Tue, 2023-04-04 at 13:43 -0500, William Roberts wrote:
> > > > [...]
> > > > > > 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.
> > > > >
> > > > > Ahh I was wondering how you were going to bootstrap trust
> > > > > using the NULL hierarchy.
> > > >
> > > > Well, actually, I changed my mind on the details of this one:
> > > > the make credential/activate credential round trip is a huge
> > > > faff given that there's no privacy issue. I think what we
> > > > should do is simply store the name of a known signing EK on
> > > > first install (using the standard P-256 derivation of the EK
> > > > template but with TPMA_OBJECT_SIGN additionally set). Then you
> > > > can use the signing EK to certify the NULL key directly and
> > > > merely check the signing EK name against the stored value to
> > > > prove everything is correct.
> > > >
> > >
> > > Yeah that model is much simpler. My guess is that on install it
> > > would persist this "Signing EK" to a specific address that is
> > > different from the typical EK Address?
> >
> > Actually, since this is used to prove trust in the TPM, we can't
> > have the TPM store it;
>
> Hmm, I think we miscommunicated here. At some point you need to call
> TPM2_CreatePrimary with the "Signing EK" template which would require
> Endorsement Hierarchy (EH) Auth.
That's right. Then you hash what you get back and check it against the
name file.
> So I would imagine this key would be persistend to avoid needing it
> all the time?
You could, but the benefit is marginal given how fast the Elliptic
Curve calculation can be done. Remember the key is only needed for a
quote or a certification, so that's once per boot to certify the NULL
seed and possibly a handful of other uses.
> Then the use of TPM2_Certify using the "EK Signing" key would also
> need EH Auth since AuthPolicy is coupled to EH Auth via PolicySecret.
> I'm just thinking every time these commands are invoked, especially
> if this is used during boot, where EH Auth would be coming from or am
> I missing something?
No, but then TPM2_CreatePrimary needs the hierarchy authorizations.
The standard assumption I tend to make is that they're empty for both
the endorsement and owner.
Although if there's a use case that actually wants them set for some
reason, then I think there might be a case for removing the policy from
the EK template, but if not, it's easier just to follow what the TCG
says with the addition of the signing permission.
> > it's going to have to be somewhere in the root
> > filesystem, like /etc. Ideally it would be in the immutable part
> > of /etc so it is write once on install.
> >
>
> I'm assuming this would be the template or name of the "Signing EK"?
Just the name, I think, assuming everyone agrees on the template. If
there's going to be a question about which template then we'd need
both.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-04 21:33 ` James Bottomley
@ 2023-04-04 21:44 ` William Roberts
0 siblings, 0 replies; 62+ messages in thread
From: William Roberts @ 2023-04-04 21:44 UTC (permalink / raw)
To: James Bottomley
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Tue, Apr 4, 2023 at 4:33 PM James Bottomley
<James.Bottomley@hansenpartnership.com> wrote:
>
> On Tue, 2023-04-04 at 16:10 -0500, William Roberts wrote:
> > On Tue, Apr 4, 2023 at 3:19 PM James Bottomley
> > <James.Bottomley@hansenpartnership.com> wrote:
> > >
> > > On Tue, 2023-04-04 at 14:42 -0500, William Roberts wrote:
> > > > On Tue, Apr 4, 2023 at 2:18 PM James Bottomley
> > > > <James.Bottomley@hansenpartnership.com> wrote:
> > > > >
> > > > > On Tue, 2023-04-04 at 13:43 -0500, William Roberts wrote:
> > > > > [...]
> > > > > > > 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.
> > > > > >
> > > > > > Ahh I was wondering how you were going to bootstrap trust
> > > > > > using the NULL hierarchy.
> > > > >
> > > > > Well, actually, I changed my mind on the details of this one:
> > > > > the make credential/activate credential round trip is a huge
> > > > > faff given that there's no privacy issue. I think what we
> > > > > should do is simply store the name of a known signing EK on
> > > > > first install (using the standard P-256 derivation of the EK
> > > > > template but with TPMA_OBJECT_SIGN additionally set). Then you
> > > > > can use the signing EK to certify the NULL key directly and
> > > > > merely check the signing EK name against the stored value to
> > > > > prove everything is correct.
> > > > >
> > > >
> > > > Yeah that model is much simpler. My guess is that on install it
> > > > would persist this "Signing EK" to a specific address that is
> > > > different from the typical EK Address?
> > >
> > > Actually, since this is used to prove trust in the TPM, we can't
> > > have the TPM store it;
> >
> > Hmm, I think we miscommunicated here. At some point you need to call
> > TPM2_CreatePrimary with the "Signing EK" template which would require
> > Endorsement Hierarchy (EH) Auth.
>
> That's right. Then you hash what you get back and check it against the
> name file.
>
> > So I would imagine this key would be persistend to avoid needing it
> > all the time?
>
> You could, but the benefit is marginal given how fast the Elliptic
> Curve calculation can be done. Remember the key is only needed for a
> quote or a certification, so that's once per boot to certify the NULL
> seed and possibly a handful of other uses.
>
> > Then the use of TPM2_Certify using the "EK Signing" key would also
> > need EH Auth since AuthPolicy is coupled to EH Auth via PolicySecret.
> > I'm just thinking every time these commands are invoked, especially
> > if this is used during boot, where EH Auth would be coming from or am
> > I missing something?
>
> No, but then TPM2_CreatePrimary needs the hierarchy authorizations.
> The standard assumption I tend to make is that they're empty for both
> the endorsement and owner.
>
That's been proven not to be a good assertion. Just look at the bugs on systemd
about not working if Owner Auth is set. I think it's important to look at models
that support auth being set for the hierarchy and minimizing the need on it.
Hierarchy Auth could even be a policy, thankfully I haven't bumped into that
yet.
If this "EK Signing" key is persisted and the AuthPolicy of the key
cleared we would only
need EH Auth one time versus assuming it's always empty. This would
essentially be
an SRK for the EH but includes sign attribute (ERK :-p).
But if we're shoving stuff into a read only config, these options
could be set in the config file
(ie use a persistent handle at location XXX, no auth, etc). But *not*
hardcoding EH auth into
the config file.
I would hate to see requirements requiring that hierarchy auth remains empty.
> Although if there's a use case that actually wants them set for some
> reason, then I think there might be a case for removing the policy from
> the EK template, but if not, it's easier just to follow what the TCG
> says with the addition of the signing permission.
>
> > > it's going to have to be somewhere in the root
> > > filesystem, like /etc. Ideally it would be in the immutable part
> > > of /etc so it is write once on install.
> > >
> >
> > I'm assuming this would be the template or name of the "Signing EK"?
>
> Just the name, I think, assuming everyone agrees on the template. If
> there's going to be a question about which template then we'd need
> both.
>
> James
>
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (13 preceding siblings ...)
2023-04-04 18:43 ` [PATCH v4 00/13] add integrity and security to TPM2 transactions William Roberts
@ 2023-04-05 18:39 ` William Roberts
2023-04-05 19:41 ` James Bottomley
2023-04-23 5:42 ` Jarkko Sakkinen
2023-12-04 18:56 ` Stefan Berger
16 siblings, 1 reply; 62+ messages in thread
From: William Roberts @ 2023-04-05 18:39 UTC (permalink / raw)
To: James Bottomley
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Mon, Apr 3, 2023 at 4:44 PM James Bottomley
<James.Bottomley@hansenpartnership.com> 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.
Rather than doing this, wouldn't the session be flushed from the TPM on
reset and thus subsequent commands using the session and session key
fail?
If that's true, couldn't we just pin the trust to an existing trusted
key that we have the
name of and move on? The kernel would know that something happened when
session protections started failing without the complexity and time of
generating
a key in the NULL hierarchy and certifying it.
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
>
> James
>
> ---
>
> Ard Biesheuvel (1):
> crypto: lib - implement library version of AES in CFB mode
>
> James Bottomley (12):
> tpm: move buffer handling from static inlines to real functions
> tpm: add kernel doc to buffer handling functions
> tpm: add buffer handling for TPM2B types
> tpm: add cursor based buffer functions for response parsing
> tpm: add buffer function to point to returned parameters
> tpm: export the context save and load commands
> tpm: Add full HMAC and encrypt/decrypt session handling code
> tpm: add hmac checks to tpm2_pcr_extend()
> tpm: add session encryption protection to tpm2_get_random()
> KEYS: trusted: Add session encryption protection to the seal/unseal
> path
> tpm: add the null key name as a sysfs export
> Documentation: add tpm-security.rst
>
> Documentation/security/tpm/tpm-security.rst | 216 ++++
> drivers/char/tpm/Kconfig | 13 +
> drivers/char/tpm/Makefile | 2 +
> drivers/char/tpm/tpm-buf.c | 307 +++++
> drivers/char/tpm/tpm-chip.c | 3 +
> drivers/char/tpm/tpm-sysfs.c | 18 +
> drivers/char/tpm/tpm.h | 14 +
> drivers/char/tpm/tpm2-cmd.c | 52 +-
> drivers/char/tpm/tpm2-sessions.c | 1158 +++++++++++++++++++
> drivers/char/tpm/tpm2-space.c | 8 +-
> include/crypto/aes.h | 5 +
> include/linux/tpm.h | 257 ++--
> lib/crypto/Kconfig | 5 +
> lib/crypto/Makefile | 3 +
> lib/crypto/aescfb.c | 257 ++++
> security/keys/trusted-keys/trusted_tpm2.c | 82 +-
> 16 files changed, 2275 insertions(+), 125 deletions(-)
> create mode 100644 Documentation/security/tpm/tpm-security.rst
> create mode 100644 drivers/char/tpm/tpm-buf.c
> create mode 100644 drivers/char/tpm/tpm2-sessions.c
> create mode 100644 lib/crypto/aescfb.c
>
> --
> 2.35.3
>
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-05 18:39 ` William Roberts
@ 2023-04-05 19:41 ` James Bottomley
2023-04-07 14:40 ` William Roberts
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-04-05 19:41 UTC (permalink / raw)
To: William Roberts
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Wed, 2023-04-05 at 13:39 -0500, William Roberts wrote:
> On Mon, Apr 3, 2023 at 4:44 PM James Bottomley
> <James.Bottomley@hansenpartnership.com> wrote:
[...]
> > 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.
>
> Rather than doing this, wouldn't the session be flushed from the TPM
> on reset and thus subsequent commands using the session and session
> key fail?
That would happen only if we kept a context saved session, which we
can't because the current session manager doesn't do de-gapping. To
get around this we start a new, short lived, session for most
operations.
There has been a thought that it would be faster if we did context save
a session to keep re-using it, so adding de-gapping is on the list
somewhere, it's just not near the top yet.
> If that's true, couldn't we just pin the trust to an existing trusted
> key that we have the name of and move on? The kernel would know that
> something happened when session protections started failing without
> the complexity and time of generating a key in the NULL hierarchy and
> certifying it.
If the goal is to check not only the kernel but also the boot
components (like OVMF/EDK2), then we need a handoff protocol. The
beauty of the NULL seed is the name is a nice short thing to handoff.
If we relied on sessions, we'd have to hand off a whole context saved
session and all its nonces, which is a bit of a security risk.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-05 19:41 ` James Bottomley
@ 2023-04-07 14:40 ` William Roberts
0 siblings, 0 replies; 62+ messages in thread
From: William Roberts @ 2023-04-07 14:40 UTC (permalink / raw)
To: James Bottomley
Cc: linux-integrity, Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Wed, Apr 5, 2023 at 1:41 PM James Bottomley
<James.Bottomley@hansenpartnership.com> wrote:
>
> On Wed, 2023-04-05 at 13:39 -0500, William Roberts wrote:
> > On Mon, Apr 3, 2023 at 4:44 PM James Bottomley
> > <James.Bottomley@hansenpartnership.com> wrote:
> [...]
> > > 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.
> >
> > Rather than doing this, wouldn't the session be flushed from the TPM
> > on reset and thus subsequent commands using the session and session
> > key fail?
>
> That would happen only if we kept a context saved session, which we
> can't because the current session manager doesn't do de-gapping. To
> get around this we start a new, short lived, session for most
> operations.
>
> There has been a thought that it would be faster if we did context save
> a session to keep re-using it, so adding de-gapping is on the list
> somewhere, it's just not near the top yet.
>
Rather than implement this half baked, why not just move this feature
to the top of the list,
userspace users are clamoring for this?
I had this on our TODO list at Intel, but I have been moved onto other
projects now and
don't have the resources to work on it or I would.
> > If that's true, couldn't we just pin the trust to an existing trusted
> > key that we have the name of and move on? The kernel would know that
> > something happened when session protections started failing without
> > the complexity and time of generating a key in the NULL hierarchy and
> > certifying it.
>
> If the goal is to check not only the kernel but also the boot
> components (like OVMF/EDK2), then we need a handoff protocol. The
> beauty of the NULL seed is the name is a nice short thing to handoff.
> If we relied on sessions, we'd have to hand off a whole context saved
> session and all its nonces, which is a bit of a security risk.
Yeah I wouldn't hand off the session information. Bit for pre-kernel
things isn't this all bootstrapped with the
name of the "Signing EK '' stored on a filesystem? I think you
suggested a RO portion of /etc. Since that's
the root it would need to be available for the initial boot strap
before you can just hand of the name of the
NULL hierarchy key. But if Session Ungapping was implemented, it could
just be a handoff of the "Signing EK"
name. Which would reduce the need for a createprimary and certify command.
>
> James
>
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (14 preceding siblings ...)
2023-04-05 18:39 ` William Roberts
@ 2023-04-23 5:42 ` Jarkko Sakkinen
2023-12-04 18:56 ` Stefan Berger
16 siblings, 0 replies; 62+ messages in thread
From: Jarkko Sakkinen @ 2023-04-23 5:42 UTC (permalink / raw)
To: James Bottomley, linux-integrity; +Cc: keyrings, Ard Biesheuvel
On Mon, 2023-04-03 at 17:39 -0400, 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
>
> James
>
> ---
>
> Ard Biesheuvel (1):
> crypto: lib - implement library version of AES in CFB mode
>
> James Bottomley (12):
> tpm: move buffer handling from static inlines to real functions
> tpm: add kernel doc to buffer handling functions
> tpm: add buffer handling for TPM2B types
> tpm: add cursor based buffer functions for response parsing
> tpm: add buffer function to point to returned parameters
> tpm: export the context save and load commands
> tpm: Add full HMAC and encrypt/decrypt session handling code
> tpm: add hmac checks to tpm2_pcr_extend()
> tpm: add session encryption protection to tpm2_get_random()
> KEYS: trusted: Add session encryption protection to the seal/unseal
> path
> tpm: add the null key name as a sysfs export
> Documentation: add tpm-security.rst
>
> Documentation/security/tpm/tpm-security.rst | 216 ++++
> drivers/char/tpm/Kconfig | 13 +
> drivers/char/tpm/Makefile | 2 +
> drivers/char/tpm/tpm-buf.c | 307 +++++
> drivers/char/tpm/tpm-chip.c | 3 +
> drivers/char/tpm/tpm-sysfs.c | 18 +
> drivers/char/tpm/tpm.h | 14 +
> drivers/char/tpm/tpm2-cmd.c | 52 +-
> drivers/char/tpm/tpm2-sessions.c | 1158 +++++++++++++++++++
> drivers/char/tpm/tpm2-space.c | 8 +-
> include/crypto/aes.h | 5 +
> include/linux/tpm.h | 257 ++--
> lib/crypto/Kconfig | 5 +
> lib/crypto/Makefile | 3 +
> lib/crypto/aescfb.c | 257 ++++
> security/keys/trusted-keys/trusted_tpm2.c | 82 +-
> 16 files changed, 2275 insertions(+), 125 deletions(-)
> create mode 100644 Documentation/security/tpm/tpm-security.rst
> create mode 100644 drivers/char/tpm/tpm-buf.c
> create mode 100644 drivers/char/tpm/tpm2-sessions.c
> create mode 100644 lib/crypto/aescfb.c
>
OK, so I have a kernel with the patches applied. How can I verify
that this working?
Are there any other user visible things than handle for the null
key? Even for that this lacks any useful instructions how to use
it while testing. For the null key I'm not even sure if the claim
is correct, given that kernel is always a middle-man, even when
user space uses /dev/tpm0. A bit more detail would help...
BR, Jarkko
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-04-03 21:39 [PATCH v4 00/13] add integrity and security to TPM2 transactions James Bottomley
` (15 preceding siblings ...)
2023-04-23 5:42 ` Jarkko Sakkinen
@ 2023-12-04 18:56 ` Stefan Berger
2023-12-04 19:24 ` James Bottomley
16 siblings, 1 reply; 62+ messages in thread
From: Stefan Berger @ 2023-12-04 18:56 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On 4/3/23 17:39, 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.
I think this is another capability of an interposer that should be
mentioned here, unless technically not possible but I would not know why:
3. Active Interposers that send their own commands to the TPM to for
example cause DoS attacks.
If we protect PCR extensions now and the interposer can send his own PCR
extensions and the TPM 2 accepts them (TPM doesn't have a mode to reject
unprotected commands in general), why protect the PCR extensions from
IMA then?
Stefan
>
> 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
>
> James
>
> ---
>
> Ard Biesheuvel (1):
> crypto: lib - implement library version of AES in CFB mode
>
> James Bottomley (12):
> tpm: move buffer handling from static inlines to real functions
> tpm: add kernel doc to buffer handling functions
> tpm: add buffer handling for TPM2B types
> tpm: add cursor based buffer functions for response parsing
> tpm: add buffer function to point to returned parameters
> tpm: export the context save and load commands
> tpm: Add full HMAC and encrypt/decrypt session handling code
> tpm: add hmac checks to tpm2_pcr_extend()
> tpm: add session encryption protection to tpm2_get_random()
> KEYS: trusted: Add session encryption protection to the seal/unseal
> path
> tpm: add the null key name as a sysfs export
> Documentation: add tpm-security.rst
>
> Documentation/security/tpm/tpm-security.rst | 216 ++++
> drivers/char/tpm/Kconfig | 13 +
> drivers/char/tpm/Makefile | 2 +
> drivers/char/tpm/tpm-buf.c | 307 +++++
> drivers/char/tpm/tpm-chip.c | 3 +
> drivers/char/tpm/tpm-sysfs.c | 18 +
> drivers/char/tpm/tpm.h | 14 +
> drivers/char/tpm/tpm2-cmd.c | 52 +-
> drivers/char/tpm/tpm2-sessions.c | 1158 +++++++++++++++++++
> drivers/char/tpm/tpm2-space.c | 8 +-
> include/crypto/aes.h | 5 +
> include/linux/tpm.h | 257 ++--
> lib/crypto/Kconfig | 5 +
> lib/crypto/Makefile | 3 +
> lib/crypto/aescfb.c | 257 ++++
> security/keys/trusted-keys/trusted_tpm2.c | 82 +-
> 16 files changed, 2275 insertions(+), 125 deletions(-)
> create mode 100644 Documentation/security/tpm/tpm-security.rst
> create mode 100644 drivers/char/tpm/tpm-buf.c
> create mode 100644 drivers/char/tpm/tpm2-sessions.c
> create mode 100644 lib/crypto/aescfb.c
>
^ permalink raw reply [flat|nested] 62+ messages in thread* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-12-04 18:56 ` Stefan Berger
@ 2023-12-04 19:24 ` James Bottomley
2023-12-04 21:02 ` Stefan Berger
0 siblings, 1 reply; 62+ messages in thread
From: James Bottomley @ 2023-12-04 19:24 UTC (permalink / raw)
To: Stefan Berger, linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 13:56 -0500, Stefan Berger wrote:
>
>
> On 4/3/23 17:39, 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.
>
> I think this is another capability of an interposer that should be
> mentioned here, unless technically not possible but I would not know
> why:
>
> 3. Active Interposers that send their own commands to the TPM to for
> example cause DoS attacks.
>
> If we protect PCR extensions now and the interposer can send his own
> PCR extensions and the TPM 2 accepts them (TPM doesn't have a mode to
> reject unprotected commands in general), why protect the PCR
> extensions from IMA then?
Well the PCRs are world writable in a standard system, so anyone with
access, i.e. anyone in the tpm group, can arbitrarily extend them and
destroy the replay. So I ignored this because while an interposer can
do this, you don't have to be an interposer to cause log replay
disruption like this.
The actual threat to PCR extends from an interposer is silent discards
where the attacker seeks to fake the log after the fact to match a
quote they've discarded a suspicious event from. Thus the HMAC check
is actually the return one, which allows the kernel to know the write
succeeded.
James
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-12-04 19:24 ` James Bottomley
@ 2023-12-04 21:02 ` Stefan Berger
2023-12-05 13:50 ` James Bottomley
0 siblings, 1 reply; 62+ messages in thread
From: Stefan Berger @ 2023-12-04 21:02 UTC (permalink / raw)
To: James Bottomley, linux-integrity
Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On 12/4/23 14:24, James Bottomley wrote:
> On Mon, 2023-12-04 at 13:56 -0500, Stefan Berger wrote:
>>
>>
>> On 4/3/23 17:39, 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.
>>
>> I think this is another capability of an interposer that should be
>> mentioned here, unless technically not possible but I would not know
>> why:
>>
>> 3. Active Interposers that send their own commands to the TPM to for
>> example cause DoS attacks.
>>
>> If we protect PCR extensions now and the interposer can send his own
>> PCR extensions and the TPM 2 accepts them (TPM doesn't have a mode to
>> reject unprotected commands in general), why protect the PCR
>> extensions from IMA then?
>
> Well the PCRs are world writable in a standard system, so anyone with
> access, i.e. anyone in the tpm group, can arbitrarily extend them and
> destroy the replay. So I ignored this because while an interposer can
> do this, you don't have to be an interposer to cause log replay
> disruption like this.
Presumably the folks in the tpm group are trusted while the interpose is
not.
>
> The actual threat to PCR extends from an interposer is silent discards
> where the attacker seeks to fake the log after the fact to match a
> quote they've discarded a suspicious event from. Thus the HMAC check
Well, it's not that simple to fake the log unless you are root and then
all bets are off when it comes to sending commands to the TPM.
> is actually the return one, which allows the kernel to know the write
> succeeded.
>
> James
>
^ permalink raw reply [flat|nested] 62+ messages in thread
* Re: [PATCH v4 00/13] add integrity and security to TPM2 transactions
2023-12-04 21:02 ` Stefan Berger
@ 2023-12-05 13:50 ` James Bottomley
0 siblings, 0 replies; 62+ messages in thread
From: James Bottomley @ 2023-12-05 13:50 UTC (permalink / raw)
To: Stefan Berger, linux-integrity; +Cc: Jarkko Sakkinen, keyrings, Ard Biesheuvel
On Mon, 2023-12-04 at 16:02 -0500, Stefan Berger wrote:
> On 12/4/23 14:24, James Bottomley wrote:
[...]
> > The actual threat to PCR extends from an interposer is silent
> > discards where the attacker seeks to fake the log after the fact to
> > match a quote they've discarded a suspicious event from. Thus the
> > HMAC check
>
> Well, it's not that simple to fake the log unless you are root and
> then all bets are off when it comes to sending commands to the TPM.
It's not just faking logs: if I can discard the true measurements and
insert my own, I can recover any object sealed to a PCR policy. Even
if I can only discard the last few bad measurements and insert good
ones, I can still likely succeed.
If an attacker gains root, the TPM still can't be faked out. As long
as the PCRs have accurate measurements, those measurements can be
quoted. The theory is that the event that allowed the root exploit got
recorded before the exploit happened (of course there's a huge problem
of whether the right thing is being recorded) because post boot
computer hacking cannot violate causality.
The interposer at boot is a more interesting problem, but that's
documented.
James
^ permalink raw reply [flat|nested] 62+ messages in thread