Skip to contentSkip to conversation

Asymmetric key operations on TPM2

PATCH New James Prestwood 1 participant 18 messages May 18, 2020

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

cover Asymmetric key operations on TPM2

This adds a TPM 2.0 key parser and asymmetric key type for access to the TPM for encryption, decryption, sign, and verify using RSA private keys. The majority of the work went into the tpm driver subsystem piggy backing off some old, not-yet-upstreamed, patches from James Bottomley. These can be found here, and they are attached in this patch set:

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

There is also a patch from James which may already be upstreamed which adds some OID registry values for TPM keys. I have also copied over the ASN.1 definition from the trusted key type in order to parse a TPM key from asymmetric keys.

These patches have been rebased on top of 5.6, and I would urge James to take a look at these and make sure I rebased them correctly. (The folder structure of the TPM/trusted subsystem had since changed in the kernel since these patches, so I did my best).

As far as the patches are concerned the majority of the functionality happens in drivers/char/tpm/tpm2-cmd.c: tpm2_rsa_decrypt(). This takes a parent handle, key blob, and data to be decrypted. Assuming the parent exists and the key blob is valid the data will be decrypted using the TPM. This API can also be used for signing by pre-padding the input data with pkcs1, effectively turning a decrypt call into an encryption using the private key.

The parser and asymmetric key type are relatively simple modules. The key parser uses the ASN.1 definition described earlier to parse out the public and private portions of the key. From here the TPM2 asymmetric key type extracts the pieces of the private and public keys which the TPM needs to perform these operations. These are whats referred to as the 'key blobs'.

This new asymmetric key type can be accessed using keyctl, and behaves exactly the same as any other pkey operations. Below is how I have been testing this functionality. It will require that you have the proper tools installed to access the TPM (tss2/openssl_tpm2_engine).

# Starting from scratch, enable and clear TPM in BIOS

export TPM_INTERFACE_TYPEŽv
export TPM_DEVICE=/dev/tpm0

# Create a primary key for wrapping the user private key

# and make it persistent.
tsscreateprimary -hi o -st -ecc
# This should return a handle, in my case 80000000
tssevictcontrol -hi o -ho 80000000 -hp 81000001
tssflushcontext -ha 80000000

# Create a private key if not already
openssl genrsa > privkey.pem

# Wrap private key using the TPM
create_tpm2_key -w privkey.pem -p 81000001 privkey.tpm # The above commands only need to be done once. A Null primary

# key could be used instead which would not require the above steps
# but that kind of key does not persist across boots meaning you
# would need to create a new wrapped TPM key every boot.
# privkey.pem could now be deleted as the key has been wrapped
# by the TPM.

# If built as modules, load parser and asymmetric key type modprobe tpm2_key_parser
modprobe asym_tpm2

# Now asymmetric keyctl operations can be performed using

# privkey.tpm. First it needs to be converted into DER for
# keyctl
openssl asn1parse -inform pem -in privkey.tpm -noout -out privkey.tpm.der

# Add key to the kernel
serial=cat privkey.tpm.der | keyctl padd asymmetric tpm @u

# Create some data do be encrypted/signed
echo "abcdefg" > plaintext.txt

# Encrypt plaintext.txt
keyctl pkey_encrypt $serial 0 plaintext.txt enc=pkcs1 > encrypted.dat

# Decrypt encrypted data
keyctl pkey_decrypt $serial 0 encrypted.dat enc=pkcs1 > decrypted.dat

# Sign
keyctl pkey_sign $serial 0 plaintext.txt enc=pkcs1 hash=sha256 > signed.dat

# Verify
keyctl pkey_verify $serial 0 plaintext.txt signed.dat enc=pkcs1 hash=sha256

James Bottomley (12):
tpm-buf: move from static inlines to real functions
tpm-buf: add handling for TPM2B types
tpm-buf: add cursor based functions for response parsing
tpm2-space: export the context save and load commands
tpm2-sessions: Add full HMAC and encrypt/decrypt session handling
tpm-buf: add tpm_buf_parameters()
tpm2: add hmac checks to tpm2_pcr_extend()
tpm2: add session encryption protection to tpm2_get_random() trusted keys: Add session encryption protection to the seal/unseal
path
tpm: add the null key name as a tpm2 sysfs variable
Documentation: add tpm-security.rst
oid_registry: Add TCG defined OIDS for TPM keys

James Prestwood (5):
tpm: tpm2-cmd: add driver API for RSA decryption
include: linux: tpm: expose tpm2_rsa_decrypt
include: crypto: add asym_tpm2_subtype definition
asymmetric_keys: add TPM2 ASN1 definition
asymmetric_keys: add tpm2 key parser/type

 Documentation/security/tpm/tpm-security.rst |  204 ++++
 crypto/asymmetric_keys/Kconfig              |   20 +
 crypto/asymmetric_keys/Makefile             |   12 +
 crypto/asymmetric_keys/asym_tpm2.c          |  653 ++++++++++
 crypto/asymmetric_keys/tpm2_parser.c        |  155 +++
 crypto/asymmetric_keys/tpm2key.asn1         |   23 +
 drivers/char/tpm/Kconfig                    |   11 +
 drivers/char/tpm/Makefile                   |    2 +
 drivers/char/tpm/tpm-buf.c                  |  202 ++++
 drivers/char/tpm/tpm-sysfs.c                |   29 +-
 drivers/char/tpm/tpm.h                      |   38 +
 drivers/char/tpm/tpm2-cmd.c                 |  523 +++++++-
 drivers/char/tpm/tpm2-sessions.c            | 1203 +++++++++++++++++++
 drivers/char/tpm/tpm2-sessions.h            |  114 ++
 drivers/char/tpm/tpm2-space.c               |    8 +-
 include/crypto/asym_tpm2_subtype.h          |   32 +
 include/linux/oid_registry.h                |    5 +
 include/linux/tpm.h                         |  160 ++-
 18 files changed, 3284 insertions(+), 110 deletions(-)
 create mode 100644 Documentation/security/tpm/tpm-security.rst
 create mode 100644 crypto/asymmetric_keys/asym_tpm2.c
 create mode 100644 crypto/asymmetric_keys/tpm2_parser.c
 create mode 100644 crypto/asymmetric_keys/tpm2key.asn1
 create mode 100644 drivers/char/tpm/tpm-buf.c
 create mode 100644 drivers/char/tpm/tpm2-sessions.c
 create mode 100644 drivers/char/tpm/tpm2-sessions.h
 create mode 100644 include/crypto/asym_tpm2_subtype.h
Signature · 1 line
2.21.1
#1 lore raw

PATCH 1/17 tpm-buf: move from static inlines to real functions

From: James Bottomley <[email protected]>

This separates out the old tpm_buf_... handling functions from static inlines in tpm.h and makes them their own tpm-buf.c file. This is a precursor so we can add new functions for other TPM type handling

---
 drivers/char/tpm/Makefile  |   1 +
 drivers/char/tpm/tpm-buf.c | 118 +++++++++++++++++++++++++++++++++++++
 drivers/char/tpm/tpm.h     |  10 ++++
 include/linux/tpm.h        | 101 ++++++-------------------------
 4 files changed, 146 insertions(+), 84 deletions(-)
 create mode 100644 drivers/char/tpm/tpm-buf.c
drivers/char/tpm/Makefile +1 -0
index 9567e5197f74..4d5765c41972 100644
@@ -15,6 +15,7 @@ tpm-y += tpm-sysfs.o
 tpm-y += eventlog/common.o
 tpm-y += eventlog/tpm1.o
 tpm-y += eventlog/tpm2.o
+tpm-y += tpm-buf.o
 
 tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
 tpm-$(CONFIG_EFI) += eventlog/efi.o
drivers/char/tpm/tpm-buf.c new file +118 -0

118 lines not on this page · raw message

drivers/char/tpm/tpm.h +10 -0
index 5620747da0cf..379629704522 100644
@@ -153,6 +153,16 @@ enum tpm_sub_capabilities {
  * compiler warnings about stack frame size. */
 #define TPM_MAX_RNG_DATA	128
 
+int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
+void tpm_buf_destroy(struct tpm_buf *buf);
+u32 tpm_buf_length(struct tpm_buf *buf);
+void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
+		    unsigned int new_len);
+void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
+void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
+void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
+
 extern struct class *tpm_class;
 extern struct class *tpmrm_class;
 extern dev_t tpm_devt;
include/linux/tpm.h +17 -84

122 lines not on this page · raw message

Signature · 1 line
2.21.1
#2 lore raw

PATCH 2/17 tpm-buf: add handling for TPM2B types

In reply to James Prestwood

From: James Bottomley <[email protected]>

Most complex TPM commands require appending TPM2B buffers to the command body. Since TPM2B types are essentially variable size arrays, it makes it impossible to represent these complex command arguments as structures and we simply have to build them up using append primitives like these.

---
 drivers/char/tpm/tpm-buf.c | 47 ++++++++++++++++++++++++++++++++++++++
 drivers/char/tpm/tpm.h     |  2 ++
 2 files changed, 49 insertions(+)
drivers/char/tpm/tpm-buf.c +47 -0
index 9fa8a9cb0fdf..8c1ed8a14e01 100644
@@ -8,6 +8,8 @@
 
 #include <linux/module.h>
 
+#include <asm/unaligned.h>
+
 static int __tpm_buf_init(struct tpm_buf *buf)
 {
 	buf->data_page = alloc_page(GFP_HIGHUSER);
@@ -46,6 +48,24 @@ int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init);
 
+int tpm_buf_init_2b(struct tpm_buf *buf)
+{
+	struct tpm_header *head;
+	int rc;
+
+	rc = __tpm_buf_init(buf);
+	if (rc)
+		return rc;
+
+	head = (struct tpm_header *) buf->data;
+
+	head->length = cpu_to_be32(sizeof(*head));
+
+	buf->flags = TPM_BUF_2B;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init_2b);
+
 void tpm_buf_destroy(struct tpm_buf *buf)
 {
 	kunmap(buf->data_page);
@@ -53,6 +73,13 @@ void tpm_buf_destroy(struct tpm_buf *buf)
 }
 EXPORT_SYMBOL_GPL(tpm_buf_destroy);
 
+static void *tpm_buf_data(struct tpm_buf *buf)
+{
+	if (buf->flags & TPM_BUF_2B)
+		return buf->data + TPM_HEADER_SIZE;
+	return buf->data;
+}
+
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
@@ -116,3 +143,23 @@ void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value)
 	tpm_buf_append(buf, (u8 *) &value2, 4);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
+
+static void tpm_buf_reset_int(struct tpm_buf *buf)
+{
+	struct tpm_header *head;
+
+	head = (struct tpm_header *)buf->data;
+	head->length = cpu_to_be32(sizeof(*head));
+}
+
+void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
+{
+	u16 len = tpm_buf_length(tpm2b);
+
+	tpm_buf_append_u16(buf, len);
+	tpm_buf_append(buf, tpm_buf_data(tpm2b), len);
+	/* clear the buf for reuse */
+	tpm_buf_reset_int(tpm2b);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
+
drivers/char/tpm/tpm.h +2 -0
index 379629704522..dfa03b63d8ee 100644
@@ -155,6 +155,7 @@ enum tpm_sub_capabilities {
 
 int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
+int tpm_buf_init_2b(struct tpm_buf *buf);
 void tpm_buf_destroy(struct tpm_buf *buf);
 u32 tpm_buf_length(struct tpm_buf *buf);
 void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
@@ -162,6 +163,7 @@ void tpm_buf_append(struct tpm_buf *buf, const unsigned char *new_data,
 void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
 void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
 void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
+void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
 
 extern struct class *tpm_class;
 extern struct class *tpmrm_class;
Signature · 1 line
2.21.1
#3 lore raw

PATCH 3/17 tpm-buf: add cursor based functions for response parsing

In reply to James Prestwood

From: James Bottomley <[email protected]>

It's very convenient when parsing responses to have a cursor you simply move over the response extracting the data. Add such cursor functions for the TPM unsigned integer types.

---
 drivers/char/tpm/tpm-buf.c | 26 ++++++++++++++++++++++++++
 drivers/char/tpm/tpm.h     |  4 ++++
 2 files changed, 30 insertions(+)
drivers/char/tpm/tpm-buf.c +26 -0
index 8c1ed8a14e01..553adb84b0ac 100644
@@ -163,3 +163,29 @@ void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b)
 }
 EXPORT_SYMBOL_GPL(tpm_buf_append_2b);
 
+/* functions for unmarshalling data and moving the cursor */
+u8 tpm_get_inc_u8(const u8 **ptr)
+{
+	return *((*ptr)++);
+}
+EXPORT_SYMBOL_GPL(tpm_get_inc_u8);
+
+u16 tpm_get_inc_u16(const u8 **ptr)
+{
+	u16 val;
+
+	val = get_unaligned_be16(*ptr);
+	*ptr += sizeof(val);
+	return val;
+}
+EXPORT_SYMBOL_GPL(tpm_get_inc_u16);
+
+u32 tpm_get_inc_u32(const u8 **ptr)
+{
+	u32 val;
+
+	val = get_unaligned_be32(*ptr);
+	*ptr += sizeof(val);
+	return val;
+}
+EXPORT_SYMBOL_GPL(tpm_get_inc_u32);
drivers/char/tpm/tpm.h +4 -0
index dfa03b63d8ee..c75340dc3bce 100644
@@ -165,6 +165,10 @@ void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
 void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
 void tpm_buf_append_2b(struct tpm_buf *buf, struct tpm_buf *tpm2b);
 
+u8 tpm_get_inc_u8(const u8 **ptr);
+u16 tpm_get_inc_u16(const u8 **ptr);
+u32 tpm_get_inc_u32(const u8 **ptr);
+
 extern struct class *tpm_class;
 extern struct class *tpmrm_class;
 extern dev_t tpm_devt;
Signature · 1 line
2.21.1
#4 lore raw

PATCH 4/17 tpm2-space: export the context save and load commands

In reply to James Prestwood

From: James Bottomley <[email protected]>

The TPM2 session handling code needs to save and restore a single volatile context for the elliptic curve version of the NULL seed, so export the APIs which do this for internal use.

---
 drivers/char/tpm/tpm.h        | 4 ++++
 drivers/char/tpm/tpm2-space.c | 8 ++++----
 2 files changed, 8 insertions(+), 4 deletions(-)
drivers/char/tpm/tpm.h +4 -0
index c75340dc3bce..ba76bec04ca4 100644
@@ -250,6 +250,10 @@ int tpm2_prepare_space(struct tpm_chip *chip, struct tpm_space *space, u8 *cmd,
 		       size_t cmdsiz);
 int tpm2_commit_space(struct tpm_chip *chip, struct tpm_space *space, void *buf,
 		      size_t *bufsiz);
+int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf,
+		      unsigned int buf_size, unsigned int *offset);
+int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
+		      unsigned int *offset, u32 *handle);
 
 int tpm_bios_log_setup(struct tpm_chip *chip);
 void tpm_bios_log_teardown(struct tpm_chip *chip);
drivers/char/tpm/tpm2-space.c +4 -4
index 982d341d8837..ca1cb56ccc51 100644
@@ -65,8 +65,8 @@ void tpm2_del_space(struct tpm_chip *chip, struct tpm_space *space)
 	kfree(space->session_buf);
 }
 
-static int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
-			     unsigned int *offset, u32 *handle)
+int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
+		      unsigned int *offset, u32 *handle)
 {
 	struct tpm_buf tbuf;
 	struct tpm2_context *ctx;
@@ -116,8 +116,8 @@ static int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
 	return 0;
 }
 
-static int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf,
-			     unsigned int buf_size, unsigned int *offset)
+int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf,
+		      unsigned int buf_size, unsigned int *offset)
 {
 	struct tpm_buf tbuf;
 	unsigned int body_size;
Signature · 1 line
2.21.1
#5 lore raw

PATCH 5/17 tpm2-sessions: Add full HMAC and encrypt/decrypt session handling

In reply to James Prestwood

From: James Bottomley <[email protected]>

This code adds true session based HMAC authentication plus parameter decryption and response encryption using AES.

The basic design of this code is to segregate all the nasty crypto, hash and hmac code into tpm2-sessions.c and export a usable API.

The API first of all starts off by gaining a session with

tpm2_start_auth_session()

Which initiates a session with the TPM and allocates an opaque tpm2_auth structure to handle the session parameters. Then the use is simply:

* tpm_buf_append_name() in place of the tpm_buf_append_u32 for the handles

* tpm_buf_append_hmac_session() where tpm2_append_auth() would go

* tpm_buf_fill_hmac_session() called after the entire command buffer is finished but before tpm_transmit_cmd() is called which computes the correct HMAC and places it in the command at the correct location.

Finally, after tpm_transmit_cmd() is called, tpm_buf_check_hmac_response() is called to check that the returned HMAC matched and collect the new state for the next use of the session, if any.

The features of the session is controlled by the session attributes set in tpm_buf_append_hmac_session(). If TPM2_SA_CONTINUE_SESSION is not specified, the session will be flushed and the tpm2_auth structure freed in tpm_buf_check_hmac_response(); otherwise the session may be used again. Parameter encryption is specified by or'ing the flag TPM2_SA_DECRYPT and response encryption by or'ing the flag TPM2_SA_ENCRYPT. the various encryptions will be taken care of by tpm_buf_fill_hmac_session() and tpm_buf_check_hmac_response() respectively.

To get all of this to work securely, the Kernel now needs a primary key to encrypt the session salt to, so we derive an EC key from the NULL seed and save its context in the tpm_chip structure. The context is loaded on demand into an available volatile handle when tpm_start_auth_session() is called, but is flushed before that function exits to conserve handles.

---
 drivers/char/tpm/Kconfig         |   11 +
 drivers/char/tpm/Makefile        |    1 +
 drivers/char/tpm/tpm-buf.c       |    1 +
 drivers/char/tpm/tpm.h           |   13 +
 drivers/char/tpm/tpm2-cmd.c      |  300 ++++++++
 drivers/char/tpm/tpm2-sessions.c | 1203 ++++++++++++++++++++++++++++++
 drivers/char/tpm/tpm2-sessions.h |  114 +++
 include/linux/tpm.h              |   49 ++
 8 files changed, 1692 insertions(+)
 create mode 100644 drivers/char/tpm/tpm2-sessions.c
 create mode 100644 drivers/char/tpm/tpm2-sessions.h
drivers/char/tpm/Kconfig +11 -0
index aacdeed93320..305775975a8b 100644
@@ -9,6 +9,9 @@ menuconfig TCG_TPM
 	imply SECURITYFS
 	select CRYPTO
 	select CRYPTO_HASH_INFO
+	select CRYPTO_ECDH
+	select CRYPTO_AES
+	select CRYPTO_CFB
 	---help---
 	  If you have a TPM security chip in your system, which
 	  implements the Trusted Computing Group's specification,
@@ -27,6 +30,14 @@ menuconfig TCG_TPM
 
 if TCG_TPM
 
+config TPM_BUS_SECURITY
+       bool "Use secure transactions on the TPM bus"
+       default y
+       ---help---
+         Setting this causes us to deploy a tamper resistent scheme
+	 for communicating with the TPM to prevent or detect bus snooping
+	 attacks like TPM Genie.  Saying Y here adds some encryption overhead
+	 to all kernel to TPM transactions.
 config HW_RANDOM_TPM
 	bool "TPM HW Random Number Generator support"
 	depends on TCG_TPM && HW_RANDOM && !(TCG_TPM=y && HW_RANDOM=m)
drivers/char/tpm/Makefile +1 -0
index 4d5765c41972..618473a9c368 100644
@@ -17,6 +17,7 @@ tpm-y += eventlog/tpm1.o
 tpm-y += eventlog/tpm2.o
 tpm-y += tpm-buf.o
 
+tpm-$(CONFIG_TPM_BUS_SECURITY) += tpm2-sessions.o
 tpm-$(CONFIG_ACPI) += tpm_ppi.o eventlog/acpi.o
 tpm-$(CONFIG_EFI) += eventlog/efi.o
 tpm-$(CONFIG_OF) += eventlog/of.o
drivers/char/tpm/tpm-buf.c +1 -0
index 553adb84b0ac..f56350123a08 100644
@@ -31,6 +31,7 @@ void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+	buf->handles = 0;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
drivers/char/tpm/tpm.h +13 -0
index ba76bec04ca4..a1959675a889 100644
@@ -169,6 +169,9 @@ u8 tpm_get_inc_u8(const u8 **ptr);
 u16 tpm_get_inc_u16(const u8 **ptr);
 u32 tpm_get_inc_u32(const u8 **ptr);
 
+/* opaque structure, holds auth session parameters like the session key */
+struct tpm2_auth;
+
 extern struct class *tpm_class;
 extern struct class *tpmrm_class;
 extern dev_t tpm_devt;
@@ -259,4 +262,14 @@ int tpm_bios_log_setup(struct tpm_chip *chip);
 void tpm_bios_log_teardown(struct tpm_chip *chip);
 int tpm_dev_common_init(void);
 void tpm_dev_common_exit(void);
+
+#ifdef CONFIG_TPM_BUS_SECURITY
+int tpm2_sessions_init(struct tpm_chip *chip);
+#else
+static inline int tpm2_sessions_init(struct tpm_chip *chip)
+{
+	return 0;
+}
+#endif
+
 #endif
drivers/char/tpm/tpm2-cmd.c +300 -0

319 lines not on this page · raw message

drivers/char/tpm/tpm2-sessions.c new file +1203 -0

1,203 lines not on this page · raw message

drivers/char/tpm/tpm2-sessions.h new file +114 -0

114 lines not on this page · raw message

include/linux/tpm.h +49 -0

108 lines not on this page · raw message

Signature · 1 line
2.21.1
#6 lore raw

PATCH 6/17 tpm-buf: add tpm_buf_parameters()

In reply to James Prestwood

From: James Bottomley <[email protected]>

Introducing encryption sessions changes where the return parameters are located in the buffer because if a return session is present they're 4 bytes beyond the header with those 4 bytes showing the parameter length. If there is no return session, then they're in the usual place immediately after the header. The tpm_buf_parameters() encapsulates this calculation and should be used everywhere &buf.data[TPM_HEADER_SIZE] is used now

---
 drivers/char/tpm/tpm-buf.c | 10 ++++++++++
 drivers/char/tpm/tpm.h     |  2 ++
 2 files changed, 12 insertions(+)
drivers/char/tpm/tpm-buf.c +10 -0
index f56350123a08..a5d793d8180d 100644
@@ -190,3 +190,13 @@ u32 tpm_get_inc_u32(const u8 **ptr)
 	return val;
 }
 EXPORT_SYMBOL_GPL(tpm_get_inc_u32);
+
+u8 *tpm_buf_parameters(struct tpm_buf *buf)
+{
+	int offset = TPM_HEADER_SIZE;
+
+	if (tpm_buf_tag(buf) = TPM2_ST_SESSIONS)
+		offset += 4;
+
+	return &buf->data[offset];
+}
drivers/char/tpm/tpm.h +2 -0
index a1959675a889..ade4af4d52ca 100644
@@ -169,6 +169,8 @@ u8 tpm_get_inc_u8(const u8 **ptr);
 u16 tpm_get_inc_u16(const u8 **ptr);
 u32 tpm_get_inc_u32(const u8 **ptr);
 
+u8 *tpm_buf_parameters(struct tpm_buf *buf);
+
 /* opaque structure, holds auth session parameters like the session key */
 struct tpm2_auth;
 
Signature · 1 line
2.21.1
#7 lore raw

PATCH 7/17 tpm2: add hmac checks to tpm2_pcr_extend()

In reply to James Prestwood

From: James Bottomley <[email protected]>

We use tpm2_pcr_extend() in trusted keys to extend a PCR to prevent a key from being re-loaded until the next reboot. To use this functionality securely, that extend must be protected by a session hmac.

---
 drivers/char/tpm/tpm2-cmd.c | 28 +++++++++++-----------------
 1 file changed, 11 insertions(+), 17 deletions(-)
drivers/char/tpm/tpm2-cmd.c +11 -17
index 8d076c6752eb..b29824ae237c 100644
@@ -218,13 +218,6 @@ int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
 	return rc;
 }
 
-struct tpm2_null_auth_area {
-	__be32  handle;
-	__be16  nonce_size;
-	u8  attributes;
-	__be16  auth_size;
-} __packed;
-
 /**
  * tpm2_pcr_extend() - extend a PCR value
  *
@@ -238,24 +231,23 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 		    struct tpm_digest *digests)
 {
 	struct tpm_buf buf;
-	struct tpm2_null_auth_area auth_area;
+	struct tpm2_auth *auth;
 	int rc;
 	int i;
 
-	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
+	rc = tpm2_start_auth_session(chip, &auth);
 	if (rc)
 		return rc;
 
-	tpm_buf_append_u32(&buf, pcr_idx);
+	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
+	if (rc) {
+		tpm2_end_auth_session(auth);
+		return rc;
+	}
 
-	auth_area.handle = cpu_to_be32(TPM2_RS_PW);
-	auth_area.nonce_size = 0;
-	auth_area.attributes = 0;
-	auth_area.auth_size = 0;
+	tpm_buf_append_name(&buf, auth, pcr_idx, NULL);
+	tpm_buf_append_hmac_session(&buf, auth, 0, NULL, 0);
 
-	tpm_buf_append_u32(&buf, sizeof(struct tpm2_null_auth_area));
-	tpm_buf_append(&buf, (const unsigned char *)&auth_area,
-		       sizeof(auth_area));
 	tpm_buf_append_u32(&buf, chip->nr_allocated_banks);
 
 	for (i = 0; i < chip->nr_allocated_banks; i++) {
@@ -264,7 +256,9 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 			       chip->allocated_banks[i].digest_size);
 	}
 
+	tpm_buf_fill_hmac_session(&buf, auth);
 	rc = tpm_transmit_cmd(chip, &buf, 0, "attempting extend a PCR value");
+	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
 
 	tpm_buf_destroy(&buf);
 
Signature · 1 line
2.21.1
#8 lore raw

PATCH 8/17 tpm2: add session encryption protection to tpm2_get_random()

In reply to James Prestwood

From: James Bottomley <[email protected]>

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

---
 drivers/char/tpm/tpm2-cmd.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
drivers/char/tpm/tpm2-cmd.c +17 -4
index b29824ae237c..92e381bfd7c8 100644
@@ -291,29 +291,40 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
 	int total = 0;
 	int retries = 5;
 	u8 *dest_ptr = dest;
+	struct tpm2_auth *auth;
 
 	if (!num_bytes || max > TPM_MAX_RNG_DATA)
 		return -EINVAL;
 
-	err = tpm_buf_init(&buf, 0, 0);
+	err = tpm2_start_auth_session(chip, &auth);
 	if (err)
 		return err;
 
+	err = tpm_buf_init(&buf, 0, 0);
+	if (err) {
+		tpm2_end_auth_session(auth);
+		return err;
+	}
+
 	do {
-		tpm_buf_reset(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_RANDOM);
+		tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_GET_RANDOM);
+		tpm_buf_append_hmac_session_opt(&buf, auth, TPM2_SA_ENCRYPT
+						| TPM2_SA_CONTINUE_SESSION,
+						NULL, 0);
 		tpm_buf_append_u16(&buf, num_bytes);
+		tpm_buf_fill_hmac_session(&buf, auth);
 		err = tpm_transmit_cmd(chip, &buf,
 				       offsetof(struct tpm2_get_random_out,
 						buffer),
 				       "attempting get random");
+		err = tpm_buf_check_hmac_response(&buf, auth, err);
 		if (err) {
 			if (err > 0)
 				err = -EIO;
 			goto out;
 		}
 
-		out = (struct tpm2_get_random_out *)
-			&buf.data[TPM_HEADER_SIZE];
+		out = (struct tpm2_get_random_out *)tpm_buf_parameters(&buf);
 		recd = min_t(u32, be16_to_cpu(out->size), num_bytes);
 		if (tpm_buf_length(&buf) <
 		    TPM_HEADER_SIZE +
@@ -330,6 +341,8 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
 	} while (retries-- && total < max);
 
 	tpm_buf_destroy(&buf);
+	tpm2_end_auth_session(auth);
+
 	return total ? total : -EIO;
 out:
 	tpm_buf_destroy(&buf);
Signature · 1 line
2.21.1
#9 lore raw

PATCH 9/17 trusted keys: Add session encryption protection to the seal/unseal path

In reply to James Prestwood

From: James Bottomley <[email protected]>

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.

---
 drivers/char/tpm/tpm2-cmd.c | 124 ++++++++++++++++++++++++------------
 1 file changed, 85 insertions(+), 39 deletions(-)
drivers/char/tpm/tpm2-cmd.c +85 -39
index 92e381bfd7c8..f11906f95252 100644
@@ -418,7 +418,9 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 {
 	unsigned int blob_len;
 	struct tpm_buf buf;
+	struct tpm_buf t2b;
 	u32 hash;
+	struct tpm2_auth *auth;
 	int i;
 	int rc;
 
@@ -432,45 +434,56 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	if (i = ARRAY_SIZE(tpm2_hash_map))
 		return -EINVAL;
 
-	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
+	rc = tpm2_start_auth_session(chip, &auth);
 	if (rc)
 		return rc;
 
-	tpm_buf_append_u32(&buf, options->keyhandle);
-	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
-			     NULL /* nonce */, 0,
-			     0 /* session_attributes */,
-			     options->keyauth /* hmac */,
-			     TPM_DIGEST_SIZE);
+	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
+	if (rc) {
+		tpm2_end_auth_session(auth);
+		return rc;
+	}
+
+	rc = tpm_buf_init_2b(&t2b);
+	if (rc) {
+		tpm_buf_destroy(&buf);
+		tpm2_end_auth_session(auth);
+		return rc;
+	}
 
+	tpm_buf_append_name(&buf, auth, options->keyhandle, NULL);
+	tpm_buf_append_hmac_session(&buf, auth, TPM2_SA_DECRYPT,
+				    options->keyauth, TPM_DIGEST_SIZE);
 	/* sensitive */
-	tpm_buf_append_u16(&buf, 4 + TPM_DIGEST_SIZE + payload->key_len + 1);
+	tpm_buf_append_u16(&t2b, TPM_DIGEST_SIZE);
+	tpm_buf_append(&t2b, options->blobauth, TPM_DIGEST_SIZE);
+	tpm_buf_append_u16(&t2b, payload->key_len + 1);
+	tpm_buf_append(&t2b, payload->key, payload->key_len);
+	tpm_buf_append_u8(&t2b, payload->migratable);
 
-	tpm_buf_append_u16(&buf, TPM_DIGEST_SIZE);
-	tpm_buf_append(&buf, options->blobauth, TPM_DIGEST_SIZE);
-	tpm_buf_append_u16(&buf, payload->key_len + 1);
-	tpm_buf_append(&buf, payload->key, payload->key_len);
-	tpm_buf_append_u8(&buf, payload->migratable);
+	tpm_buf_append_2b(&buf, &t2b);
 
 	/* public */
-	tpm_buf_append_u16(&buf, 14 + options->policydigest_len);
-	tpm_buf_append_u16(&buf, TPM_ALG_KEYEDHASH);
-	tpm_buf_append_u16(&buf, hash);
+	tpm_buf_append_u16(&t2b, TPM_ALG_KEYEDHASH);
+	tpm_buf_append_u16(&t2b, hash);
 
 	/* policy */
 	if (options->policydigest_len) {
-		tpm_buf_append_u32(&buf, 0);
-		tpm_buf_append_u16(&buf, options->policydigest_len);
-		tpm_buf_append(&buf, options->policydigest,
+		tpm_buf_append_u32(&t2b, 0);
+		tpm_buf_append_u16(&t2b, options->policydigest_len);
+		tpm_buf_append(&t2b, options->policydigest,
 			       options->policydigest_len);
 	} else {
-		tpm_buf_append_u32(&buf, TPM2_OA_USER_WITH_AUTH);
-		tpm_buf_append_u16(&buf, 0);
+		tpm_buf_append_u32(&t2b, TPM2_OA_USER_WITH_AUTH);
+		tpm_buf_append_u16(&t2b, 0);
 	}
 
 	/* public parameters */
-	tpm_buf_append_u16(&buf, TPM_ALG_NULL);
-	tpm_buf_append_u16(&buf, 0);
+	tpm_buf_append_u16(&t2b, TPM_ALG_NULL);
+	/* unique (zero) */
+	tpm_buf_append_u16(&t2b, 0);
+
+	tpm_buf_append_2b(&buf, &t2b);
 
 	/* outside info */
 	tpm_buf_append_u16(&buf, 0);
@@ -483,7 +496,9 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 		goto out;
 	}
 
+	tpm_buf_fill_hmac_session(&buf, auth);
 	rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data");
+	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
 	if (rc)
 		goto out;
 
@@ -501,6 +516,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
 	payload->blob_len = blob_len;
 
 out:
+	tpm_buf_destroy(&t2b);
 	tpm_buf_destroy(&buf);
 
 	if (rc > 0) {
@@ -532,6 +548,7 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
 			 u32 *blob_handle)
 {
 	struct tpm_buf buf;
+	struct tpm2_auth *auth;
 	unsigned int private_len;
 	unsigned int public_len;
 	unsigned int blob_len;
@@ -546,17 +563,18 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
 	if (blob_len > payload->blob_len)
 		return -E2BIG;
 
-	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
+	rc = tpm2_start_auth_session(chip, &auth);
 	if (rc)
 		return rc;
 
-	tpm_buf_append_u32(&buf, options->keyhandle);
-	tpm2_buf_append_auth(&buf, TPM2_RS_PW,
-			     NULL /* nonce */, 0,
-			     0 /* session_attributes */,
-			     options->keyauth /* hmac */,
-			     TPM_DIGEST_SIZE);
+	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
+	if (rc) {
+		tpm2_end_auth_session(auth);
+		return rc;
+	}
 
+	tpm_buf_append_name(&buf, auth, options->keyhandle, NULL);
+	tpm_buf_append_hmac_session(&buf, auth, 0, options->keyauth, TPM_DIGEST_SIZE);
 	tpm_buf_append(&buf, payload->blob, blob_len);
 
 	if (buf.flags & TPM_BUF_OVERFLOW) {
@@ -564,7 +582,9 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
 		goto out;
 	}
 
+	tpm_buf_fill_hmac_session(&buf, auth);
 	rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob");
+	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
 	if (!rc)
 		*blob_handle = be32_to_cpup(
 			(__be32 *) &buf.data[TPM_HEADER_SIZE]);
@@ -596,24 +616,50 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
 			   u32 blob_handle)
 {
 	struct tpm_buf buf;
+	struct tpm2_auth *auth;
 	u16 data_len;
 	u8 *data;
 	int rc;
 
-	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
+	rc = tpm2_start_auth_session(chip, &auth);
 	if (rc)
 		return rc;
 
-	tpm_buf_append_u32(&buf, blob_handle);
-	tpm2_buf_append_auth(&buf,
-			     options->policyhandle ?
-			     options->policyhandle : TPM2_RS_PW,
-			     NULL /* nonce */, 0,
-			     TPM2_SA_CONTINUE_SESSION,
-			     options->blobauth /* hmac */,
-			     TPM_DIGEST_SIZE);
+	rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
+	if (rc) {
+		tpm2_end_auth_session(auth);
+		return rc;
+	}
+
+	tpm_buf_append_name(&buf, auth, blob_handle, NULL);
+
+	if (!options->policyhandle) {
+		tpm_buf_append_hmac_session(&buf, auth, TPM2_SA_ENCRYPT,
+					    options->blobauth, TPM_DIGEST_SIZE);
+	} else {
+		/*
+		 * FIXME: the policy can't be used for HMAC protection
+		 * of the authorization because it must be generated
+		 * with the initial nonces which isn't passed in, so
+		 * append a second encryption session to at least HMAC
+		 * protect the command and encrypt the sealed blob on
+		 * return.
+		 *
+		 * Note: this also means the caller either has to use
+		 * an empty password or compute the password HMAC
+		 * based on the policy nonces and place it in blobauth
+		 */
+		tpm2_buf_append_auth(&buf, options->policyhandle,
+				     NULL /* nonce */, 0, 0,
+				     options->blobauth /* hmac */,
+				     TPM_DIGEST_SIZE);
+		tpm_buf_append_hmac_session_opt(&buf, auth, TPM2_SA_ENCRYPT,
+						NULL, 0);
+	}
 
+	tpm_buf_fill_hmac_session(&buf, auth);
 	rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing");
+	rc = tpm_buf_check_hmac_response(&buf, auth, rc);
 	if (rc > 0)
 		rc = -EPERM;
 
Signature · 1 line
2.21.1
#10 lore raw

PATCH 10/17 tpm: add the null key name as a tpm2 sysfs variable

In reply to James Prestwood

From: James Bottomley <[email protected]>

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

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

---
 drivers/char/tpm/tpm-sysfs.c | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm-sysfs.c +28 -1
index d52bf4df0bca..c2733252320a 100644
@@ -310,6 +310,19 @@ static ssize_t timeouts_show(struct device *dev, struct device_attribute *attr,
 }
 static DEVICE_ATTR_RO(timeouts);
 
+static ssize_t null_name_show(struct device *dev, struct device_attribute *attr,
+			      char *buf)
+{
+	struct tpm_chip *chip = to_tpm_chip(dev);
+	int size = TPM2_NAME_SIZE;
+
+	bin2hex(buf, chip->tpmkeyname, size);
+	size *= 2;
+	buf[size++] = '\n';
+	return size;
+}
+static DEVICE_ATTR_RO(null_name);
+
 static ssize_t tpm_version_major_show(struct device *dev,
 				  struct device_attribute *attr, char *buf)
 {
@@ -336,7 +349,7 @@ static struct attribute *tpm1_dev_attrs[] = {
 };
 
 static struct attribute *tpm2_dev_attrs[] = {
-	&dev_attr_tpm_version_major.attr,
+	&dev_attr_null_name.attr,
 	NULL
 };
 
@@ -346,10 +359,24 @@ static const struct attribute_group tpm1_dev_group = {
 
 static const struct attribute_group tpm2_dev_group = {
 	.attrs = tpm2_dev_attrs,
+
 };
 
 void tpm_sysfs_add_device(struct tpm_chip *chip)
 {
+	/* XXX: If you wish to remove this restriction, you must first update
+	 * tpm_sysfs to explicitly lock chip->ops.
+	 */
+	if (chip->flags & TPM_CHIP_FLAG_TPM2) {
+		WARN_ON(chip->groups_cnt != 0);
+		chip->groups[chip->groups_cnt++] = &tpm2_dev_group;
+		return;
+	}
+
+	/* The sysfs routines rely on an implicit tpm_try_get_ops, device_del
+	 * is called before ops is null'd and the sysfs core synchronizes this
+	 * removal so that no callbacks are running or can run again
+	 */
 	WARN_ON(chip->groups_cnt != 0);
 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
 		chip->groups[chip->groups_cnt++] = &tpm2_dev_group;
Signature · 1 line
2.21.1
#11 lore raw

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

In reply to James Prestwood

From: James Bottomley <[email protected]>

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

---
 Documentation/security/tpm/tpm-security.rst | 204 ++++++++++++++++++++
 1 file changed, 204 insertions(+)
 create mode 100644 Documentation/security/tpm/tpm-security.rst
Documentation/security/tpm/tpm-security.rst new file +203 -0
new file mode 100644
index 000000000000..3411030505a1
@@ -0,0 +1,204 @@
+TPM Security
+======
+
+The object of this document is to describe how we make the kernel's
+use of the TPM reasonably robust in the face of external snooping and
+packet alteration attacks.  The current security document is for TPM
+2.0.
+
+Introduction
+------------
+
+The TPM is usually a discrete chip attached to a PC via some type of
+low bandwidth bus.  There are exceptions to this such as the Intel
+PTT, which is a software TPM running inside a software environment
+close to the CPU, which are subject to different attacks, but right at
+the moment, most hardened security environments require a discrete
+hardware TPM, which is the use case discussed here.
+
+Snooping and Alteration Attacks against the bus
+-----------------------------------------------
+
+The current state of the art for snooping the TPM Genie hardware
+interposer https://www.nccgroup.trust/us/our-research/tpm-genie/ which
+is a simple external device that can be installed in a couple of
+seconds on any system or laptop.  However, the next phase of research
+seems to be hacking existing devices on the bus to act as interposers,
+so the fact that the attacker requires physical access for a few
+seconds might evaporate.  However, the goal of this document is to
+protect TPM secrets and integrity as far as we are able in this
+environment and to try to insure that if we can't prevent the attack
+then at least we can detect it.
+
+Unfortunately, most of the TPM functionality, including the hardware
+reset capability can be controlled by an attacker who has access to
+the bus, so we'll discuss some of the disruption possibilities below.
+
+Measurement (PCR) Integrity
+---------------------------
+
+Since the attacker can send their own commands to the TPM, they can
+send arbitrary PCR extends and thus disrupt the measurement system,
+which would be an annoying denial of service attack.  However, there
+are two, more serious, classes of attack aimed at entities sealed to
+trust measurements.
+
+1. The attacker could intercept all PCR extends coming from the system
+   and completely substitute their own values, producing a replay of
+   an untampered state that would cause PCR measurements to attest to
+   a trusted state and release secrets
+
+2. At some point in time the attacker could reset the TPM, clearing
+   the PCRs and then send down their own measurements which would
+   effectively overwrite the boot time measurements the TPM has
+   already done.
+
+The first can be thwarted by always doing HMAC protection of the PCR
+extend and read command meaning measurement values cannot be
+substituted without producing a detectable HMAC failure in the
+response.  However, the second can only really be detected by relying
+on some sort of mechanism for protection which would change over TPM
+reset.
+
+Secrets Guarding
+----------------
+
+Certain information passing in and out of the TPM, such as key sealing
+and private key import and random number generation, is vulnerable to
+interception which HMAC protection alone cannot protect, so for these
+types of command we must also employ request and response encryption
+to prevent the loss of secret information.
+
+Establishing Initial Trust with the TPM
+---------------------------------------
+
+In order to provide security from the beginning, an initial shared or
+asymmetric secret must be established which must also be unknown to
+the attacker.  The most obvious avenues for this are the endorsement
+and storage seeds, which can be used to derive asymmetric keys.
+However, using these keys is difficult because the only way to pass
+them into the kernel would be on the command line, which requires
+extensive support in the boot system, and there's no guarantee that
+either hierarchy would not have some type of authorization.
+
+The mechanism chosen for the Linux Kernel is to derive the primary
+elliptic curve key from the null seed using the standard storage seed
+parameters.  The null seed has two advantages: firstly the hierarchy
+physically cannot have an authorization, so we are always able to use
+it and secondly, the null seed changes across TPM resets, meaning if
+we establish trust on the null seed at start of day, all sessions
+salted with the derived key will fail if the TPM is reset and the seed
+changes.
+
+Obviously using the null seed without any other prior shared secrets,
+we have to create and read the initial public key which could, of
+course, be intercepted and substituted by the bus interposer.
+However, the TPM has a key certification mechanism (using the EK
+endorsement certificate, creating an attestation identity key and
+certifying the null seed primary with that key) which is too complex
+to run within the kernel, so we keep a copy of the null primary key
+name, which is what is certified so user-space can run the full
+certification when it boots.  The definitive guarantee here is that if
+the null primary key certifies correctly, you know all your TPM
+transactions since start of day were secure and if it doesn't, you
+know there's an interposer on your system (and that any secret used
+during boot may have been leaked).
+
+Stacking Trust
+--------------
+
+In the current null primary scenario, the TPM must be completely
+cleared before handing it on to the next consumer.  However the kernel
+hands to user-space the name of the derived null seed key which can
+then be verified by certification in user-space.  Therefore, this chain
+of name handoff can be used between the various boot components as
+well (via an unspecified mechanism).  For instance, grub could use the
+null seed scheme for security and hand the name off to the kernel in
+the boot area.  The kernel could make its own derivation of the key
+and the name and know definitively that if they differ from the handed
+off version that tampering has occurred.  Thus it becomes possible to
+chain arbitrary boot components together (UEFI to grub to kernel) via
+the name handoff provided each successive component knows how to
+collect the name and verifies it against its derived key.
+
+Session Properties
+------------------
+
+All TPM commands the kernel uses allow sessions.  HMAC sessions may be
+used to check the integrity of requests and responses and decrypt and
+encrypt flags may be used to shield parameters and responses.  The
+HMAC and encryption keys are usually derived from the shared
+authorization secret, but for a lot of kernel operations that is well
+known (and usually empty).  Thus, every HMAC session used by the
+kernel must be created using the null primary key as the salt key
+which thus provides a cryptographic input into the session key
+derivation.  Thus, the kernel creates the null primary key once (as a
+volatile TPM handle) and keeps it around in a saved context stored in
+tpm_chip for every in-kernel use of the TPM.  Currently, because of a
+lack of de-gapping in the in-kernel resource manager, the session must
+be created and destroyed for each operation, but, in future, a single
+session may also be reused for the in-kernel HMAC, encryption and
+decryption sessions.
+
+Protection Types
+----------------
+
+For every in-kernel operation we use null primary salted HMAC to
+protect the integrity.  Additionally, we use parameter encryption to
+protect key sealing and parameter decryption to protect key unsealing
+and random number generation.
+
+Null Primary Key Certification in Userspace
+=====================+
+Every TPM comes shipped with a couple of X.509 certificates for the
+primary endorsement key.  This document assumes that the Elliptic
+Curve version of the certificate exists at 01C00002, but will work
+equally well with the RSA certificate (at 01C00001).
+
+The first step in the certification is primary creation using the
+template from the `TCG EK Credential Profile`_ which allows comparison
+of the generated primary key against the one in the certificate (the
+public key must match).  Note that generation of the EK primary
+requires the EK hierarchy password, but a pre-generated version of the
+EC primary should exist at 81010002 and a TPM2_ReadPublic() may be
+performed on this without needing the key authority.  Next, the
+certificate itself must be verified to chain back to the manufacturer
+root (which should be published on the manufacturer website).  Once
+this is done, the generated EK primary key may now be used to run an
+attestation on the null seed.  The specific problem here is that the
+EK primary is not a signing key so cannot on its own be used to sign
+the key certification, hence the complex process below.
+
+Note: this process is a simplified abbreviation of the usual privacy
+CA based attestation process.  The assumption here is that the
+attestation is done by the TPM owner who thus has access to only the
+owner hierarchy.  The owner creates an external public/private key
+pair (assume elliptic curve in this case) and wraps the private key
+for import using an inner wrapping process and parented to the EC
+derived storage primary.  The TPM2_Import() is done using a parameter
+decryption HMAC session salted to the EK primary (which also does not
+require the EK key authority) meaning that the inner wrapping key is
+the encrypted parameter and thus the TPM will not be able to perform
+the import unless is possesses the certified EK so if the command
+succeeds and the HMAC verifies on return we know we have a loadable
+copy of the private key only for the certified TPM.  This key is now
+loaded into the TPM and the Storage primary flushed (to free up space
+for the null key generation).
+
+The null EC primary is now generated using the Storage profile
+outlined in the `TCG TPM v2.0 Provisioning Guidance`_; the name of
+this key (the hash of the public area) is computed and compared to the
+null seed name presented by the kernel in
+/sys/class/tpm/tpm0/null_name.  If the names do not match, the TPM is
+compromised.  If the names match, the user performs a TPM2_Certify()
+using the null primary as the object handle and the loaded private key
+as the sign handle and providing randomized qualifying data.  The
+signature of the returned certifyInfo is verified against the public
+part of the loaded private key and the qualifying data checked to
+prevent replay.  If all of these tests pass, the user is now assured
+that TPM integrity and privacy was preserved across the entire boot
+sequence of this kernel.
+
+.. _TCG EK Credential Profile: https://trustedcomputinggroup.org/resource/tcg-ek-credential-profile-for-tpm-family-2-0/
+.. _TCG TPM v2.0 Provisioning Guidance: https://trustedcomputinggroup.org/resource/tcg-tpm-v2-0-provisioning-guidance/
Signature · 1 line
2.21.1
#12 lore raw

PATCH 12/17 oid_registry: Add TCG defined OIDS for TPM keys

In reply to James Prestwood

From: James Bottomley <[email protected]>

The TCG has defined an OID prefix "2.23.133.10.1" for the various TPM key uses. We've defined three of the available numbers:

2.23.133.10.1.3 TPM Loadable key. This is an asymmetric key (Usually
RSA2048 or Elliptic Curve) which can be imported by a TPM2_Load() operation.

2.23.133.10.1.4 TPM Importable Key. This is an asymmetric key (Usually
RSA2048 or Elliptic Curve) which can be imported by a TPM2_Import() operation.

Both loadable and importable keys are specific to a given TPM, the difference is that a loadable key is wrapped with the symmetric secret, so must have been created by the TPM itself. An importable key is wrapped with a DH shared secret, and may be created without access to the TPM provided you know the public part of the parent key.

2.23.133.10.1.5 TPM Sealed Data. This is a set of data (up to 128
bytes) which is sealed by the TPM. It usually represents a symmetric key and must be unsealed before use.

The ASN.1 binary key form starts of with this OID as the first element of a sequence, giving the binary form a unique recognizable identity marker regardless of encoding.

---
 include/linux/oid_registry.h | 5 +++++
 1 file changed, 5 insertions(+)
include/linux/oid_registry.h +5 -0
index 657d6bf2c064..f6e2276e5f30 100644
@@ -107,6 +107,11 @@ enum OID {
 	OID_gostTC26Sign512B,		/* 1.2.643.7.1.2.1.2.2 */
 	OID_gostTC26Sign512C,		/* 1.2.643.7.1.2.1.2.3 */
 
+	/* TCG defined OIDS for TPM based keys */
+	OID_TPMLoadableKey,		/* 2.23.133.10.1.3 */
+	OID_TPMImportableKey,		/* 2.23.133.10.1.4 */
+	OID_TPMSealedData,		/* 2.23.133.10.1.5 */
+
 	OID__NR
 };
 
Signature · 1 line
2.21.1
#13 lore raw

PATCH 13/17 tpm: tpm2-cmd: add driver API for RSA decryption

In reply to James Prestwood

Added a new TPM driver level API for RSA decryption.

The API parameters take a raw asymmetric key blob rather than depending on trusted types. This is so it can be easily used across the kernel rather than only in the trusted module as this will be used by a new asymmetric key type. The blob does still need to be parsed by the caller and formatted correctly to be accepted by the TPM.

At the TPM level decrypt and sign use the same operation, TPM2_CC_RSA_DECRYPT. The difference is that data to be signed is pre-padded with pkcs1 up to the key size. This effectively makes the call to decrypt actually an encryption operation suitable for signing.

If the parent handle passed in is TPM2_RH_NULL the null key context is loaded and that key handle is used. Any other handle will use that parent for the operations, and its expected that the parent handle exists in the TPM.

---
 drivers/char/tpm/tpm.h      |   3 +
 drivers/char/tpm/tpm2-cmd.c | 128 ++++++++++++++++++++++++++++++++++++
 include/linux/tpm.h         |   1 +
 3 files changed, 132 insertions(+)
drivers/char/tpm/tpm.h +3 -0
index ade4af4d52ca..f872132f9a68 100644
@@ -259,6 +259,9 @@ int tpm2_save_context(struct tpm_chip *chip, u32 handle, u8 *buf,
 		      unsigned int buf_size, unsigned int *offset);
 int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
 		      unsigned int *offset, u32 *handle);
+int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent,
+			    const unsigned char *keyblob, size_t bloblen,
+			    const void *data, size_t len, void *out);
 
 int tpm_bios_log_setup(struct tpm_chip *chip);
 void tpm_bios_log_teardown(struct tpm_chip *chip);
drivers/char/tpm/tpm2-cmd.c +128 -0

134 lines not on this page · raw message

include/linux/tpm.h +1 -0
index 52bfb673ab48..b1c96ee7b672 100644
@@ -247,6 +247,7 @@ enum tpm2_command_codes {
 	TPM2_CC_NV_READ                 = 0x014E,
 	TPM2_CC_CREATE		        = 0x0153,
 	TPM2_CC_LOAD		        = 0x0157,
+	TPM2_CC_RSA_DECRYPT	        = 0x0159,
 	TPM2_CC_SEQUENCE_UPDATE         = 0x015C,
 	TPM2_CC_UNSEAL		        = 0x015E,
 	TPM2_CC_CONTEXT_LOAD	        = 0x0161,
Signature · 1 line
2.21.1
#14 lore raw

PATCH 14/17 include: linux: tpm: expose tpm2_rsa_decrypt

In reply to James Prestwood

Expose these APIs so other modules can use them.

---
 include/linux/tpm.h | 9 +++++++++
 1 file changed, 9 insertions(+)
include/linux/tpm.h +9 -0
index b1c96ee7b672..7dd33f144bce 100644
@@ -387,6 +387,9 @@ static inline u32 tpm2_rc_value(u32 rc)
        return (rc & BIT(7)) ? rc & 0xff : rc;
 }
 
+extern int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent,
+			    const unsigned char *keyblob, size_t bloblen,
+			    const void *data, size_t len, void *out);
 #else
 static inline int tpm_is_tpm2(struct tpm_chip *chip)
 {
@@ -418,5 +421,11 @@ static inline struct tpm_chip *tpm_default_chip(void)
 {
 	return NULL;
 }
+static inline int tpm2_rsa_decrypt(struct tpm_chip *chip, u32 parent,
+				   const unsigned char *keyblob, size_t bloblen,
+				   const void *data, size_t len, void *out)
+{
+	return -ENODEV;
+}
 #endif
 #endif
Signature · 1 line
2.21.1
#15 lore raw

PATCH 15/17 include: crypto: add asym_tpm2_subtype definition

In reply to James Prestwood

This defines the structure of a TPM2 key in the kernel.

---
 include/crypto/asym_tpm2_subtype.h | 32 ++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
 create mode 100644 include/crypto/asym_tpm2_subtype.h
include/crypto/asym_tpm2_subtype.h new file +32 -0
new file mode 100644
index 000000000000..dea80b2e6e66
@@ -0,0 +1,32 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_ASYM_TPM2_SUBTYPE_H
+#define _LINUX_ASYM_TPM2_SUBTYPE_H
+
+#include <linux/keyctl.h>
+
+struct tpm2_parse_context {
+	u32 parent;
+	const u8 *pub;
+	u32 pub_len;
+	const u8 *priv;
+	u32 priv_len;
+};
+
+struct tpm2_key {
+	struct tpm_chip *chip;
+	u32 parent;
+
+	u8 *blob;
+	u32 bloblen;
+
+	/* pointer into 'blob' where public key begins */
+	const u8 *pub;
+	u32 pub_len;
+
+};
+
+struct tpm2_key *tpm2_key_create(struct tpm2_parse_context *ctx);
+
+extern struct asymmetric_key_subtype asym_tpm2_subtype;
+
+#endif /* _LINUX_ASYM_TPM2_SUBTYPE_H */
Signature · 1 line
2.21.1
#16 lore raw

PATCH 16/17 asymmetric_keys: add TPM2 ASN1 definition

In reply to James Prestwood

Copied the TPM2 ASN1 definition from trusted-keys

---
 crypto/asymmetric_keys/tpm2key.asn1 | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
 create mode 100644 crypto/asymmetric_keys/tpm2key.asn1
crypto/asymmetric_keys/tpm2key.asn1 new file +23 -0
new file mode 100644
index 000000000000..f930fd812db3
@@ -0,0 +1,23 @@
+---
+--- Note: This isn't quite the definition in the standard
+---       However, the Linux asn.1 parser doesn't understand
+---       [2] EXPLICIT SEQUENCE OF OPTIONAL
+---       So there's an extra intermediate TPMPolicySequence
+---       definition to work around this
+
+TPMKey ::= SEQUENCE {
+	type		OBJECT IDENTIFIER ({tpmkey_type}),
+	emptyAuth	[0] EXPLICIT BOOLEAN OPTIONAL,
+	policy		[1] EXPLICIT TPMPolicySequence OPTIONAL,
+	secret		[2] EXPLICIT OCTET STRING OPTIONAL,
+	parent		INTEGER ({tpmkey_parent}),
+	pubkey		OCTET STRING ({tpmkey_pub}),
+	privkey		OCTET STRING ({tpmkey_priv})
+	}
+
+TPMPolicySequence ::= SEQUENCE OF TPMPolicy
+
+TPMPolicy ::= SEQUENCE {
+	commandCode		[0] EXPLICIT INTEGER ({tpmkey_code}),
+	commandPolicy		[1] EXPLICIT OCTET STRING ({tpmkey_policy})
+	}
Signature · 1 line
2.21.1
#17 lore raw

PATCH 17/17 asymmetric_keys: add tpm2 key parser/type

In reply to James Prestwood

This adds support for RSA key operations using a TPM2 wrapped private key. Encryption and verify are done in software as these are operations using only the public key which is not hidden behind the TPM. Decryption and sign use tpm2_rsa_decrypt() for most of the leg work.

The key parser uses the ASN.1 definition for TPM2 keys. This parses out the private and public portion of the keys. From here a bit more parsing is done in order to find the portions of these keys which can be handed directly to the TPM for decryption/sign.

---
 crypto/asymmetric_keys/Kconfig       |  20 +
 crypto/asymmetric_keys/Makefile      |  12 +
 crypto/asymmetric_keys/asym_tpm2.c   | 653 +++++++++++++++++++++++++++
 crypto/asymmetric_keys/tpm2_parser.c | 155 +++++++
 4 files changed, 840 insertions(+)
 create mode 100644 crypto/asymmetric_keys/asym_tpm2.c
 create mode 100644 crypto/asymmetric_keys/tpm2_parser.c
crypto/asymmetric_keys/Kconfig +20 -0
index 1f1f004dc757..f3f7afffa9b0 100644
@@ -34,6 +34,17 @@ config ASYMMETRIC_TPM_KEY_SUBTYPE
 	  Operations such as sign, verify, encrypt, decrypt are performed by
 	  the TPM after the private key is loaded.
 
+config ASYMMETRIC_TPM2_KEY_SUBTYPE
+	tristate "Asymmetric TPM2 backed private key subtype"
+	depends on TCG_TPM
+	select CRYPTO_RSA
+	select CRYPTO_SHA256
+	select CRYPTO_HASH_INFO
+	help
+	  This option provides support for TPM2 backed private key type
+	  handling. Operations such as sign, verify, encrypt, decrypt are
+	  performed by the TPM2 after the private key is loaded.
+
 config X509_CERTIFICATE_PARSER
 	tristate "X.509 certificate parser"
 	depends on ASYMMETRIC_PUBLIC_KEY_SUBTYPE
@@ -63,6 +74,15 @@ config TPM_KEY_PARSER
 	  private key data and provides the ability to instantiate a crypto key
 	  from that data.
 
+config TPM2_KEY_PARSER
+	tristate "TPM2 private key parser"
+	depends on ASYMMETRIC_TPM2_KEY_SUBTYPE
+	select ASN1
+	help
+	  This option provides support for parsing TPM2 format blobs for
+	  private key data and provides the ability to instantiate a crypto key
+	  from that data.
+
 config PKCS7_MESSAGE_PARSER
 	tristate "PKCS#7 message parser"
 	depends on X509_CERTIFICATE_PARSER
crypto/asymmetric_keys/Makefile +12 -0
index 28b91adba2ae..7ce121366395 100644
@@ -12,6 +12,7 @@ asymmetric_keys-y := \
 
 obj-$(CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE) += public_key.o
 obj-$(CONFIG_ASYMMETRIC_TPM_KEY_SUBTYPE) += asym_tpm.o
+obj-$(CONFIG_ASYMMETRIC_TPM2_KEY_SUBTYPE) += asym_tpm2.o
 
 #
 # X.509 Certificate handling
@@ -86,3 +87,14 @@ tpm_key_parser-y := \
 
 $(obj)/tpm_parser.o: $(obj)/tpm.asn1.h
 $(obj)/tpm.asn1.o: $(obj)/tpm.asn1.c $(obj)/tpm.asn1.h
+
+#
+# TPM2 private key parsing
+#
+obj-$(CONFIG_TPM2_KEY_PARSER) += tpm2_key_parser.o
+tpm2_key_parser-y := \
+	tpm2key.asn1.o \
+	tpm2_parser.o
+
+$(obj)/tpm2_parser.o: $(obj)/tpm2key.asn1.h
+$(obj)/tpm2key.asn1.o: $(obj)/tpm2key.asn1.c $(obj)/tpm2key.asn1.h
crypto/asymmetric_keys/asym_tpm2.c new file +652 -0

652 lines not on this page · raw message

crypto/asymmetric_keys/tpm2_parser.c new file +155 -0

155 lines not on this page · raw message

Signature · 1 line
2.21.1