Skip to contentSkip to conversation

tpm: robust stack allocations

PATCH In review Jarkko Sakkinen 1 participant 6 messages Sep 23, 2025 – Sep 24, 2025

Subsystems (4)
lore
Share & tools
lore

Jarkko Sakkinen

author maintainer
#0 lore raw

v11 cover tpm: robust stack allocations

1. These are previous changes to tpm_buf, which make stack allocations much more feasible than previously.
2. Migrate low-hanging fruit to use stack allocations.
3. Re-orchestrate tpm_get_random().

Jarkko Sakkinen (3):
tpm: Make TPM buffer allocations more robust
tpm: Use TPM_MIN_BUF_SIZE in driver commands tpm orchestrate tpm_get_random() in the function

 drivers/char/tpm/tpm-buf.c                | 139 +++++----
 drivers/char/tpm/tpm-dev-common.c         |   4 +-
 drivers/char/tpm/tpm-dev.h                |   2 +-
 drivers/char/tpm/tpm-interface.c          |  36 ++-
 drivers/char/tpm/tpm-sysfs.c              |  20 +-
 drivers/char/tpm/tpm.h                    |  16 +-
 drivers/char/tpm/tpm1-cmd.c               | 177 +++++------
 drivers/char/tpm/tpm2-cmd.c               | 349 +++++++++-------------
 drivers/char/tpm/tpm2-sessions.c          | 127 ++++----
 drivers/char/tpm/tpm2-space.c             |  44 ++-
 drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
 drivers/char/tpm/tpm_vtpm_proxy.c         |  34 +--
 include/linux/tpm.h                       |  28 +-
 security/keys/trusted-keys/trusted_tpm1.c |  34 +--
 security/keys/trusted-keys/trusted_tpm2.c | 156 +++++-----
 15 files changed, 556 insertions(+), 614 deletions(-)
Signature · 1 line
2.39.5
author maintainer
#1 lore raw

PATCH v11 1/3 tpm: Make TPM buffer allocations more robust

From: Jarkko Sakkinen <[email protected]>

Create more ergonomic primitives to work with TPM buffers, where 'tpm_buf_init*' initialize the memory and 'tpm_buf_reset*' (re)set a buffer for a particular use and purpose. The new primitives are ubiquitos when it comes to heap and stack usage.

Given that the kzalloc is decoupled, a managed allocation can be done trivially:

	struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUF_MAX_SIZE,
							GFP_KERNEL);

This effectively zeros out the odds having any memory leaks with TPM buffers. The new structures can be later used to widen the use of stack over heap in the subsystem in the critical code paths..

---
v11
- No changes.
v10:
- Fix compiler warning about format string in __tpm_buf_size_invariant(). v9:
- Rename pre-existing TPM_BUFSIZE as TPM_BUF_MAX_SIZE and redeclare it in include/linux/tpm.h, and use this constant instead of PAGE_SIZE in tpm_buf_init*. Define TPM_BUF_MIN_SIZE to be a sane placeholder value for stack allocations.
- Fix and restructure invariant for the sake of clarity.
- memset buffers to zero in tpm_buf_init* in order to guarantee a legit initial state. This does not cause any regressions but once tpm_buf is allocaed from stack at some site, this will zero out chance of corrupted state.
v8:
- Decouple memory init i.e. bring tpm_init* back but with new fresh form.
- Cap buf_size to page size and also make checks in tpm_buf_append safe:
https://lore.kernel.org/linux-integrity/hwsx2t2tkbos3g7k2syemxbvc6sfrsbviwm64ubcdl6ms7ljvo@toetomkhheht/
- Fix trusted_tpm_send() and simplify the flow.
v7:
- Additional function comments and invariant was unfortunately left to my staging area so here's the addition (does not affect functionality).
v6:
- Removed two empty lines as requested by Stefan:
https://lore.kernel.org/linux-integrity/[email protected]/
- Add 'capacity' field as this makes easy to stretch tpm_buf into stack allocation.
v5:
- I tested this version also with TPM 1.2 by booting up and checking that sysfs attributes work.
- Fixed the length check against capacity (James) with TPM_BUF_CAPACITY.
- Fixed declaration style: do it at the site (Jason).
- Improved commit message (Stefan).
- Removed "out" label from tpm2_pcr_read() (Stefan).
- Removed spurious "return rc;" from tpm2_get_pcr_allocation() (Stefan). v4:
- Wrote a more a descriptive short summary and improved description.
- Fixed the error in documentation: there is 4090 bytes of space left for the payload - not 4088 bytes.
- Turned tpm_buf_alloc() into inline function.
v3:
- Removed the cleanup class and moved on using __free(kfree) instead.
- Removed buf_size (James).
- I'm open for the idea of splitting still (Jason) but I'll hold at least this revision just to check that my core idea here is correct.
v2:
- Implement also memory allocation using the cleanup class.
- Rewrote the commit message.
- Implemented CLASS_TPM_BUF() helper macro.

---
 drivers/char/tpm/tpm-buf.c                | 139 +++++++----
 drivers/char/tpm/tpm-dev-common.c         |   4 +-
 drivers/char/tpm/tpm-dev.h                |   2 +-
 drivers/char/tpm/tpm-interface.c          |   4 +-
 drivers/char/tpm/tpm-sysfs.c              |  20 +-
 drivers/char/tpm/tpm.h                    |   3 +-
 drivers/char/tpm/tpm1-cmd.c               | 149 ++++++------
 drivers/char/tpm/tpm2-cmd.c               | 282 ++++++++++------------
 drivers/char/tpm/tpm2-sessions.c          | 121 +++++-----
 drivers/char/tpm/tpm2-space.c             |  44 ++--
 drivers/char/tpm/tpm_tis_i2c.c            |   4 +-
 drivers/char/tpm/tpm_vtpm_proxy.c         |  32 ++-
 include/linux/tpm.h                       |  28 ++-
 security/keys/trusted-keys/trusted_tpm1.c |  34 ++-
 security/keys/trusted-keys/trusted_tpm2.c | 156 ++++++------
 15 files changed, 495 insertions(+), 527 deletions(-)
drivers/char/tpm/tpm-buf.c +86 -53
index dc882fc9fa9e..b45bf12f7d45 100644
@@ -7,82 +7,109 @@
 #include <linux/module.h>
 #include <linux/tpm.h>
 
-/**
- * tpm_buf_init() - Allocate and initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- *
- * Return: 0 or -ENOMEM
- */
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_size_invariant(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
-
-	tpm_buf_reset(buf, tag, ordinal);
-	return 0;
+	u32 buf_size_2 = (u32)buf->capacity + (u32)sizeof(*buf);
+
+	if (!buf->capacity) {
+		if (buf_size > TPM_BUF_MAX_SIZE) {
+			WARN(1, "%s: size overflow: %u\n", __func__, buf_size);
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	} else {
+		if (buf_size != buf_size_2) {
+			WARN(1, "%s: size mismatch: %u != %u\n", __func__, buf_size,
+			     buf_size_2);
+			buf->flags |= TPM_BUF_ERROR;
+		}
+	}
 }
-EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-/**
- * tpm_buf_reset() - Initialize a TPM command
- * @buf:	A &tpm_buf
- * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
- * @ordinal:	A command ordinal
- */
-void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
+static void __tpm_buf_reset(struct tpm_buf *buf, u16 buf_size, u16 tag, u32 ordinal)
 {
 	struct tpm_header *head = (struct tpm_header *)buf->data;
 
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	WARN_ON(tag != TPM_TAG_RQU_COMMAND && tag != TPM2_ST_NO_SESSIONS &&
 		tag != TPM2_ST_SESSIONS && tag != 0);
 
 	buf->flags = 0;
 	buf->length = sizeof(*head);
+	buf->capacity = buf_size - sizeof(*buf);
+	buf->handles = 0;
 	head->tag = cpu_to_be16(tag);
 	head->length = cpu_to_be32(sizeof(*head));
 	head->ordinal = cpu_to_be32(ordinal);
+}
+
+static void __tpm_buf_reset_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	__tpm_buf_size_invariant(buf, buf_size);
+
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
+	buf->flags = TPM_BUF_TPM2B;
+	buf->length = 2;
+	buf->capacity = buf_size - sizeof(*buf);
 	buf->handles = 0;
+	buf->data[0] = 0;
+	buf->data[1] = 0;
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
 /**
- * tpm_buf_init_sized() - Allocate and initialize a sized (TPM2B) buffer
- * @buf:	A @tpm_buf
- *
- * Return: 0 or -ENOMEM
+ * tpm_buf_init() - Initialize a TPM command
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
  */
-int tpm_buf_init_sized(struct tpm_buf *buf)
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size)
 {
-	buf->data = (u8 *)__get_free_page(GFP_KERNEL);
-	if (!buf->data)
-		return -ENOMEM;
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset(buf, buf_size, TPM_TAG_RQU_COMMAND, 0);
+}
+EXPORT_SYMBOL_GPL(tpm_buf_init);
 
-	tpm_buf_reset_sized(buf);
-	return 0;
+/**
+ * tpm_buf_init_sized() - Initialize a sized buffer
+ * @buf:	A &tpm_buf
+ * @buf_size:	Size of the buffer.
+ */
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size)
+{
+	memset(buf, 0, buf_size);
+	__tpm_buf_reset_sized(buf, buf_size);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_init_sized);
 
 /**
- * tpm_buf_reset_sized() - Initialize a sized buffer
+ * tpm_buf_reset() - Re-initialize a TPM command
  * @buf:	A &tpm_buf
+ * @tag:	TPM_TAG_RQU_COMMAND, TPM2_ST_NO_SESSIONS or TPM2_ST_SESSIONS
+ * @ordinal:	A command ordinal
  */
-void tpm_buf_reset_sized(struct tpm_buf *buf)
+void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal)
 {
-	buf->flags = TPM_BUF_TPM2B;
-	buf->length = 2;
-	buf->data[0] = 0;
-	buf->data[1] = 0;
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset(buf, buf_size, tag, ordinal);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
+EXPORT_SYMBOL_GPL(tpm_buf_reset);
 
-void tpm_buf_destroy(struct tpm_buf *buf)
+/**
+ * tpm_buf_reset_sized() - Re-initialize a sized buffer
+ * @buf:	A &tpm_buf
+ */
+void tpm_buf_reset_sized(struct tpm_buf *buf)
 {
-	free_page((unsigned long)buf->data);
+	u16 buf_size = buf->capacity + sizeof(*buf);
+
+	__tpm_buf_reset_sized(buf, buf_size);
 }
-EXPORT_SYMBOL_GPL(tpm_buf_destroy);
+EXPORT_SYMBOL_GPL(tpm_buf_reset_sized);
 
 /**
  * tpm_buf_length() - Return the number of bytes consumed by the data
@@ -92,6 +119,9 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
  */
 u32 tpm_buf_length(struct tpm_buf *buf)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return 0;
+
 	return buf->length;
 }
 EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -104,13 +134,14 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
  */
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
 {
-	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_OVERFLOW)
+	u32 total_length = (u32)buf->length + (u32)new_length;
+
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
-	if ((buf->length + new_length) > PAGE_SIZE) {
+	if (total_length > (u32)buf->capacity) {
 		WARN(1, "tpm_buf: write overflow\n");
-		buf->flags |= TPM_BUF_OVERFLOW;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -157,8 +188,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
  */
 void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle)
 {
+	if (buf->flags & TPM_BUF_ERROR)
+		return;
+
 	if (buf->flags & TPM_BUF_TPM2B) {
-		dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+		dev_err(&chip->dev, "%s: invalid for buffer type: TPM2B\n", __func__);
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -178,13 +213,13 @@ static void tpm_buf_read(struct tpm_buf *buf, off_t *offset, size_t count, void
 	off_t next_offset;
 
 	/* Return silently if overflow has already happened. */
-	if (buf->flags & TPM_BUF_BOUNDARY_ERROR)
+	if (buf->flags & TPM_BUF_ERROR)
 		return;
 
 	next_offset = *offset + count;
 	if (next_offset > buf->length) {
 		WARN(1, "tpm_buf: read out of boundary\n");
-		buf->flags |= TPM_BUF_BOUNDARY_ERROR;
+		buf->flags |= TPM_BUF_ERROR;
 		return;
 	}
 
@@ -242,5 +277,3 @@ u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset)
 	return be32_to_cpu(value);
 }
 EXPORT_SYMBOL_GPL(tpm_buf_read_u32);
-
-
drivers/char/tpm/tpm-dev-common.c +2 -2
index f2a5e09257dd..4f5893555fb7 100644
@@ -147,7 +147,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf,
 
 		rc = copy_to_user(buf, priv->data_buffer + *off, ret_size);
 		if (rc) {
-			memset(priv->data_buffer, 0, TPM_BUFSIZE);
+			memset(priv->data_buffer, 0, TPM_BUF_MAX_SIZE);
 			priv->response_length = 0;
 			ret_size = -EFAULT;
 		} else {
@@ -173,7 +173,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf,
 	struct file_priv *priv = file->private_data;
 	int ret = 0;
 
-	if (size > TPM_BUFSIZE)
+	if (size > TPM_BUF_MAX_SIZE)
 		return -E2BIG;
 
 	mutex_lock(&priv->buffer_mutex);
drivers/char/tpm/tpm-dev.h +1 -1
index f3742bcc73e3..700e3d9d8b64 100644
@@ -18,7 +18,7 @@ struct file_priv {
 	bool response_read;
 	bool command_enqueued;
 
-	u8 data_buffer[TPM_BUFSIZE];
+	u8 data_buffer[TPM_BUF_MAX_SIZE];
 };
 
 void tpm_common_open(struct file *file, struct tpm_chip *chip,
drivers/char/tpm/tpm-interface.c +2 -2
index c9f173001d0e..b0d5098fb92b 100644
@@ -100,8 +100,8 @@ static ssize_t tpm_try_transmit(struct tpm_chip *chip, void *buf, size_t bufsiz)
 	if (bufsiz < TPM_HEADER_SIZE)
 		return -EINVAL;
 
-	if (bufsiz > TPM_BUFSIZE)
-		bufsiz = TPM_BUFSIZE;
+	if (bufsiz > TPM_BUF_MAX_SIZE)
+		bufsiz = TPM_BUF_MAX_SIZE;
 
 	count = be32_to_cpu(header->length);
 	ordinal = be32_to_cpu(header->ordinal);
drivers/char/tpm/tpm-sysfs.c +10 -10
index 94231f052ea7..4213a8285ed0 100644
@@ -32,28 +32,30 @@ struct tpm_readpubek_out {
 static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,
 			  char *buf)
 {
-	struct tpm_buf tpm_buf;
 	struct tpm_readpubek_out *out;
 	int i;
 	char *str = buf;
 	struct tpm_chip *chip = to_tpm_chip(dev);
 	char anti_replay[20];
 
+	struct tpm_buf *tpm_buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!tpm_buf)
+		return -ENOMEM;
+
 	memset(&anti_replay, 0, sizeof(anti_replay));
 
 	if (tpm_try_get_ops(chip))
 		return 0;
 
-	if (tpm_buf_init(&tpm_buf, TPM_TAG_RQU_COMMAND, TPM_ORD_READPUBEK))
-		goto out_ops;
-
-	tpm_buf_append(&tpm_buf, anti_replay, sizeof(anti_replay));
+	tpm_buf_init(tpm_buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_reset(tpm_buf, TPM_TAG_RQU_COMMAND, TPM_ORD_READPUBEK);
+	tpm_buf_append(tpm_buf, anti_replay, sizeof(anti_replay));
 
-	if (tpm_transmit_cmd(chip, &tpm_buf, READ_PUBEK_RESULT_MIN_BODY_SIZE,
+	if (tpm_transmit_cmd(chip, tpm_buf, READ_PUBEK_RESULT_MIN_BODY_SIZE,
 			     "attempting to read the PUBEK"))
-		goto out_buf;
+		goto out_ops;
 
-	out = (struct tpm_readpubek_out *)&tpm_buf.data[10];
+	out = (struct tpm_readpubek_out *)&tpm_buf->data[10];
 	str +=
 	    sprintf(str,
 		    "Algorithm: %4ph\n"
@@ -71,8 +73,6 @@ static ssize_t pubek_show(struct device *dev, struct device_attribute *attr,
 	for (i = 0; i < 256; i += 16)
 		str += sprintf(str, "%16ph\n", &out->modulus[i]);
 
-out_buf:
-	tpm_buf_destroy(&tpm_buf);
 out_ops:
 	tpm_put_ops(chip);
 	return str - buf;
drivers/char/tpm/tpm.h +1 -2
index 2726bd38e5ac..1a4abe54db15 100644
@@ -32,7 +32,6 @@
 #endif
 
 #define TPM_MINOR		224	/* officially assigned */
-#define TPM_BUFSIZE		4096
 #define TPM_NUM_DEVICES		65536
 #define TPM_RETRY		50
 
@@ -224,7 +223,7 @@ enum tpm2_pt_props {
 	TPM2_PT_AUDIT_COUNTER_1 = TPM2_PT_VAR + 20,
 };
 
-/* 128 bytes is an arbitrary cap. This could be as large as TPM_BUFSIZE - 18
+/* 128 bytes is an arbitrary cap. This could be as large as TPM_BUF_MAX_SIZE - 18
  * bytes, but 128 is still a relatively large number of random bytes and
  * anything much bigger causes users of struct tpm_cmd_t to start getting
  * compiler warnings about stack frame size. */
drivers/char/tpm/tpm1-cmd.c +70 -79

271 lines not on this page · raw message

drivers/char/tpm/tpm2-cmd.c +130 -152

522 lines not on this page · raw message

drivers/char/tpm/tpm2-sessions.c +58 -63

224 lines not on this page · raw message

drivers/char/tpm/tpm2-space.c +18 -26

106 lines not on this page · raw message

drivers/char/tpm/tpm_tis_i2c.c +2 -2
index 6cd07dd34507..5832713b1a2c 100644
@@ -232,7 +232,7 @@ static int tpm_tis_i2c_write_bytes(struct tpm_tis_data *data, u32 addr, u16 len,
 	int ret;
 	u16 wrote = 0;
 
-	if (len > TPM_BUFSIZE - 1)
+	if (len > TPM_BUF_MAX_SIZE - 1)
 		return -EIO;
 
 	phy->io_buf[0] = reg;
@@ -339,7 +339,7 @@ static int tpm_tis_i2c_probe(struct i2c_client *dev)
 	if (!phy)
 		return -ENOMEM;
 
-	phy->io_buf = devm_kzalloc(&dev->dev, TPM_BUFSIZE, GFP_KERNEL);
+	phy->io_buf = devm_kzalloc(&dev->dev, TPM_BUF_MAX_SIZE, GFP_KERNEL);
 	if (!phy->io_buf)
 		return -ENOMEM;
 
drivers/char/tpm/tpm_vtpm_proxy.c +14 -18
index 0818bb517805..e5de14379eb2 100644
@@ -42,7 +42,7 @@ struct proxy_dev {
 
 	size_t req_len;              /* length of queued TPM request */
 	size_t resp_len;             /* length of queued TPM response */
-	u8 buffer[TPM_BUFSIZE];      /* request/response buffer */
+	u8 buffer[TPM_BUF_MAX_SIZE];      /* request/response buffer */
 
 	struct work_struct work;     /* task that retrieves TPM timeouts */
 };
@@ -395,40 +395,36 @@ static bool vtpm_proxy_tpm_req_canceled(struct tpm_chip  *chip, u8 status)
 
 static int vtpm_proxy_request_locality(struct tpm_chip *chip, int locality)
 {
-	struct tpm_buf buf;
 	int rc;
 	const struct tpm_header *header;
 	struct proxy_dev *proxy_dev = dev_get_drvdata(&chip->dev);
 
+	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!buf)
+		return -ENOMEM;
+
+	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
-		rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS,
-				  TPM2_CC_SET_LOCALITY);
+		tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_SET_LOCALITY);
 	else
-		rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND,
-				  TPM_ORD_SET_LOCALITY);
-	if (rc)
-		return rc;
-	tpm_buf_append_u8(&buf, locality);
+		tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_SET_LOCALITY);
+
+	tpm_buf_append_u8(buf, locality);
 
 	proxy_dev->state |= STATE_DRIVER_COMMAND;
 
-	rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to set locality");
+	rc = tpm_transmit_cmd(chip, buf, 0, "attempting to set locality");
 
 	proxy_dev->state &= ~STATE_DRIVER_COMMAND;
 
-	if (rc < 0) {
-		locality = rc;
-		goto out;
-	}
+	if (rc < 0)
+		return rc;
 
-	header = (const struct tpm_header *)buf.data;
+	header = (const struct tpm_header *)buf->data;
 	rc = be32_to_cpu(header->return_code);
 	if (rc)
 		locality = -1;
 
-out:
-	tpm_buf_destroy(&buf);
-
 	return locality;
 }
 
include/linux/tpm.h +15 -13
index dc0338a783f3..a0ce1b565769 100644
@@ -367,22 +367,25 @@ struct tpm_header {
 } __packed;
 
 enum tpm_buf_flags {
-	/* the capacity exceeded: */
-	TPM_BUF_OVERFLOW	= BIT(0),
-	/* TPM2B format: */
-	TPM_BUF_TPM2B		= BIT(1),
-	/* read out of boundary: */
-	TPM_BUF_BOUNDARY_ERROR	= BIT(2),
+	/* TPM2B format */
+	TPM_BUF_TPM2B	= BIT(1),
+	/* overflow or underrun error */
+	TPM_BUF_ERROR	= BIT(2),
 };
 
+#define TPM_BUF_MIN_SIZE	256	/* size for stack allocations */
+#define TPM_BUF_MAX_SIZE	4096	/* size for heap allocations */
+
 /*
- * A string buffer type for constructing TPM commands.
+ * A buffer for constructing and parsing TPM commands, responses and sized
+ * (TPM2B) buffers.
  */
 struct tpm_buf {
-	u32 flags;
-	u32 length;
-	u8 *data;
+	u8 flags;
 	u8 handles;
+	u16 length;
+	u16 capacity;
+	u8 data[];
 };
 
 enum tpm2_object_attributes {
@@ -413,11 +416,10 @@ struct tpm2_hash {
 	unsigned int tpm_id;
 };
 
-int tpm_buf_init(struct tpm_buf *buf, u16 tag, u32 ordinal);
+void tpm_buf_init(struct tpm_buf *buf, u16 buf_size);
+void tpm_buf_init_sized(struct tpm_buf *buf, u16 buf_size);
 void tpm_buf_reset(struct tpm_buf *buf, u16 tag, u32 ordinal);
-int tpm_buf_init_sized(struct tpm_buf *buf);
 void tpm_buf_reset_sized(struct tpm_buf *buf);
-void tpm_buf_destroy(struct tpm_buf *buf);
 u32 tpm_buf_length(struct tpm_buf *buf);
 void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length);
 void tpm_buf_append_u8(struct tpm_buf *buf, const u8 value);
security/keys/trusted-keys/trusted_tpm1.c +15 -19
index 636acb66a4f6..fec7b6de7887 100644
@@ -310,9 +310,8 @@ static int TSS_checkhmac2(unsigned char *buffer,
  * For key specific tpm requests, we will generate and send our
  * own TPM command packets using the drivers send function.
  */
-static int trusted_tpm_send(unsigned char *cmd, size_t buflen)
+static int trusted_tpm_send(void *cmd, size_t buflen)
 {
-	struct tpm_buf buf;
 	int rc;
 
 	if (!chip)
@@ -322,15 +321,12 @@ static int trusted_tpm_send(unsigned char *cmd, size_t buflen)
 	if (rc)
 		return rc;
 
-	buf.flags = 0;
-	buf.length = buflen;
-	buf.data = cmd;
 	dump_tpm_buf(cmd);
-	rc = tpm_transmit_cmd(chip, &buf, 4, "sending data");
+	rc = tpm_transmit_cmd(chip, cmd, 4, "sending data");
 	dump_tpm_buf(cmd);
 
+	/* Convert TPM error to -EPERM. */
 	if (rc > 0)
-		/* TPM error */
 		rc = -EPERM;
 
 	tpm_put_ops(chip);
@@ -624,23 +620,23 @@ static int tpm_unseal(struct tpm_buf *tb,
 static int key_seal(struct trusted_key_payload *p,
 		    struct trusted_key_options *o)
 {
-	struct tpm_buf tb;
 	int ret;
 
-	ret = tpm_buf_init(&tb, 0, 0);
-	if (ret)
-		return ret;
+	struct tpm_buf *tb __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!tb)
+		return -ENOMEM;
+
+	tpm_buf_init(tb, TPM_BUF_MAX_SIZE);
 
 	/* include migratable flag at end of sealed key */
 	p->key[p->key_len] = p->migratable;
 
-	ret = tpm_seal(&tb, o->keytype, o->keyhandle, o->keyauth,
+	ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
 		       p->key, p->key_len + 1, p->blob, &p->blob_len,
 		       o->blobauth, o->pcrinfo, o->pcrinfo_len);
 	if (ret < 0)
 		pr_info("srkseal failed (%d)\n", ret);
 
-	tpm_buf_destroy(&tb);
 	return ret;
 }
 
@@ -650,14 +646,15 @@ static int key_seal(struct trusted_key_payload *p,
 static int key_unseal(struct trusted_key_payload *p,
 		      struct trusted_key_options *o)
 {
-	struct tpm_buf tb;
 	int ret;
 
-	ret = tpm_buf_init(&tb, 0, 0);
-	if (ret)
-		return ret;
+	struct tpm_buf *tb __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
+	if (!tb)
+		return -ENOMEM;
+
+	tpm_buf_init(tb, TPM_BUF_MAX_SIZE);
 
-	ret = tpm_unseal(&tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
+	ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
 			 o->blobauth, p->key, &p->key_len);
 	if (ret < 0)
 		pr_info("srkunseal failed (%d)\n", ret);
@@ -665,7 +662,6 @@ static int key_unseal(struct trusted_key_payload *p,
 		/* pull migratable flag out of sealed key */
 		p->migratable = p->key[--p->key_len];
 
-	tpm_buf_destroy(&tb);
 	return ret;
 }
 
security/keys/trusted-keys/trusted_tpm2.c +71 -85

286 lines not on this page · raw message

Signature · 1 line
2.39.5
author maintainer
#2 lore raw

PATCH v11 2/3 tpm: Use TPM_MIN_BUF_SIZE in driver commands

In reply to Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

Use TPM_BUF_MIN_SIZE and stack allocation in the following commands:

1. tpm1_startup
2. tpm2_shutdown
3. tpm1_get_random
4. tpm2_do_selftest
5. tpm2_probe
6. tpm2_startup
7. tpm2_get_random
8. vtpm_proxy_request_locality

---
v11:
- A new patch that squashes previous stack updates. It's in the end of day easier review like this. Thus, also the sanity check list in the commit message in order to catch up unintended changes if there were any.

---
 drivers/char/tpm/tpm.h            |  9 ++---
 drivers/char/tpm/tpm1-cmd.c       | 22 ++++-------
 drivers/char/tpm/tpm2-cmd.c       | 65 ++++++++++++-------------------
 drivers/char/tpm/tpm_vtpm_proxy.c | 12 +++---
 4 files changed, 42 insertions(+), 66 deletions(-)
drivers/char/tpm/tpm.h +4 -5
index 1a4abe54db15..df426e281f88 100644
@@ -223,11 +223,10 @@ enum tpm2_pt_props {
 	TPM2_PT_AUDIT_COUNTER_1 = TPM2_PT_VAR + 20,
 };
 
-/* 128 bytes is an arbitrary cap. This could be as large as TPM_BUF_MAX_SIZE - 18
- * bytes, but 128 is still a relatively large number of random bytes and
- * anything much bigger causes users of struct tpm_cmd_t to start getting
- * compiler warnings about stack frame size. */
-#define TPM_MAX_RNG_DATA	128
+/*
+ * The parameter is capped to fit to a stack allocated TPM buffer.
+ */
+#define TPM_MAX_RNG_DATA	(TPM_BUF_MIN_SIZE / 2)
 
 extern const struct class tpm_class;
 extern const struct class tpmrm_class;
drivers/char/tpm/tpm1-cmd.c +8 -14
index ca3e7f9a105d..fdb55dab80e1 100644
@@ -323,19 +323,15 @@ unsigned long tpm1_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal)
  */
 static int tpm1_startup(struct tpm_chip *chip)
 {
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	dev_info(&chip->dev, "starting up the TPM manually\n");
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	dev_info(&chip->dev, "TPM_Startup\n");
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_STARTUP);
 	tpm_buf_append_u16(buf, TPM_ST_CLEAR);
-
-	rc = tpm_transmit_cmd(chip, buf, 0, "attempting to start the TPM");
+	rc = tpm_transmit_cmd(chip, buf, 0, "TPM_Startup");
 	return rc;
 }
 
@@ -530,6 +526,8 @@ struct tpm1_get_random_out {
  */
 int tpm1_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
 {
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
 	struct tpm1_get_random_out *out;
 	u32 num_bytes =  min_t(u32, max, TPM_MAX_RNG_DATA);
 	u32 total = 0;
@@ -537,11 +535,7 @@ int tpm1_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
 	u32 recd;
 	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	do {
 		tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_GET_RANDOM);
 		tpm_buf_append_u32(buf, num_bytes);
drivers/char/tpm/tpm2-cmd.c +25 -40

135 lines not on this page · raw message

drivers/char/tpm/tpm_vtpm_proxy.c +5 -7
index e5de14379eb2..0f1b1b67ed4e 100644
@@ -395,15 +395,13 @@ static bool vtpm_proxy_tpm_req_canceled(struct tpm_chip  *chip, u8 status)
 
 static int vtpm_proxy_request_locality(struct tpm_chip *chip, int locality)
 {
-	int rc;
-	const struct tpm_header *header;
 	struct proxy_dev *proxy_dev = dev_get_drvdata(&chip->dev);
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
+	const struct tpm_header *header;
+	int rc;
 
-	struct tpm_buf *buf __free(kfree) = kzalloc(PAGE_SIZE, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	tpm_buf_init(buf, TPM_BUF_MAX_SIZE);
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
 		tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_SET_LOCALITY);
 	else
Signature · 1 line
2.39.5
author maintainer
#3 lore raw

PATCH v11 3/3 tpm orchestrate tpm_get_random() in the function

In reply to Jarkko Sakkinen

From: Jarkko Sakkinen <[email protected]>

tpm1_get_random() and tpm2_get_random() repeat the same orchestration. Move the orchestration into tpm_get_random(). This is especially useful for TPM 1.2 as the code for that does not get exercised a lot these days.

---
v11:
- A new patch.

---
 drivers/char/tpm/tpm-interface.c | 32 ++++++++++--
 drivers/char/tpm/tpm.h           |  6 ++-
 drivers/char/tpm/tpm1-cmd.c      | 54 +++++++++-----------
 drivers/char/tpm/tpm2-cmd.c      | 84 ++++++++++++--------------------
 drivers/char/tpm/tpm2-sessions.c |  6 +++
 5 files changed, 90 insertions(+), 92 deletions(-)
drivers/char/tpm/tpm-interface.c +27 -5
index b0d5098fb92b..0c6d25cf7cac 100644
@@ -487,22 +487,44 @@ EXPORT_SYMBOL_GPL(tpm_pm_resume);
  */
 int tpm_get_random(struct tpm_chip *chip, u8 *out, size_t max)
 {
+	u8 buf_data[TPM_BUF_MIN_SIZE];
+	struct tpm_buf *buf = (struct tpm_buf *)buf_data;
+	u32 num_bytes = max;
+	u8 *dest_ptr = out;
+	int retries = 5;
+	int total = 0;
 	int rc;
 
 	if (!out || max > TPM_MAX_RNG_DATA)
 		return -EINVAL;
 
+	tpm_buf_init(buf, TPM_BUF_MIN_SIZE);
+
 	chip = tpm_find_get_ops(chip);
 	if (!chip)
 		return -ENODEV;
 
-	if (chip->flags & TPM_CHIP_FLAG_TPM2)
-		rc = tpm2_get_random(chip, out, max);
-	else
-		rc = tpm1_get_random(chip, out, max);
+	rc = tpm2_start_auth_session(chip);
+	if (rc)
+		return rc;
 
+	do {
+		if (chip->flags & TPM_CHIP_FLAG_TPM2)
+			rc = tpm2_get_random(chip, buf, out, max);
+		else
+			rc = tpm1_get_random(chip, buf, out, max);
+
+		if (rc < 0)
+			break;
+
+		dest_ptr += rc;
+		total += rc;
+		num_bytes -= rc;
+	} while (retries-- && total < max);
+
+	tpm2_end_auth_session(chip);
 	tpm_put_ops(chip);
-	return rc;
+	return total ? total : -EIO;
 }
 EXPORT_SYMBOL_GPL(tpm_get_random);
 
drivers/char/tpm/tpm.h +4 -2
index df426e281f88..0dc2397bc55a 100644
@@ -249,7 +249,8 @@ int tpm1_pcr_extend(struct tpm_chip *chip, u32 pcr_idx, const u8 *hash,
 int tpm1_pcr_read(struct tpm_chip *chip, u32 pcr_idx, u8 *res_buf);
 ssize_t tpm1_getcap(struct tpm_chip *chip, u32 subcap_id, cap_t *cap,
 		    const char *desc, size_t min_cap_length);
-int tpm1_get_random(struct tpm_chip *chip, u8 *out, size_t max);
+int tpm1_get_random(struct tpm_chip *chip, struct tpm_buf *buf, u8 *out,
+		    size_t max);
 int tpm1_get_pcr_allocation(struct tpm_chip *chip);
 unsigned long tpm_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal);
 int tpm_pm_suspend(struct device *dev);
@@ -290,7 +291,8 @@ int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
 		  struct tpm_digest *digest, u16 *digest_size_ptr);
 int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
 		    struct tpm_digest *digests);
-int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max);
+int tpm2_get_random(struct tpm_chip *chip, struct tpm_buf *buf, u8 *dest,
+		    size_t max);
 ssize_t tpm2_get_tpm_pt(struct tpm_chip *chip, u32 property_id,
 			u32 *value, const char *desc);
 
drivers/char/tpm/tpm1-cmd.c +22 -32

77 lines not on this page · raw message

drivers/char/tpm/tpm2-cmd.c +31 -53

110 lines not on this page · raw message

drivers/char/tpm/tpm2-sessions.c +6 -0
index fd0f56e0018b..654b3e326292 100644
@@ -837,6 +837,9 @@ void tpm2_end_auth_session(struct tpm_chip *chip)
 {
 	struct tpm2_auth *auth = chip->auth;
 
+	if (!(chip->flags & TPM_CHIP_FLAG_TPM2))
+		return;
+
 	if (!auth)
 		return;
 
@@ -927,6 +930,9 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
 	u32 null_key;
 	int rc;
 
+	if (!(chip->flags & TPM_CHIP_FLAG_TPM2))
+		return 0;
+
 	if (chip->auth) {
 		dev_dbg_once(&chip->dev, "auth session is active\n");
 		return 0;
Signature · 1 line
2.39.5
author maintainer
#4 lore raw
In reply to Jarkko Sakkinen
Quoted 9 lines · Jarkko Sakkinen

1. These are previous changes to tpm_buf, which make stack allocations much more feasible than previously.
2. Migrate low-hanging fruit to use stack allocations.
3. Re-orchestrate tpm_get_random().

Jarkko Sakkinen (3):
tpm: Make TPM buffer allocations more robust
tpm: Use TPM_MIN_BUF_SIZE in driver commands tpm orchestrate tpm_get_random() in the function

I'm quite soon sending v12 because I randomly noticed a resource over-cosumption bug. which could be theoretically triggered e.g. via interposing a bus or a faulty device: tpm2_get_pcr_allocation() does not have a hard limit for the number of PCR banks.

The fix:

https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/commit/?h=tpm-buf&id=3d92f14c204d09babadaa0b7c7a82c40d11696d0

It does a bit of extra (out of scope) grouping those related constants but I'd like to keep it that way (should not cause much harm in the context of merge conflicts).

BR, Jarkko

author maintainer
#5 lore raw
Quoted 11 lines · Jarkko Sakkinen
Quoted 9 lines · Jarkko Sakkinen

1. These are previous changes to tpm_buf, which make stack allocations much more feasible than previously.
2. Migrate low-hanging fruit to use stack allocations.
3. Re-orchestrate tpm_get_random().

Jarkko Sakkinen (3):
tpm: Make TPM buffer allocations more robust
tpm: Use TPM_MIN_BUF_SIZE in driver commands tpm orchestrate tpm_get_random() in the function

Quoted 8 lines

I'm quite soon sending v12 because I randomly noticed a resource over-cosumption bug. which could be theoretically triggered e.g. via interposing a bus or a faulty device: tpm2_get_pcr_allocation() does not have a hard limit for the number of PCR banks.

The fix:

https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/commit/?h=tpm-buf&id=3d92f14c204d09babadaa0b7c7a82c40d11696d0

[should have "ret = -E2BIG; goto out;". The reason for that bug is that
I just rebased the patch from tip to the bottom of the series, which caused some merge conflicts.]

BR, Jarkko