* [PATCH v5 08/12] tpm2-sessions: Remove AUTH_MAX_NAMES
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Peter Huewe, Jason Gunthorpe,
David Howells, Paul Moore, James Morris, Serge E. Hallyn,
open list, open list:KEYS/KEYRINGS, open list:SECURITY SUBSYSTEM
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
In all of the call sites only one session is ever append. Thus, reduce
AUTH_MAX_NAMES, which leads into removing constant completely.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
drivers/char/tpm/tpm2-sessions.c | 31 +++++++++++--------------------
1 file changed, 11 insertions(+), 20 deletions(-)
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 0816a91134fc..62a200ae72d7 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -72,9 +72,6 @@
#include <crypto/sha2.h>
#include <crypto/utils.h>
-/* maximum number of names the TPM must remember for authorization */
-#define AUTH_MAX_NAMES 3
-
#define AES_KEY_BYTES AES_KEYSIZE_128
#define AES_KEY_BITS (AES_KEY_BYTES*8)
@@ -136,8 +133,8 @@ struct tpm2_auth {
* handle, but they are part of the session by name, which
* we must compute and remember
*/
- u8 name[AUTH_MAX_NAMES][TPM2_MAX_NAME_SIZE];
- u16 name_size_tbl[AUTH_MAX_NAMES];
+ u8 name[TPM2_MAX_NAME_SIZE];
+ u16 name_size;
};
#ifdef CONFIG_TCG_TPM2_HMAC
@@ -254,11 +251,14 @@ EXPORT_SYMBOL_GPL(tpm2_read_public);
int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
u32 handle, u8 *name, u16 name_size)
{
-#ifdef CONFIG_TCG_TPM2_HMAC
struct tpm2_auth *auth;
- int slot;
int ret;
-#endif
+
+ if (tpm_buf_length(buf) != TPM_HEADER_SIZE) {
+ dev_err(&chip->dev, "too many handles\n");
+ ret = -EIO;
+ goto err;
+ }
if (!tpm2_chip_auth(chip)) {
tpm_buf_append_handle(buf, handle);
@@ -266,12 +266,6 @@ int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
}
#ifdef CONFIG_TCG_TPM2_HMAC
- slot = (tpm_buf_length(buf) - TPM_HEADER_SIZE) / 4;
- if (slot >= AUTH_MAX_NAMES) {
- dev_err(&chip->dev, "too many handles\n");
- ret = -EIO;
- goto err;
- }
auth = chip->auth;
if (auth->session != tpm_buf_length(buf)) {
dev_err(&chip->dev, "session state malformed");
@@ -280,16 +274,14 @@ int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
}
tpm_buf_append_u32(buf, handle);
auth->session += 4;
- memcpy(auth->name[slot], name, name_size);
- auth->name_size_tbl[slot] = name_size;
+ memcpy(auth->name, name, name_size);
+ auth->name_size = name_size;
#endif
return 0;
-#ifdef CONFIG_TCG_TPM2_HMAC
err:
tpm2_end_auth_session(chip);
return ret;
-#endif
}
EXPORT_SYMBOL_GPL(tpm_buf_append_name);
@@ -658,8 +650,7 @@ int tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)
/* ordinal is already BE */
sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));
/* add the handle names */
- for (i = 0; i < handles; i++)
- sha256_update(&sctx, auth->name[i], auth->name_size_tbl[i]);
+ sha256_update(&sctx, auth->name, auth->name_size);
if (offset_s != tpm_buf_length(buf))
sha256_update(&sctx, &buf->data[offset_s],
tpm_buf_length(buf) - offset_s);
--
2.39.5
^ permalink raw reply related
* [PATCH v5 07/12] KEYS: trusted: Re-orchestrate tpm2_read_public() calls
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Peter Huewe, Jason Gunthorpe,
David Howells, Paul Moore, James Morris, Serge E. Hallyn,
James Bottomley, Mimi Zohar, open list, open list:KEYS/KEYRINGS,
open list:SECURITY SUBSYSTEM
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
tpm2_load_cmd() and tpm2_unseal_cmd() use the same parent, and calls to
tpm_buf_append_name() cause the exact same TPM2_ReadPublic command to be
sent to the chip, causing unnecessary traffic.
1. Export tpm2_read_public in order to make it callable from
'trusted_tpm2'.
2. Re-orchestrate tpm2_seal_trusted() and tpm2_unseal_trusted() in order to
halve the name resolutions required:
2a. Move tpm2_read_public() calls into trusted_tpm2.
2b. Pass TPM name to tpm_buf_append_name().
2c. Rework tpm_buf_append_name() to use the pre-resolved name.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
drivers/char/tpm/tpm2-cmd.c | 3 +-
drivers/char/tpm/tpm2-sessions.c | 95 +++++------------
include/linux/tpm.h | 10 +-
security/keys/trusted-keys/trusted_tpm2.c | 124 ++++++++++++++--------
4 files changed, 118 insertions(+), 114 deletions(-)
diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index 543c1c62c938..436ee82620e4 100644
--- a/drivers/char/tpm/tpm2-cmd.c
+++ b/drivers/char/tpm/tpm2-cmd.c
@@ -199,7 +199,8 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
if (!disable_pcr_integrity) {
- rc = tpm_buf_append_name(chip, buf, pcr_idx, NULL);
+ rc = tpm_buf_append_name(chip, buf, pcr_idx, (u8 *)&pcr_idx,
+ sizeof(u32));
if (rc)
return rc;
tpm_buf_append_hmac_session(chip, buf, 0, NULL, 0);
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index a0c88fb1804c..0816a91134fc 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -136,8 +136,8 @@ struct tpm2_auth {
* handle, but they are part of the session by name, which
* we must compute and remember
*/
- u32 name_h[AUTH_MAX_NAMES];
u8 name[AUTH_MAX_NAMES][TPM2_MAX_NAME_SIZE];
+ u16 name_size_tbl[AUTH_MAX_NAMES];
};
#ifdef CONFIG_TCG_TPM2_HMAC
@@ -163,7 +163,17 @@ static int name_size(const u8 *name)
}
}
-static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
+/**
+ * tpm2_read_public: Resolve TPM name for a handle
+ * @chip: TPM chip to use.
+ * @handle: TPM handle.
+ * @name: A buffer for returning the name blob. Must have a
+ * capacity of 'SHA512_DIGET_SIZE + 2' bytes at minimum
+ *
+ * Returns size of TPM handle name of success.
+ * Returns tpm_transmit_cmd error codes when TPM2_ReadPublic fails.
+ */
+int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
{
u32 mso = tpm2_handle_mso(handle);
off_t offset = TPM_HEADER_SIZE;
@@ -212,14 +222,16 @@ static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
memcpy(name, &buf->data[offset], rc);
return name_size_alg;
}
+EXPORT_SYMBOL_GPL(tpm2_read_public);
#endif /* CONFIG_TCG_TPM2_HMAC */
/**
- * 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)
+ * tpm_buf_append_name() - Append a handle and store TPM name
+ * @chip: TPM chip to use.
+ * @buf: TPM buffer containing the TPM command in-transit.
+ * @handle: TPM handle to be appended.
+ * @name: TPM name of the handle
+ * @name_size: Size of the TPM name.
*
* In order to compute session HMACs, we need to know the names of the
* objects pointed to by the handles. For most objects, this is simply
@@ -236,15 +248,14 @@ static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
* will be caused by an incorrect programming model and indicated by a
* kernel message.
*
- * Ends the authorization session on failure.
+ * Returns zero on success.
+ * Returns -EIO when the authorization area state is malformed.
*/
int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
- u32 handle, u8 *name)
+ u32 handle, u8 *name, u16 name_size)
{
#ifdef CONFIG_TCG_TPM2_HMAC
- enum tpm2_mso_type mso = tpm2_handle_mso(handle);
struct tpm2_auth *auth;
- u16 name_size_alg;
int slot;
int ret;
#endif
@@ -269,36 +280,15 @@ int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
}
tpm_buf_append_u32(buf, handle);
auth->session += 4;
-
- if (mso == TPM2_MSO_PERSISTENT ||
- mso == TPM2_MSO_VOLATILE ||
- mso == TPM2_MSO_NVRAM) {
- if (!name) {
- ret = tpm2_read_public(chip, handle, auth->name[slot]);
- if (ret < 0)
- goto err;
-
- name_size_alg = ret;
- }
- } else {
- if (name) {
- dev_err(&chip->dev, "handle 0x%08x does not use a name\n",
- handle);
- ret = -EIO;
- goto err;
- }
- }
-
- auth->name_h[slot] = handle;
- if (name)
- memcpy(auth->name[slot], name, name_size_alg);
+ memcpy(auth->name[slot], name, name_size);
+ auth->name_size_tbl[slot] = name_size;
#endif
return 0;
#ifdef CONFIG_TCG_TPM2_HMAC
err:
tpm2_end_auth_session(chip);
- return tpm_ret_to_err(ret);
+ return ret;
#endif
}
EXPORT_SYMBOL_GPL(tpm_buf_append_name);
@@ -606,22 +596,8 @@ int tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)
attrs = chip->cc_attrs_tbl[i];
handles = (attrs >> TPM2_CC_ATTR_CHANDLES) & GENMASK(2, 0);
+ offset_s += handles * sizeof(u32);
- /*
- * just check the names, it's easy to make mistakes. This
- * would happen if someone added a handle via
- * tpm_buf_append_u32() instead of tpm_buf_append_name()
- */
- for (i = 0; i < handles; i++) {
- u32 handle = tpm_buf_read_u32(buf, &offset_s);
-
- if (auth->name_h[i] != handle) {
- dev_err(&chip->dev, "invalid handle 0x%08x\n", handle);
- ret = -EIO;
- goto err;
- }
- }
- /* point offset_s to the start of the sessions */
val = tpm_buf_read_u32(buf, &offset_s);
/* point offset_p to the start of the parameters */
offset_p = offset_s + val;
@@ -682,23 +658,8 @@ int tpm_buf_fill_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf)
/* ordinal is already BE */
sha256_update(&sctx, (u8 *)&head->ordinal, sizeof(head->ordinal));
/* add the handle names */
- for (i = 0; i < handles; i++) {
- enum tpm2_mso_type mso = tpm2_handle_mso(auth->name_h[i]);
-
- if (mso == TPM2_MSO_PERSISTENT ||
- mso == TPM2_MSO_VOLATILE ||
- mso == TPM2_MSO_NVRAM) {
- ret = name_size(auth->name[i]);
- if (ret < 0)
- goto err;
-
- sha256_update(&sctx, auth->name[i], ret);
- } else {
- __be32 h = cpu_to_be32(auth->name_h[i]);
-
- sha256_update(&sctx, (u8 *)&h, 4);
- }
- }
+ for (i = 0; i < handles; i++)
+ sha256_update(&sctx, auth->name[i], auth->name_size_tbl[i]);
if (offset_s != tpm_buf_length(buf))
sha256_update(&sctx, &buf->data[offset_s],
tpm_buf_length(buf) - offset_s);
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 922a43ef23b5..9f684fc7ae04 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -543,7 +543,7 @@ static inline struct tpm2_auth *tpm2_chip_auth(struct tpm_chip *chip)
}
int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
- u32 handle, u8 *name);
+ u32 handle, u8 *name, u16 name_size);
void tpm_buf_append_hmac_session(struct tpm_chip *chip, struct tpm_buf *buf,
u8 attributes, u8 *passphrase,
int passphraselen);
@@ -557,6 +557,7 @@ int 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);
+int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name);
#else
#include <linux/unaligned.h>
@@ -580,6 +581,13 @@ static inline int tpm_buf_check_hmac_response(struct tpm_chip *chip,
{
return rc;
}
+
+static inline int tpm2_read_public(struct tpm_chip *chip, u32 handle,
+ void *name)
+{
+ memcpy(name, &handle, sizeof(u32));
+ return sizeof(u32);
+}
#endif /* CONFIG_TCG_TPM2_HMAC */
#endif
diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index 27424e1a4a63..63539b344ffb 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -203,7 +203,9 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
struct trusted_key_payload *payload,
struct trusted_key_options *options)
{
+ u8 parent_name[TPM2_MAX_NAME_SIZE];
off_t offset = TPM_HEADER_SIZE;
+ u16 parent_name_size;
int blob_len = 0;
int hash;
u32 flags;
@@ -220,6 +222,12 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
if (rc)
return rc;
+ rc = tpm2_read_public(chip, options->keyhandle, parent_name);
+ if (rc < 0)
+ goto out_put;
+
+ parent_name_size = rc;
+
rc = tpm2_start_auth_session(chip);
if (rc)
goto out_put;
@@ -234,7 +242,8 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
tpm_buf_init(buf, TPM_BUFSIZE);
tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
- rc = tpm_buf_append_name(chip, buf, options->keyhandle, NULL);
+ rc = tpm_buf_append_name(chip, buf, options->keyhandle, parent_name,
+ parent_name_size);
if (rc)
goto out_put;
@@ -326,48 +335,38 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
}
/**
- * tpm2_load_cmd() - execute a TPM2_Load command
- *
- * @chip: TPM chip to use
- * @payload: the key data in clear and encrypted form
- * @options: authentication values and other options
- * @blob_handle: returned blob handle
+ * tpm2_load_cmd() - Execute TPM2_Load
+ * @chip: TPM chip to use.
+ * @payload: Key data in clear text.
+ * @options: Trusted key options.
+ * @parent_name: A cryptographic name, i.e. a TPMT_HA blob, of the
+ * parent key.
+ * @blob: The decoded payload for the key.
+ * @blob_handle: On success, will contain handle to the loaded keyedhash
+ * blob.
*
- * Return: 0 on success.
- * -E2BIG on wrong payload size.
- * -EPERM on tpm error status.
- * < 0 error from tpm_send.
+ * Return -E2BIG when the blob size is too small for all the data.
+ * Returns tpm_transmit_cmd() error codes when either TPM2_Load fails.
*/
static int tpm2_load_cmd(struct tpm_chip *chip,
struct trusted_key_payload *payload,
struct trusted_key_options *options,
+ u8 *parent_name,
+ u16 parent_name_size,
+ const u8 *blob,
u32 *blob_handle)
{
u8 *blob_ref __free(kfree) = NULL;
unsigned int private_len;
unsigned int public_len;
unsigned int blob_len;
- u8 *blob, *pub;
+ const u8 *pub;
int rc;
u32 attrs;
- rc = tpm2_key_decode(payload, options, &blob);
- if (rc) {
- /* old form */
- blob = payload->blob;
- payload->old_format = 1;
- } else {
- /* Bind for cleanup: */
- blob_ref = blob;
- }
-
- /* new format carries keyhandle but old format doesn't */
- if (!options->keyhandle)
- return -EINVAL;
-
/* must be big enough for at least the two be16 size counts */
if (payload->blob_len < 4)
- return -EINVAL;
+ return -E2BIG;
private_len = get_unaligned_be16(blob);
@@ -406,7 +405,8 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
tpm_buf_init(buf, TPM_BUFSIZE);
tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
- rc = tpm_buf_append_name(chip, buf, options->keyhandle, NULL);
+ rc = tpm_buf_append_name(chip, buf, options->keyhandle, parent_name,
+ parent_name_size);
if (rc)
return rc;
@@ -434,20 +434,23 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
}
/**
- * tpm2_unseal_cmd() - execute a TPM2_Unload command
+ * tpm2_unseal_cmd() - Execute TPM2_Unload
*
- * @chip: TPM chip to use
- * @payload: the key data in clear and encrypted form
- * @options: authentication values and other options
- * @blob_handle: blob handle
+ * @chip: TPM chip to use
+ * @payload: Key data in clear text.
+ * @options: Trusted key options.
+ * @parent_name: A cryptographic name, i.e. a TPMT_HA blob, of the
+ * parent key.
+ * @blob_handle: Handle to the loaded keyedhash blob.
*
- * Return: 0 on success
- * -EPERM on tpm error status
- * < 0 error from tpm_send
+ * Return -E2BIG when the blob size is too small for all the data.
+ * Returns tpm_transmit_cmd() error codes when either TPM2_Load fails.
*/
static int tpm2_unseal_cmd(struct tpm_chip *chip,
struct trusted_key_payload *payload,
struct trusted_key_options *options,
+ u8 *parent_name,
+ u16 parent_name_size,
u32 blob_handle)
{
u16 data_len;
@@ -465,7 +468,8 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
tpm_buf_init(buf, TPM_BUFSIZE);
tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
- rc = tpm_buf_append_name(chip, buf, options->keyhandle, NULL);
+ rc = tpm_buf_append_name(chip, buf, options->keyhandle, parent_name,
+ parent_name_size);
if (rc)
return rc;
@@ -526,30 +530,60 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
}
/**
- * tpm2_unseal_trusted() - unseal the payload of a trusted key
+ * tpm2_unseal_trusted() - Unseal a trusted key
+ * @chip: TPM chip to use.
+ * @payload: Key data in clear text.
+ * @options: Trusted key options.
*
- * @chip: TPM chip to use
- * @payload: the key data in clear and encrypted form
- * @options: authentication values and other options
- *
- * Return: Same as with tpm_send.
+ * Return -E2BIG when the blob size is too small for all the data.
+ * Return -EINVAL when parent's key handle has not been set.
+ * Returns tpm_transmit_cmd() error codes when either TPM2_Load or TPM2_Unseal
+ * fails.
*/
int tpm2_unseal_trusted(struct tpm_chip *chip,
struct trusted_key_payload *payload,
struct trusted_key_options *options)
{
+ u8 *blob_ref __free(kfree) = NULL;
+ u8 parent_name[TPM2_MAX_NAME_SIZE];
+ u16 parent_name_size;
u32 blob_handle;
+ u8 *blob;
int rc;
+ /*
+ * Try to decode the provided blob as an ASN.1 blob. Assume that the
+ * blob is in the legacy format if decoding does not end successfully.
+ */
+ rc = tpm2_key_decode(payload, options, &blob);
+ if (rc) {
+ blob = payload->blob;
+ payload->old_format = 1;
+ } else {
+ blob_ref = blob;
+ }
+
+ if (!options->keyhandle)
+ return -EINVAL;
+
rc = tpm_try_get_ops(chip);
if (rc)
return rc;
- rc = tpm2_load_cmd(chip, payload, options, &blob_handle);
+ rc = tpm2_read_public(chip, options->keyhandle, parent_name);
+ if (rc < 0)
+ goto out;
+
+ parent_name_size = rc;
+
+ rc = tpm2_load_cmd(chip, payload, options, parent_name,
+ parent_name_size, blob, &blob_handle);
if (rc)
goto out;
- rc = tpm2_unseal_cmd(chip, payload, options, blob_handle);
+ rc = tpm2_unseal_cmd(chip, payload, options, parent_name,
+ parent_name_size, blob_handle);
+
tpm2_flush_context(chip, blob_handle);
out:
--
2.39.5
^ permalink raw reply related
* [PATCH v5 06/12] tpm-buf: Implement managed allocations
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Stefan Berger, Peter Huewe,
Jarkko Sakkinen, Jason Gunthorpe, David Howells, Paul Moore,
James Morris, Serge E. Hallyn, James Bottomley, Mimi Zohar,
open list, open list:KEYS/KEYRINGS, open list:SECURITY SUBSYSTEM
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
From: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Decouple kzalloc from buffer creation, so that a managed allocation can be
used:
struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUFSIZE,
GFP_KERNEL);
if (!buf)
return -ENOMEM;
tpm_buf_init(buf, TPM_BUFSIZE);
Alternatively, stack allocations are also possible:
u8 buf_data[512];
struct tpm_buf *buf = (struct tpm_buf *)buf_data;
tpm_buf_init(buf, sizeof(buf_data));
This is achieved by embedding buffer's header inside the allocated blob,
instead of having an outer wrapper.
Cc: Ross Philipson <ross.philipson@oracle.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
---
drivers/char/tpm/tpm-buf.c | 124 +++++----
drivers/char/tpm/tpm-sysfs.c | 21 +-
drivers/char/tpm/tpm.h | 1 -
drivers/char/tpm/tpm1-cmd.c | 166 +++++-------
drivers/char/tpm/tpm2-cmd.c | 311 ++++++++++------------
drivers/char/tpm/tpm2-sessions.c | 142 +++++-----
drivers/char/tpm/tpm2-space.c | 44 ++-
drivers/char/tpm/tpm_vtpm_proxy.c | 30 +--
include/linux/tpm.h | 20 +-
security/keys/trusted-keys/trusted_tpm1.c | 36 +--
security/keys/trusted-keys/trusted_tpm2.c | 173 ++++++------
11 files changed, 506 insertions(+), 562 deletions(-)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 1b9dee0d0681..73be8a87b472 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -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_BUFSIZE) {
+ WARN(1, "%s: size overflow: %u\n", __func__, buf_size);
+ buf->flags |= TPM_BUF_INVALID;
+ }
+ } 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_INVALID;
+ }
+ }
}
-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_INVALID)
+ 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_INVALID)
+ 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
@@ -90,8 +117,11 @@ EXPORT_SYMBOL_GPL(tpm_buf_destroy);
*
* Return: The number of bytes consumed by the buffer
*/
-u32 tpm_buf_length(struct tpm_buf *buf)
+u16 tpm_buf_length(struct tpm_buf *buf)
{
+ if (buf->flags & TPM_BUF_INVALID)
+ return 0;
+
return buf->length;
}
EXPORT_SYMBOL_GPL(tpm_buf_length);
@@ -104,10 +134,12 @@ EXPORT_SYMBOL_GPL(tpm_buf_length);
*/
void tpm_buf_append(struct tpm_buf *buf, const u8 *new_data, u16 new_length)
{
+ u32 total_length = (u32)buf->length + (u32)new_length;
+
if (buf->flags & TPM_BUF_INVALID)
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_INVALID;
return;
diff --git a/drivers/char/tpm/tpm-sysfs.c b/drivers/char/tpm/tpm-sysfs.c
index 4a6a27ee295d..0f321c307bc6 100644
--- a/drivers/char/tpm/tpm-sysfs.c
+++ b/drivers/char/tpm/tpm-sysfs.c
@@ -32,28 +32,29 @@ 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(TPM_BUFSIZE, 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_BUFSIZE);
+ 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,
- "attempting to read the PUBEK"))
- goto out_buf;
+ if (tpm_transmit_cmd(chip, tpm_buf, READ_PUBEK_RESULT_MIN_BODY_SIZE, "TPM_ReadPubek"))
+ 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 +72,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;
diff --git a/drivers/char/tpm/tpm.h b/drivers/char/tpm/tpm.h
index 02c07fef41ba..5395927c62fc 100644
--- a/drivers/char/tpm/tpm.h
+++ b/drivers/char/tpm/tpm.h
@@ -32,7 +32,6 @@
#endif
#define TPM_MINOR 224 /* officially assigned */
-#define TPM_BUFSIZE 4096
#define TPM_NUM_DEVICES 65536
#define TPM_RETRY 50
diff --git a/drivers/char/tpm/tpm1-cmd.c b/drivers/char/tpm/tpm1-cmd.c
index b49a790f1bd5..11090053ef54 100644
--- a/drivers/char/tpm/tpm1-cmd.c
+++ b/drivers/char/tpm/tpm1-cmd.c
@@ -323,20 +323,14 @@ unsigned long tpm1_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal)
*/
static int tpm1_startup(struct tpm_chip *chip)
{
- struct tpm_buf buf;
- int rc;
-
- dev_info(&chip->dev, "starting up the TPM manually\n");
-
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_STARTUP);
- if (rc < 0)
- return rc;
-
- tpm_buf_append_u16(&buf, TPM_ST_CLEAR);
-
- rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to start the TPM");
- tpm_buf_destroy(&buf);
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_STARTUP);
+ tpm_buf_append_u16(buf, TPM_ST_CLEAR);
+ return tpm_transmit_cmd(chip, buf, 0, "TPM_Startup");
}
int tpm1_get_timeouts(struct tpm_chip *chip)
@@ -463,50 +457,47 @@ int tpm1_get_timeouts(struct tpm_chip *chip)
int tpm1_pcr_extend(struct tpm_chip *chip, u32 pcr_idx, const u8 *hash,
const char *log_msg)
{
- struct tpm_buf buf;
- int rc;
-
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_PCR_EXTEND);
- if (rc)
- return rc;
-
- tpm_buf_append_u32(&buf, pcr_idx);
- tpm_buf_append(&buf, hash, TPM_DIGEST_SIZE);
-
- rc = tpm_transmit_cmd(chip, &buf, TPM_DIGEST_SIZE, log_msg);
- tpm_buf_destroy(&buf);
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_PCR_EXTEND);
+ tpm_buf_append_u32(buf, pcr_idx);
+ tpm_buf_append(buf, hash, TPM_DIGEST_SIZE);
+ return tpm_transmit_cmd(chip, buf, TPM_DIGEST_SIZE, log_msg);
}
#define TPM_ORD_GET_CAP 101
ssize_t tpm1_getcap(struct tpm_chip *chip, u32 subcap_id, cap_t *cap,
const char *desc, size_t min_cap_length)
{
- struct tpm_buf buf;
int rc;
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_GET_CAP);
- if (rc)
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_GET_CAP);
if (subcap_id == TPM_CAP_VERSION_1_1 ||
subcap_id == TPM_CAP_VERSION_1_2) {
- tpm_buf_append_u32(&buf, subcap_id);
- tpm_buf_append_u32(&buf, 0);
+ tpm_buf_append_u32(buf, subcap_id);
+ tpm_buf_append_u32(buf, 0);
} else {
if (subcap_id == TPM_CAP_FLAG_PERM ||
subcap_id == TPM_CAP_FLAG_VOL)
- tpm_buf_append_u32(&buf, TPM_CAP_FLAG);
+ tpm_buf_append_u32(buf, TPM_CAP_FLAG);
else
- tpm_buf_append_u32(&buf, TPM_CAP_PROP);
+ tpm_buf_append_u32(buf, TPM_CAP_PROP);
- tpm_buf_append_u32(&buf, 4);
- tpm_buf_append_u32(&buf, subcap_id);
+ tpm_buf_append_u32(buf, 4);
+ tpm_buf_append_u32(buf, subcap_id);
}
- rc = tpm_transmit_cmd(chip, &buf, min_cap_length, desc);
+ rc = tpm_transmit_cmd(chip, buf, min_cap_length, desc);
if (!rc)
- *cap = *(cap_t *)&buf.data[TPM_HEADER_SIZE + 4];
- tpm_buf_destroy(&buf);
+ *cap = *(cap_t *)&buf->data[TPM_HEADER_SIZE + 4];
return rc;
}
EXPORT_SYMBOL_GPL(tpm1_getcap);
@@ -531,81 +522,69 @@ int tpm1_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
{
struct tpm1_get_random_out *out;
u32 num_bytes = min_t(u32, max, TPM_MAX_RNG_DATA);
- struct tpm_buf buf;
u32 total = 0;
int retries = 5;
u32 recd;
int rc;
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_GET_RANDOM);
- if (rc)
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+ tpm_buf_init(buf, TPM_BUFSIZE);
do {
- tpm_buf_append_u32(&buf, num_bytes);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_GET_RANDOM);
+ tpm_buf_append_u32(buf, num_bytes);
- rc = tpm_transmit_cmd(chip, &buf, sizeof(out->rng_data_len),
- "attempting get random");
+ rc = tpm_transmit_cmd(chip, buf, sizeof(out->rng_data_len), "TPM_GetRandom");
if (rc) {
if (rc > 0)
rc = -EIO;
- goto out;
+ return rc;
}
- out = (struct tpm1_get_random_out *)&buf.data[TPM_HEADER_SIZE];
+ out = (struct tpm1_get_random_out *)&buf->data[TPM_HEADER_SIZE];
recd = be32_to_cpu(out->rng_data_len);
- if (recd > num_bytes) {
- rc = -EFAULT;
- goto out;
- }
+ if (recd > num_bytes)
+ return -EFAULT;
+
+ if (buf->length < TPM_HEADER_SIZE +
+ sizeof(out->rng_data_len) + recd)
+ return -EFAULT;
- if (tpm_buf_length(&buf) < TPM_HEADER_SIZE +
- sizeof(out->rng_data_len) + recd) {
- rc = -EFAULT;
- goto out;
- }
memcpy(dest, out->rng_data, recd);
dest += recd;
total += recd;
num_bytes -= recd;
-
- tpm_buf_reset(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_GET_RANDOM);
} while (retries-- && total < max);
rc = total ? (int)total : -EIO;
-out:
- tpm_buf_destroy(&buf);
return rc;
}
#define TPM_ORD_PCRREAD 21
int tpm1_pcr_read(struct tpm_chip *chip, u32 pcr_idx, u8 *res_buf)
{
- struct tpm_buf buf;
int rc;
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_PCRREAD);
- if (rc)
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
- tpm_buf_append_u32(&buf, pcr_idx);
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_PCRREAD);
+ tpm_buf_append_u32(buf, pcr_idx);
- rc = tpm_transmit_cmd(chip, &buf, TPM_DIGEST_SIZE,
- "attempting to read a pcr value");
+ rc = tpm_transmit_cmd(chip, buf, TPM_DIGEST_SIZE, "TPM_PCRRead");
if (rc)
- goto out;
-
- if (tpm_buf_length(&buf) < TPM_DIGEST_SIZE) {
- rc = -EFAULT;
- goto out;
- }
+ return rc;
- memcpy(res_buf, &buf.data[TPM_HEADER_SIZE], TPM_DIGEST_SIZE);
+ if (buf->length < TPM_DIGEST_SIZE)
+ return -EFAULT;
-out:
- tpm_buf_destroy(&buf);
+ memcpy(res_buf, &buf->data[TPM_HEADER_SIZE], TPM_DIGEST_SIZE);
return rc;
}
@@ -619,16 +598,13 @@ int tpm1_pcr_read(struct tpm_chip *chip, u32 pcr_idx, u8 *res_buf)
*/
static int tpm1_continue_selftest(struct tpm_chip *chip)
{
- struct tpm_buf buf;
- int rc;
-
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_CONTINUE_SELFTEST);
- if (rc)
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
- rc = tpm_transmit_cmd(chip, &buf, 0, "continue selftest");
- tpm_buf_destroy(&buf);
- return rc;
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_CONTINUE_SELFTEST);
+ return tpm_transmit_cmd(chip, buf, 0, "TPM_ContinueSelfTest");
}
/**
@@ -742,22 +718,24 @@ int tpm1_auto_startup(struct tpm_chip *chip)
int tpm1_pm_suspend(struct tpm_chip *chip, u32 tpm_suspend_pcr)
{
u8 dummy_hash[TPM_DIGEST_SIZE] = { 0 };
- struct tpm_buf buf;
unsigned int try;
int rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
/* for buggy tpm, flush pcrs with extend to selected dummy */
if (tpm_suspend_pcr)
rc = tpm1_pcr_extend(chip, tpm_suspend_pcr, dummy_hash,
"extending dummy pcr before suspend");
- rc = tpm_buf_init(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_SAVESTATE);
- if (rc)
- return rc;
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_SAVESTATE);
+
/* now do the actual savestate */
for (try = 0; try < TPM_RETRY; try++) {
- rc = tpm_transmit_cmd(chip, &buf, 0, NULL);
+ rc = tpm_transmit_cmd(chip, buf, 0, NULL);
/*
* If the TPM indicates that it is too busy to respond to
* this command then retry before giving up. It can take
@@ -772,7 +750,7 @@ int tpm1_pm_suspend(struct tpm_chip *chip, u32 tpm_suspend_pcr)
break;
tpm_msleep(TPM_TIMEOUT_RETRY);
- tpm_buf_reset(&buf, TPM_TAG_RQU_COMMAND, TPM_ORD_SAVESTATE);
+ tpm_buf_reset(buf, TPM_TAG_RQU_COMMAND, TPM_ORD_SAVESTATE);
}
if (rc)
@@ -782,8 +760,6 @@ int tpm1_pm_suspend(struct tpm_chip *chip, u32 tpm_suspend_pcr)
dev_warn(&chip->dev, "TPM savestate took %dms\n",
try * TPM_TIMEOUT_RETRY);
- tpm_buf_destroy(&buf);
-
return rc;
}
diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index 82076b6cfcf7..543c1c62c938 100644
--- a/drivers/char/tpm/tpm2-cmd.c
+++ b/drivers/char/tpm/tpm2-cmd.c
@@ -119,12 +119,15 @@ int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
{
int i;
int rc;
- struct tpm_buf buf;
struct tpm2_pcr_read_out *out;
u8 pcr_select[TPM2_PCR_SELECT_MIN] = {0};
u16 digest_size;
u16 expected_digest_size = 0;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
if (pcr_idx >= TPM2_PLATFORM_PCR)
return -EINVAL;
@@ -139,36 +142,31 @@ int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
expected_digest_size = chip->allocated_banks[i].digest_size;
}
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_PCR_READ);
- if (rc)
- return rc;
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_PCR_READ);
pcr_select[pcr_idx >> 3] = 1 << (pcr_idx & 0x7);
- tpm_buf_append_u32(&buf, 1);
- tpm_buf_append_u16(&buf, digest->alg_id);
- tpm_buf_append_u8(&buf, TPM2_PCR_SELECT_MIN);
- tpm_buf_append(&buf, (const unsigned char *)pcr_select,
+ tpm_buf_append_u32(buf, 1);
+ tpm_buf_append_u16(buf, digest->alg_id);
+ tpm_buf_append_u8(buf, TPM2_PCR_SELECT_MIN);
+ tpm_buf_append(buf, (const unsigned char *)pcr_select,
sizeof(pcr_select));
- rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to read a pcr value");
+ rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_PCR_Read");
if (rc)
- goto out;
+ return rc;
- out = (struct tpm2_pcr_read_out *)&buf.data[TPM_HEADER_SIZE];
+ out = (struct tpm2_pcr_read_out *)&buf->data[TPM_HEADER_SIZE];
digest_size = be16_to_cpu(out->digest_size);
if (digest_size > sizeof(digest->digest) ||
- (!digest_size_ptr && digest_size != expected_digest_size)) {
- rc = -EINVAL;
- goto out;
- }
+ (!digest_size_ptr && digest_size != expected_digest_size))
+ return rc;
if (digest_size_ptr)
*digest_size_ptr = digest_size;
memcpy(digest->digest, out->digest, digest_size);
-out:
- tpm_buf_destroy(&buf);
return rc;
}
@@ -184,56 +182,52 @@ int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
struct tpm_digest *digests)
{
- struct tpm_buf buf;
int rc;
int i;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
if (!disable_pcr_integrity) {
rc = tpm2_start_auth_session(chip);
if (rc)
return rc;
}
- rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
- if (rc) {
- if (!disable_pcr_integrity)
- tpm2_end_auth_session(chip);
- return rc;
- }
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
if (!disable_pcr_integrity) {
- rc = tpm_buf_append_name(chip, &buf, pcr_idx, NULL);
- if (rc) {
- tpm_buf_destroy(&buf);
+ rc = tpm_buf_append_name(chip, buf, pcr_idx, NULL);
+ if (rc)
return rc;
- }
- tpm_buf_append_hmac_session(chip, &buf, 0, NULL, 0);
+ tpm_buf_append_hmac_session(chip, buf, 0, NULL, 0);
} else {
- tpm_buf_append_handle(&buf, pcr_idx);
- tpm_buf_append_auth(chip, &buf, NULL, 0);
+ tpm_buf_append_handle(buf, pcr_idx);
+ tpm_buf_append_auth(chip, buf, NULL, 0);
}
- tpm_buf_append_u32(&buf, chip->nr_allocated_banks);
+ tpm_buf_append_u32(buf, chip->nr_allocated_banks);
for (i = 0; i < chip->nr_allocated_banks; i++) {
- tpm_buf_append_u16(&buf, digests[i].alg_id);
- tpm_buf_append(&buf, (const unsigned char *)&digests[i].digest,
+ tpm_buf_append_u16(buf, digests[i].alg_id);
+ tpm_buf_append(buf, (const unsigned char *)&digests[i].digest,
chip->allocated_banks[i].digest_size);
}
+ if (buf->flags & TPM_BUF_INVALID)
+ return -EINVAL;
if (!disable_pcr_integrity) {
- rc = tpm_buf_fill_hmac_session(chip, &buf);
- if (rc) {
- tpm_buf_destroy(&buf);
+ rc = tpm_buf_fill_hmac_session(chip, buf);
+ if (rc)
return rc;
- }
}
- rc = tpm_transmit_cmd(chip, &buf, 0, "attempting extend a PCR value");
- if (!disable_pcr_integrity)
- rc = tpm_buf_check_hmac_response(chip, &buf, rc);
+ rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_PCR_Extend");
- tpm_buf_destroy(&buf);
+ if (!disable_pcr_integrity)
+ rc = tpm_buf_check_hmac_response(chip, buf, rc);
return rc;
}
@@ -258,7 +252,6 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
{
struct tpm2_get_random_out *out;
struct tpm_header *head;
- struct tpm_buf buf;
u32 recd;
u32 num_bytes = max;
int err;
@@ -270,56 +263,53 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
if (!num_bytes || max > TPM_MAX_RNG_DATA)
return -EINVAL;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
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;
- }
-
+ tpm_buf_init(buf, TPM_BUFSIZE);
do {
- tpm_buf_reset(&buf, TPM2_ST_SESSIONS, TPM2_CC_GET_RANDOM);
+ tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_GET_RANDOM);
if (tpm2_chip_auth(chip)) {
- tpm_buf_append_hmac_session(chip, &buf,
+ tpm_buf_append_hmac_session(chip, buf,
TPM2_SA_ENCRYPT |
TPM2_SA_CONTINUE_SESSION,
NULL, 0);
} else {
- offset = buf.handles * 4 + TPM_HEADER_SIZE;
- head = (struct tpm_header *)buf.data;
- if (tpm_buf_length(&buf) == offset)
+ offset = buf->handles * 4 + TPM_HEADER_SIZE;
+ head = (struct tpm_header *)buf->data;
+ if (tpm_buf_length(buf) == offset)
head->tag = cpu_to_be16(TPM2_ST_NO_SESSIONS);
}
- tpm_buf_append_u16(&buf, num_bytes);
- err = tpm_buf_fill_hmac_session(chip, &buf);
- if (err) {
- tpm_buf_destroy(&buf);
+ tpm_buf_append_u16(buf, num_bytes);
+ err = tpm_buf_fill_hmac_session(chip, buf);
+ if (err)
return err;
- }
- err = tpm_transmit_cmd(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);
+ "TPM2_GetRandom");
+ err = tpm_buf_check_hmac_response(chip, buf, err);
if (err) {
if (err > 0)
err = -EIO;
goto out;
}
- head = (struct tpm_header *)buf.data;
+ head = (struct tpm_header *)buf->data;
offset = TPM_HEADER_SIZE;
/* Skip the parameter size field: */
if (be16_to_cpu(head->tag) == TPM2_ST_SESSIONS)
offset += 4;
- out = (struct tpm2_get_random_out *)&buf.data[offset];
+ out = (struct tpm2_get_random_out *)&buf->data[offset];
recd = min_t(u32, be16_to_cpu(out->size), num_bytes);
- if (tpm_buf_length(&buf) <
+ if (tpm_buf_length(buf) <
TPM_HEADER_SIZE +
offsetof(struct tpm2_get_random_out, buffer) +
recd) {
@@ -333,11 +323,8 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
num_bytes -= recd;
} while (retries-- && total < max);
- tpm_buf_destroy(&buf);
-
return total ? total : -EIO;
out:
- tpm_buf_destroy(&buf);
tpm2_end_auth_session(chip);
return err;
}
@@ -349,20 +336,18 @@ int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
*/
void tpm2_flush_context(struct tpm_chip *chip, u32 handle)
{
- struct tpm_buf buf;
- int rc;
-
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_FLUSH_CONTEXT);
- if (rc) {
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf) {
dev_warn(&chip->dev, "0x%08x was not flushed, out of memory\n",
handle);
return;
}
- tpm_buf_append_u32(&buf, handle);
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_FLUSH_CONTEXT);
+ tpm_buf_append_u32(buf, handle);
- tpm_transmit_cmd(chip, &buf, 0, "flushing context");
- tpm_buf_destroy(&buf);
+ tpm_transmit_cmd(chip, buf, 0, "TPM2_FlushContext");
}
EXPORT_SYMBOL_GPL(tpm2_flush_context);
@@ -389,19 +374,20 @@ ssize_t tpm2_get_tpm_pt(struct tpm_chip *chip, u32 property_id, u32 *value,
const char *desc)
{
struct tpm2_get_cap_out *out;
- struct tpm_buf buf;
int rc;
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
- if (rc)
- return rc;
- tpm_buf_append_u32(&buf, TPM2_CAP_TPM_PROPERTIES);
- tpm_buf_append_u32(&buf, property_id);
- tpm_buf_append_u32(&buf, 1);
- rc = tpm_transmit_cmd(chip, &buf, 0, NULL);
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
+ tpm_buf_append_u32(buf, TPM2_CAP_TPM_PROPERTIES);
+ tpm_buf_append_u32(buf, property_id);
+ tpm_buf_append_u32(buf, 1);
+ rc = tpm_transmit_cmd(chip, buf, 0, NULL);
if (!rc) {
- out = (struct tpm2_get_cap_out *)
- &buf.data[TPM_HEADER_SIZE];
+ out = (struct tpm2_get_cap_out *)&buf->data[TPM_HEADER_SIZE];
/*
* To prevent failing boot up of some systems, Infineon TPM2.0
* returns SUCCESS on TPM2_Startup in field upgrade mode. Also
@@ -413,7 +399,6 @@ ssize_t tpm2_get_tpm_pt(struct tpm_chip *chip, u32 property_id, u32 *value,
else
rc = -ENODATA;
}
- tpm_buf_destroy(&buf);
return rc;
}
EXPORT_SYMBOL_GPL(tpm2_get_tpm_pt);
@@ -430,15 +415,14 @@ EXPORT_SYMBOL_GPL(tpm2_get_tpm_pt);
*/
void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
{
- struct tpm_buf buf;
- int rc;
-
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SHUTDOWN);
- if (rc)
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
return;
- tpm_buf_append_u16(&buf, shutdown_type);
- tpm_transmit_cmd(chip, &buf, 0, "stopping the TPM");
- tpm_buf_destroy(&buf);
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SHUTDOWN);
+ tpm_buf_append_u16(buf, shutdown_type);
+ tpm_transmit_cmd(chip, buf, 0, "TPM2_Shutdown");
}
/**
@@ -456,20 +440,19 @@ void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
*/
static int tpm2_do_selftest(struct tpm_chip *chip)
{
- struct tpm_buf buf;
int full;
int rc;
- for (full = 0; full < 2; full++) {
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
- if (rc)
- return rc;
-
- tpm_buf_append_u8(&buf, full);
- rc = tpm_transmit_cmd(chip, &buf, 0,
- "attempting the self test");
- tpm_buf_destroy(&buf);
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
+ for (full = 0; full < 2; full++) {
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
+ tpm_buf_append_u8(buf, full);
+ rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_SelfTest");
if (rc == TPM2_RC_TESTING)
rc = TPM2_RC_SUCCESS;
if (rc == TPM2_RC_INITIALIZE || rc == TPM2_RC_SUCCESS)
@@ -494,23 +477,24 @@ static int tpm2_do_selftest(struct tpm_chip *chip)
int tpm2_probe(struct tpm_chip *chip)
{
struct tpm_header *out;
- struct tpm_buf buf;
int rc;
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
- if (rc)
- return rc;
- tpm_buf_append_u32(&buf, TPM2_CAP_TPM_PROPERTIES);
- tpm_buf_append_u32(&buf, TPM_PT_TOTAL_COMMANDS);
- tpm_buf_append_u32(&buf, 1);
- rc = tpm_transmit_cmd(chip, &buf, 0, NULL);
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
+ tpm_buf_append_u32(buf, TPM2_CAP_TPM_PROPERTIES);
+ tpm_buf_append_u32(buf, TPM_PT_TOTAL_COMMANDS);
+ tpm_buf_append_u32(buf, 1);
+ rc = tpm_transmit_cmd(chip, buf, 0, NULL);
/* We ignore TPM return codes on purpose. */
if (rc >= 0) {
- out = (struct tpm_header *)buf.data;
+ out = (struct tpm_header *)buf->data;
if (be16_to_cpu(out->tag) == TPM2_ST_NO_SESSIONS)
chip->flags |= TPM_CHIP_FLAG_TPM2;
}
- tpm_buf_destroy(&buf);
return 0;
}
EXPORT_SYMBOL_GPL(tpm2_probe);
@@ -550,7 +534,6 @@ struct tpm2_pcr_selection {
ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
{
struct tpm2_pcr_selection pcr_selection;
- struct tpm_buf buf;
void *marker;
void *end;
void *pcr_select_offset;
@@ -562,39 +545,37 @@ ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
int rc;
int i = 0;
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
- if (rc)
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
- tpm_buf_append_u32(&buf, TPM2_CAP_PCRS);
- tpm_buf_append_u32(&buf, 0);
- tpm_buf_append_u32(&buf, 1);
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
+ tpm_buf_append_u32(buf, TPM2_CAP_PCRS);
+ tpm_buf_append_u32(buf, 0);
+ tpm_buf_append_u32(buf, 1);
- rc = tpm_transmit_cmd(chip, &buf, 9, "get tpm pcr allocation");
+ rc = tpm_transmit_cmd(chip, buf, 9, "TPM2_GetCapability(PCRS)");
if (rc)
- goto out;
+ return rc;
- nr_possible_banks = be32_to_cpup(
- (__be32 *)&buf.data[TPM_HEADER_SIZE + 5]);
+ nr_possible_banks = be32_to_cpup((__be32 *)&buf->data[TPM_HEADER_SIZE + 5]);
if (nr_possible_banks > TPM2_MAX_PCR_BANKS) {
pr_err("tpm: out of bank capacity: %u > %u\n",
nr_possible_banks, TPM2_MAX_PCR_BANKS);
- rc = -ENOMEM;
- goto out;
+ return -ENOMEM;
}
- marker = &buf.data[TPM_HEADER_SIZE + 9];
+ marker = &buf->data[TPM_HEADER_SIZE + 9];
- rsp_len = be32_to_cpup((__be32 *)&buf.data[2]);
- end = &buf.data[rsp_len];
+ rsp_len = be32_to_cpup((__be32 *)&buf->data[2]);
+ end = &buf->data[rsp_len];
for (i = 0; i < nr_possible_banks; i++) {
pcr_select_offset = marker +
offsetof(struct tpm2_pcr_selection, size_of_select);
- if (pcr_select_offset >= end) {
- rc = -EFAULT;
- break;
- }
+ if (pcr_select_offset >= end)
+ return -EFAULT;
memcpy(&pcr_selection, marker, sizeof(pcr_selection));
hash_alg = be16_to_cpu(pcr_selection.hash_alg);
@@ -606,7 +587,7 @@ ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
rc = tpm2_init_bank_info(chip, nr_alloc_banks);
if (rc < 0)
- break;
+ return rc;
nr_alloc_banks++;
}
@@ -618,21 +599,21 @@ ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
}
chip->nr_allocated_banks = nr_alloc_banks;
-out:
- tpm_buf_destroy(&buf);
-
- return rc;
+ return 0;
}
int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip)
{
- struct tpm_buf buf;
u32 nr_commands;
__be32 *attrs;
u32 cc;
int i;
int rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
rc = tpm2_get_tpm_pt(chip, TPM_PT_TOTAL_COMMANDS, &nr_commands, NULL);
if (rc)
goto out;
@@ -649,30 +630,24 @@ int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip)
goto out;
}
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
- if (rc)
- goto out;
-
- tpm_buf_append_u32(&buf, TPM2_CAP_COMMANDS);
- tpm_buf_append_u32(&buf, TPM2_CC_FIRST);
- tpm_buf_append_u32(&buf, nr_commands);
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
+ tpm_buf_append_u32(buf, TPM2_CAP_COMMANDS);
+ tpm_buf_append_u32(buf, TPM2_CC_FIRST);
+ tpm_buf_append_u32(buf, nr_commands);
- rc = tpm_transmit_cmd(chip, &buf, 9 + 4 * nr_commands, NULL);
- if (rc) {
- tpm_buf_destroy(&buf);
+ rc = tpm_transmit_cmd(chip, buf, 9 + 4 * nr_commands, NULL);
+ if (rc)
goto out;
- }
- if (nr_commands !=
- be32_to_cpup((__be32 *)&buf.data[TPM_HEADER_SIZE + 5])) {
+ if (nr_commands != be32_to_cpup((__be32 *)&buf->data[TPM_HEADER_SIZE + 5])) {
rc = -EFAULT;
- tpm_buf_destroy(&buf);
goto out;
}
chip->nr_commands = nr_commands;
- attrs = (__be32 *)&buf.data[TPM_HEADER_SIZE + 9];
+ attrs = (__be32 *)&buf->data[TPM_HEADER_SIZE + 9];
for (i = 0; i < nr_commands; i++, attrs++) {
chip->cc_attrs_tbl[i] = be32_to_cpup(attrs);
cc = chip->cc_attrs_tbl[i] & 0xFFFF;
@@ -684,8 +659,6 @@ int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip)
}
}
- tpm_buf_destroy(&buf);
-
out:
if (rc > 0)
rc = -ENODEV;
@@ -706,20 +679,14 @@ EXPORT_SYMBOL_GPL(tpm2_get_cc_attrs_tbl);
static int tpm2_startup(struct tpm_chip *chip)
{
- struct tpm_buf buf;
- int rc;
-
- dev_info(&chip->dev, "starting up the TPM manually\n");
-
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_STARTUP);
- if (rc < 0)
- return rc;
-
- tpm_buf_append_u16(&buf, TPM2_SU_CLEAR);
- rc = tpm_transmit_cmd(chip, &buf, 0, "attempting to start the TPM");
- tpm_buf_destroy(&buf);
-
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_STARTUP);
+ tpm_buf_append_u16(buf, TPM2_SU_CLEAR);
+ return tpm_transmit_cmd(chip, buf, 0, "TPM2_Startup");
}
/**
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 4432f123af97..a0c88fb1804c 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -168,7 +168,6 @@ static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
u32 mso = tpm2_handle_mso(handle);
off_t offset = TPM_HEADER_SIZE;
int rc, name_size_alg;
- struct tpm_buf buf;
if (mso != TPM2_MSO_PERSISTENT && mso != TPM2_MSO_VOLATILE &&
mso != TPM2_MSO_NVRAM) {
@@ -176,47 +175,41 @@ static int tpm2_read_public(struct tpm_chip *chip, u32 handle, void *name)
return sizeof(u32);
}
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
- if (rc)
- return rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
- tpm_buf_append_u32(&buf, handle);
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_READ_PUBLIC);
+ tpm_buf_append_u32(buf, handle);
- rc = tpm_transmit_cmd(chip, &buf, 0, "TPM2_ReadPublic");
- if (rc) {
- tpm_buf_destroy(&buf);
+ rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_ReadPublic");
+ if (rc)
return tpm_ret_to_err(rc);
- }
/* Skip TPMT_PUBLIC: */
- offset += tpm_buf_read_u16(&buf, &offset);
+ offset += tpm_buf_read_u16(buf, &offset);
/*
* Ensure space for the length field of TPM2B_NAME and hashAlg field of
* TPMT_HA (the extra four bytes).
*/
- if (offset + 4 > tpm_buf_length(&buf)) {
- tpm_buf_destroy(&buf);
+ if (offset + 4 > tpm_buf_length(buf))
return -EIO;
- }
- rc = tpm_buf_read_u16(&buf, &offset);
- name_size_alg = name_size(&buf.data[offset]);
+ rc = tpm_buf_read_u16(buf, &offset);
+ name_size_alg = name_size(&buf->data[offset]);
if (name_size_alg < 0)
return name_size_alg;
- if (rc != name_size_alg) {
- tpm_buf_destroy(&buf);
+ if (rc != name_size_alg)
return -EIO;
- }
- if (offset + rc > tpm_buf_length(&buf)) {
- tpm_buf_destroy(&buf);
+ if (offset + rc > tpm_buf_length(buf))
return -EIO;
- }
- memcpy(name, &buf.data[offset], rc);
+ memcpy(name, &buf->data[offset], rc);
return name_size_alg;
}
#endif /* CONFIG_TCG_TPM2_HMAC */
@@ -982,7 +975,6 @@ static int tpm2_load_null(struct tpm_chip *chip, u32 *null_key)
int tpm2_start_auth_session(struct tpm_chip *chip)
{
struct tpm2_auth *auth;
- struct tpm_buf buf;
u32 null_key;
int rc;
@@ -991,6 +983,10 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
return 0;
}
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
auth = kzalloc(sizeof(*auth), GFP_KERNEL);
if (!auth)
return -ENOMEM;
@@ -1001,41 +997,37 @@ int tpm2_start_auth_session(struct tpm_chip *chip)
auth->session = TPM_HEADER_SIZE;
- rc = tpm_buf_init(&buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
- if (rc)
- goto out;
-
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_START_AUTH_SESS);
/* salt key handle */
- tpm_buf_append_u32(&buf, null_key);
+ tpm_buf_append_u32(buf, null_key);
/* bind key handle */
- tpm_buf_append_u32(&buf, TPM2_RH_NULL);
+ 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));
+ 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, auth);
+ tpm_buf_append_salt(buf, chip, auth);
/* session type (HMAC, audit or policy) */
- tpm_buf_append_u8(&buf, TPM2_SE_HMAC);
+ tpm_buf_append_u8(buf, TPM2_SE_HMAC);
/* symmetric encryption parameters */
/* symmetric algorithm */
- tpm_buf_append_u16(&buf, TPM_ALG_AES);
+ tpm_buf_append_u16(buf, TPM_ALG_AES);
/* bits for symmetric algorithm */
- tpm_buf_append_u16(&buf, AES_KEY_BITS);
+ tpm_buf_append_u16(buf, AES_KEY_BITS);
/* symmetric algorithm mode (must be CFB) */
- tpm_buf_append_u16(&buf, TPM_ALG_CFB);
+ tpm_buf_append_u16(buf, TPM_ALG_CFB);
/* hash algorithm for session */
- tpm_buf_append_u16(&buf, TPM_ALG_SHA256);
+ tpm_buf_append_u16(buf, TPM_ALG_SHA256);
- rc = tpm_ret_to_err(tpm_transmit_cmd(chip, &buf, 0, "StartAuthSession"));
+ rc = tpm_ret_to_err(tpm_transmit_cmd(chip, buf, 0, "TPM2_StartAuthSession"));
tpm2_flush_context(chip, null_key);
if (rc == TPM2_RC_SUCCESS)
- rc = tpm2_parse_start_auth_session(auth, &buf);
-
- tpm_buf_destroy(&buf);
+ rc = tpm2_parse_start_auth_session(auth, buf);
if (rc == TPM2_RC_SUCCESS) {
chip->auth = auth;
@@ -1257,18 +1249,18 @@ static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
u32 *handle, u8 *name)
{
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;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
- rc = tpm_buf_init_sized(&template);
- if (rc) {
- tpm_buf_destroy(&buf);
- return rc;
- }
+ struct tpm_buf *template __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!template)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE_PRIMARY);
+ tpm_buf_init_sized(template, TPM_BUFSIZE);
/*
* create the template. Note: in order for userspace to
@@ -1280,75 +1272,71 @@ static int tpm2_create_primary(struct tpm_chip *chip, u32 hierarchy,
*/
/* key type */
- tpm_buf_append_u16(&template, TPM_ALG_ECC);
+ tpm_buf_append_u16(template, TPM_ALG_ECC);
/* name algorithm */
- tpm_buf_append_u16(&template, TPM_ALG_SHA256);
+ tpm_buf_append_u16(template, TPM_ALG_SHA256);
/* object properties */
- tpm_buf_append_u32(&template, TPM2_OA_NULL_KEY);
+ tpm_buf_append_u32(template, TPM2_OA_NULL_KEY);
/* sauth policy (empty) */
- tpm_buf_append_u16(&template, 0);
+ tpm_buf_append_u16(template, 0);
/* BEGIN parameters: key specific; for ECC*/
/* symmetric algorithm */
- tpm_buf_append_u16(&template, TPM_ALG_AES);
+ tpm_buf_append_u16(template, TPM_ALG_AES);
/* bits for symmetric algorithm */
- tpm_buf_append_u16(&template, AES_KEY_BITS);
+ tpm_buf_append_u16(template, AES_KEY_BITS);
/* algorithm mode (must be CFB) */
- tpm_buf_append_u16(&template, TPM_ALG_CFB);
+ tpm_buf_append_u16(template, TPM_ALG_CFB);
/* scheme (NULL means any scheme) */
- tpm_buf_append_u16(&template, TPM_ALG_NULL);
+ tpm_buf_append_u16(template, TPM_ALG_NULL);
/* ECC Curve ID */
- tpm_buf_append_u16(&template, TPM2_ECC_NIST_P256);
+ tpm_buf_append_u16(template, TPM2_ECC_NIST_P256);
/* KDF Scheme */
- tpm_buf_append_u16(&template, TPM_ALG_NULL);
+ tpm_buf_append_u16(template, TPM_ALG_NULL);
/* unique: key specific; for ECC it is two zero size points */
- tpm_buf_append_u16(&template, 0);
- tpm_buf_append_u16(&template, 0);
+ 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);
+ 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);
+ tpm_buf_append_u16(buf, 4);
/* sensitive create auth data (empty) */
- tpm_buf_append_u16(&buf, 0);
+ tpm_buf_append_u16(buf, 0);
/* sensitive create sensitive data (empty) */
- tpm_buf_append_u16(&buf, 0);
+ tpm_buf_append_u16(buf, 0);
/* the public template */
- tpm_buf_append(&buf, template.data, template.length);
- tpm_buf_destroy(&template);
+ tpm_buf_append(buf, template->data, template->length);
/* outside info (empty) */
- tpm_buf_append_u16(&buf, 0);
+ tpm_buf_append_u16(buf, 0);
/* creation PCR (none) */
- tpm_buf_append_u32(&buf, 0);
+ tpm_buf_append_u32(buf, 0);
- rc = tpm_transmit_cmd(chip, &buf, 0,
- "attempting to create NULL primary");
+ rc = tpm_transmit_cmd(chip, buf, 0, "TPM2_CreatePrimary");
if (rc == TPM2_RC_SUCCESS)
- rc = tpm2_parse_create_primary(chip, &buf, handle, hierarchy,
+ rc = tpm2_parse_create_primary(chip, buf, handle, hierarchy,
name);
- tpm_buf_destroy(&buf);
-
return rc;
}
diff --git a/drivers/char/tpm/tpm2-space.c b/drivers/char/tpm/tpm2-space.c
index 60354cd53b5c..cbf86ff5931f 100644
--- a/drivers/char/tpm/tpm2-space.c
+++ b/drivers/char/tpm/tpm2-space.c
@@ -71,24 +71,25 @@ void tpm2_del_space(struct tpm_chip *chip, struct tpm_space *space)
int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
unsigned int *offset, u32 *handle)
{
- struct tpm_buf tbuf;
struct tpm2_context *ctx;
unsigned int body_size;
int rc;
- rc = tpm_buf_init(&tbuf, TPM2_ST_NO_SESSIONS, TPM2_CC_CONTEXT_LOAD);
- if (rc)
- return rc;
+ struct tpm_buf *tbuf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!tbuf)
+ return -ENOMEM;
+
+ tpm_buf_init(tbuf, TPM_BUFSIZE);
+ tpm_buf_reset(tbuf, TPM2_ST_NO_SESSIONS, TPM2_CC_CONTEXT_LOAD);
ctx = (struct tpm2_context *)&buf[*offset];
body_size = sizeof(*ctx) + be16_to_cpu(ctx->blob_size);
- tpm_buf_append(&tbuf, &buf[*offset], body_size);
+ tpm_buf_append(tbuf, &buf[*offset], body_size);
- rc = tpm_transmit_cmd(chip, &tbuf, 4, NULL);
+ rc = tpm_transmit_cmd(chip, tbuf, 4, NULL);
if (rc < 0) {
dev_warn(&chip->dev, "%s: failed with a system error %d\n",
__func__, rc);
- tpm_buf_destroy(&tbuf);
return -EFAULT;
} else if (tpm2_rc_value(rc) == TPM2_RC_HANDLE ||
rc == TPM2_RC_REFERENCE_H0) {
@@ -103,64 +104,55 @@ int tpm2_load_context(struct tpm_chip *chip, u8 *buf,
* flushed outside the space
*/
*handle = 0;
- tpm_buf_destroy(&tbuf);
return -ENOENT;
} else if (tpm2_rc_value(rc) == TPM2_RC_INTEGRITY) {
- tpm_buf_destroy(&tbuf);
return -EINVAL;
} else if (rc > 0) {
dev_warn(&chip->dev, "%s: failed with a TPM error 0x%04X\n",
__func__, rc);
- tpm_buf_destroy(&tbuf);
return -EFAULT;
}
- *handle = be32_to_cpup((__be32 *)&tbuf.data[TPM_HEADER_SIZE]);
+ *handle = be32_to_cpup((__be32 *)&tbuf->data[TPM_HEADER_SIZE]);
*offset += body_size;
-
- tpm_buf_destroy(&tbuf);
return 0;
}
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;
int rc;
- rc = tpm_buf_init(&tbuf, TPM2_ST_NO_SESSIONS, TPM2_CC_CONTEXT_SAVE);
- if (rc)
- return rc;
+ struct tpm_buf *tbuf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!tbuf)
+ return -ENOMEM;
- tpm_buf_append_u32(&tbuf, handle);
+ tpm_buf_init(tbuf, TPM_BUFSIZE);
+ tpm_buf_reset(tbuf, TPM2_ST_NO_SESSIONS, TPM2_CC_CONTEXT_SAVE);
+ tpm_buf_append_u32(tbuf, handle);
- rc = tpm_transmit_cmd(chip, &tbuf, 0, NULL);
+ rc = tpm_transmit_cmd(chip, tbuf, 0, NULL);
if (rc < 0) {
dev_warn(&chip->dev, "%s: failed with a system error %d\n",
__func__, rc);
- tpm_buf_destroy(&tbuf);
return -EFAULT;
} else if (tpm2_rc_value(rc) == TPM2_RC_REFERENCE_H0) {
- tpm_buf_destroy(&tbuf);
return -ENOENT;
} else if (rc) {
dev_warn(&chip->dev, "%s: failed with a TPM error 0x%04X\n",
__func__, rc);
- tpm_buf_destroy(&tbuf);
return -EFAULT;
}
- body_size = tpm_buf_length(&tbuf) - TPM_HEADER_SIZE;
+ body_size = tpm_buf_length(tbuf) - TPM_HEADER_SIZE;
if ((*offset + body_size) > buf_size) {
dev_warn(&chip->dev, "%s: out of backing storage\n", __func__);
- tpm_buf_destroy(&tbuf);
return -ENOMEM;
}
- memcpy(&buf[*offset], &tbuf.data[TPM_HEADER_SIZE], body_size);
+ memcpy(&buf[*offset], &tbuf->data[TPM_HEADER_SIZE], body_size);
*offset += body_size;
- tpm_buf_destroy(&tbuf);
return 0;
}
diff --git a/drivers/char/tpm/tpm_vtpm_proxy.c b/drivers/char/tpm/tpm_vtpm_proxy.c
index 0818bb517805..682dfc93845d 100644
--- a/drivers/char/tpm/tpm_vtpm_proxy.c
+++ b/drivers/char/tpm/tpm_vtpm_proxy.c
@@ -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(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ tpm_buf_init(buf, TPM_BUFSIZE);
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;
}
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index f07376eae4cb..922a43ef23b5 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -25,7 +25,8 @@
#include <crypto/hash_info.h>
#include <crypto/aes.h>
-#define TPM_DIGEST_SIZE 20 /* Max TPM v1.2 PCR size */
+#define TPM_DIGEST_SIZE 20 /* Max TPM v1.2 PCR size */
+#define TPM_BUFSIZE 4096
/*
* SHA-512 is, as of today, the largest digest in the TCG algorithm repository.
@@ -389,13 +390,15 @@ enum tpm_buf_flags {
};
/*
- * 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 {
@@ -426,12 +429,11 @@ 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);
+u16 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);
void tpm_buf_append_u16(struct tpm_buf *buf, const u16 value);
diff --git a/security/keys/trusted-keys/trusted_tpm1.c b/security/keys/trusted-keys/trusted_tpm1.c
index 636acb66a4f6..759c1ecb0435 100644
--- a/security/keys/trusted-keys/trusted_tpm1.c
+++ b/security/keys/trusted-keys/trusted_tpm1.c
@@ -310,9 +310,10 @@ 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 cmd_len)
{
- struct tpm_buf buf;
+ u8 buf_data[512];
+ struct tpm_buf *buf = (struct tpm_buf *)buf_data;
int rc;
if (!chip)
@@ -322,11 +323,10 @@ static int trusted_tpm_send(unsigned char *cmd, size_t buflen)
if (rc)
return rc;
- buf.flags = 0;
- buf.length = buflen;
- buf.data = cmd;
+ tpm_buf_init(buf, sizeof(buf_data));
+ tpm_buf_append(buf, cmd, cmd_len);
dump_tpm_buf(cmd);
- rc = tpm_transmit_cmd(chip, &buf, 4, "sending data");
+ rc = tpm_transmit_cmd(chip, buf, 4, "sending data");
dump_tpm_buf(cmd);
if (rc > 0)
@@ -624,23 +624,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(TPM_BUFSIZE, GFP_KERNEL);
+ if (!tb)
+ return -ENOMEM;
+
+ tpm_buf_init(tb, TPM_BUFSIZE);
/* 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 +650,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(TPM_BUFSIZE, GFP_KERNEL);
+ if (!tb)
+ return -ENOMEM;
+
+ tpm_buf_init(tb, TPM_BUFSIZE);
- 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 +666,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;
}
diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index ef6dd88e56cf..27424e1a4a63 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -204,7 +204,6 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
struct trusted_key_options *options)
{
off_t offset = TPM_HEADER_SIZE;
- struct tpm_buf buf, sized;
int blob_len = 0;
int hash;
u32 flags;
@@ -225,97 +224,99 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
if (rc)
goto out_put;
- rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
- if (rc) {
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf) {
+ rc = -ENOMEM;
tpm2_end_auth_session(chip);
goto out_put;
}
- rc = tpm_buf_init_sized(&sized);
- if (rc) {
- tpm_buf_destroy(&buf);
- tpm2_end_auth_session(chip);
- goto out_put;
- }
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_CREATE);
- rc = tpm_buf_append_name(chip, &buf, options->keyhandle, NULL);
+ rc = tpm_buf_append_name(chip, buf, options->keyhandle, NULL);
if (rc)
- goto out;
+ goto out_put;
- tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_DECRYPT,
+ tpm_buf_append_hmac_session(chip, buf, TPM2_SA_DECRYPT,
options->keyauth, TPM_DIGEST_SIZE);
+ struct tpm_buf *sized __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!sized) {
+ rc = -ENOMEM;
+ tpm2_end_auth_session(chip);
+ goto out_put;
+ }
+
/* sensitive */
- tpm_buf_append_u16(&sized, options->blobauth_len);
+ tpm_buf_init_sized(sized, TPM_BUFSIZE);
+ tpm_buf_append_u16(sized, options->blobauth_len);
if (options->blobauth_len)
- tpm_buf_append(&sized, options->blobauth, options->blobauth_len);
+ tpm_buf_append(sized, options->blobauth, options->blobauth_len);
- tpm_buf_append_u16(&sized, payload->key_len);
- tpm_buf_append(&sized, payload->key, payload->key_len);
- tpm_buf_append(&buf, sized.data, sized.length);
+ tpm_buf_append_u16(sized, payload->key_len);
+ tpm_buf_append(sized, payload->key, payload->key_len);
+ tpm_buf_append(buf, sized->data, sized->length);
/* public */
- tpm_buf_reset_sized(&sized);
- tpm_buf_append_u16(&sized, TPM_ALG_KEYEDHASH);
- tpm_buf_append_u16(&sized, hash);
+ tpm_buf_init_sized(sized, TPM_BUFSIZE);
+ tpm_buf_append_u16(sized, TPM_ALG_KEYEDHASH);
+ tpm_buf_append_u16(sized, hash);
/* key properties */
flags = 0;
flags |= options->policydigest_len ? 0 : TPM2_OA_USER_WITH_AUTH;
flags |= payload->migratable ? 0 : (TPM2_OA_FIXED_TPM | TPM2_OA_FIXED_PARENT);
- tpm_buf_append_u32(&sized, flags);
+ tpm_buf_append_u32(sized, flags);
/* policy */
- tpm_buf_append_u16(&sized, options->policydigest_len);
+ tpm_buf_append_u16(sized, options->policydigest_len);
if (options->policydigest_len)
- tpm_buf_append(&sized, options->policydigest, options->policydigest_len);
+ tpm_buf_append(sized, options->policydigest, options->policydigest_len);
/* public parameters */
- tpm_buf_append_u16(&sized, TPM_ALG_NULL);
- tpm_buf_append_u16(&sized, 0);
+ tpm_buf_append_u16(sized, TPM_ALG_NULL);
+ tpm_buf_append_u16(sized, 0);
- tpm_buf_append(&buf, sized.data, sized.length);
+ tpm_buf_append(buf, sized->data, sized->length);
/* outside info */
- tpm_buf_append_u16(&buf, 0);
+ tpm_buf_append_u16(buf, 0);
/* creation PCR */
- tpm_buf_append_u32(&buf, 0);
+ tpm_buf_append_u32(buf, 0);
- if (buf.flags & TPM_BUF_INVALID) {
+ if (buf->flags & TPM_BUF_INVALID) {
rc = -E2BIG;
tpm2_end_auth_session(chip);
goto out;
}
- rc = tpm_buf_fill_hmac_session(chip, &buf);
+ rc = tpm_buf_fill_hmac_session(chip, buf);
if (rc)
goto out;
- rc = tpm_transmit_cmd(chip, &buf, 4, "sealing data");
- rc = tpm_buf_check_hmac_response(chip, &buf, rc);
+ rc = tpm_transmit_cmd(chip, buf, 4, "sealing data");
+ rc = tpm_buf_check_hmac_response(chip, buf, rc);
if (rc)
goto out;
- blob_len = tpm_buf_read_u32(&buf, &offset);
- if (blob_len > MAX_BLOB_SIZE || buf.flags & TPM_BUF_INVALID) {
+ blob_len = tpm_buf_read_u32(buf, &offset);
+ if (blob_len > MAX_BLOB_SIZE || buf->flags & TPM_BUF_INVALID) {
rc = -E2BIG;
goto out;
}
- if (buf.length - offset < blob_len) {
+ if (buf->length - offset < blob_len) {
rc = -EFAULT;
goto out;
}
- blob_len = tpm2_key_encode(payload, options, &buf.data[offset], blob_len);
+ blob_len = tpm2_key_encode(payload, options, &buf->data[offset], blob_len);
if (blob_len < 0)
rc = blob_len;
out:
- tpm_buf_destroy(&sized);
- tpm_buf_destroy(&buf);
-
if (!rc)
payload->blob_len = blob_len;
@@ -343,7 +344,6 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
u32 *blob_handle)
{
u8 *blob_ref __free(kfree) = NULL;
- struct tpm_buf buf;
unsigned int private_len;
unsigned int public_len;
unsigned int blob_len;
@@ -397,39 +397,38 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
if (rc)
return rc;
- rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
- if (rc) {
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf) {
tpm2_end_auth_session(chip);
- return rc;
+ return -ENOMEM;
}
- rc = tpm_buf_append_name(chip, &buf, options->keyhandle, NULL);
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_LOAD);
+
+ rc = tpm_buf_append_name(chip, buf, options->keyhandle, NULL);
if (rc)
- goto out;
+ return rc;
- tpm_buf_append_hmac_session(chip, &buf, 0, options->keyauth,
+ tpm_buf_append_hmac_session(chip, buf, 0, options->keyauth,
TPM_DIGEST_SIZE);
- tpm_buf_append(&buf, blob, blob_len);
+ tpm_buf_append(buf, blob, blob_len);
- if (buf.flags & TPM_BUF_INVALID) {
- rc = -E2BIG;
+ if (buf->flags & TPM_BUF_INVALID) {
tpm2_end_auth_session(chip);
- goto out;
+ return -E2BIG;
}
- rc = tpm_buf_fill_hmac_session(chip, &buf);
+ rc = tpm_buf_fill_hmac_session(chip, buf);
if (rc)
- goto out;
+ return rc;
- rc = tpm_transmit_cmd(chip, &buf, 4, "loading blob");
- rc = tpm_buf_check_hmac_response(chip, &buf, rc);
+ 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]);
-
-out:
- tpm_buf_destroy(&buf);
+ (__be32 *)&buf->data[TPM_HEADER_SIZE]);
return tpm_ret_to_err(rc);
}
@@ -451,27 +450,27 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
struct trusted_key_options *options,
u32 blob_handle)
{
- struct tpm_buf buf;
u16 data_len;
u8 *data;
int rc;
+ struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
rc = tpm2_start_auth_session(chip);
if (rc)
return rc;
- rc = tpm_buf_init(&buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
- if (rc) {
- tpm2_end_auth_session(chip);
- return rc;
- }
+ tpm_buf_init(buf, TPM_BUFSIZE);
+ tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_UNSEAL);
- rc = tpm_buf_append_name(chip, &buf, options->keyhandle, NULL);
+ rc = tpm_buf_append_name(chip, buf, options->keyhandle, NULL);
if (rc)
- goto out;
+ return rc;
if (!options->policyhandle) {
- tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_ENCRYPT,
+ tpm_buf_append_hmac_session(chip, buf, TPM2_SA_ENCRYPT,
options->blobauth,
options->blobauth_len);
} else {
@@ -480,37 +479,33 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
* the password will end up being unencrypted on the bus, as
* HMAC nonce cannot be calculated for it.
*/
- tpm_buf_append_u32(&buf, 9 + options->blobauth_len);
- tpm_buf_append_u32(&buf, options->policyhandle);
- tpm_buf_append_u16(&buf, 0);
- tpm_buf_append_u8(&buf, 0);
- tpm_buf_append_u16(&buf, options->blobauth_len);
- tpm_buf_append(&buf, options->blobauth, options->blobauth_len);
+ tpm_buf_append_u32(buf, 9 + options->blobauth_len);
+ tpm_buf_append_u32(buf, options->policyhandle);
+ tpm_buf_append_u16(buf, 0);
+ tpm_buf_append_u8(buf, 0);
+ tpm_buf_append_u16(buf, options->blobauth_len);
+ tpm_buf_append(buf, options->blobauth, options->blobauth_len);
if (tpm2_chip_auth(chip))
- tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_ENCRYPT, NULL, 0);
+ tpm_buf_append_hmac_session(chip, buf, TPM2_SA_ENCRYPT, NULL, 0);
}
- rc = tpm_buf_fill_hmac_session(chip, &buf);
+ rc = tpm_buf_fill_hmac_session(chip, buf);
if (rc)
- goto out;
+ return rc;
- rc = tpm_transmit_cmd(chip, &buf, 6, "unsealing");
- rc = tpm_buf_check_hmac_response(chip, &buf, rc);
+ rc = tpm_transmit_cmd(chip, buf, 6, "unsealing");
+ rc = tpm_buf_check_hmac_response(chip, buf, rc);
if (!rc) {
data_len = be16_to_cpup(
- (__be16 *) &buf.data[TPM_HEADER_SIZE + 4]);
- if (data_len < MIN_KEY_SIZE || data_len > MAX_KEY_SIZE) {
- rc = -EFAULT;
- goto out;
- }
+ (__be16 *)&buf->data[TPM_HEADER_SIZE + 4]);
+ if (data_len < MIN_KEY_SIZE || data_len > MAX_KEY_SIZE)
+ return -EFAULT;
- if (tpm_buf_length(&buf) < TPM_HEADER_SIZE + 6 + data_len) {
- rc = -EFAULT;
- goto out;
- }
- data = &buf.data[TPM_HEADER_SIZE + 6];
+ if (tpm_buf_length(buf) < TPM_HEADER_SIZE + 6 + data_len)
+ return -EFAULT;
+ data = &buf->data[TPM_HEADER_SIZE + 6];
if (payload->old_format) {
/* migratable flag is at the end of the key */
@@ -527,8 +522,6 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
}
}
-out:
- tpm_buf_destroy(&buf);
return tpm_ret_to_err(rc);
}
--
2.39.5
^ permalink raw reply related
* [PATCH v5 05/12] tpm-buf: Remove chip parameter from tpm_buf_append_handle
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Jonathan McDowell, Peter Huewe,
Jarkko Sakkinen, Jason Gunthorpe, David Howells, Paul Moore,
James Morris, Serge E. Hallyn, open list, open list:KEYS/KEYRINGS,
open list:SECURITY SUBSYSTEM
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
From: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Remove @chip from tpm_buf_append_handle() in order to decouple it from
driver. This allows tpm-buf.c to be compiled as part of early boot code,
thus providing a mechanism to build and parse TPM data.
E.g., Trenchboot can use this to manage TPM2_PcrExtend protocol data as
part of its early boot blob simply by compiling and linking the object
file.
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Reviewed-by: Jonathan McDowell <noodles@meta.com>
---
drivers/char/tpm/tpm-buf.c | 5 ++---
drivers/char/tpm/tpm2-cmd.c | 2 +-
drivers/char/tpm/tpm2-sessions.c | 2 +-
include/linux/tpm.h | 2 +-
4 files changed, 5 insertions(+), 6 deletions(-)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index 69ee77400539..1b9dee0d0681 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -147,20 +147,19 @@ EXPORT_SYMBOL_GPL(tpm_buf_append_u32);
/**
* tpm_buf_append_handle() - Add a handle
- * @chip: &tpm_chip instance
* @buf: &tpm_buf instance
* @handle: a TPM object handle
*
* Add a handle to the buffer, and increase the count tracking the number of
* handles in the command buffer. Works only for command buffers.
*/
-void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle)
+void tpm_buf_append_handle(struct tpm_buf *buf, u32 handle)
{
if (buf->flags & TPM_BUF_INVALID)
return;
if (buf->flags & TPM_BUF_TPM2B) {
- dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+ WARN(1, "tpm-buf: invalid type: TPM2B\n");
buf->flags |= TPM_BUF_INVALID;
return;
}
diff --git a/drivers/char/tpm/tpm2-cmd.c b/drivers/char/tpm/tpm2-cmd.c
index 3a77be7ebf4a..82076b6cfcf7 100644
--- a/drivers/char/tpm/tpm2-cmd.c
+++ b/drivers/char/tpm/tpm2-cmd.c
@@ -209,7 +209,7 @@ int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
}
tpm_buf_append_hmac_session(chip, &buf, 0, NULL, 0);
} else {
- tpm_buf_append_handle(chip, &buf, pcr_idx);
+ tpm_buf_append_handle(&buf, pcr_idx);
tpm_buf_append_auth(chip, &buf, NULL, 0);
}
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 525b8622d1c3..4432f123af97 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -257,7 +257,7 @@ int tpm_buf_append_name(struct tpm_chip *chip, struct tpm_buf *buf,
#endif
if (!tpm2_chip_auth(chip)) {
- tpm_buf_append_handle(chip, buf, handle);
+ tpm_buf_append_handle(buf, handle);
return 0;
}
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index f43725c52204..f07376eae4cb 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -439,7 +439,7 @@ void tpm_buf_append_u32(struct tpm_buf *buf, const u32 value);
u8 tpm_buf_read_u8(struct tpm_buf *buf, off_t *offset);
u16 tpm_buf_read_u16(struct tpm_buf *buf, off_t *offset);
u32 tpm_buf_read_u32(struct tpm_buf *buf, off_t *offset);
-void tpm_buf_append_handle(struct tpm_chip *chip, struct tpm_buf *buf, u32 handle);
+void tpm_buf_append_handle(struct tpm_buf *buf, u32 handle);
/*
* Check if TPM device is in the firmware upgrade mode.
--
2.39.5
^ permalink raw reply related
* [PATCH v5 04/12] tpm-buf: Merge TPM_BUF_BOUNDARY_ERROR and TPM_BUF_OVERFLOW
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Jonathan McDowell, Peter Huewe,
Jarkko Sakkinen, Jason Gunthorpe, David Howells, Paul Moore,
James Morris, Serge E. Hallyn, James Bottomley, Mimi Zohar,
open list, open list:KEYS/KEYRINGS, open list:SECURITY SUBSYSTEM
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
From: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Merge TPM_BUF_BOUNDARY_ERROR and TPM_BUF_OVERFLOW into TPM_BUF_INVALID,
given that they are identical. The only difference are the log messages.
In addition, add a missing TPM_BUF_INVALID check to tpm_buf_append_handle()
following the pattern from other functions in tpm-buf.c.
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Reviewed-by: Jonathan McDowell <noodles@meta.com>
---
drivers/char/tpm/tpm-buf.c | 14 ++++++++------
include/linux/tpm.h | 8 +++-----
security/keys/trusted-keys/trusted_tpm2.c | 6 +++---
3 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/drivers/char/tpm/tpm-buf.c b/drivers/char/tpm/tpm-buf.c
index dc882fc9fa9e..69ee77400539 100644
--- a/drivers/char/tpm/tpm-buf.c
+++ b/drivers/char/tpm/tpm-buf.c
@@ -104,13 +104,12 @@ 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)
+ if (buf->flags & TPM_BUF_INVALID)
return;
if ((buf->length + new_length) > PAGE_SIZE) {
WARN(1, "tpm_buf: write overflow\n");
- buf->flags |= TPM_BUF_OVERFLOW;
+ buf->flags |= TPM_BUF_INVALID;
return;
}
@@ -157,8 +156,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_INVALID)
+ return;
+
if (buf->flags & TPM_BUF_TPM2B) {
dev_err(&chip->dev, "Invalid buffer type (TPM2B)\n");
+ buf->flags |= TPM_BUF_INVALID;
return;
}
@@ -177,14 +180,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_INVALID)
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_INVALID;
return;
}
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index e10f2096eae7..f43725c52204 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -382,12 +382,10 @@ 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),
+ TPM_BUF_TPM2B = BIT(0),
+ /* The buffer is in invalid and unusable state: */
+ TPM_BUF_INVALID = BIT(1),
};
/*
diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index 77e1532ef9d4..ef6dd88e56cf 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -283,7 +283,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
/* creation PCR */
tpm_buf_append_u32(&buf, 0);
- if (buf.flags & TPM_BUF_OVERFLOW) {
+ if (buf.flags & TPM_BUF_INVALID) {
rc = -E2BIG;
tpm2_end_auth_session(chip);
goto out;
@@ -299,7 +299,7 @@ int tpm2_seal_trusted(struct tpm_chip *chip,
goto out;
blob_len = tpm_buf_read_u32(&buf, &offset);
- if (blob_len > MAX_BLOB_SIZE || buf.flags & TPM_BUF_BOUNDARY_ERROR) {
+ if (blob_len > MAX_BLOB_SIZE || buf.flags & TPM_BUF_INVALID) {
rc = -E2BIG;
goto out;
}
@@ -412,7 +412,7 @@ static int tpm2_load_cmd(struct tpm_chip *chip,
tpm_buf_append(&buf, blob, blob_len);
- if (buf.flags & TPM_BUF_OVERFLOW) {
+ if (buf.flags & TPM_BUF_INVALID) {
rc = -E2BIG;
tpm2_end_auth_session(chip);
goto out;
--
2.39.5
^ permalink raw reply related
* [PATCH v5 03/12] tpm2-sessions: Define TPM2_NAME_MAX_SIZE
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Peter Huewe, Jason Gunthorpe,
David Howells, Paul Moore, James Morris, Serge E. Hallyn,
open list, open list:KEYS/KEYRINGS, open list:SECURITY SUBSYSTEM
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
This is somewhat cosmetic change but it does serve a purpose on tracking
the value set for the maximum length of TPM names, and to clearly states
what components it is composed of. It also anchors the value so that when
buffers are declared for this particular purpose, the same value is used
for the capacity.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
v2:
- Rename TPM2_NAME_SIZE as TPM2_NULL_NAME_SIZE.
---
drivers/char/tpm/tpm-sysfs.c | 2 +-
drivers/char/tpm/tpm2-sessions.c | 2 +-
include/linux/tpm.h | 37 +++++++++++++++++++++-----------
3 files changed, 27 insertions(+), 14 deletions(-)
diff --git a/drivers/char/tpm/tpm-sysfs.c b/drivers/char/tpm/tpm-sysfs.c
index 94231f052ea7..4a6a27ee295d 100644
--- a/drivers/char/tpm/tpm-sysfs.c
+++ b/drivers/char/tpm/tpm-sysfs.c
@@ -314,7 +314,7 @@ 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;
+ int size = TPM2_NULL_NAME_SIZE;
bin2hex(buf, chip->null_key_name, size);
size *= 2;
diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c
index 4149379665c4..525b8622d1c3 100644
--- a/drivers/char/tpm/tpm2-sessions.c
+++ b/drivers/char/tpm/tpm2-sessions.c
@@ -137,7 +137,7 @@ struct tpm2_auth {
* we must compute and remember
*/
u32 name_h[AUTH_MAX_NAMES];
- u8 name[AUTH_MAX_NAMES][2 + SHA512_DIGEST_SIZE];
+ u8 name[AUTH_MAX_NAMES][TPM2_MAX_NAME_SIZE];
};
#ifdef CONFIG_TCG_TPM2_HMAC
diff --git a/include/linux/tpm.h b/include/linux/tpm.h
index 202da079d500..e10f2096eae7 100644
--- a/include/linux/tpm.h
+++ b/include/linux/tpm.h
@@ -27,9 +27,33 @@
#define TPM_DIGEST_SIZE 20 /* Max TPM v1.2 PCR size */
+/*
+ * SHA-512 is, as of today, the largest digest in the TCG algorithm repository.
+ */
#define TPM2_MAX_DIGEST_SIZE SHA512_DIGEST_SIZE
+
+/*
+ * A TPM name digest i.e., TPMT_HA, is a concatenation of TPM_ALG_ID of the
+ * name algorithm and hash of TPMT_PUBLIC.
+ */
+#define TPM2_MAX_NAME_SIZE (TPM2_MAX_DIGEST_SIZE + 2)
+
+/*
+ * The maximum number of PCR banks.
+ */
#define TPM2_MAX_PCR_BANKS 8
+/*
+ * fixed define for the size of a name. This is actually HASHALG size
+ * plus 2, so 32 for SHA256
+ */
+#define TPM2_NULL_NAME_SIZE 34
+
+/*
+ * The maximum size for an object context
+ */
+#define TPM2_MAX_CONTEXT_SIZE 4096
+
struct tpm_chip;
struct trusted_key_payload;
struct trusted_key_options;
@@ -139,17 +163,6 @@ struct tpm_chip_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;
@@ -211,7 +224,7 @@ struct tpm_chip {
/* saved context for NULL seed */
u8 null_key_context[TPM2_MAX_CONTEXT_SIZE];
/* name of NULL seed */
- u8 null_key_name[TPM2_NAME_SIZE];
+ u8 null_key_name[TPM2_NULL_NAME_SIZE];
u8 null_ec_key_x[EC_PT_SZ];
u8 null_ec_key_y[EC_PT_SZ];
struct tpm2_auth *auth;
--
2.39.5
^ permalink raw reply related
* [PATCH v5 02/12] KEYS: trusted: Remove dead branch from tpm2_unseal_cmd
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, David Howells, Paul Moore,
James Morris, Serge E. Hallyn, James Bottomley, Mimi Zohar,
open list:KEYS/KEYRINGS, open list:SECURITY SUBSYSTEM, open list
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
TPM2_Unseal requires TPM2_ST_SESSIONS, and tpm2_unseal_cmd() always does
set up either password or HMAC session.
Remove the branch in tpm2_unseal_cmd() conditionally setting
TPM2_ST_NO_SESSIONS. It is faulty but luckily it is never exercised at
run-time, and thus does not cause regressions.
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
security/keys/trusted-keys/trusted_tpm2.c | 10 +---------
1 file changed, 1 insertion(+), 9 deletions(-)
diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index d25d065c2af0..77e1532ef9d4 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -451,10 +451,8 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
struct trusted_key_options *options,
u32 blob_handle)
{
- struct tpm_header *head;
struct tpm_buf buf;
u16 data_len;
- int offset;
u8 *data;
int rc;
@@ -489,14 +487,8 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
tpm_buf_append_u16(&buf, options->blobauth_len);
tpm_buf_append(&buf, options->blobauth, options->blobauth_len);
- if (tpm2_chip_auth(chip)) {
+ if (tpm2_chip_auth(chip))
tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_ENCRYPT, NULL, 0);
- } else {
- offset = buf.handles * 4 + TPM_HEADER_SIZE;
- head = (struct tpm_header *)buf.data;
- if (tpm_buf_length(&buf) == offset)
- head->tag = cpu_to_be16(TPM2_ST_NO_SESSIONS);
- }
}
rc = tpm_buf_fill_hmac_session(chip, &buf);
--
2.39.5
^ permalink raw reply related
* [PATCH v5 01/12] KEYS: trusted: Open code tpm2_buf_append()
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, Jonathan McDowell, David Howells,
Jarkko Sakkinen, Paul Moore, James Morris, Serge E. Hallyn,
James Bottomley, Mimi Zohar, open list:KEYS/KEYRINGS,
open list:SECURITY SUBSYSTEM, open list
In-Reply-To: <20251213203220.317498-1-jarkko@kernel.org>
From: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
tpm2_buf_append_auth() has only single call site and most of its parameters
are redundant. Open code it to the call site. Remove illegit FIXME comment
as there is no categorized bug and replace it with more sane comment about
implementation (i.e. "non-opionated inline comment").
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com>
Reviewed-by: Jonathan McDowell <noodles@earth.li>
---
security/keys/trusted-keys/trusted_tpm2.c | 52 +++++------------------
1 file changed, 10 insertions(+), 42 deletions(-)
diff --git a/security/keys/trusted-keys/trusted_tpm2.c b/security/keys/trusted-keys/trusted_tpm2.c
index a7ea4a1c3bed..d25d065c2af0 100644
--- a/security/keys/trusted-keys/trusted_tpm2.c
+++ b/security/keys/trusted-keys/trusted_tpm2.c
@@ -190,36 +190,6 @@ int tpm2_key_priv(void *context, size_t hdrlen,
return 0;
}
-/**
- * tpm2_buf_append_auth() - append TPMS_AUTH_COMMAND to the buffer.
- *
- * @buf: an allocated tpm_buf instance
- * @session_handle: session handle
- * @nonce: the session nonce, may be NULL if not used
- * @nonce_len: the session nonce length, may be 0 if not used
- * @attributes: the session attributes
- * @hmac: the session HMAC or password, may be NULL if not used
- * @hmac_len: the session HMAC or password length, maybe 0 if not used
- */
-static void tpm2_buf_append_auth(struct tpm_buf *buf, u32 session_handle,
- const u8 *nonce, u16 nonce_len,
- u8 attributes,
- const u8 *hmac, u16 hmac_len)
-{
- tpm_buf_append_u32(buf, 9 + nonce_len + hmac_len);
- tpm_buf_append_u32(buf, session_handle);
- tpm_buf_append_u16(buf, nonce_len);
-
- if (nonce && nonce_len)
- tpm_buf_append(buf, nonce, nonce_len);
-
- tpm_buf_append_u8(buf, attributes);
- tpm_buf_append_u16(buf, hmac_len);
-
- if (hmac && hmac_len)
- tpm_buf_append(buf, hmac, hmac_len);
-}
-
/**
* tpm2_seal_trusted() - seal the payload of a trusted key
*
@@ -508,19 +478,17 @@ static int tpm2_unseal_cmd(struct tpm_chip *chip,
options->blobauth_len);
} else {
/*
- * FIXME: The policy session was generated outside the
- * kernel so we don't known the nonce and thus can't
- * calculate a HMAC on it. Therefore, the user can
- * only really use TPM2_PolicyPassword and we must
- * send down the plain text password, which could be
- * intercepted. We can still encrypt the returned
- * key, but that's small comfort since the interposer
- * could repeat our actions with the exfiltrated
- * password.
+ * The policy session is generated outside the kernel, and thus
+ * the password will end up being unencrypted on the bus, as
+ * HMAC nonce cannot be calculated for it.
*/
- tpm2_buf_append_auth(&buf, options->policyhandle,
- NULL /* nonce */, 0, 0,
- options->blobauth, options->blobauth_len);
+ tpm_buf_append_u32(&buf, 9 + options->blobauth_len);
+ tpm_buf_append_u32(&buf, options->policyhandle);
+ tpm_buf_append_u16(&buf, 0);
+ tpm_buf_append_u8(&buf, 0);
+ tpm_buf_append_u16(&buf, options->blobauth_len);
+ tpm_buf_append(&buf, options->blobauth, options->blobauth_len);
+
if (tpm2_chip_auth(chip)) {
tpm_buf_append_hmac_session(chip, &buf, TPM2_SA_ENCRYPT, NULL, 0);
} else {
--
2.39.5
^ permalink raw reply related
* [PATCH v5 00/12] Streamline TPM2 HMAC sessions
From: Jarkko Sakkinen @ 2025-12-13 20:32 UTC (permalink / raw)
To: linux-integrity
Cc: Ross Philipson, Jarkko Sakkinen, David Howells, Paul Moore,
James Morris, Serge E. Hallyn, open list:KEYS/KEYRINGS,
open list:SECURITY SUBSYSTEM, open list
Since we cannot at this point cache names of the keys given limitations
of the ASN.1 file format, I'll start a fresh patch set. Let's fixup what
we can right now.
This patch set addresses two major issues in the feature:
1. Dynamic resolution without gain. All kernel sites have at most single
handle to authorize. Even if this changes some day this is how it is
as of today and we definitely do not want to dictate the future but
instead downscale code to the metrics that we have as of today.
2. Eliminate at least one unnnecessary tpm2_read_public() call.
Change Log
==========
v5:
- I decided to add the managed allocation patch to this and take it from
the master branch for the time being, as it needs more eyes despite
having already one reviewed-by tag (especially tested-by tags).
Jarkko Sakkinen (12):
KEYS: trusted: Open code tpm2_buf_append()
KEYS: trusted: Remove dead branch from tpm2_unseal_cmd
tpm2-sessions: Define TPM2_NAME_MAX_SIZE
tpm-buf: Merge TPM_BUF_BOUNDARY_ERROR and TPM_BUF_OVERFLOW
tpm-buf: Remove chip parameter from tpm_buf_append_handle
tpm-buf: Implement managed allocations
KEYS: trusted: Re-orchestrate tpm2_read_public() calls
tpm2-sessions: Remove AUTH_MAX_NAMES
tpm-buf: Remove tpm_buf_append_handle
tpm: Orchestrate TPM commands in tpm_get_random()
tpm: Send only one at most TPM2_GetRandom command
tpm: In tpm_get_random() replace 'retries' with a zero check
drivers/char/tpm/tpm-buf.c | 154 ++++-----
drivers/char/tpm/tpm-chip.c | 2 +-
drivers/char/tpm/tpm-interface.c | 177 ++++++++++-
drivers/char/tpm/tpm-sysfs.c | 23 +-
drivers/char/tpm/tpm.h | 3 -
drivers/char/tpm/tpm1-cmd.c | 198 ++++--------
drivers/char/tpm/tpm2-cmd.c | 371 +++++++---------------
drivers/char/tpm/tpm2-sessions.c | 272 ++++++----------
drivers/char/tpm/tpm2-space.c | 44 ++-
drivers/char/tpm/tpm_vtpm_proxy.c | 30 +-
include/linux/tpm.h | 79 +++--
security/keys/trusted-keys/trusted_tpm1.c | 44 +--
security/keys/trusted-keys/trusted_tpm2.c | 341 ++++++++++----------
13 files changed, 802 insertions(+), 936 deletions(-)
--
2.39.5
^ permalink raw reply
* Re: [PATCH 5/6] keys/trusted_keys: establish PKWM as a trusted source
From: Jarkko Sakkinen @ 2025-12-13 19:22 UTC (permalink / raw)
To: Srish Srinivasan
Cc: linux-integrity, keyrings, linuxppc-dev, maddy, mpe, npiggin,
christophe.leroy, James.Bottomley, zohar, nayna, rnsastry,
linux-kernel, linux-security-module
In-Reply-To: <20251213052618.190691-6-ssrish@linux.ibm.com>
On Sat, Dec 13, 2025 at 10:56:17AM +0530, Srish Srinivasan wrote:
> The wrapping key does not exist by default and is generated by the
> hypervisor as a part of PKWM initialization. This key is then persisted by
> the hypervisor and is used to wrap trusted keys. These are variable length
> symmetric keys, which in the case of PowerVM Key Wrapping Module (PKWM) are
> generated using the kernel RNG. PKWM can be used as a trust source through
> the following example keyctl command
>
> keyctl add trusted my_trusted_key "new 32" @u
>
> Use the wrap_flags command option to set the secure boot requirement for
> the wrapping request through the following keyctl commands
>
> case1: no secure boot requirement. (default)
> keyctl usage: keyctl add trusted my_trusted_key "new 32" @u
> OR
> keyctl add trusted my_trusted_key "new 32 wrap_flags=0x00" @u
>
> case2: secure boot required to in either audit or enforce mode. set bit 0
> keyctl usage: keyctl add trusted my_trusted_key "new 32 wrap_flags=0x01" @u
>
> case3: secure boot required to be in enforce mode. set bit 1
> keyctl usage: keyctl add trusted my_trusted_key "new 32 wrap_flags=0x02" @u
>
> NOTE:
> -> Setting the secure boot requirement is NOT a must.
> -> Only either of the secure boot requirement options should be set. Not
> both.
> -> All the other bits are requied to be not set.
> -> Set the kernel parameter trusted.source=pkwm to choose PKWM as the
> backend for trusted keys implementation.
> -> CONFIG_PSERIES_PLPKS must be enabled to build PKWM.
>
> Add PKWM, which is a combination of IBM PowerVM and Power LPAR Platform
> KeyStore, as a new trust source for trusted keys.
>
> Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
> ---
> MAINTAINERS | 9 ++
> include/keys/trusted-type.h | 7 +-
> include/keys/trusted_pkwm.h | 30 ++++
> security/keys/trusted-keys/Kconfig | 8 ++
> security/keys/trusted-keys/Makefile | 2 +
> security/keys/trusted-keys/trusted_core.c | 6 +-
> security/keys/trusted-keys/trusted_pkwm.c | 168 ++++++++++++++++++++++
> 7 files changed, 228 insertions(+), 2 deletions(-)
> create mode 100644 include/keys/trusted_pkwm.h
> create mode 100644 security/keys/trusted-keys/trusted_pkwm.c
>
> diff --git a/MAINTAINERS b/MAINTAINERS
> index aff3e162180d..bf78ab78a309 100644
> --- a/MAINTAINERS
> +++ b/MAINTAINERS
> @@ -13993,6 +13993,15 @@ S: Supported
> F: include/keys/trusted_dcp.h
> F: security/keys/trusted-keys/trusted_dcp.c
>
> +KEYS-TRUSTED-PLPKS
> +M: Srish Srinivasan <ssrish@linux.ibm.com>
> +M: Nayna Jain <nayna@linux.ibm.com>
> +L: linux-integrity@vger.kernel.org
> +L: keyrings@vger.kernel.org
> +S: Supported
> +F: include/keys/trusted_plpks.h
> +F: security/keys/trusted-keys/trusted_pkwm.c
> +
> KEYS-TRUSTED-TEE
> M: Sumit Garg <sumit.garg@kernel.org>
> L: linux-integrity@vger.kernel.org
> diff --git a/include/keys/trusted-type.h b/include/keys/trusted-type.h
> index 4eb64548a74f..45c6c538df22 100644
> --- a/include/keys/trusted-type.h
> +++ b/include/keys/trusted-type.h
> @@ -19,7 +19,11 @@
>
> #define MIN_KEY_SIZE 32
> #define MAX_KEY_SIZE 128
> -#define MAX_BLOB_SIZE 512
> +#if IS_ENABLED(CONFIG_TRUSTED_KEYS_PKWM)
> +#define MAX_BLOB_SIZE 1152
> +#else
> +#define MAX_BLOB_SIZE 512
> +#endif
> #define MAX_PCRINFO_SIZE 64
> #define MAX_DIGEST_SIZE 64
>
> @@ -46,6 +50,7 @@ struct trusted_key_options {
> uint32_t policydigest_len;
> unsigned char policydigest[MAX_DIGEST_SIZE];
> uint32_t policyhandle;
> + uint16_t wrap_flags;
> };
>
> struct trusted_key_ops {
> diff --git a/include/keys/trusted_pkwm.h b/include/keys/trusted_pkwm.h
> new file mode 100644
> index 000000000000..736edfc1e1dd
> --- /dev/null
> +++ b/include/keys/trusted_pkwm.h
> @@ -0,0 +1,30 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +#ifndef __PKWM_TRUSTED_KEY_H
> +#define __PKWM_TRUSTED_KEY_H
> +
> +#include <keys/trusted-type.h>
> +
> +extern struct trusted_key_ops pkwm_trusted_key_ops;
> +
> +#define PKWM_DEBUG 0
> +
> +#if PKWM_DEBUG
> +static inline void dump_options(struct trusted_key_options *o)
> +{
> + bool sb_audit_or_enforce_bit = o->policyhandle & BIT(0);
> + bool sb_enforce_bit = o->policyhandle & BIT(1);
> +
> + if (sb_audit_or_enforce_bit)
> + pr_info("secure boot mode: audit or enforce");
> + else if (sb_enforce_bit)
> + pr_info("secure boot mode: enforce");
> + else
> + pr_info("secure boot mode: disabled");
> +}
> +#else
> +static inline void dump_options(struct trusted_key_options *o)
> +{
> +}
> +#endif
Please use pr_debug() instead of emulating this with 'PKWM_DEBUG'.
> +
> +#endif
> diff --git a/security/keys/trusted-keys/Kconfig b/security/keys/trusted-keys/Kconfig
> index 204a68c1429d..9e00482d886a 100644
> --- a/security/keys/trusted-keys/Kconfig
> +++ b/security/keys/trusted-keys/Kconfig
> @@ -46,6 +46,14 @@ config TRUSTED_KEYS_DCP
> help
> Enable use of NXP's DCP (Data Co-Processor) as trusted key backend.
>
> +config TRUSTED_KEYS_PKWM
> + bool "PKWM-based trusted keys"
> + depends on PSERIES_PLPKS >= TRUSTED_KEYS
> + default y
> + select HAVE_TRUSTED_KEYS
> + help
> + Enable use of IBM PowerVM Key Wrapping Module (PKWM) as a trusted key backend.
> +
> if !HAVE_TRUSTED_KEYS
> comment "No trust source selected!"
> endif
> diff --git a/security/keys/trusted-keys/Makefile b/security/keys/trusted-keys/Makefile
> index f0f3b27f688b..5fc053a21dad 100644
> --- a/security/keys/trusted-keys/Makefile
> +++ b/security/keys/trusted-keys/Makefile
> @@ -16,3 +16,5 @@ trusted-$(CONFIG_TRUSTED_KEYS_TEE) += trusted_tee.o
> trusted-$(CONFIG_TRUSTED_KEYS_CAAM) += trusted_caam.o
>
> trusted-$(CONFIG_TRUSTED_KEYS_DCP) += trusted_dcp.o
> +
> +trusted-$(CONFIG_TRUSTED_KEYS_PKWM) += trusted_pkwm.o
> diff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c
> index b1680ee53f86..2d328de170e8 100644
> --- a/security/keys/trusted-keys/trusted_core.c
> +++ b/security/keys/trusted-keys/trusted_core.c
> @@ -12,6 +12,7 @@
> #include <keys/trusted_caam.h>
> #include <keys/trusted_dcp.h>
> #include <keys/trusted_tpm.h>
> +#include <keys/trusted_pkwm.h>
> #include <linux/capability.h>
> #include <linux/err.h>
> #include <linux/init.h>
> @@ -31,7 +32,7 @@ MODULE_PARM_DESC(rng, "Select trusted key RNG");
>
> static char *trusted_key_source;
> module_param_named(source, trusted_key_source, charp, 0);
> -MODULE_PARM_DESC(source, "Select trusted keys source (tpm, tee, caam or dcp)");
> +MODULE_PARM_DESC(source, "Select trusted keys source (tpm, tee, caam, dcp or pkwm)");
>
> static const struct trusted_key_source trusted_key_sources[] = {
> #if defined(CONFIG_TRUSTED_KEYS_TPM)
> @@ -46,6 +47,9 @@ static const struct trusted_key_source trusted_key_sources[] = {
> #if defined(CONFIG_TRUSTED_KEYS_DCP)
> { "dcp", &dcp_trusted_key_ops },
> #endif
> +#if defined(CONFIG_TRUSTED_KEYS_PKWM)
> + { "pkwm", &pkwm_trusted_key_ops },
> +#endif
> };
>
> DEFINE_STATIC_CALL_NULL(trusted_key_seal, *trusted_key_sources[0].ops->seal);
> diff --git a/security/keys/trusted-keys/trusted_pkwm.c b/security/keys/trusted-keys/trusted_pkwm.c
> new file mode 100644
> index 000000000000..7968601dcf42
> --- /dev/null
> +++ b/security/keys/trusted-keys/trusted_pkwm.c
> @@ -0,0 +1,168 @@
> +// SPDX-License-Identifier: GPL-2.0-only
> +/*
> + * Copyright (C) 2025 IBM Corporation, Srish Srinivasan <ssrish@linux.ibm.com>
> + */
> +
> +#include <keys/trusted_pkwm.h>
> +#include <keys/trusted-type.h>
> +#include <linux/build_bug.h>
> +#include <linux/key-type.h>
> +#include <linux/parser.h>
> +#include <asm/plpks.h>
> +
> +enum {
> + Opt_err,
> + Opt_wrap_flags,
> +};
> +
> +static const match_table_t key_tokens = {
> + {Opt_wrap_flags, "wrap_flags=%s"},
> + {Opt_err, NULL}
> +};
> +
> +static int getoptions(char *datablob, struct trusted_key_options **opt)
> +{
> + substring_t args[MAX_OPT_ARGS];
> + char *p = datablob;
> + int token;
> + int res;
> + unsigned long wrap_flags;
> + unsigned long token_mask = 0;
> +
> + if (!datablob)
> + return 0;
> +
> + while ((p = strsep(&datablob, " \t"))) {
> + if (*p == '\0' || *p == ' ' || *p == '\t')
> + continue;
> +
> + token = match_token(p, key_tokens, args);
> + if (test_and_set_bit(token, &token_mask))
> + return -EINVAL;
> +
> + switch (token) {
> + case Opt_wrap_flags:
> + res = kstrtoul(args[0].from, 16, &wrap_flags);
> + if (res < 0 || wrap_flags > 2)
> + return -EINVAL;
> + (*opt)->wrap_flags = wrap_flags;
> + break;
> + default:
> + return -EINVAL;
> + }
> + }
> + return 0;
> +}
> +
> +static struct trusted_key_options *trusted_options_alloc(void)
> +{
> + struct trusted_key_options *options;
> +
> + options = kzalloc(sizeof(*options), GFP_KERNEL);
> + return options;
> +}
> +
> +static int trusted_pkwm_seal(struct trusted_key_payload *p, char *datablob)
> +{
> + struct trusted_key_options *options = NULL;
> + u8 *input_buf, *output_buf;
> + u32 output_len, input_len;
> + int rc;
> +
> + options = trusted_options_alloc();
> + if (!options)
> + return -ENOMEM;
> +
> + rc = getoptions(datablob, &options);
> + if (rc < 0)
> + goto out;
> + dump_options(options);
> +
> + input_len = p->key_len;
> + input_buf = kmalloc(ALIGN(input_len, 4096), GFP_KERNEL);
> + if (!input_buf) {
> + pr_err("Input buffer allocation failed. Returning -ENOMEM.");
> + return -ENOMEM;
> + }
> +
> + memcpy(input_buf, p->key, p->key_len);
> +
> + rc = plpks_wrap_object(&input_buf, input_len, options->wrap_flags,
> + &output_buf, &output_len);
> + if (!rc) {
> + memcpy(p->blob, output_buf, output_len);
> + p->blob_len = output_len;
> + dump_payload(p);
> + } else {
> + pr_err("Invalid argument");
> + }
> +
> + kfree(input_buf);
> + kfree(output_buf);
> +
> +out:
> + kfree_sensitive(options);
> + return rc;
> +}
> +
> +static int trusted_pkwm_unseal(struct trusted_key_payload *p, char *datablob)
> +{
> + u8 *input_buf, *output_buf;
> + u32 input_len, output_len;
> + int rc;
> +
> + input_len = p->blob_len;
> + input_buf = kmalloc(ALIGN(input_len, 4096), GFP_KERNEL);
> + if (!input_buf)
> + return -ENOMEM;
> +
> + memcpy(input_buf, p->blob, p->blob_len);
> +
> + rc = plpks_unwrap_object(&input_buf, input_len, &output_buf,
> + &output_len);
> + if (!rc) {
> + memcpy(p->key, output_buf, output_len);
> + p->key_len = output_len;
> + dump_payload(p);
> + } else {
> + pr_err("Invalid argument");
I don't get this error message. What does this mean? pr_err() is used
when you have actual malfunction.
> + }
> +
> + kfree(input_buf);
> + kfree(output_buf);
> +
> + return rc;
> +}
> +
> +static int trusted_pkwm_init(void)
> +{
> + int ret;
> +
> + if (!plpks_wrapping_is_supported()) {
> + pr_err("H_PKS_WRAP_OBJECT interface not supported\n");
> +
> + return -ENODEV;
> + }
> +
> + ret = plpks_gen_wrapping_key();
> + if (ret) {
> + pr_err("Failed to generate default wrapping key\n");
> +
> + return -EINVAL;
> + }
> +
> + return register_key_type(&key_type_trusted);
> +}
> +
> +static void trusted_pkwm_exit(void)
> +{
> + unregister_key_type(&key_type_trusted);
> +}
> +
> +struct trusted_key_ops pkwm_trusted_key_ops = {
> + .migratable = 0, /* non-migratable */
> + .init = trusted_pkwm_init,
> + .seal = trusted_pkwm_seal,
> + .unseal = trusted_pkwm_unseal,
> + .exit = trusted_pkwm_exit,
> +};
> --
> 2.47.3
>
BR, Jarkko
^ permalink raw reply
* Re: [PATCH 2/6] powerpc/pseries: move the PLPKS config inside its own sysfs directory
From: kernel test robot @ 2025-12-13 18:21 UTC (permalink / raw)
To: Srish Srinivasan, linux-integrity, keyrings, linuxppc-dev
Cc: oe-kbuild-all, maddy, mpe, npiggin, christophe.leroy,
James.Bottomley, jarkko, zohar, nayna, rnsastry, linux-kernel,
linux-security-module, ssrish
In-Reply-To: <20251213052618.190691-3-ssrish@linux.ibm.com>
Hi Srish,
kernel test robot noticed the following build warnings:
[auto build test WARNING on powerpc/next]
[also build test WARNING on powerpc/fixes zohar-integrity/next-integrity linus/master v6.18 next-20251212]
[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/Srish-Srinivasan/pseries-plpks-fix-kernel-doc-comment-inconsistencies/20251213-132948
base: https://git.kernel.org/pub/scm/linux/kernel/git/powerpc/linux.git next
patch link: https://lore.kernel.org/r/20251213052618.190691-3-ssrish%40linux.ibm.com
patch subject: [PATCH 2/6] powerpc/pseries: move the PLPKS config inside its own sysfs directory
config: powerpc-allnoconfig (https://download.01.org/0day-ci/archive/20251214/202512140150.PUqCvp88-lkp@intel.com/config)
compiler: powerpc-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251214/202512140150.PUqCvp88-lkp@intel.com/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202512140150.PUqCvp88-lkp@intel.com/
All warnings (new ones prefixed by >>):
In file included from arch/powerpc/kernel/prom.c:59:
>> arch/powerpc/include/asm/plpks.h:118:12: warning: 'plpks_config_create_softlink' defined but not used [-Wunused-function]
118 | static int plpks_config_create_softlink(struct kobject *from) { return 0; }
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
vim +/plpks_config_create_softlink +118 arch/powerpc/include/asm/plpks.h
111
112 int plpks_config_create_softlink(struct kobject *from);
113 #else // CONFIG_PSERIES_PLPKS
114 static inline bool plpks_is_available(void) { return false; }
115 static inline u16 plpks_get_passwordlen(void) { BUILD_BUG(); }
116 static inline void plpks_early_init_devtree(void) { }
117 static inline int plpks_populate_fdt(void *fdt) { BUILD_BUG(); }
> 118 static int plpks_config_create_softlink(struct kobject *from) { return 0; }
119 #endif // CONFIG_PSERIES_PLPKS
120
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
^ permalink raw reply
* [PATCH 6/6] docs: trusted-encryped: add PKWM as a new trust source
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
In-Reply-To: <20251213052618.190691-1-ssrish@linux.ibm.com>
From: Nayna Jain <nayna@linux.ibm.com>
Update Documentation/security/keys/trusted-encrypted.rst and Documentation/
admin-guide/kernel-parameters.txt with PowerVM Key Wrapping Module (PKWM)
as a new trust source
Signed-off-by: Nayna Jain <nayna@linux.ibm.com>
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
---
.../admin-guide/kernel-parameters.txt | 1 +
.../security/keys/trusted-encrypted.rst | 50 +++++++++++++++++++
2 files changed, 51 insertions(+)
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index a8d0afde7f85..ccb9c2f502fb 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -7755,6 +7755,7 @@ Kernel parameters
- "tee"
- "caam"
- "dcp"
+ - "pkwm"
If not specified then it defaults to iterating through
the trust source list starting with TPM and assigns the
first trust source as a backend which is initialized
diff --git a/Documentation/security/keys/trusted-encrypted.rst b/Documentation/security/keys/trusted-encrypted.rst
index eae6a36b1c9a..ddff7c7c2582 100644
--- a/Documentation/security/keys/trusted-encrypted.rst
+++ b/Documentation/security/keys/trusted-encrypted.rst
@@ -81,6 +81,14 @@ safe.
and the UNIQUE key. Default is to use the UNIQUE key, but selecting
the OTP key can be done via a module parameter (dcp_use_otp_key).
+ (5) PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
+
+ Rooted to a unique, per-LPAR key, which is derived from a system-wide,
+ randomly generated LPAR root key. Both the per-LPAR keys and the LPAR
+ root key are stored in hypervisor-owned secure memory at runtime,
+ and the LPAR root key is additionally persisted in secure locations
+ such as the processor SEEPROMs and encrypted NVRAM.
+
* Execution isolation
(1) TPM
@@ -102,6 +110,14 @@ safe.
environment. Only basic blob key encryption is executed there.
The actual key sealing/unsealing is done on main processor/kernel space.
+ (5) PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
+
+ Fixed set of cryptographic operations done on on-chip hardware
+ cryptographic acceleration unit NX. Keys for wrapping and unwrapping
+ are managed by PowerVM Platform KeyStore, which stores keys in an
+ isolated in-memory copy in secure hypervisor memory, as well as in a
+ persistent copy in hypervisor-encrypted NVRAM.
+
* Optional binding to platform integrity state
(1) TPM
@@ -129,6 +145,11 @@ safe.
Relies on Secure/Trusted boot process (called HAB by vendor) for
platform integrity.
+ (5) PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
+
+ Relies on secure and trusted boot process of IBM Power systems for
+ platform integrity.
+
* Interfaces and APIs
(1) TPM
@@ -149,6 +170,11 @@ safe.
Vendor-specific API that is implemented as part of the DCP crypto driver in
``drivers/crypto/mxs-dcp.c``.
+ (5) PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
+
+ Platform Keystore has well documented interfaces in PAPR document.
+ Refer to ``Documentation/arch/powerpc/papr_hcalls.rst``
+
* Threat model
The strength and appropriateness of a particular trust source for a given
@@ -191,6 +217,10 @@ selected trust source:
a dedicated hardware RNG that is independent from DCP which can be enabled
to back the kernel RNG.
+ * PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
+
+ The normal kernel random number generator is used to generate keys.
+
Users may override this by specifying ``trusted.rng=kernel`` on the kernel
command-line to override the used RNG with the kernel's random number pool.
@@ -321,6 +351,26 @@ Usage::
specific to this DCP key-blob implementation. The key length for new keys is
always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).
+Trusted Keys usage: PKWM
+------------------------
+
+Usage::
+
+ keyctl add trusted name "new keylen [options]" ring
+ keyctl add trusted name "load hex_blob" ring
+ keyctl print keyid
+
+ options:
+ wrap_flags= ascii hex value of security policy requirement
+ 0x00: no secure boot requirement (default)
+ 0x01: require secure boot to be in either audit or
+ enforced mode
+ 0x02: require secure boot to be in enforced mode
+
+"keyctl print" returns an ASCII hex copy of the sealed key, which is in format
+specific to PKWM key-blob implementation. The key length for new keys is
+always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).
+
Encrypted Keys usage
--------------------
--
2.47.3
^ permalink raw reply related
* [PATCH 5/6] keys/trusted_keys: establish PKWM as a trusted source
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
In-Reply-To: <20251213052618.190691-1-ssrish@linux.ibm.com>
The wrapping key does not exist by default and is generated by the
hypervisor as a part of PKWM initialization. This key is then persisted by
the hypervisor and is used to wrap trusted keys. These are variable length
symmetric keys, which in the case of PowerVM Key Wrapping Module (PKWM) are
generated using the kernel RNG. PKWM can be used as a trust source through
the following example keyctl command
keyctl add trusted my_trusted_key "new 32" @u
Use the wrap_flags command option to set the secure boot requirement for
the wrapping request through the following keyctl commands
case1: no secure boot requirement. (default)
keyctl usage: keyctl add trusted my_trusted_key "new 32" @u
OR
keyctl add trusted my_trusted_key "new 32 wrap_flags=0x00" @u
case2: secure boot required to in either audit or enforce mode. set bit 0
keyctl usage: keyctl add trusted my_trusted_key "new 32 wrap_flags=0x01" @u
case3: secure boot required to be in enforce mode. set bit 1
keyctl usage: keyctl add trusted my_trusted_key "new 32 wrap_flags=0x02" @u
NOTE:
-> Setting the secure boot requirement is NOT a must.
-> Only either of the secure boot requirement options should be set. Not
both.
-> All the other bits are requied to be not set.
-> Set the kernel parameter trusted.source=pkwm to choose PKWM as the
backend for trusted keys implementation.
-> CONFIG_PSERIES_PLPKS must be enabled to build PKWM.
Add PKWM, which is a combination of IBM PowerVM and Power LPAR Platform
KeyStore, as a new trust source for trusted keys.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
---
MAINTAINERS | 9 ++
include/keys/trusted-type.h | 7 +-
include/keys/trusted_pkwm.h | 30 ++++
security/keys/trusted-keys/Kconfig | 8 ++
security/keys/trusted-keys/Makefile | 2 +
security/keys/trusted-keys/trusted_core.c | 6 +-
security/keys/trusted-keys/trusted_pkwm.c | 168 ++++++++++++++++++++++
7 files changed, 228 insertions(+), 2 deletions(-)
create mode 100644 include/keys/trusted_pkwm.h
create mode 100644 security/keys/trusted-keys/trusted_pkwm.c
diff --git a/MAINTAINERS b/MAINTAINERS
index aff3e162180d..bf78ab78a309 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -13993,6 +13993,15 @@ S: Supported
F: include/keys/trusted_dcp.h
F: security/keys/trusted-keys/trusted_dcp.c
+KEYS-TRUSTED-PLPKS
+M: Srish Srinivasan <ssrish@linux.ibm.com>
+M: Nayna Jain <nayna@linux.ibm.com>
+L: linux-integrity@vger.kernel.org
+L: keyrings@vger.kernel.org
+S: Supported
+F: include/keys/trusted_plpks.h
+F: security/keys/trusted-keys/trusted_pkwm.c
+
KEYS-TRUSTED-TEE
M: Sumit Garg <sumit.garg@kernel.org>
L: linux-integrity@vger.kernel.org
diff --git a/include/keys/trusted-type.h b/include/keys/trusted-type.h
index 4eb64548a74f..45c6c538df22 100644
--- a/include/keys/trusted-type.h
+++ b/include/keys/trusted-type.h
@@ -19,7 +19,11 @@
#define MIN_KEY_SIZE 32
#define MAX_KEY_SIZE 128
-#define MAX_BLOB_SIZE 512
+#if IS_ENABLED(CONFIG_TRUSTED_KEYS_PKWM)
+#define MAX_BLOB_SIZE 1152
+#else
+#define MAX_BLOB_SIZE 512
+#endif
#define MAX_PCRINFO_SIZE 64
#define MAX_DIGEST_SIZE 64
@@ -46,6 +50,7 @@ struct trusted_key_options {
uint32_t policydigest_len;
unsigned char policydigest[MAX_DIGEST_SIZE];
uint32_t policyhandle;
+ uint16_t wrap_flags;
};
struct trusted_key_ops {
diff --git a/include/keys/trusted_pkwm.h b/include/keys/trusted_pkwm.h
new file mode 100644
index 000000000000..736edfc1e1dd
--- /dev/null
+++ b/include/keys/trusted_pkwm.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __PKWM_TRUSTED_KEY_H
+#define __PKWM_TRUSTED_KEY_H
+
+#include <keys/trusted-type.h>
+
+extern struct trusted_key_ops pkwm_trusted_key_ops;
+
+#define PKWM_DEBUG 0
+
+#if PKWM_DEBUG
+static inline void dump_options(struct trusted_key_options *o)
+{
+ bool sb_audit_or_enforce_bit = o->policyhandle & BIT(0);
+ bool sb_enforce_bit = o->policyhandle & BIT(1);
+
+ if (sb_audit_or_enforce_bit)
+ pr_info("secure boot mode: audit or enforce");
+ else if (sb_enforce_bit)
+ pr_info("secure boot mode: enforce");
+ else
+ pr_info("secure boot mode: disabled");
+}
+#else
+static inline void dump_options(struct trusted_key_options *o)
+{
+}
+#endif
+
+#endif
diff --git a/security/keys/trusted-keys/Kconfig b/security/keys/trusted-keys/Kconfig
index 204a68c1429d..9e00482d886a 100644
--- a/security/keys/trusted-keys/Kconfig
+++ b/security/keys/trusted-keys/Kconfig
@@ -46,6 +46,14 @@ config TRUSTED_KEYS_DCP
help
Enable use of NXP's DCP (Data Co-Processor) as trusted key backend.
+config TRUSTED_KEYS_PKWM
+ bool "PKWM-based trusted keys"
+ depends on PSERIES_PLPKS >= TRUSTED_KEYS
+ default y
+ select HAVE_TRUSTED_KEYS
+ help
+ Enable use of IBM PowerVM Key Wrapping Module (PKWM) as a trusted key backend.
+
if !HAVE_TRUSTED_KEYS
comment "No trust source selected!"
endif
diff --git a/security/keys/trusted-keys/Makefile b/security/keys/trusted-keys/Makefile
index f0f3b27f688b..5fc053a21dad 100644
--- a/security/keys/trusted-keys/Makefile
+++ b/security/keys/trusted-keys/Makefile
@@ -16,3 +16,5 @@ trusted-$(CONFIG_TRUSTED_KEYS_TEE) += trusted_tee.o
trusted-$(CONFIG_TRUSTED_KEYS_CAAM) += trusted_caam.o
trusted-$(CONFIG_TRUSTED_KEYS_DCP) += trusted_dcp.o
+
+trusted-$(CONFIG_TRUSTED_KEYS_PKWM) += trusted_pkwm.o
diff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c
index b1680ee53f86..2d328de170e8 100644
--- a/security/keys/trusted-keys/trusted_core.c
+++ b/security/keys/trusted-keys/trusted_core.c
@@ -12,6 +12,7 @@
#include <keys/trusted_caam.h>
#include <keys/trusted_dcp.h>
#include <keys/trusted_tpm.h>
+#include <keys/trusted_pkwm.h>
#include <linux/capability.h>
#include <linux/err.h>
#include <linux/init.h>
@@ -31,7 +32,7 @@ MODULE_PARM_DESC(rng, "Select trusted key RNG");
static char *trusted_key_source;
module_param_named(source, trusted_key_source, charp, 0);
-MODULE_PARM_DESC(source, "Select trusted keys source (tpm, tee, caam or dcp)");
+MODULE_PARM_DESC(source, "Select trusted keys source (tpm, tee, caam, dcp or pkwm)");
static const struct trusted_key_source trusted_key_sources[] = {
#if defined(CONFIG_TRUSTED_KEYS_TPM)
@@ -46,6 +47,9 @@ static const struct trusted_key_source trusted_key_sources[] = {
#if defined(CONFIG_TRUSTED_KEYS_DCP)
{ "dcp", &dcp_trusted_key_ops },
#endif
+#if defined(CONFIG_TRUSTED_KEYS_PKWM)
+ { "pkwm", &pkwm_trusted_key_ops },
+#endif
};
DEFINE_STATIC_CALL_NULL(trusted_key_seal, *trusted_key_sources[0].ops->seal);
diff --git a/security/keys/trusted-keys/trusted_pkwm.c b/security/keys/trusted-keys/trusted_pkwm.c
new file mode 100644
index 000000000000..7968601dcf42
--- /dev/null
+++ b/security/keys/trusted-keys/trusted_pkwm.c
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2025 IBM Corporation, Srish Srinivasan <ssrish@linux.ibm.com>
+ */
+
+#include <keys/trusted_pkwm.h>
+#include <keys/trusted-type.h>
+#include <linux/build_bug.h>
+#include <linux/key-type.h>
+#include <linux/parser.h>
+#include <asm/plpks.h>
+
+enum {
+ Opt_err,
+ Opt_wrap_flags,
+};
+
+static const match_table_t key_tokens = {
+ {Opt_wrap_flags, "wrap_flags=%s"},
+ {Opt_err, NULL}
+};
+
+static int getoptions(char *datablob, struct trusted_key_options **opt)
+{
+ substring_t args[MAX_OPT_ARGS];
+ char *p = datablob;
+ int token;
+ int res;
+ unsigned long wrap_flags;
+ unsigned long token_mask = 0;
+
+ if (!datablob)
+ return 0;
+
+ while ((p = strsep(&datablob, " \t"))) {
+ if (*p == '\0' || *p == ' ' || *p == '\t')
+ continue;
+
+ token = match_token(p, key_tokens, args);
+ if (test_and_set_bit(token, &token_mask))
+ return -EINVAL;
+
+ switch (token) {
+ case Opt_wrap_flags:
+ res = kstrtoul(args[0].from, 16, &wrap_flags);
+ if (res < 0 || wrap_flags > 2)
+ return -EINVAL;
+ (*opt)->wrap_flags = wrap_flags;
+ break;
+ default:
+ return -EINVAL;
+ }
+ }
+ return 0;
+}
+
+static struct trusted_key_options *trusted_options_alloc(void)
+{
+ struct trusted_key_options *options;
+
+ options = kzalloc(sizeof(*options), GFP_KERNEL);
+ return options;
+}
+
+static int trusted_pkwm_seal(struct trusted_key_payload *p, char *datablob)
+{
+ struct trusted_key_options *options = NULL;
+ u8 *input_buf, *output_buf;
+ u32 output_len, input_len;
+ int rc;
+
+ options = trusted_options_alloc();
+ if (!options)
+ return -ENOMEM;
+
+ rc = getoptions(datablob, &options);
+ if (rc < 0)
+ goto out;
+ dump_options(options);
+
+ input_len = p->key_len;
+ input_buf = kmalloc(ALIGN(input_len, 4096), GFP_KERNEL);
+ if (!input_buf) {
+ pr_err("Input buffer allocation failed. Returning -ENOMEM.");
+ return -ENOMEM;
+ }
+
+ memcpy(input_buf, p->key, p->key_len);
+
+ rc = plpks_wrap_object(&input_buf, input_len, options->wrap_flags,
+ &output_buf, &output_len);
+ if (!rc) {
+ memcpy(p->blob, output_buf, output_len);
+ p->blob_len = output_len;
+ dump_payload(p);
+ } else {
+ pr_err("Invalid argument");
+ }
+
+ kfree(input_buf);
+ kfree(output_buf);
+
+out:
+ kfree_sensitive(options);
+ return rc;
+}
+
+static int trusted_pkwm_unseal(struct trusted_key_payload *p, char *datablob)
+{
+ u8 *input_buf, *output_buf;
+ u32 input_len, output_len;
+ int rc;
+
+ input_len = p->blob_len;
+ input_buf = kmalloc(ALIGN(input_len, 4096), GFP_KERNEL);
+ if (!input_buf)
+ return -ENOMEM;
+
+ memcpy(input_buf, p->blob, p->blob_len);
+
+ rc = plpks_unwrap_object(&input_buf, input_len, &output_buf,
+ &output_len);
+ if (!rc) {
+ memcpy(p->key, output_buf, output_len);
+ p->key_len = output_len;
+ dump_payload(p);
+ } else {
+ pr_err("Invalid argument");
+ }
+
+ kfree(input_buf);
+ kfree(output_buf);
+
+ return rc;
+}
+
+static int trusted_pkwm_init(void)
+{
+ int ret;
+
+ if (!plpks_wrapping_is_supported()) {
+ pr_err("H_PKS_WRAP_OBJECT interface not supported\n");
+
+ return -ENODEV;
+ }
+
+ ret = plpks_gen_wrapping_key();
+ if (ret) {
+ pr_err("Failed to generate default wrapping key\n");
+
+ return -EINVAL;
+ }
+
+ return register_key_type(&key_type_trusted);
+}
+
+static void trusted_pkwm_exit(void)
+{
+ unregister_key_type(&key_type_trusted);
+}
+
+struct trusted_key_ops pkwm_trusted_key_ops = {
+ .migratable = 0, /* non-migratable */
+ .init = trusted_pkwm_init,
+ .seal = trusted_pkwm_seal,
+ .unseal = trusted_pkwm_unseal,
+ .exit = trusted_pkwm_exit,
+};
--
2.47.3
^ permalink raw reply related
* [PATCH 4/6] pseries/plpks: add HCALLs for PowerVM Key Wrapping Module
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
In-Reply-To: <20251213052618.190691-1-ssrish@linux.ibm.com>
The hypervisor generated wrapping key is an AES-GCM-256 symmetric key which
is stored in a non-volatile, secure, and encrypted storage called the Power
LPAR Platform KeyStore. It has policy based protections that prevent it
from being read out or exposed to the user.
Implement H_PKS_GEN_KEY, H_PKS_WRAP_OBJECT, and H_PKS_UNWRAP_OBJECT HCALLs
to enable using the PowerVM Key Wrapping Module (PKWM) as a new trust
source for trusted keys. Disallow H_PKS_READ_OBJECT, H_PKS_SIGNED_UPDATE,
and H_PKS_WRITE_OBJECT for objects with the 'wrapping key' policy set.
Capture the availability status for the H_PKS_WRAP_OBJECT interface.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
---
Documentation/arch/powerpc/papr_hcalls.rst | 43 +++
arch/powerpc/include/asm/plpks.h | 10 +
arch/powerpc/platforms/pseries/plpks.c | 345 ++++++++++++++++++++-
3 files changed, 396 insertions(+), 2 deletions(-)
diff --git a/Documentation/arch/powerpc/papr_hcalls.rst b/Documentation/arch/powerpc/papr_hcalls.rst
index 805e1cb9bab9..14e39f095a1c 100644
--- a/Documentation/arch/powerpc/papr_hcalls.rst
+++ b/Documentation/arch/powerpc/papr_hcalls.rst
@@ -300,6 +300,49 @@ H_HTM supports setup, configuration, control and dumping of Hardware Trace
Macro (HTM) function and its data. HTM buffer stores tracing data for functions
like core instruction, core LLAT and nest.
+**H_PKS_GEN_KEY**
+
+| Input: authorization, objectlabel, objectlabellen, policy, out, outlen
+| Out: *Hypervisor Generated Key, or None when the wrapping key policy is set*
+| Return Value: *H_SUCCESS, H_Function, H_State, H_R_State, H_Parameter, H_P2,
+ H_P3, H_P4, H_P5, H_P6, H_Authority, H_Nomem, H_Busy, H_Resource,
+ H_Aborted*
+
+H_PKS_GEN_KEY is used to have the hypervisor generate a new random key.
+This key is stored as an object in the Power LPAR Platform KeyStore with
+the provided object label. With the wrapping key policy set the key is only
+visible to the hypervisor, while the key's label would still be visible to
+the user. Generation of wrapping keys is supported only for a key size of
+32 bytes.
+
+**H_PKS_WRAP_OBJECT**
+
+| Input: authorization, wrapkeylabel, wrapkeylabellen, objectwrapflags, in,
+| inlen, out, outlen, continue-token
+| Out: *continue-token, byte size of wrapped object, wrapped object*
+| Return Value: *H_SUCCESS, H_Function, H_State, H_R_State, H_Parameter, H_P2,
+ H_P3, H_P4, H_P5, H_P6, H_P7, H_P8, H_P9, H_Authority, H_Invalid_Key,
+ H_NOT_FOUND, H_Busy, H_LongBusy, H_Aborted*
+
+H_PKS_WRAP_OBJECT is used to wrap an object using a wrapping key stored in the
+Power LPAR Platform KeyStore and return the wrapped object to the caller. The
+caller provides a label to a wrapping key with the 'wrapping key' policy set,
+which must have been previously created with H_PKS_GEN_KEY. The provided object
+is then encrypted with the wrapping key and additional metadata and the result
+is returned to the caller.
+
+
+**H_PKS_UNWRAP_OBJECT**
+
+| Input: authorization, objectwrapflags, in, inlen, out, outlen, continue-token
+| Out: *continue-token, byte size of unwrapped object, unwrapped object*
+| Return Value: *H_SUCCESS, H_Function, H_State, H_R_State, H_Parameter, H_P2,
+ H_P3, H_P4, H_P5, H_P6, H_P7, H_Authority, H_Unsupported, H_Bad_Data,
+ H_NOT_FOUND, H_Invalid_Key, H_Busy, H_LongBusy, H_Aborted*
+
+H_PKS_UNWRAP_OBJECT is used to unwrap an object that was previously warapped with
+H_PKS_WRAP_OBJECT.
+
References
==========
.. [1] "Power Architecture Platform Reference"
diff --git a/arch/powerpc/include/asm/plpks.h b/arch/powerpc/include/asm/plpks.h
index 8c20fd5a8fd4..42ef23519956 100644
--- a/arch/powerpc/include/asm/plpks.h
+++ b/arch/powerpc/include/asm/plpks.h
@@ -113,6 +113,16 @@ void plpks_early_init_devtree(void);
int plpks_populate_fdt(void *fdt);
int plpks_config_create_softlink(struct kobject *from);
+
+bool plpks_wrapping_is_supported(void);
+
+int plpks_gen_wrapping_key(void);
+
+int plpks_wrap_object(u8 **input_buf, u32 input_len, u16 wrap_flags,
+ u8 **output_buf, u32 *output_len);
+
+int plpks_unwrap_object(u8 **input_buf, u32 input_len,
+ u8 **output_buf, u32 *output_len);
#else // CONFIG_PSERIES_PLPKS
static inline bool plpks_is_available(void) { return false; }
static inline u16 plpks_get_passwordlen(void) { BUILD_BUG(); }
diff --git a/arch/powerpc/platforms/pseries/plpks.c b/arch/powerpc/platforms/pseries/plpks.c
index 4a08f51537c8..2ec04908b057 100644
--- a/arch/powerpc/platforms/pseries/plpks.c
+++ b/arch/powerpc/platforms/pseries/plpks.c
@@ -9,6 +9,32 @@
#define pr_fmt(fmt) "plpks: " fmt
+#define PLPKS_WRAPKEY_COMPONENT "PLPKSWR"
+#define PLPKS_WRAPKEY_NAME "default-wrapping-key"
+
+/*
+ * To 4K align the {input, output} buffers to the {UN}WRAP H_CALLs
+ */
+#define PLPKS_WRAPPING_BUF_ALIGN 4096
+
+/*
+ * To ensure the output buffer's length is at least 1024 bytes greater
+ * than the input buffer's length during the WRAP H_CALL
+ */
+#define PLPKS_WRAPPING_BUF_DIFF 1024
+
+#define PLPKS_WRAP_INTERFACE_BIT 3
+#define PLPKS_WRAPPING_KEY_LENGTH 32
+
+#define WRAPFLAG_BE_BIT_SET(be_bit) \
+ BIT_ULL(63 - (be_bit))
+
+#define WRAPFLAG_BE_GENMASK(be_bit_hi, be_bit_lo) \
+ GENMASK_ULL(63 - (be_bit_hi), 63 - (be_bit_lo))
+
+#define WRAPFLAG_BE_FIELD_PREP(be_bit_hi, be_bit_lo, val) \
+ FIELD_PREP(WRAPFLAG_BE_GENMASK(be_bit_hi, be_bit_lo), (val))
+
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/io.h>
@@ -39,6 +65,7 @@ static u32 supportedpolicies;
static u32 maxlargeobjectsize;
static u64 signedupdatealgorithms;
static u64 wrappingfeatures;
+static bool wrapsupport;
struct plpks_auth {
u8 version;
@@ -283,6 +310,7 @@ static int _plpks_get_config(void)
maxlargeobjectsize = be32_to_cpu(config->maxlargeobjectsize);
signedupdatealgorithms = be64_to_cpu(config->signedupdatealgorithms);
wrappingfeatures = be64_to_cpu(config->wrappingfeatures);
+ wrapsupport = config->flags & PPC_BIT8(PLPKS_WRAP_INTERFACE_BIT);
// Validate that the numbers we get back match the requirements of the spec
if (maxpwsize < 32) {
@@ -614,6 +642,9 @@ int plpks_signed_update_var(struct plpks_var *var, u64 flags)
if (!(var->policy & PLPKS_SIGNEDUPDATE))
return -EINVAL;
+ if (var->policy & PLPKS_WRAPPINGKEY)
+ return -EINVAL;
+
// Signed updates need the component to be NULL.
if (var->component)
return -EINVAL;
@@ -696,6 +727,9 @@ int plpks_write_var(struct plpks_var var)
if (var.policy & PLPKS_SIGNEDUPDATE)
return -EINVAL;
+ if (var.policy & PLPKS_WRAPPINGKEY)
+ return -EINVAL;
+
auth = construct_auth(PLPKS_OS_OWNER);
if (IS_ERR(auth))
return PTR_ERR(auth);
@@ -790,6 +824,9 @@ static int plpks_read_var(u8 consumer, struct plpks_var *var)
if (var->namelen > PLPKS_MAX_NAME_SIZE)
return -EINVAL;
+ if (var->policy & PLPKS_WRAPPINGKEY)
+ return -EINVAL;
+
auth = construct_auth(consumer);
if (IS_ERR(auth))
return PTR_ERR(auth);
@@ -845,8 +882,312 @@ static int plpks_read_var(u8 consumer, struct plpks_var *var)
}
/**
- * plpks_read_os_var() - Fetch the data for the specified variable that is
- * owned by the OS consumer.
+ * plpks_wrapping_is_supported() - Get the H_PKS_WRAP_OBJECT interface
+ * availability status for the LPAR.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * sets bit 3 of the flags variable in the PLPKS config structure if the
+ * H_PKS_WRAP_OBJECT interface is supported.
+ *
+ * Returns: true if the H_PKS_WRAP_OBJECT interface is supported, false if not.
+ */
+bool plpks_wrapping_is_supported(void)
+{
+ return wrapsupport;
+}
+
+/**
+ * plpks_gen_wrapping_key() - Generate a new random key with the 'wrapping key'
+ * policy set.
+ *
+ * The H_PKS_GEN_KEY HCALL makes the hypervisor generate a new random key and
+ * store the key in a PLPKS object with the provided object label. With the
+ * 'wrapping key' policy set, only the label to the newly generated random key
+ * would be visible to the user.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if PLPKS modification is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * if invalid or unsupported policy declaration
+ * if invalid output buffer parameter
+ * if invalid output buffer length parameter
+ * -EPERM if access is denied
+ * -ENOMEM if there is inadequate memory to perform this operation
+ * -EBUSY if unable to handle the request
+ * -EEXIST if the object label already exists
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
+int plpks_gen_wrapping_key(void)
+{
+ unsigned long retbuf[PLPAR_HCALL_BUFSIZE] = { 0 };
+ struct plpks_auth *auth;
+ struct label *label;
+ int rc = 0, pseries_status = 0;
+ struct plpks_var var = {
+ .name = PLPKS_WRAPKEY_NAME,
+ .namelen = strlen(var.name),
+ .policy = PLPKS_WRAPPINGKEY,
+ .os = PLPKS_VAR_LINUX,
+ .component = PLPKS_WRAPKEY_COMPONENT
+ };
+
+ auth = construct_auth(PLPKS_OS_OWNER);
+ if (IS_ERR(auth))
+ return PTR_ERR(auth);
+
+ label = construct_label(var.component, var.os, var.name, var.namelen);
+ if (IS_ERR(label)) {
+ rc = PTR_ERR(label);
+ goto out;
+ }
+
+ rc = plpar_hcall(H_PKS_GEN_KEY, retbuf,
+ virt_to_phys(auth), virt_to_phys(label),
+ label->size, var.policy,
+ NULL, PLPKS_WRAPPING_KEY_LENGTH);
+
+ if (!rc)
+ rc = plpks_confirm_object_flushed(label, auth);
+
+ pseries_status = rc;
+ rc = pseries_status_to_err(rc);
+
+ if (rc && rc != -EEXIST) {
+ pr_err("H_PKS_GEN_KEY failed.");
+ pr_err("pseries_status = %d, error code = %d", pseries_status,
+ rc);
+ } else {
+ rc = 0;
+ }
+
+ kfree(label);
+out:
+ kfree(auth);
+ return rc;
+}
+EXPORT_SYMBOL_GPL(plpks_gen_wrapping_key);
+
+/**
+ * plpks_wrap_object() - Wrap an object using the default wrapping key stored in
+ * the PLPKS.
+ * @input_buf: buffer containing the data to be wrapped
+ * @input_len: length of the input buffer
+ * @wrap_flags: object wrapping flags
+ * @output_buf: buffer to store the wrapped data
+ * @output_len: length of the output buffer
+ *
+ * The H_PKS_WRAP_OBJECT HCALL wraps an object using a wrapping key stored in
+ * the PLPKS and returns the wrapped object to the caller. The caller provides a
+ * label to the wrapping key with the 'wrapping key' policy set that must have
+ * been previously created with the H_PKS_GEN_KEY HCALL. The provided object is
+ * then encrypted with the wrapping key and additional metadata and the result
+ * is returned to the user. The metadata includes the wrapping algorithm and the
+ * wrapping key name so those parameters are not required during unwrap.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if PLPKS modification is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid wraping key label parameter
+ * if invalid wrapping key label length parameter
+ * if invalid or unsupported object wrapping flags
+ * if invalid inut buffer parameter
+ * if invalid input buffer length parameter
+ * if invalid output buffer parameter
+ * if invalid output buffer length parameter
+ * if invalid continue token parameter
+ * if the wrapping key is not compatible with the wrapping
+ * algorithm
+ * -EPERM if access is denied
+ * -ENOENT if the requested wrapping key was not found
+ * -EBUSY if unable to handle the request or long running operation
+ * initiated, retry later.
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
+int plpks_wrap_object(u8 **input_buf, u32 input_len, u16 wrap_flags,
+ u8 **output_buf, u32 *output_len)
+{
+ unsigned long retbuf[PLPAR_HCALL9_BUFSIZE] = { 0 };
+ struct plpks_auth *auth;
+ struct label *label;
+ u64 continuetoken = 0;
+ u64 objwrapflags = 0;
+ int rc = 0, pseries_status = 0;
+ bool sb_audit_or_enforce_bit = wrap_flags & BIT(0);
+ bool sb_enforce_bit = wrap_flags & BIT(1);
+ struct plpks_var var = {
+ .name = PLPKS_WRAPKEY_NAME,
+ .namelen = strlen(var.name),
+ .os = PLPKS_VAR_LINUX,
+ .component = PLPKS_WRAPKEY_COMPONENT
+ };
+
+ auth = construct_auth(PLPKS_OS_OWNER);
+ if (IS_ERR(auth))
+ return PTR_ERR(auth);
+
+ label = construct_label(var.component, var.os, var.name, var.namelen);
+ if (IS_ERR(label)) {
+ rc = PTR_ERR(label);
+ goto out;
+ }
+
+ /* Set the consumer password requirement bit. A must have. */
+ objwrapflags |= WRAPFLAG_BE_BIT_SET(3);
+
+ /* Set the wrapping algorithm bit. Just one algorithm option for now */
+ objwrapflags |= WRAPFLAG_BE_FIELD_PREP(60, 63, 0x1);
+
+ if (sb_audit_or_enforce_bit & sb_enforce_bit) {
+ pr_err("Cannot set both audit/enforce and enforce bits.");
+ rc = -EINVAL;
+ goto out_free_label;
+ } else if (sb_audit_or_enforce_bit) {
+ objwrapflags |= WRAPFLAG_BE_BIT_SET(1);
+ } else if (sb_enforce_bit) {
+ objwrapflags |= WRAPFLAG_BE_BIT_SET(2);
+ }
+
+ *output_len = input_len + PLPKS_WRAPPING_BUF_DIFF;
+
+ *output_buf = kzalloc(ALIGN(*output_len, PLPKS_WRAPPING_BUF_ALIGN),
+ GFP_KERNEL);
+ if (!(*output_buf)) {
+ pr_err("Output buffer allocation failed. Returning -ENOMEM.");
+ rc = -ENOMEM;
+ goto out_free_label;
+ }
+
+ do {
+ rc = plpar_hcall9(H_PKS_WRAP_OBJECT, retbuf,
+ virt_to_phys(auth), virt_to_phys(label),
+ label->size, objwrapflags,
+ virt_to_phys(*input_buf), input_len,
+ virt_to_phys(*output_buf), *output_len,
+ continuetoken);
+
+ continuetoken = retbuf[0];
+ pseries_status = rc;
+ rc = pseries_status_to_err(rc);
+ } while (rc == -EBUSY);
+
+ if (rc) {
+ pr_err("H_PKS_WRAP_OBJECT failed.");
+ pr_err("pseries_status = %d, return code = %d", pseries_status,
+ rc);
+ kfree(*output_buf);
+ *output_buf = NULL;
+ } else {
+ *output_len = retbuf[1];
+ }
+
+out_free_label:
+ kfree(label);
+out:
+ kfree(auth);
+ return rc;
+}
+EXPORT_SYMBOL_GPL(plpks_wrap_object);
+
+/**
+ * plpks_unwrap_object() - Unwrap an object using the default wrapping key
+ * stored in the PLPKS.
+ * @input_buf: buffer containing the data to be unwrapped
+ * @input_len: length of the input buffer
+ * @output_buf: buffer to store the unwrapped data
+ * @output_len: length of the output buffer
+ *
+ * The H_PKS_UNWRAP_OBJECT HCALL unwraps an object that was previously wrapped
+ * using the H_PKS_WRAP_OBJECT HCALL.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if PLPKS modification is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid or unsupported object unwrapping flags
+ * if invalid inut buffer parameter
+ * if invalid input buffer length parameter
+ * if invalid output buffer parameter
+ * if invalid output buffer length parameter
+ * if invalid continue token parameter
+ * if the wrapping key is not compatible with the wrapping
+ * algorithm
+ * if the wrapped object's format is not supported
+ * if the wrapped object is invalid
+ * -EPERM if access is denied
+ * -ENOENT if the wrapping key for the provided object was not found
+ * -EBUSY if unable to handle the request or long running operation
+ * initiated, retry later.
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
+int plpks_unwrap_object(u8 **input_buf, u32 input_len, u8 **output_buf,
+ u32 *output_len)
+{
+ unsigned long retbuf[PLPAR_HCALL9_BUFSIZE] = { 0 };
+ struct plpks_auth *auth;
+ u64 continuetoken = 0;
+ u64 objwrapflags = 0;
+ int rc = 0, pseries_status = 0;
+
+ auth = construct_auth(PLPKS_OS_OWNER);
+ if (IS_ERR(auth))
+ return PTR_ERR(auth);
+
+ *output_len = input_len - PLPKS_WRAPPING_BUF_DIFF;
+ *output_buf = kzalloc(ALIGN(*output_len, PLPKS_WRAPPING_BUF_ALIGN),
+ GFP_KERNEL);
+ if (!(*output_buf)) {
+ pr_err("Output buffer allocation failed. Returning -ENOMEM.");
+ rc = -ENOMEM;
+ goto out;
+ }
+
+ do {
+ rc = plpar_hcall9(H_PKS_UNWRAP_OBJECT, retbuf,
+ virt_to_phys(auth), objwrapflags,
+ virt_to_phys(*input_buf), input_len,
+ virt_to_phys(*output_buf), *output_len,
+ continuetoken);
+
+ continuetoken = retbuf[0];
+ pseries_status = rc;
+ rc = pseries_status_to_err(rc);
+ } while (rc == -EBUSY);
+
+ if (rc) {
+ pr_err("H_PKS_UNWRAP_OBJECT failed.");
+ pr_err("pseries_status = %d, return code = %d", pseries_status,
+ rc);
+ kfree(*output_buf);
+ *output_buf = NULL;
+ } else {
+ *output_len = retbuf[1];
+ }
+
+out:
+ kfree(auth);
+ return rc;
+}
+EXPORT_SYMBOL_GPL(plpks_unwrap_object);
+
+/**
+ * plpks_read_os_var() - Fetch the data for the specified variable that is owned
+ * by the OS consumer.
* @var: variable to be read from the PLPKS
*
* The consumer or the owner of the object is the os kernel. The
--
2.47.3
^ permalink raw reply related
* [PATCH 2/6] powerpc/pseries: move the PLPKS config inside its own sysfs directory
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
In-Reply-To: <20251213052618.190691-1-ssrish@linux.ibm.com>
The /sys/firmware/secvar/config directory represents Power LPAR Platform
KeyStore (PLPKS) configuration properties such as max_object_size, signed_
update_algorithms, supported_policies, total_size, used_space, and version.
These attributes describe the PLPKS, and not the secure boot variables
(secvars).
Create /sys/firmware/plpks directory and move the PLPKS config inside this
directory. For backwards compatibility, create a soft link from the secvar
sysfs directory to this config and emit a warning stating that the older
sysfs path has been deprecated. Separate out the plpks specific
documentation from secvar.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
---
.../ABI/testing/sysfs-firmware-plpks | 50 ++++++++++
Documentation/ABI/testing/sysfs-secvar | 65 -------------
arch/powerpc/include/asm/plpks.h | 4 +
arch/powerpc/include/asm/secvar.h | 1 -
arch/powerpc/kernel/secvar-sysfs.c | 21 ++---
arch/powerpc/platforms/pseries/Makefile | 2 +-
arch/powerpc/platforms/pseries/plpks-secvar.c | 29 ------
arch/powerpc/platforms/pseries/plpks-sysfs.c | 94 +++++++++++++++++++
8 files changed, 155 insertions(+), 111 deletions(-)
create mode 100644 Documentation/ABI/testing/sysfs-firmware-plpks
create mode 100644 arch/powerpc/platforms/pseries/plpks-sysfs.c
diff --git a/Documentation/ABI/testing/sysfs-firmware-plpks b/Documentation/ABI/testing/sysfs-firmware-plpks
new file mode 100644
index 000000000000..af0353f34115
--- /dev/null
+++ b/Documentation/ABI/testing/sysfs-firmware-plpks
@@ -0,0 +1,50 @@
+What: /sys/firmware/plpks/config
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: This optional directory contains read-only config attributes as
+ defined by the PLPKS implementation. All data is in ASCII
+ format.
+
+What: /sys/firmware/plpks/config/version
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: Config version as reported by the hypervisor in ASCII decimal
+ format.
+
+What: /sys/firmware/plpks/config/max_object_size
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: Maximum allowed size of objects in the keystore in bytes,
+ represented in ASCII decimal format.
+
+ This is not necessarily the same as the max size that can be
+ written to an update file as writes can contain more than
+ object data, you should use the size of the update file for
+ that purpose.
+
+What: /sys/firmware/plpks/config/total_size
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: Total size of the PLPKS in bytes, represented in ASCII decimal
+ format.
+
+What: /sys/firmware/plpks/config/used_space
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: Current space consumed by the key store, in bytes, represented
+ in ASCII decimal format.
+
+What: /sys/firmware/plpks/config/supported_policies
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: Bitmask of supported policy flags by the hypervisor, represented
+ as an 8 byte hexadecimal ASCII string. Consult the hypervisor
+ documentation for what these flags are.
+
+What: /sys/firmware/plpks/config/signed_update_algorithms
+Date: February 2023
+Contact: Nayna Jain <nayna@linux.ibm.com>
+Description: Bitmask of flags indicating which algorithms the hypervisor
+ supports for signed update of objects, represented as a 16 byte
+ hexadecimal ASCII string. Consult the hypervisor documentation
+ for what these flags mean.
diff --git a/Documentation/ABI/testing/sysfs-secvar b/Documentation/ABI/testing/sysfs-secvar
index 1016967a730f..c52a5fd15709 100644
--- a/Documentation/ABI/testing/sysfs-secvar
+++ b/Documentation/ABI/testing/sysfs-secvar
@@ -63,68 +63,3 @@ Contact: Nayna Jain <nayna@linux.ibm.com>
Description: A write-only file that is used to submit the new value for the
variable. The size of the file represents the maximum size of
the variable data that can be written.
-
-What: /sys/firmware/secvar/config
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: This optional directory contains read-only config attributes as
- defined by the secure variable implementation. All data is in
- ASCII format. The directory is only created if the backing
- implementation provides variables to populate it, which at
- present is only PLPKS on the pseries platform.
-
-What: /sys/firmware/secvar/config/version
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: Config version as reported by the hypervisor in ASCII decimal
- format.
-
- Currently only provided by PLPKS on the pseries platform.
-
-What: /sys/firmware/secvar/config/max_object_size
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: Maximum allowed size of objects in the keystore in bytes,
- represented in ASCII decimal format.
-
- This is not necessarily the same as the max size that can be
- written to an update file as writes can contain more than
- object data, you should use the size of the update file for
- that purpose.
-
- Currently only provided by PLPKS on the pseries platform.
-
-What: /sys/firmware/secvar/config/total_size
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: Total size of the PLPKS in bytes, represented in ASCII decimal
- format.
-
- Currently only provided by PLPKS on the pseries platform.
-
-What: /sys/firmware/secvar/config/used_space
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: Current space consumed by the key store, in bytes, represented
- in ASCII decimal format.
-
- Currently only provided by PLPKS on the pseries platform.
-
-What: /sys/firmware/secvar/config/supported_policies
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: Bitmask of supported policy flags by the hypervisor,
- represented as an 8 byte hexadecimal ASCII string. Consult the
- hypervisor documentation for what these flags are.
-
- Currently only provided by PLPKS on the pseries platform.
-
-What: /sys/firmware/secvar/config/signed_update_algorithms
-Date: February 2023
-Contact: Nayna Jain <nayna@linux.ibm.com>
-Description: Bitmask of flags indicating which algorithms the hypervisor
- supports for signed update of objects, represented as a 16 byte
- hexadecimal ASCII string. Consult the hypervisor documentation
- for what these flags mean.
-
- Currently only provided by PLPKS on the pseries platform.
diff --git a/arch/powerpc/include/asm/plpks.h b/arch/powerpc/include/asm/plpks.h
index f303922bf622..53e5839b0cbe 100644
--- a/arch/powerpc/include/asm/plpks.h
+++ b/arch/powerpc/include/asm/plpks.h
@@ -13,6 +13,7 @@
#include <linux/types.h>
#include <linux/list.h>
+#include <linux/kobject.h>
// Object policy flags from supported_policies
#define PLPKS_OSSECBOOTAUDIT PPC_BIT32(1) // OS secure boot must be audit/enforce
@@ -107,11 +108,14 @@ u16 plpks_get_passwordlen(void);
void plpks_early_init_devtree(void);
int plpks_populate_fdt(void *fdt);
+
+int plpks_config_create_softlink(struct kobject *from);
#else // CONFIG_PSERIES_PLPKS
static inline bool plpks_is_available(void) { return false; }
static inline u16 plpks_get_passwordlen(void) { BUILD_BUG(); }
static inline void plpks_early_init_devtree(void) { }
static inline int plpks_populate_fdt(void *fdt) { BUILD_BUG(); }
+static int plpks_config_create_softlink(struct kobject *from) { return 0; }
#endif // CONFIG_PSERIES_PLPKS
#endif // _ASM_POWERPC_PLPKS_H
diff --git a/arch/powerpc/include/asm/secvar.h b/arch/powerpc/include/asm/secvar.h
index 4828e0ab7e3c..fd5006307f2a 100644
--- a/arch/powerpc/include/asm/secvar.h
+++ b/arch/powerpc/include/asm/secvar.h
@@ -20,7 +20,6 @@ struct secvar_operations {
int (*set)(const char *key, u64 key_len, u8 *data, u64 data_size);
ssize_t (*format)(char *buf, size_t bufsize);
int (*max_size)(u64 *max_size);
- const struct attribute **config_attrs;
// NULL-terminated array of fixed variable names
// Only used if get_next() isn't provided
diff --git a/arch/powerpc/kernel/secvar-sysfs.c b/arch/powerpc/kernel/secvar-sysfs.c
index ec900bce0257..4111b21962eb 100644
--- a/arch/powerpc/kernel/secvar-sysfs.c
+++ b/arch/powerpc/kernel/secvar-sysfs.c
@@ -12,6 +12,7 @@
#include <linux/string.h>
#include <linux/of.h>
#include <asm/secvar.h>
+#include <asm/plpks.h>
#define NAME_MAX_SIZE 1024
@@ -145,19 +146,6 @@ static __init int update_kobj_size(void)
return 0;
}
-static __init int secvar_sysfs_config(struct kobject *kobj)
-{
- struct attribute_group config_group = {
- .name = "config",
- .attrs = (struct attribute **)secvar_ops->config_attrs,
- };
-
- if (secvar_ops->config_attrs)
- return sysfs_create_group(kobj, &config_group);
-
- return 0;
-}
-
static __init int add_var(const char *name)
{
struct kobject *kobj;
@@ -260,12 +248,15 @@ static __init int secvar_sysfs_init(void)
goto err;
}
- rc = secvar_sysfs_config(secvar_kobj);
+ rc = plpks_config_create_softlink(secvar_kobj);
if (rc) {
- pr_err("Failed to create config directory\n");
+ pr_err("Failed to create softlink to PLPKS config directory");
goto err;
}
+ pr_info("/sys/firmware/secvar/config is now deprecated.\n");
+ pr_info("Will be removed in future versions.\n");
+
if (secvar_ops->get_next)
rc = secvar_sysfs_load();
else
diff --git a/arch/powerpc/platforms/pseries/Makefile b/arch/powerpc/platforms/pseries/Makefile
index 931ebaa474c8..3ced289a675b 100644
--- a/arch/powerpc/platforms/pseries/Makefile
+++ b/arch/powerpc/platforms/pseries/Makefile
@@ -30,7 +30,7 @@ obj-$(CONFIG_PAPR_SCM) += papr_scm.o
obj-$(CONFIG_PPC_SPLPAR) += vphn.o
obj-$(CONFIG_PPC_SVM) += svm.o
obj-$(CONFIG_FA_DUMP) += rtas-fadump.o
-obj-$(CONFIG_PSERIES_PLPKS) += plpks.o
+obj-$(CONFIG_PSERIES_PLPKS) += plpks.o plpks-sysfs.o
obj-$(CONFIG_PPC_SECURE_BOOT) += plpks-secvar.o
obj-$(CONFIG_PSERIES_PLPKS_SED) += plpks_sed_ops.o
obj-$(CONFIG_SUSPEND) += suspend.o
diff --git a/arch/powerpc/platforms/pseries/plpks-secvar.c b/arch/powerpc/platforms/pseries/plpks-secvar.c
index f9e9cc40c9d0..a50ff6943d80 100644
--- a/arch/powerpc/platforms/pseries/plpks-secvar.c
+++ b/arch/powerpc/platforms/pseries/plpks-secvar.c
@@ -20,33 +20,6 @@
#include <asm/secvar.h>
#include <asm/plpks.h>
-// Config attributes for sysfs
-#define PLPKS_CONFIG_ATTR(name, fmt, func) \
- static ssize_t name##_show(struct kobject *kobj, \
- struct kobj_attribute *attr, \
- char *buf) \
- { \
- return sysfs_emit(buf, fmt, func()); \
- } \
- static struct kobj_attribute attr_##name = __ATTR_RO(name)
-
-PLPKS_CONFIG_ATTR(version, "%u\n", plpks_get_version);
-PLPKS_CONFIG_ATTR(max_object_size, "%u\n", plpks_get_maxobjectsize);
-PLPKS_CONFIG_ATTR(total_size, "%u\n", plpks_get_totalsize);
-PLPKS_CONFIG_ATTR(used_space, "%u\n", plpks_get_usedspace);
-PLPKS_CONFIG_ATTR(supported_policies, "%08x\n", plpks_get_supportedpolicies);
-PLPKS_CONFIG_ATTR(signed_update_algorithms, "%016llx\n", plpks_get_signedupdatealgorithms);
-
-static const struct attribute *config_attrs[] = {
- &attr_version.attr,
- &attr_max_object_size.attr,
- &attr_total_size.attr,
- &attr_used_space.attr,
- &attr_supported_policies.attr,
- &attr_signed_update_algorithms.attr,
- NULL,
-};
-
static u32 get_policy(const char *name)
{
if ((strcmp(name, "db") == 0) ||
@@ -225,7 +198,6 @@ static const struct secvar_operations plpks_secvar_ops_static = {
.set = plpks_set_variable,
.format = plpks_secvar_format,
.max_size = plpks_max_size,
- .config_attrs = config_attrs,
.var_names = plpks_var_names_static,
};
@@ -234,7 +206,6 @@ static const struct secvar_operations plpks_secvar_ops_dynamic = {
.set = plpks_set_variable,
.format = plpks_secvar_format,
.max_size = plpks_max_size,
- .config_attrs = config_attrs,
.var_names = plpks_var_names_dynamic,
};
diff --git a/arch/powerpc/platforms/pseries/plpks-sysfs.c b/arch/powerpc/platforms/pseries/plpks-sysfs.c
new file mode 100644
index 000000000000..01d526185783
--- /dev/null
+++ b/arch/powerpc/platforms/pseries/plpks-sysfs.c
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2025 IBM Corporation, Srish Srinivasan <ssrish@linux.ibm.com>
+ *
+ * This code exposes PLPKS config to user via sysfs
+ */
+
+#define pr_fmt(fmt) "plpks-sysfs: "fmt
+
+#include <linux/init.h>
+#include <linux/printk.h>
+#include <linux/types.h>
+#include <asm/machdep.h>
+#include <asm/plpks.h>
+
+/* config attributes for sysfs */
+#define PLPKS_CONFIG_ATTR(name, fmt, func) \
+ static ssize_t name##_show(struct kobject *kobj, \
+ struct kobj_attribute *attr, \
+ char *buf) \
+ { \
+ return sysfs_emit(buf, fmt, func()); \
+ } \
+ static struct kobj_attribute attr_##name = __ATTR_RO(name)
+
+PLPKS_CONFIG_ATTR(version, "%u\n", plpks_get_version);
+PLPKS_CONFIG_ATTR(max_object_size, "%u\n", plpks_get_maxobjectsize);
+PLPKS_CONFIG_ATTR(total_size, "%u\n", plpks_get_totalsize);
+PLPKS_CONFIG_ATTR(used_space, "%u\n", plpks_get_usedspace);
+PLPKS_CONFIG_ATTR(supported_policies, "%08x\n", plpks_get_supportedpolicies);
+PLPKS_CONFIG_ATTR(signed_update_algorithms, "%016llx\n",
+ plpks_get_signedupdatealgorithms);
+
+static const struct attribute *config_attrs[] = {
+ &attr_version.attr,
+ &attr_max_object_size.attr,
+ &attr_total_size.attr,
+ &attr_used_space.attr,
+ &attr_supported_policies.attr,
+ &attr_signed_update_algorithms.attr,
+ NULL,
+};
+
+static struct kobject *plpks_kobj, *plpks_config_kobj;
+
+int plpks_config_create_softlink(struct kobject *from)
+{
+ if (!plpks_config_kobj)
+ return -EINVAL;
+ return sysfs_create_link(from, plpks_config_kobj, "config");
+}
+
+static __init int plpks_sysfs_config(struct kobject *kobj)
+{
+ struct attribute_group config_group = {
+ .name = NULL,
+ .attrs = (struct attribute **)config_attrs,
+ };
+
+ return sysfs_create_group(kobj, &config_group);
+}
+
+static __init int plpks_sysfs_init(void)
+{
+ int rc;
+
+ if (!plpks_is_available())
+ return -ENODEV;
+
+ plpks_kobj = kobject_create_and_add("plpks", firmware_kobj);
+ if (!plpks_kobj) {
+ pr_err("Failed to create plpks kobj\n");
+ return -ENOMEM;
+ }
+
+ plpks_config_kobj = kobject_create_and_add("config", plpks_kobj);
+ if (!plpks_config_kobj) {
+ pr_err("Failed to create plpks config kobj\n");
+ kobject_put(plpks_kobj);
+ return -ENOMEM;
+ }
+
+ rc = plpks_sysfs_config(plpks_config_kobj);
+ if (rc) {
+ pr_err("Failed to create attribute group for plpks config\n");
+ kobject_put(plpks_config_kobj);
+ kobject_put(plpks_kobj);
+ return rc;
+ }
+
+ return 0;
+}
+
+machine_subsys_initcall(pseries, plpks_sysfs_init);
--
2.47.3
^ permalink raw reply related
* [PATCH 1/6] pseries/plpks: fix kernel-doc comment inconsistencies
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
In-Reply-To: <20251213052618.190691-1-ssrish@linux.ibm.com>
Fix issues with comments for all the applicable functions to be
consistent with kernel-doc format. Move them before the function
definition as opposed to the function prototype.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
---
arch/powerpc/include/asm/plpks.h | 77 ------
arch/powerpc/platforms/pseries/plpks.c | 328 ++++++++++++++++++++++++-
2 files changed, 318 insertions(+), 87 deletions(-)
diff --git a/arch/powerpc/include/asm/plpks.h b/arch/powerpc/include/asm/plpks.h
index 7a84069759b0..f303922bf622 100644
--- a/arch/powerpc/include/asm/plpks.h
+++ b/arch/powerpc/include/asm/plpks.h
@@ -67,122 +67,45 @@ struct plpks_var_name_list {
struct plpks_var_name varlist[];
};
-/**
- * Updates the authenticated variable. It expects NULL as the component.
- */
int plpks_signed_update_var(struct plpks_var *var, u64 flags);
-/**
- * Writes the specified var and its data to PKS.
- * Any caller of PKS driver should present a valid component type for
- * their variable.
- */
int plpks_write_var(struct plpks_var var);
-/**
- * Removes the specified var and its data from PKS.
- */
int plpks_remove_var(char *component, u8 varos,
struct plpks_var_name vname);
-/**
- * Returns the data for the specified os variable.
- *
- * Caller must allocate a buffer in var->data with length in var->datalen.
- * If no buffer is provided, var->datalen will be populated with the object's
- * size.
- */
int plpks_read_os_var(struct plpks_var *var);
-/**
- * Returns the data for the specified firmware variable.
- *
- * Caller must allocate a buffer in var->data with length in var->datalen.
- * If no buffer is provided, var->datalen will be populated with the object's
- * size.
- */
int plpks_read_fw_var(struct plpks_var *var);
-/**
- * Returns the data for the specified bootloader variable.
- *
- * Caller must allocate a buffer in var->data with length in var->datalen.
- * If no buffer is provided, var->datalen will be populated with the object's
- * size.
- */
int plpks_read_bootloader_var(struct plpks_var *var);
-/**
- * Returns if PKS is available on this LPAR.
- */
bool plpks_is_available(void);
-/**
- * Returns version of the Platform KeyStore.
- */
u8 plpks_get_version(void);
-/**
- * Returns hypervisor storage overhead per object, not including the size of
- * the object or label. Only valid for config version >= 2
- */
u16 plpks_get_objoverhead(void);
-/**
- * Returns maximum password size. Must be >= 32 bytes
- */
u16 plpks_get_maxpwsize(void);
-/**
- * Returns maximum object size supported by Platform KeyStore.
- */
u16 plpks_get_maxobjectsize(void);
-/**
- * Returns maximum object label size supported by Platform KeyStore.
- */
u16 plpks_get_maxobjectlabelsize(void);
-/**
- * Returns total size of the configured Platform KeyStore.
- */
u32 plpks_get_totalsize(void);
-/**
- * Returns used space from the total size of the Platform KeyStore.
- */
u32 plpks_get_usedspace(void);
-/**
- * Returns bitmask of policies supported by the hypervisor.
- */
u32 plpks_get_supportedpolicies(void);
-/**
- * Returns maximum byte size of a single object supported by the hypervisor.
- * Only valid for config version >= 3
- */
u32 plpks_get_maxlargeobjectsize(void);
-/**
- * Returns bitmask of signature algorithms supported for signed updates.
- * Only valid for config version >= 3
- */
u64 plpks_get_signedupdatealgorithms(void);
-/**
- * Returns the length of the PLPKS password in bytes.
- */
u16 plpks_get_passwordlen(void);
-/**
- * Called in early init to retrieve and clear the PLPKS password from the DT.
- */
void plpks_early_init_devtree(void);
-/**
- * Populates the FDT with the PLPKS password to prepare for kexec.
- */
int plpks_populate_fdt(void *fdt);
#else // CONFIG_PSERIES_PLPKS
static inline bool plpks_is_available(void) { return false; }
diff --git a/arch/powerpc/platforms/pseries/plpks.c b/arch/powerpc/platforms/pseries/plpks.c
index b1667ed05f98..03722fabf9c3 100644
--- a/arch/powerpc/platforms/pseries/plpks.c
+++ b/arch/powerpc/platforms/pseries/plpks.c
@@ -312,40 +312,107 @@ static int _plpks_get_config(void)
return rc;
}
+/**
+ * plpks_get_version() - Get the version of the PLPKS config structure.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the PLPKS config structure version and saves it in a file local static
+ * version variable.
+ *
+ * Returns: On success the saved PLPKS config structure version is returned, 0
+ * if not.
+ */
u8 plpks_get_version(void)
{
return version;
}
+/**
+ * plpks_get_objoverhead() - Get the hypervisor storage overhead per object.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the per object hypervisor storage overhead in bytes into the local
+ * static objoverhead variable, excluding the size of the object or the label.
+ * This value can be treated as valid only when the PLPKS config structure
+ * version >= 2.
+ *
+ * Returns: If PLPKS config structure version >= 2 then the storage overhead is
+ * returned, 0 otherwise.
+ */
u16 plpks_get_objoverhead(void)
{
return objoverhead;
}
+/**
+ * plpks_get_maxpwsize() - Get the maximum password size.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the maximum password size and checks if it is 32 bytes at the least
+ * before storing it in the local static maxpwsize variable.
+ *
+ * Returns: On success the maximum password size is returned, 0 if not.
+ */
u16 plpks_get_maxpwsize(void)
{
return maxpwsize;
}
+/**
+ * plpks_get_maxobjectsize() - Get the maximum object size supported by the
+ * PLPKS.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the maximum object size into the file local static maxobjsize variable.
+ *
+ * Returns: On success the maximum object size is returned, 0 if not.
+ */
u16 plpks_get_maxobjectsize(void)
{
return maxobjsize;
}
+/**
+ * plpks_get_maxobjectlabelsize() - Get the maximum object label size supported
+ * by the PLPKS.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the maximum object label size into the local static maxobjlabelsize
+ * variable.
+ *
+ * Returns: On success the maximum object label size is returned, 0 if not.
+ */
u16 plpks_get_maxobjectlabelsize(void)
{
return maxobjlabelsize;
}
+/**
+ * plpks_get_totalsize() - Get the total size of the PLPKS that is configured.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the total size of the PLPKS that is configured for the LPAR into the
+ * file local static totalsize variable.
+ *
+ * Returns: On success the total size of the PLPKS configured is returned, 0 if
+ * not.
+ */
u32 plpks_get_totalsize(void)
{
return totalsize;
}
+/**
+ * plpks_get_usedspace() - Get the used space from the total size of the PLPKS.
+ *
+ * Invoke the H_PKS_GET_CONFIG HCALL to refresh the latest value for the used
+ * space as this keeps changing with the creation and removal of objects in the
+ * PLPKS.
+ *
+ * Returns: On success the used space is returned, 0 if not.
+ */
u32 plpks_get_usedspace(void)
{
- // Unlike other config values, usedspace regularly changes as objects
- // are updated, so we need to refresh.
int rc = _plpks_get_config();
if (rc) {
pr_err("Couldn't get config, rc: %d\n", rc);
@@ -354,26 +421,84 @@ u32 plpks_get_usedspace(void)
return usedspace;
}
+/**
+ * plpks_get_supportedpolicies() - Get a bitmask of the policies supported by
+ * the hypervisor.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads a bitmask of the policies supported by the hypervisor into the file
+ * local static supportedpolicies variable.
+ *
+ * Returns: On success the bitmask of the policies supported by the hypervisor
+ * are returned, 0 if not.
+ */
u32 plpks_get_supportedpolicies(void)
{
return supportedpolicies;
}
+/**
+ * plpks_get_maxlargeobjectsize() - Get the maximum object size supported for
+ * PLPKS config structure version >= 3
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads the maximum object size into the local static maxlargeobjectsize
+ * variable for PLPKS config structure version >= 3. This was introduced
+ * starting with PLPKS config structure version 3 to allow for objects of
+ * size >= 64K.
+ *
+ * Returns: If PLPKS config structure version >= 3 then the new maximum object
+ * size is returned, 0 if not.
+ */
u32 plpks_get_maxlargeobjectsize(void)
{
return maxlargeobjectsize;
}
+/**
+ * plpks_get_signedupdatealgorithms() - Get a bitmask of the signature
+ * algorithms supported for signed updates.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads a bitmask of the signature algorithms supported for signed updates into
+ * the file local static signedupdatealgorithms variable. This is valid only
+ * when the PLPKS config structure version >= 3.
+ *
+ * Returns: On success the bitmask of the signature algorithms supported for
+ * signed updates is returned, 0 if not.
+ */
u64 plpks_get_signedupdatealgorithms(void)
{
return signedupdatealgorithms;
}
+/**
+ * plpks_get_passwordlen() - Get the length of the PLPKS password in bytes.
+ *
+ * The H_PKS_GEN_PASSWORD HCALL makes the hypervisor generate a random password
+ * for the specified consumer, apply that password to the PLPKS and return it to
+ * the caller. In this process, the password length for the OS consumer is
+ * stored in the local static ospasswordlength variable.
+ *
+ * Returns: On success the password length for the OS consumer in bytes is
+ * returned, 0 if not.
+ */
u16 plpks_get_passwordlen(void)
{
return ospasswordlength;
}
+/**
+ * plpks_is_available() - Get the PLPKS availability status for the LPAR.
+ *
+ * The availability of PLPKS is inferred based upon the successful execution of
+ * the H_PKS_GET_CONFIG HCALL provided the firmware supports this feature. The
+ * H_PKS_GET_CONFIG HCALL reads the configuration and status information related
+ * to the PLPKS. The configuration structure provides a version number to inform
+ * the caller of the supported features.
+ *
+ * Returns: true is returned if PLPKS is available, false if not.
+ */
bool plpks_is_available(void)
{
int rc;
@@ -425,6 +550,35 @@ static int plpks_confirm_object_flushed(struct label *label,
return pseries_status_to_err(rc);
}
+/**
+ * plpks_signed_update_var() - Update the specified authenticated variable.
+ * @var: authenticated variable to be updated
+ * @flags: signed update request operation flags
+ *
+ * The H_PKS_SIGNED_UPDATE HCALL performs a signed update to an object in the
+ * PLPKS. The object must have the signed update policy flag set.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if PLPKS modification is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * if invalid or unsupported policy declaration
+ * if invalid signed update flags
+ * if invalid input data parameter
+ * if invalid input data len parameter
+ * if invalid continue token parameter
+ * -EPERM if access is denied
+ * -ENOMEM if there is inadequate memory to perform the operation
+ * -EBUSY if unable to handle the request or long running operation
+ * initiated, retry later
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
int plpks_signed_update_var(struct plpks_var *var, u64 flags)
{
unsigned long retbuf[PLPAR_HCALL9_BUFSIZE] = {0};
@@ -481,6 +635,33 @@ int plpks_signed_update_var(struct plpks_var *var, u64 flags)
return rc;
}
+/**
+ * plpks_write_var() - Write the specified variable and its data to PLPKS.
+ * @var: variable to be written into the PLPKS
+ *
+ * The H_PKS_WRITE_OBJECT HCALL writes an object into the PLPKS. The caller must
+ * provide a valid component type for the variable, and the signed update policy
+ * flag must not be set.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if PLPKS modification is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * if invalid or unsupported policy declaration
+ * if invalid input data parameter
+ * if invalid input data len parameter
+ * -EPERM if access is denied
+ * -ENOMEM if unable to store the requested object in the space available
+ * -EBUSY if unable to handle the request
+ * -EEXIST if the object label already exists
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
int plpks_write_var(struct plpks_var var)
{
unsigned long retbuf[PLPAR_HCALL_BUFSIZE] = { 0 };
@@ -520,6 +701,30 @@ int plpks_write_var(struct plpks_var var)
return rc;
}
+/**
+ * plpks_remove_var() - Remove the specified variable and its data from PLPKS.
+ * @component: metadata prefix in the object label metadata structure
+ * @varos: metadata OS flags in the object label metadata structure
+ * @vname: object label for the object that needs to be removed
+ *
+ * The H_PKS_REMOVE_OBJECT HCALL removes an object from the PLPKS. The removal
+ * is independent of the policy bits that are set.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if PLPKS modification is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * -EPERM if access is denied
+ * -ENOENT if the requested object was not found
+ * -EBUSY if unable to handle the request
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
int plpks_remove_var(char *component, u8 varos, struct plpks_var_name vname)
{
unsigned long retbuf[PLPAR_HCALL_BUFSIZE] = { 0 };
@@ -619,21 +824,119 @@ static int plpks_read_var(u8 consumer, struct plpks_var *var)
return rc;
}
+/**
+ * plpks_read_os_var() - Fetch the data for the specified variable that is
+ * owned by the OS consumer.
+ * @var: variable to be read from the PLPKS
+ *
+ * The consumer or the owner of the object is the os kernel. The
+ * H_PKS_READ_OBJECT HCALL reads an object from the PLPKS. The caller must
+ * allocate the buffer var->data and specify the length for this buffer in
+ * var->datalen. If no buffer is provided, var->datalen will be populated with
+ * the requested object's size.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * if invalid output data parameter
+ * if invalid output data len parameter
+ * -EPERM if access is denied
+ * -ENOENT if the requested object was not found
+ * -EFBIG if the requested object couldn't be
+ * stored in the buffer provided
+ * -EBUSY if unable to handle the request
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
int plpks_read_os_var(struct plpks_var *var)
{
return plpks_read_var(PLPKS_OS_OWNER, var);
}
+/**
+ * plpks_read_fw_var() - Fetch the data for the specified variable that is
+ * owned by the firmware consumer.
+ * @var: variable to be read from the PLPKS
+ *
+ * The consumer or the owner of the object is the firmware. The
+ * H_PKS_READ_OBJECT HCALL reads an object from the PLPKS. The caller must
+ * allocate the buffer var->data and specify the length for this buffer in
+ * var->datalen. If no buffer is provided, var->datalen will be populated with
+ * the requested object's size.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * if invalid output data parameter
+ * if invalid output data len parameter
+ * -EPERM if access is denied
+ * -ENOENT if the requested object was not found
+ * -EFBIG if the requested object couldn't be
+ * stored in the buffer provided
+ * -EBUSY if unable to handle the request
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
int plpks_read_fw_var(struct plpks_var *var)
{
return plpks_read_var(PLPKS_FW_OWNER, var);
}
+/**
+ * plpks_read_bootloader_var() - Fetch the data for the specified variable
+ * owned by the bootloader consumer.
+ * @var: variable to be read from the PLPKS
+ *
+ * The consumer or the owner of the object is the bootloader. The
+ * H_PKS_READ_OBJECT HCALL reads an object from the PLPKS. The caller must
+ * allocate the buffer var->data and specify the length for this buffer in
+ * var->datalen. If no buffer is provided, var->datalen will be populated with
+ * the requested object's size.
+ *
+ * Possible reasons for the returned errno values:
+ *
+ * -ENXIO if PLPKS is not supported
+ * -EIO if PLPKS access is blocked due to the LPAR's state
+ * if an error occurred while processing the request
+ * -EINVAL if invalid authorization parameter
+ * if invalid object label parameter
+ * if invalid object label len parameter
+ * if invalid output data parameter
+ * if invalid output data len parameter
+ * -EPERM if access is denied
+ * -ENOENT if the requested object was not found
+ * -EFBIG if the requested object couldn't be
+ * stored in the buffer provided
+ * -EBUSY if unable to handle the request
+ *
+ * Returns: On success 0 is returned, a negative errno if not.
+ */
int plpks_read_bootloader_var(struct plpks_var *var)
{
return plpks_read_var(PLPKS_BOOTLOADER_OWNER, var);
}
+/**
+ * plpks_populate_fdt(): Populates the FDT with the PLPKS password to prepare
+ * for kexec.
+ * @fdt: pointer to the device tree blob
+ *
+ * Upon confirming the existence of the chosen node, invoke fdt_setprop to
+ * populate the device tree with the PLPKS password in order to prepare for
+ * kexec.
+ *
+ * Returns: On success 0 is returned, a negative value if not.
+ */
int plpks_populate_fdt(void *fdt)
{
int chosen_offset = fdt_path_offset(fdt, "/chosen");
@@ -647,14 +950,19 @@ int plpks_populate_fdt(void *fdt)
return fdt_setprop(fdt, chosen_offset, "ibm,plpks-pw", ospassword, ospasswordlength);
}
-// Once a password is registered with the hypervisor it cannot be cleared without
-// rebooting the LPAR, so to keep using the PLPKS across kexec boots we need to
-// recover the previous password from the FDT.
-//
-// There are a few challenges here. We don't want the password to be visible to
-// users, so we need to clear it from the FDT. This has to be done in early boot.
-// Clearing it from the FDT would make the FDT's checksum invalid, so we have to
-// manually cause the checksum to be recalculated.
+/**
+ * plpks_early_init_devtree() - Retrieves and clears the PLPKS password from the
+ * DT in early init.
+ *
+ * Once a password is registered with the hypervisor it cannot be cleared
+ * without rebooting the LPAR, so to keep using the PLPKS across kexec boots we
+ * need to recover the previous password from the FDT.
+ *
+ * There are a few challenges here. We don't want the password to be visible to
+ * users, so we need to clear it from the FDT. This has to be done in early
+ * boot. Clearing it from the FDT would make the FDT's checksum invalid, so we
+ * have to manually cause the checksum to be recalculated.
+ */
void __init plpks_early_init_devtree(void)
{
void *fdt = initial_boot_params;
--
2.47.3
^ permalink raw reply related
* [PATCH 3/6] pseries/plpks: expose PowerVM wrapping features via the sysfs
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
In-Reply-To: <20251213052618.190691-1-ssrish@linux.ibm.com>
Starting with Power11, PowerVM supports a new feature called "Key Wrapping"
that protects user secrets by wrapping them using a hypervisor generated
wrapping key. The status of this feature can be read by the
H_PKS_GET_CONFIG HCALL.
Expose the Power LPAR Platform KeyStore (PLPKS) wrapping features config
via the sysfs file /sys/firmware/plpks/config/wrapping_features.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
---
.../ABI/testing/sysfs-firmware-plpks | 8 ++++++++
arch/powerpc/include/asm/hvcall.h | 4 +++-
arch/powerpc/include/asm/plpks.h | 3 +++
arch/powerpc/platforms/pseries/plpks-sysfs.c | 2 ++
arch/powerpc/platforms/pseries/plpks.c | 20 +++++++++++++++++++
5 files changed, 36 insertions(+), 1 deletion(-)
diff --git a/Documentation/ABI/testing/sysfs-firmware-plpks b/Documentation/ABI/testing/sysfs-firmware-plpks
index af0353f34115..cba061e4eee2 100644
--- a/Documentation/ABI/testing/sysfs-firmware-plpks
+++ b/Documentation/ABI/testing/sysfs-firmware-plpks
@@ -48,3 +48,11 @@ Description: Bitmask of flags indicating which algorithms the hypervisor
supports for signed update of objects, represented as a 16 byte
hexadecimal ASCII string. Consult the hypervisor documentation
for what these flags mean.
+
+What: /sys/firmware/plpks/config/wrapping_features
+Date: November 2025
+Contact: Srish Srinivasan <ssrish@linux.ibm.com>
+Description: Bitmask of the wrapping features indicating the wrapping
+ algorithms that are supported for the H_PKS_WRAP_OBJECT requests
+ , represented as a 8 byte hexadecimal ASCII string. Consult the
+ hypervisor documentation for what these flags mean.
diff --git a/arch/powerpc/include/asm/hvcall.h b/arch/powerpc/include/asm/hvcall.h
index 9aef16149d92..dff90a7d7f70 100644
--- a/arch/powerpc/include/asm/hvcall.h
+++ b/arch/powerpc/include/asm/hvcall.h
@@ -360,7 +360,9 @@
#define H_GUEST_RUN_VCPU 0x480
#define H_GUEST_COPY_MEMORY 0x484
#define H_GUEST_DELETE 0x488
-#define MAX_HCALL_OPCODE H_GUEST_DELETE
+#define H_PKS_WRAP_OBJECT 0x490
+#define H_PKS_UNWRAP_OBJECT 0x494
+#define MAX_HCALL_OPCODE H_PKS_UNWRAP_OBJECT
/* Scope args for H_SCM_UNBIND_ALL */
#define H_UNBIND_SCOPE_ALL (0x1)
diff --git a/arch/powerpc/include/asm/plpks.h b/arch/powerpc/include/asm/plpks.h
index 53e5839b0cbe..8c20fd5a8fd4 100644
--- a/arch/powerpc/include/asm/plpks.h
+++ b/arch/powerpc/include/asm/plpks.h
@@ -23,6 +23,7 @@
#define PLPKS_IMMUTABLE PPC_BIT32(5) // Once written, object cannot be removed
#define PLPKS_TRANSIENT PPC_BIT32(6) // Object does not persist through reboot
#define PLPKS_SIGNEDUPDATE PPC_BIT32(7) // Object can only be modified by signed updates
+#define PLPKS_WRAPPINGKEY PPC_BIT32(8) // Object contains a wrapping key
#define PLPKS_HVPROVISIONED PPC_BIT32(28) // Hypervisor has provisioned this object
// Signature algorithm flags from signed_update_algorithms
@@ -103,6 +104,8 @@ u32 plpks_get_maxlargeobjectsize(void);
u64 plpks_get_signedupdatealgorithms(void);
+u64 plpks_get_wrappingfeatures(void);
+
u16 plpks_get_passwordlen(void);
void plpks_early_init_devtree(void);
diff --git a/arch/powerpc/platforms/pseries/plpks-sysfs.c b/arch/powerpc/platforms/pseries/plpks-sysfs.c
index 01d526185783..c2ebcbb41ae3 100644
--- a/arch/powerpc/platforms/pseries/plpks-sysfs.c
+++ b/arch/powerpc/platforms/pseries/plpks-sysfs.c
@@ -30,6 +30,7 @@ PLPKS_CONFIG_ATTR(used_space, "%u\n", plpks_get_usedspace);
PLPKS_CONFIG_ATTR(supported_policies, "%08x\n", plpks_get_supportedpolicies);
PLPKS_CONFIG_ATTR(signed_update_algorithms, "%016llx\n",
plpks_get_signedupdatealgorithms);
+PLPKS_CONFIG_ATTR(wrapping_features, "%016llx\n", plpks_get_wrappingfeatures);
static const struct attribute *config_attrs[] = {
&attr_version.attr,
@@ -38,6 +39,7 @@ static const struct attribute *config_attrs[] = {
&attr_used_space.attr,
&attr_supported_policies.attr,
&attr_signed_update_algorithms.attr,
+ &attr_wrapping_features.attr,
NULL,
};
diff --git a/arch/powerpc/platforms/pseries/plpks.c b/arch/powerpc/platforms/pseries/plpks.c
index 03722fabf9c3..4a08f51537c8 100644
--- a/arch/powerpc/platforms/pseries/plpks.c
+++ b/arch/powerpc/platforms/pseries/plpks.c
@@ -38,6 +38,7 @@ static u32 usedspace;
static u32 supportedpolicies;
static u32 maxlargeobjectsize;
static u64 signedupdatealgorithms;
+static u64 wrappingfeatures;
struct plpks_auth {
u8 version;
@@ -248,6 +249,7 @@ static int _plpks_get_config(void)
__be32 supportedpolicies;
__be32 maxlargeobjectsize;
__be64 signedupdatealgorithms;
+ __be64 wrappingfeatures;
u8 rsvd1[476];
} __packed * config;
size_t size;
@@ -280,6 +282,7 @@ static int _plpks_get_config(void)
supportedpolicies = be32_to_cpu(config->supportedpolicies);
maxlargeobjectsize = be32_to_cpu(config->maxlargeobjectsize);
signedupdatealgorithms = be64_to_cpu(config->signedupdatealgorithms);
+ wrappingfeatures = be64_to_cpu(config->wrappingfeatures);
// Validate that the numbers we get back match the requirements of the spec
if (maxpwsize < 32) {
@@ -472,6 +475,23 @@ u64 plpks_get_signedupdatealgorithms(void)
return signedupdatealgorithms;
}
+/**
+ * plpks_get_wrappingfeatures() - Returns a bitmask of the wrapping features
+ * supported by the hypervisor.
+ *
+ * Successful execution of the H_PKS_GET_CONFIG HCALL during initialization
+ * reads a bitmask of the wrapping features supported by the hypervisor into the
+ * file local static wrappingfeatures variable. This is valid only when the
+ * PLPKS config structure version >= 3.
+ *
+ * Return:
+ * bitmask of the wrapping features supported by the hypervisor
+ */
+u64 plpks_get_wrappingfeatures(void)
+{
+ return wrappingfeatures;
+}
+
/**
* plpks_get_passwordlen() - Get the length of the PLPKS password in bytes.
*
--
2.47.3
^ permalink raw reply related
* [PATCH 0/6] Extend "trusted" keys to support a new trust source named the PowerVM Key Wrapping Module (PKWM)
From: Srish Srinivasan @ 2025-12-13 5:26 UTC (permalink / raw)
To: linux-integrity, keyrings, linuxppc-dev
Cc: maddy, mpe, npiggin, christophe.leroy, James.Bottomley, jarkko,
zohar, nayna, rnsastry, linux-kernel, linux-security-module,
ssrish
Power11 has introduced a feature called the PowerVM Key Wrapping Module
(PKWM), where PowerVM in combination with Power LPAR Platform KeyStore
(PLPKS) [1] supports a new feature called "Key Wrapping" [2] to protect
user secrets by wrapping them using a hypervisor generated wrapping key.
This wrapping key is an AES-GCM-256 symmetric key that is stored as an
object in the PLPKS. It has policy based protections that prevents it from
being read out or exposed to the user. This wrapping key can then be used
by the OS to wrap or unwrap secrets via hypervisor calls.
This patchset intends to add the PKWM, which is a combination of IBM
PowerVM and PLPKS, as a new trust source for trusted keys. The wrapping key
does not exist by default and its generation is requested by the kernel at
the time of PKWM initialization. This key is then persisted by the PKWM and
is used for wrapping any kernel provided key, and is never exposed to the
user. The kernel is aware of only the label to this wrapping key.
Along with the PKWM implementation, this patchset includes two preparatory
patches: one fixing the kernel-doc incosistencies in the PLPKS code and
another reorganizing PLPKS config variables in the sysfs.
Nayna Jain (1):
docs: trusted-encryped: add PKWM as a new trust source
Srish Srinivasan (5):
pseries/plpks: fix kernel-doc comment inconsistencies
powerpc/pseries: move the PLPKS config inside its own sysfs directory
pseries/plpks: expose PowerVM wrapping features via the sysfs
pseries/plpks: add HCALLs for PowerVM Key Wrapping Module
keys/trusted_keys: establish PKWM as a trusted source
.../ABI/testing/sysfs-firmware-plpks | 58 ++
Documentation/ABI/testing/sysfs-secvar | 65 --
.../admin-guide/kernel-parameters.txt | 1 +
Documentation/arch/powerpc/papr_hcalls.rst | 43 ++
.../security/keys/trusted-encrypted.rst | 50 ++
MAINTAINERS | 9 +
arch/powerpc/include/asm/hvcall.h | 4 +-
arch/powerpc/include/asm/plpks.h | 94 +--
arch/powerpc/include/asm/secvar.h | 1 -
arch/powerpc/kernel/secvar-sysfs.c | 21 +-
arch/powerpc/platforms/pseries/Makefile | 2 +-
arch/powerpc/platforms/pseries/plpks-secvar.c | 29 -
arch/powerpc/platforms/pseries/plpks-sysfs.c | 96 +++
arch/powerpc/platforms/pseries/plpks.c | 689 +++++++++++++++++-
include/keys/trusted-type.h | 7 +-
include/keys/trusted_pkwm.h | 30 +
security/keys/trusted-keys/Kconfig | 8 +
security/keys/trusted-keys/Makefile | 2 +
security/keys/trusted-keys/trusted_core.c | 6 +-
security/keys/trusted-keys/trusted_pkwm.c | 168 +++++
20 files changed, 1182 insertions(+), 201 deletions(-)
create mode 100644 Documentation/ABI/testing/sysfs-firmware-plpks
create mode 100644 arch/powerpc/platforms/pseries/plpks-sysfs.c
create mode 100644 include/keys/trusted_pkwm.h
create mode 100644 security/keys/trusted-keys/trusted_pkwm.c
--
2.47.3
^ permalink raw reply
* Re: [RFC][PATCH v2] ima: Add support for staging measurements for deletion and trimming
From: Paul Moore @ 2025-12-13 2:06 UTC (permalink / raw)
To: Roberto Sassu
Cc: corbet, zohar, dmitry.kasatkin, eric.snowberg, jmorris, serge,
linux-doc, linux-kernel, linux-integrity, linux-security-module,
gregorylumen, chenste, nramas, Roberto Sassu
In-Reply-To: <20251212171932.316676-1-roberto.sassu@huaweicloud.com>
On Fri, Dec 12, 2025 at 12:19 PM Roberto Sassu
<roberto.sassu@huaweicloud.com> wrote:
> From: Roberto Sassu <roberto.sassu@huawei.com>
>
> Introduce the ability of staging the entire (or a portion of the) IMA
> measurement list for deletion. Staging means moving the current content of
> the measurement list to a separate location, and allowing users to read and
> delete it. This causes the measurement list to be atomically truncated
> before new measurements can be added. Staging can be done only once at a
> time. In the event of kexec(), staging is reverted and staged entries will
> be carried over to the new kernel.
>
> User space is responsible to concatenate the staged IMA measurements list
> portions following the temporal order in which the operations were done,
> together with the current measurement list. Then, it can send the collected
> data to the remote verifiers.
>
> Also introduce the ability of trimming N measurements entries from the IMA
> measurements list, provided that user space has already read them. Trimming
> combines staging and deletion in one operation.
>
> The benefit of these solutions is the ability to free precious kernel
> memory, in exchange of delegating user space to reconstruct the full
> measurement list from the chunks. No trust needs to be given to user space,
> since the integrity of the measurement list is protected by the TPM.
>
> By default, staging/trimming the measurements list does not alter the hash
> table. When staging/trimming are done, IMA is still able to detect
> collisions on the staged and later deleted measurement entries, by keeping
> the entry digests (only template data are freed).
>
> However, since during the measurements list serialization only the SHA1
> digest is passed, and since there are no template data to recalculate the
> other digests from, the hash table is currently not populated with digests
> from staged/deleted entries after kexec().
>
> Introduce the new kernel option ima_flush_htable to decide whether or not
> the digests of staged measurement entries are flushed from the hash table.
>
> Then, introduce ascii_runtime_measurements_staged_<algo> and
> binary_runtime_measurement_staged_<algo> interfaces to stage/trim/delete
> the measurements. Use 'echo A > <IMA interface>' and
> 'echo D > <IMA interface>' to respectively stage and delete the entire
> measurements list. Use 'echo N > <IMA interface>', with N between 1 and
> LONG_MAX, to stage the selected portion of the measurements list, and
> 'echo -N > <IMA interface>' to trim N measurements entries.
In an effort to help preserve the sanity of admins, I might suggest
avoiding commands that start with a dash/'-'. I'd probably also
simplify the commands a bit and drop all/'A' since the measurement
list could change at any time, stick with an explicit number and just
let the admin go over, e.g. write LONG_MAX, which effectively becomes
'A'. I think you could do everything you need with just two commands:
<NUM>: stage <NUM> entries
D: delete staged entries
I intentionally left out the trim/'T' command, because I'm not sure it
is really necessary if you are going to implement the phased
stage/delete process. Yes, you have to do two operations (stage and
delete) as opposed to just the trim, but I'd probably take the
simplicity of just supporting a single approach over the trivial
necessity of having to do two operations in userspace.
Staging also has the benefit of having a sane way of handling two
tasks racing to stage the measurement list. I could see cases where
multiple tasks race to trim the list and end up trimming more than was
intended since they both hit in sequence.
If you did want to take a trim approach over a stage/delete approach,
I could see something like this working:
1. process opens the measurement list
2. process reads from the measurement list, keeps the fd open
3. process does whatever it wants to preserve the list
4. process writes <NUM> to the measurement list, kernel trims <NUM> entries
5. process closes fd
... error handling shouldn't be too bad. The process only writes
<NUM> to the fd if it has already finished whatever it needs to do to
preserve the list outside the kernel, think of it as a "commit"
operation on a transaction. If the fd is closed for some reason
(error, interruption, killed) before the process writes <NUM> to the
fd then IMA does nothing - no trim takes place.
Multiple process racing can easily be solved when the log is opened;
only one open(O_RDWR) is allowed at a time, other racing processes
will get EBUSY. Yes, one process could block others from trimming by
holding the fd open for an extended period of time, but I would expect
that CAP_SYS_ADMIN and root fs perms would be required to open the log
read/write (not to mention any LSM access rights in place).
I know I mentioned this basic idea to someone at some point, but there
have been various discussion threads and multiple people over a fairly
lengthy time that I've lost track of where it was mentioned. If it
was already discussed on-list and rejected for a good reason you can
simply ignore the above approach ... although I still think the
stage/delete API could be simplified as described :)
[UPDATE: as I'm reading Steven's replies it looks like he has proposed
something very similar to the above]
--
paul-moore.com
^ permalink raw reply
* Re: [RFC][PATCH v2] ima: Add support for staging measurements for deletion and trimming
From: steven chen @ 2025-12-12 22:58 UTC (permalink / raw)
To: Roberto Sassu, corbet, zohar, dmitry.kasatkin, eric.snowberg,
paul, jmorris, serge
Cc: linux-doc, linux-kernel, linux-integrity, linux-security-module,
gregorylumen, nramas, Roberto Sassu, steven chen
In-Reply-To: <ee41e18a-6f58-47d4-a6bc-797cef8317c3@linux.microsoft.com>
On 12/12/2025 11:41 AM, steven chen wrote:
> On 12/12/2025 9:19 AM, Roberto Sassu wrote:
>> From: Roberto Sassu <roberto.sassu@huawei.com>
>>
>> Introduce the ability of staging the entire (or a portion of the) IMA
>> measurement list for deletion. Staging means moving the current
>> content of
>> the measurement list to a separate location, and allowing users to
>> read and
>> delete it. This causes the measurement list to be atomically truncated
>> before new measurements can be added. Staging can be done only once at a
>> time. In the event of kexec(), staging is reverted and staged entries
>> will
>> be carried over to the new kernel.
>>
>> User space is responsible to concatenate the staged IMA measurements
>> list
>> portions following the temporal order in which the operations were done,
>> together with the current measurement list. Then, it can send the
>> collected
>> data to the remote verifiers.
>>
>> Also introduce the ability of trimming N measurements entries from
>> the IMA
>> measurements list, provided that user space has already read them.
>> Trimming
>> combines staging and deletion in one operation.
>>
>> The benefit of these solutions is the ability to free precious kernel
>> memory, in exchange of delegating user space to reconstruct the full
>> measurement list from the chunks. No trust needs to be given to user
>> space,
>> since the integrity of the measurement list is protected by the TPM.
>>
>> By default, staging/trimming the measurements list does not alter the
>> hash
>> table. When staging/trimming are done, IMA is still able to detect
>> collisions on the staged and later deleted measurement entries, by
>> keeping
>> the entry digests (only template data are freed).
>>
>> However, since during the measurements list serialization only the SHA1
>> digest is passed, and since there are no template data to recalculate
>> the
>> other digests from, the hash table is currently not populated with
>> digests
>> from staged/deleted entries after kexec().
>>
>> Introduce the new kernel option ima_flush_htable to decide whether or
>> not
>> the digests of staged measurement entries are flushed from the hash
>> table.
>>
>> Then, introduce ascii_runtime_measurements_staged_<algo> and
>> binary_runtime_measurement_staged_<algo> interfaces to stage/trim/delete
>> the measurements. Use 'echo A > <IMA interface>' and
>> 'echo D > <IMA interface>' to respectively stage and delete the entire
>> measurements list. Use 'echo N > <IMA interface>', with N between 1 and
>> LONG_MAX, to stage the selected portion of the measurements list, and
>> 'echo -N > <IMA interface>' to trim N measurements entries.
>>
>> The ima_measure_users counter (protected by the ima_measure_lock
>> mutex) has
>> been introduced to protect access to the measurements list and the
>> staged
>> part. The open method of all the measurement interfaces has been
>> extended
>> to allow only one writer at a time or, in alternative, multiple readers.
>> The write permission is used to stage/trim/delete the measurements, the
>> read permission to read them. Write requires also the CAP_SYS_ADMIN
>> capability.
>>
>> Finally, introduce and maintain dedicate counters for the number of
>> measurement entries and binary size, for the current measurements list
>> (BINARY_SIZE), for the current measurements list plus staged entries
>> (BINARY_SIZE_STAGED) useful for kexec() segment allocation, and for the
>> entire measurement list without staging/trimming (BINARY_SIZE_FULL)
>> useful
>> for the kexec-related critical data records.
> Hello Roberto,
>
> I think staged N proposal without one step trim N solution has
> following shortages compare
> "one step trim N solution":
> list lock time longer
> UM need to do more work
> implementation more complex
> more code changed/added
> not energy green: cost more to run the function
>
> I appreciate that you have fully incorporated my one-step solution for
> trimming N entries
> into your RFC. I will now review your proposed roadmap and compare it
> with mine.
>
> Roberto’s | Steven’s
> |
> Version 0: Snapshot (staged) | Trim N entries, one step
> (version 1)
> Two steps to trim log | One step to trim log
> |
> |
> Version 1: Staged N | Trim N entries, one step
> (version 2)
> Two steps to trim log | One step to trim log
> |
> Take “N” from Steven’s |
> | Resolve comments
> (From Roberto, acked)
> | Performance
> improvement (From Roberto, acked)
> |
> |
> Version 2: Staged plus | Trim N entries, one step
> Two step to trim log | One step to trim log
> |
> Take “N” from Steven’s |
> One step from Steven's |
> | will release soon
> | Will take good points
> from everyone
> |
> Possible |
> Version 3: Trim N entries, one step (please refer to Steven's proposal)
> No body will need Staged
> because of no value
>
Add estimated number to show the differences
I think staged N proposal without one step trim N solution has following
shortages comparing with "one step trim N solution":
list lock time longer (around 2 times)
UM need to do more work (double steps used on log trimming)
implementation more complex (more than 2 times)
more code changed/added (around 2 times)
not energy green: cost more to run the function (at lease 1.5 times)
I appreciate that you have fully incorporated my one-step solution for
trimming N entries into your RFC. I will now review your proposed roadmap
and compare it with mine.
Roberto’s | Steven’s
|
V0: Snapshot (staged) |Trim N entries, one step (v1)
|
Two steps to trim log | One step to trim log
|
|
V1: Staged N |Trim N entries, one step (v2)
|
Two steps to trim log | One step to trim log
|
N from Steven’s |
| Resolve comments (Roberto, acked)
| Performance improvement (Roberto,acked)
|
|
V2: Staged N + one step |Trim N entries, one step
Two step to trim log | One step to trim log
|
N from Steven’s |
One step from Steven's |
| will release soon
| Will take good points from everyone
|
Possible future
Version ?: Trim N entries, one step
No body will need Staged because of no value
> The follow are differences of two proposals:
>
> The cost of proposal
>
> Staged without "one step trim N" | Trim N entries, one step
> |
> running cost: 150 cents | 100 cents (for example)
> code added: 400+ | 200+
>
>
> The complex of proposal
>
> Staged without "one step trim N" | Trim N entries, one step
> total 6 steps | total 3 steps
> |
> 1. UM reads list without lock | 1. UM reads list without
> lock
> 2. UM stages list with lock | 2. UM decides to trim N
> entries
> 3. UM decides to trim N entries | 3. Kernel trim log with
> lock
> 4. Kernel trim staged list |
> 5. kexec save the staged list |
> 6. kexec restore the staged list|
>
>
> The lock time of proposal
>
> Staged without "one step trim N" | Trim N entries, one step
> |
> time 1 ms (for example) | should less than 1 ms
>
>
> I think everyone knows the Trim N entries one step solution is the
> best for now.
>
> If you insist on staged, it is not good for open source community!!!
>
> You did not reply my comments in your version 1 release so I add refer
> here.
>
> [RFC][PATCH] ima: Add support for staging measurements for deletion
> https://lore.kernel.org/linux-integrity/207fd6d7-53c-57bb-36d8-13a0902052d1@linux.microsoft.com/T/#t
>
>
> I also add my Trim N entries on step version 2 refer here.
>
> [PATCH v2 0/1] Trim N entries of IMA event logs
> https://lore.kernel.org/linux-integrity/20251210235314.3341-1-chenste@linux.microsoft.com/T/#t
>
>
> Thanks,
>
> Steven
>
>> Note: This code derives from the Alt-IMA Huawei project, and is being
>> released under the dual license model (GPL-2.0 OR MIT).
>>
>> Link: https://github.com/linux-integrity/linux/issues/1
>> Signed-off-by: Roberto Sassu <roberto.sassu@huawei.com>
>> ---
>> .../admin-guide/kernel-parameters.txt | 4 +
>> security/integrity/ima/ima.h | 18 +-
>> security/integrity/ima/ima_fs.c | 240 +++++++++++++++++-
>> security/integrity/ima/ima_kexec.c | 42 ++-
>> security/integrity/ima/ima_queue.c | 169 +++++++++++-
>> 5 files changed, 439 insertions(+), 34 deletions(-)
>>
>> diff --git a/Documentation/admin-guide/kernel-parameters.txt
>> b/Documentation/admin-guide/kernel-parameters.txt
>> index 6c42061ca20e..e5f1e11bd0a2 100644
>> --- a/Documentation/admin-guide/kernel-parameters.txt
>> +++ b/Documentation/admin-guide/kernel-parameters.txt
>> @@ -2215,6 +2215,10 @@
>> Use the canonical format for the binary runtime
>> measurements, instead of host native format.
>> + ima_flush_htable [IMA]
>> + Flush the IMA hash table when staging for deletion or
>> + trimming measurement entries.
>> +
>> ima_hash= [IMA]
>> Format: { md5 | sha1 | rmd160 | sha256 | sha384
>> | sha512 | ... }
>> diff --git a/security/integrity/ima/ima.h b/security/integrity/ima/ima.h
>> index e3d71d8d56e3..8a6be4284210 100644
>> --- a/security/integrity/ima/ima.h
>> +++ b/security/integrity/ima/ima.h
>> @@ -28,6 +28,15 @@ enum ima_show_type { IMA_SHOW_BINARY,
>> IMA_SHOW_BINARY_NO_FIELD_LEN,
>> IMA_SHOW_BINARY_OLD_STRING_FMT, IMA_SHOW_ASCII };
>> enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
>> +/*
>> + * BINARY_SIZE: size of the current measurements list
>> + * BINARY_SIZE_STAGED: size of current measurements list + staged
>> entries
>> + * BINARY_SIZE_FULL: size of measurements list since IMA initialization
>> + */
>> +enum binary_size_types {
>> + BINARY_SIZE, BINARY_SIZE_STAGED, BINARY_SIZE_FULL, BINARY__LAST
>> +};
>> +
>> /* digest size for IMA, fits SHA1 or MD5 */
>> #define IMA_DIGEST_SIZE SHA1_DIGEST_SIZE
>> #define IMA_EVENT_NAME_LEN_MAX 255
>> @@ -117,6 +126,8 @@ struct ima_queue_entry {
>> struct ima_template_entry *entry;
>> };
>> extern struct list_head ima_measurements; /* list of all
>> measurements */
>> +extern struct list_head ima_measurements_staged; /* list of staged
>> meas. */
>> +extern bool ima_measurements_staged_exist; /* If there are staged
>> meas. */
>> /* Some details preceding the binary serialized measurement list */
>> struct ima_kexec_hdr {
>> @@ -281,10 +292,12 @@ struct ima_template_desc
>> *ima_template_desc_current(void);
>> struct ima_template_desc *ima_template_desc_buf(void);
>> struct ima_template_desc *lookup_template_desc(const char *name);
>> bool ima_template_has_modsig(const struct ima_template_desc
>> *ima_template);
>> +int ima_queue_stage_trim(unsigned long req_value, bool trim);
>> +int ima_queue_delete_staged_trimmed(bool staged_moved);
>> int ima_restore_measurement_entry(struct ima_template_entry *entry);
>> int ima_restore_measurement_list(loff_t bufsize, void *buf);
>> int ima_measurements_show(struct seq_file *m, void *v);
>> -unsigned long ima_get_binary_runtime_size(void);
>> +unsigned long ima_get_binary_runtime_size(enum binary_size_types type);
>> int ima_init_template(void);
>> void ima_init_template_list(void);
>> int __init ima_init_digests(void);
>> @@ -298,11 +311,12 @@ int ima_lsm_policy_change(struct notifier_block
>> *nb, unsigned long event,
>> extern spinlock_t ima_queue_lock;
>> struct ima_h_table {
>> - atomic_long_t len; /* number of stored measurements in the
>> list */
>> + atomic_long_t len[BINARY__LAST]; /* num of stored meas. in the
>> list */
>> atomic_long_t violations;
>> struct hlist_head queue[IMA_MEASURE_HTABLE_SIZE];
>> };
>> extern struct ima_h_table ima_htable;
>> +extern struct mutex ima_extend_list_mutex;
>> static inline unsigned int ima_hash_key(u8 *digest)
>> {
>> diff --git a/security/integrity/ima/ima_fs.c
>> b/security/integrity/ima/ima_fs.c
>> index 87045b09f120..a96f7c36b34a 100644
>> --- a/security/integrity/ima/ima_fs.c
>> +++ b/security/integrity/ima/ima_fs.c
>> @@ -24,7 +24,18 @@
>> #include "ima.h"
>> +/*
>> + * Requests:
>> + * 'A\n': stage the entire measurements list
>> + * '[1, LONG_MAX]\n' stage N measurements entries
>> + * '-[1, LONG_MAX]\n' trim N measurements entries
>> + * 'D\n': delete staged measurements
>> + */
>> +#define STAGED_REQ_LENGTH 21
>> +
>> static DEFINE_MUTEX(ima_write_mutex);
>> +static DEFINE_MUTEX(ima_measure_lock);
>> +static long ima_measure_users;
>> bool ima_canonical_fmt;
>> static int __init default_canonical_fmt_setup(char *str)
>> @@ -64,7 +75,8 @@ static ssize_t ima_show_measurements_count(struct
>> file *filp,
>> char __user *buf,
>> size_t count, loff_t *ppos)
>> {
>> - return ima_show_htable_value(buf, count, ppos, &ima_htable.len);
>> + return ima_show_htable_value(buf, count, ppos,
>> + &ima_htable.len[BINARY_SIZE]);
>> }
>> @@ -74,14 +86,15 @@ static const struct file_operations
>> ima_measurements_count_ops = {
>> };
>> /* returns pointer to hlist_node */
>> -static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
>> +static void *_ima_measurements_start(struct seq_file *m, loff_t *pos,
>> + struct list_head *head)
>> {
>> loff_t l = *pos;
>> struct ima_queue_entry *qe;
>> /* we need a lock since pos could point beyond last element */
>> rcu_read_lock();
>> - list_for_each_entry_rcu(qe, &ima_measurements, later) {
>> + list_for_each_entry_rcu(qe, head, later) {
>> if (!l--) {
>> rcu_read_unlock();
>> return qe;
>> @@ -91,7 +104,18 @@ static void *ima_measurements_start(struct
>> seq_file *m, loff_t *pos)
>> return NULL;
>> }
>> -static void *ima_measurements_next(struct seq_file *m, void *v,
>> loff_t *pos)
>> +static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
>> +{
>> + return _ima_measurements_start(m, pos, &ima_measurements);
>> +}
>> +
>> +static void *ima_measurements_staged_start(struct seq_file *m,
>> loff_t *pos)
>> +{
>> + return _ima_measurements_start(m, pos, &ima_measurements_staged);
>> +}
>> +
>> +static void *_ima_measurements_next(struct seq_file *m, void *v,
>> loff_t *pos,
>> + struct list_head *head)
>> {
>> struct ima_queue_entry *qe = v;
>> @@ -103,7 +127,18 @@ static void *ima_measurements_next(struct
>> seq_file *m, void *v, loff_t *pos)
>> rcu_read_unlock();
>> (*pos)++;
>> - return (&qe->later == &ima_measurements) ? NULL : qe;
>> + return (&qe->later == head) ? NULL : qe;
>> +}
>> +
>> +static void *ima_measurements_next(struct seq_file *m, void *v,
>> loff_t *pos)
>> +{
>> + return _ima_measurements_next(m, v, pos, &ima_measurements);
>> +}
>> +
>> +static void *ima_measurements_staged_next(struct seq_file *m, void *v,
>> + loff_t *pos)
>> +{
>> + return _ima_measurements_next(m, v, pos, &ima_measurements_staged);
>> }
>> static void ima_measurements_stop(struct seq_file *m, void *v)
>> @@ -202,16 +237,147 @@ static const struct seq_operations
>> ima_measurments_seqops = {
>> .show = ima_measurements_show
>> };
>> +static int _ima_measurements_open(struct inode *inode, struct file
>> *file,
>> + const struct seq_operations *seq_ops)
>> +{
>> + bool write = !!(file->f_mode & FMODE_WRITE);
>> + int ret;
>> +
>> + if (write && !capable(CAP_SYS_ADMIN))
>> + return -EPERM;
>> +
>> + mutex_lock(&ima_measure_lock);
>> + if ((write && ima_measure_users != 0) ||
>> + (!write && ima_measure_users < 0)) {
>> + mutex_unlock(&ima_measure_lock);
>> + return -EBUSY;
>> + }
>> +
>> + ret = seq_open(file, seq_ops);
>> + if (ret < 0) {
>> + mutex_unlock(&ima_measure_lock);
>> + return ret;
>> + }
>> +
>> + if (write)
>> + ima_measure_users--;
>> + else
>> + ima_measure_users++;
>> +
>> + mutex_unlock(&ima_measure_lock);
>> + return ret;
>> +}
>> +
>> static int ima_measurements_open(struct inode *inode, struct file
>> *file)
>> {
>> - return seq_open(file, &ima_measurments_seqops);
>> + return _ima_measurements_open(inode, file,
>> &ima_measurments_seqops);
>> +}
>> +
>> +static int ima_measurements_release(struct inode *inode, struct file
>> *file)
>> +{
>> + bool write = !!(file->f_mode & FMODE_WRITE);
>> + int ret;
>> +
>> + mutex_lock(&ima_measure_lock);
>> + ret = seq_release(inode, file);
>> + if (!ret) {
>> + if (write)
>> + ima_measure_users++;
>> + else
>> + ima_measure_users--;
>> + }
>> +
>> + mutex_unlock(&ima_measure_lock);
>> + return ret;
>> }
>> static const struct file_operations ima_measurements_ops = {
>> .open = ima_measurements_open,
>> .read = seq_read,
>> .llseek = seq_lseek,
>> - .release = seq_release,
>> + .release = ima_measurements_release,
>> +};
>> +
>> +static const struct seq_operations ima_measurments_staged_seqops = {
Trim N entries one step proposal does not need this.
>> + .start = ima_measurements_staged_start,
>> + .next = ima_measurements_staged_next,
>> + .stop = ima_measurements_stop,
>> + .show = ima_measurements_show
>> +};
>> +
>> +static int ima_measurements_staged_open(struct inode *inode, struct
>> file *file)
>> +{
>> + return _ima_measurements_open(inode, file,
>> + &ima_measurments_staged_seqops);
>> +}
>> +
>> +static ssize_t ima_measurements_staged_read(struct file *file, char
>> __user *buf,
>> + size_t size, loff_t *ppos)
>> +{
>> + if (!ima_measurements_staged_exist)
>> + return -ENOENT;
>> +
>> + return seq_read(file, buf, size, ppos);
>> +}
>> +
>> +static ssize_t ima_measurements_staged_write(struct file *file,
>> + const char __user *buf,
>> + size_t datalen, loff_t *ppos)
>> +{
>> + char req[STAGED_REQ_LENGTH], *req_ptr = req;
>> + unsigned long req_value;
>> + bool trim = false;
>> + int ret;
>> +
>> + if (*ppos > 0 || datalen < 2 || datalen > STAGED_REQ_LENGTH)
>> + return -EINVAL;
>> +
>> + if (copy_from_user(req, buf, datalen) != 0)
>> + return -EFAULT;
>> +
>> + if (req[datalen - 1] != '\n')
>> + return -EINVAL;
>> +
>> + req[datalen - 1] = '\0';
>> + req_ptr = req;
>> +
>> + switch (req[0]) {
>> + case 'A':
>> + if (datalen != 2 || req[1] != '\0')
>> + return -EINVAL;
>> +
>> + ret = ima_queue_stage_trim(LONG_MAX, false);
>> + break;
>> + case 'D':
>> + if (datalen != 2 || req[1] != '\0')
>> + return -EINVAL;
>> +
>> + ret = ima_queue_delete_staged_trimmed(false);
>> + break;
>> + case '-':
>> + trim = true;
>> + req_ptr++;
>> + fallthrough;
>> + default:
>> + ret = kstrtoul(req_ptr, 0, &req_value);
>> + if (ret < 0)
>> + return ret;
>> +
>> + ret = ima_queue_stage_trim(req_value, trim);
>> + }
>> +
>> + if (ret < 0)
>> + return ret;
>> +
>> + return datalen;
>> +}
>> +
>> +static const struct file_operations ima_measurements_staged_ops = {
>> + .open = ima_measurements_staged_open,
>> + .read = ima_measurements_staged_read,
>> + .write = ima_measurements_staged_write,
>> + .llseek = seq_lseek,
>> + .release = ima_measurements_release,
>> };
>> void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
>> @@ -279,14 +445,37 @@ static const struct seq_operations
>> ima_ascii_measurements_seqops = {
>> static int ima_ascii_measurements_open(struct inode *inode,
>> struct file *file)
>> {
>> - return seq_open(file, &ima_ascii_measurements_seqops);
>> + return _ima_measurements_open(inode, file,
>> + &ima_ascii_measurements_seqops);
>> }
>> static const struct file_operations ima_ascii_measurements_ops = {
>> .open = ima_ascii_measurements_open,
>> .read = seq_read,
>> .llseek = seq_lseek,
>> - .release = seq_release,
>> + .release = ima_measurements_release,
>> +};
>> +
>> +static const struct seq_operations
>> ima_ascii_measurements_staged_seqops = {
>> + .start = ima_measurements_staged_start,
>> + .next = ima_measurements_staged_next,
>> + .stop = ima_measurements_stop,
>> + .show = ima_ascii_measurements_show
>> +};
Trim N entries one step proposal does not need this.
>> +
>> +static int ima_ascii_measurements_staged_open(struct inode *inode,
>> + struct file *file)
>> +{
>> + return _ima_measurements_open(inode, file,
>> + &ima_ascii_measurements_staged_seqops);
>> +}
>> +
>> +static const struct file_operations
>> ima_ascii_measurements_staged_ops = {
Trim N entries one step proposal does not need this.
>> + .open = ima_ascii_measurements_staged_open,
>> + .read = ima_measurements_staged_read,
>> + .write = ima_measurements_staged_write,
>> + .llseek = seq_lseek,
>> + .release = ima_measurements_release,
>> };
>> static ssize_t ima_read_policy(char *path)
>> @@ -419,6 +608,25 @@ static int __init
>> create_securityfs_measurement_lists(void)
>> &ima_measurements_ops);
>> if (IS_ERR(dentry))
>> return PTR_ERR(dentry);
>> +
>> + sprintf(file_name, "ascii_runtime_measurements_staged_%s",
>> + hash_algo_name[algo]);
>> + dentry = securityfs_create_file(file_name,
>> + S_IRUSR | S_IRGRP | S_IWUSR | S_IWGRP,
>> + ima_dir, (void *)(uintptr_t)i,
>> + &ima_ascii_measurements_staged_ops);
>> + if (IS_ERR(dentry))
>> + return PTR_ERR(dentry);
Trim N entries one step proposal does not need this.
>> +
>> + sprintf(file_name, "binary_runtime_measurements_staged_%s",
>> + hash_algo_name[algo]);
>> + dentry = securityfs_create_file(file_name,
>> + S_IRUSR | S_IRGRP |
>> + S_IWUSR | S_IWGRP,
>> + ima_dir, (void *)(uintptr_t)i,
>> + &ima_measurements_staged_ops);
>> + if (IS_ERR(dentry))
>> + return PTR_ERR(dentry);
Trim N entries one step proposal does not need this.
>> }
>> return 0;
>> @@ -528,6 +736,20 @@ int __init ima_fs_init(void)
>> goto out;
>> }
>> + dentry =
>> securityfs_create_symlink("binary_runtime_measurements_staged",
>> + ima_dir, "binary_runtime_measurements_staged_sha1", NULL);
>> + if (IS_ERR(dentry)) {
>> + ret = PTR_ERR(dentry);
>> + goto out;
>> + }
>> +
>> + dentry =
>> securityfs_create_symlink("ascii_runtime_measurements_staged",
>> + ima_dir, "ascii_runtime_measurements_staged_sha1", NULL);
>> + if (IS_ERR(dentry)) {
>> + ret = PTR_ERR(dentry);
>> + goto out;
>> + }
Trim N entries one step proposal does not need this.
>> +
>> dentry = securityfs_create_file("runtime_measurements_count",
>> S_IRUSR | S_IRGRP, ima_dir, NULL,
>> &ima_measurements_count_ops);
>> diff --git a/security/integrity/ima/ima_kexec.c
>> b/security/integrity/ima/ima_kexec.c
>> index 7362f68f2d8b..13c7e78aeefd 100644
>> --- a/security/integrity/ima/ima_kexec.c
>> +++ b/security/integrity/ima/ima_kexec.c
>> @@ -40,8 +40,8 @@ void ima_measure_kexec_event(const char *event_name)
>> long len;
>> int n;
>> - buf_size = ima_get_binary_runtime_size();
>> - len = atomic_long_read(&ima_htable.len);
>> + buf_size = ima_get_binary_runtime_size(BINARY_SIZE_FULL);
>> + len = atomic_long_read(&ima_htable.len[BINARY_SIZE_FULL]);
>> n = scnprintf(ima_kexec_event, IMA_KEXEC_EVENT_LEN,
>> "kexec_segment_size=%lu;ima_binary_runtime_size=%lu;"
>> @@ -78,6 +78,17 @@ static int ima_alloc_kexec_file_buf(size_t
>> segment_size)
>> return 0;
>> }
>> +static int ima_dump_measurement(struct ima_kexec_hdr *khdr,
>> + struct ima_queue_entry *qe)
>> +{
>> + if (ima_kexec_file.count >= ima_kexec_file.size)
>> + return -EINVAL;
>> +
>> + khdr->count++;
>> + ima_measurements_show(&ima_kexec_file, qe);
>> + return 0;
>> +}
>> +
>> static int ima_dump_measurement_list(unsigned long *buffer_size,
>> void **buffer,
>> unsigned long segment_size)
>> {
>> @@ -93,17 +104,25 @@ static int ima_dump_measurement_list(unsigned
>> long *buffer_size, void **buffer,
>> memset(&khdr, 0, sizeof(khdr));
>> khdr.version = 1;
>> - /* This is an append-only list, no need to hold the RCU read
>> lock */
>> - list_for_each_entry_rcu(qe, &ima_measurements, later, true) {
>> - if (ima_kexec_file.count < ima_kexec_file.size) {
>> - khdr.count++;
>> - ima_measurements_show(&ima_kexec_file, qe);
>> - } else {
>> - ret = -EINVAL;
>> +
>> + /* It can race with ima_queue_stage_trim(). */
>> + mutex_lock(&ima_extend_list_mutex);
>> +
>> + list_for_each_entry(qe, &ima_measurements_staged, later) {
>> + ret = ima_dump_measurement(&khdr, qe);
>> + if (ret < 0)
>> + break;
>> + }
Trim N entries one step proposal does not need this.
>> +
>> + list_for_each_entry(qe, &ima_measurements, later) {
>> + if (!ret)
>> + ret = ima_dump_measurement(&khdr, qe);
>> + if (ret < 0)
>> break;
>> - }
>> }
>> + mutex_unlock(&ima_extend_list_mutex);
>> +
>> /*
>> * fill in reserved space with some buffer details
>> * (eg. version, buffer size, number of measurements)
>> @@ -157,7 +176,8 @@ void ima_add_kexec_buffer(struct kimage *image)
>> else
>> extra_memory = CONFIG_IMA_KEXEC_EXTRA_MEMORY_KB * 1024;
>> - binary_runtime_size = ima_get_binary_runtime_size() +
>> extra_memory;
>> + binary_runtime_size =
>> ima_get_binary_runtime_size(BINARY_SIZE_STAGED) +
>> + extra_memory;
>> if (binary_runtime_size >= ULONG_MAX - PAGE_SIZE)
>> kexec_segment_size = ULONG_MAX;
>> diff --git a/security/integrity/ima/ima_queue.c
>> b/security/integrity/ima/ima_queue.c
>> index 590637e81ad1..7dfa24b8ae31 100644
>> --- a/security/integrity/ima/ima_queue.c
>> +++ b/security/integrity/ima/ima_queue.c
>> @@ -22,19 +22,32 @@
>> #define AUDIT_CAUSE_LEN_MAX 32
>> +bool ima_flush_htable;
>> +static int __init ima_flush_htable_setup(char *str)
>> +{
>> + ima_flush_htable = true;
>> + return 1;
>> +}
>> +__setup("ima_flush_htable", ima_flush_htable_setup);
>> +
>> /* pre-allocated array of tpm_digest structures to extend a PCR */
>> static struct tpm_digest *digests;
>> LIST_HEAD(ima_measurements); /* list of all measurements */
>> +LIST_HEAD(ima_measurements_staged); /* list of staged measurements */
>> +static LIST_HEAD(ima_measurements_trim); /* list of measurements to
>> trim */
>> +bool ima_measurements_staged_exist; /* If there are staged
>> measurements */
>> #ifdef CONFIG_IMA_KEXEC
>> -static unsigned long binary_runtime_size;
>> +static unsigned long binary_runtime_size[BINARY__LAST];
>> #else
>> -static unsigned long binary_runtime_size = ULONG_MAX;
>> +static unsigned long binary_runtime_size[BINARY_SIZE] = ULONG_MAX;
>> +static unsigned long binary_runtime_size[BINARY_SIZE_FULL] = ULONG_MAX;
>> +static unsigned long binary_runtime_size[BINARY_SIZE_STAGED] =
>> ULONG_MAX;
>> #endif
>> /* key: inode (before secure-hashing a file) */
>> struct ima_h_table ima_htable = {
>> - .len = ATOMIC_LONG_INIT(0),
>> + .len = { ATOMIC_LONG_INIT(0) },
>> .violations = ATOMIC_LONG_INIT(0),
>> .queue[0 ... IMA_MEASURE_HTABLE_SIZE - 1] = HLIST_HEAD_INIT
>> };
>> @@ -43,7 +56,7 @@ struct ima_h_table ima_htable = {
>> * and extending the TPM PCR aggregate. Since tpm_extend can take
>> * long (and the tpm driver uses a mutex), we can't use the spinlock.
>> */
>> -static DEFINE_MUTEX(ima_extend_list_mutex);
>> +DEFINE_MUTEX(ima_extend_list_mutex);
>> /*
>> * Used internally by the kernel to suspend measurements.
>> @@ -101,7 +114,7 @@ static int ima_add_digest_entry(struct
>> ima_template_entry *entry,
>> bool update_htable)
>> {
>> struct ima_queue_entry *qe;
>> - unsigned int key;
>> + unsigned int i, key;
>> qe = kmalloc(sizeof(*qe), GFP_KERNEL);
>> if (qe == NULL) {
>> @@ -113,18 +126,23 @@ static int ima_add_digest_entry(struct
>> ima_template_entry *entry,
>> INIT_LIST_HEAD(&qe->later);
>> list_add_tail_rcu(&qe->later, &ima_measurements);
>> - atomic_long_inc(&ima_htable.len);
>> + for (i = 0; i < BINARY__LAST; i++)
>> + atomic_long_inc(&ima_htable.len[i]);
>> +
>> if (update_htable) {
>> key = ima_hash_key(entry->digests[ima_hash_algo_idx].digest);
>> hlist_add_head_rcu(&qe->hnext, &ima_htable.queue[key]);
>> }
>> - if (binary_runtime_size != ULONG_MAX) {
>> + if (binary_runtime_size[BINARY_SIZE_FULL] != ULONG_MAX) {
>> int size;
>> size = get_binary_runtime_size(entry);
>> - binary_runtime_size = (binary_runtime_size < ULONG_MAX -
>> size) ?
>> - binary_runtime_size + size : ULONG_MAX;
>> +
>> + for (i = 0; i < BINARY__LAST; i++)
>> + binary_runtime_size[i] =
>> + (binary_runtime_size[i] < ULONG_MAX - size) ?
>> + binary_runtime_size[i] + size : ULONG_MAX;
>> }
>> return 0;
>> }
>> @@ -134,12 +152,18 @@ static int ima_add_digest_entry(struct
>> ima_template_entry *entry,
>> * entire binary_runtime_measurement list, including the ima_kexec_hdr
>> * structure.
>> */
>> -unsigned long ima_get_binary_runtime_size(void)
>> +unsigned long ima_get_binary_runtime_size(enum binary_size_types type)
>> {
>> - if (binary_runtime_size >= (ULONG_MAX - sizeof(struct
>> ima_kexec_hdr)))
>> + unsigned long val;
>> +
>> + mutex_lock(&ima_extend_list_mutex);
>> + val = binary_runtime_size[type];
>> + mutex_unlock(&ima_extend_list_mutex);
Trim N entries one step proposal does not need this.
>> +
>> + if (val >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
>> return ULONG_MAX;
>> else
>> - return binary_runtime_size + sizeof(struct ima_kexec_hdr);
>> + return val + sizeof(struct ima_kexec_hdr);
>> }
>> static int ima_pcr_extend(struct tpm_digest *digests_arg, int pcr)
>> @@ -220,6 +244,127 @@ int ima_add_template_entry(struct
>> ima_template_entry *entry, int violation,
>> return result;
>> }
>> +int ima_queue_stage_trim(unsigned long req_value, bool trim)
> req_value idea comes from Trim N entries one step proposal
> trim idea come from Trim N entries one step proposal
After adding above two parameters, Trim N entries one step idea is
fully added
>> +{
>> + unsigned long req_value_copy = req_value, to_remove = 0;
>> + struct list_head *moved = &ima_measurements_staged;
>> + struct ima_queue_entry *qe;
>> +
>> + if (req_value == 0 || req_value > LONG_MAX)
>> + return -EINVAL;
>> +
>> + if (ima_measurements_staged_exist)
>> + return -EEXIST;
>> +
>> + if (trim)
>> + moved = &ima_measurements_trim;
>> +
>> + mutex_lock(&ima_extend_list_mutex);
>> + if (list_empty(&ima_measurements)) {
>> + mutex_unlock(&ima_extend_list_mutex);
>> + return -ENOENT;
>> + }
>> +
>> + if (req_value == LONG_MAX) {
This will make UM more complicated because PCR Quote may no match the
end point of list.
>> + list_replace(&ima_measurements, moved);
>> + INIT_LIST_HEAD(&ima_measurements);
>> + atomic_long_set(&ima_htable.len[BINARY_SIZE], 0);
>> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
>> + binary_runtime_size[BINARY_SIZE] = 0;
>> +
>> + if (trim) {
>> + atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
>> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
>> + binary_runtime_size[BINARY_SIZE_STAGED] = 0;
>> + }
>> + } else {
>> + list_for_each_entry(qe, &ima_measurements, later) {
>> + to_remove += get_binary_runtime_size(qe->entry);
> Trim N entries one step proposal does not need this step, this will
> save lock time
>> + if (--req_value_copy == 0)
>> + break;
>> + }
>> +
>> + if (req_value_copy > 0) {
>> + mutex_unlock(&ima_extend_list_mutex);
>> + return -ENOENT;
>> + }
>> +
>> + __list_cut_position(moved, &ima_measurements, &qe->later);
>> + atomic_long_sub(req_value, &ima_htable.len[BINARY_SIZE]);
>> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
>> + binary_runtime_size[BINARY_SIZE] -= to_remove;
>> +
>> + if (trim) {
>> + atomic_long_sub(req_value,
>> + &ima_htable.len[BINARY_SIZE_STAGED]);
>> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
>> + binary_runtime_size[BINARY_SIZE_STAGED] -=
>> + to_remove;
>> + }
>> + }
>> +
>> + if (ima_flush_htable)
>> + /* Either staged/trimmed entries are removed from hash
>> table. */
>> + list_for_each_entry(qe, moved, later)
>> + /* It can race with ima_lookup_digest_entry(). */
>> + hlist_del_rcu(&qe->hnext);
>> +
>> + mutex_unlock(&ima_extend_list_mutex);
Trim N entries one step proposal only need to lock/unlock here.
At any where else lock is not required.
Thanks,
Steven
>> + ima_measurements_staged_exist = true;
>> +
>> + if (ima_flush_htable)
>> + synchronize_rcu();
>> +
>> + if (trim)
>> + return ima_queue_delete_staged_trimmed(true);
>> +
>> + return 0;
>> +}
>> +
>> +int ima_queue_delete_staged_trimmed(bool staged_moved)
>> +{
>> + struct ima_queue_entry *qe, *qe_tmp;
>> + unsigned int i;
>> +
>> + if (!ima_measurements_staged_exist)
>> + return -ENOENT;
>> +
>> + if (!staged_moved) {
>> + mutex_lock(&ima_extend_list_mutex);
>> + list_replace(&ima_measurements_staged, &ima_measurements_trim);
>> + INIT_LIST_HEAD(&ima_measurements_staged);
>> + atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
>> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
>> + binary_runtime_size[BINARY_SIZE_STAGED] = 0;
>> +
>> + mutex_unlock(&ima_extend_list_mutex);
>> + }
>> +
>> + list_for_each_entry_safe(qe, qe_tmp, &ima_measurements_trim,
>> later) {
>> + /*
>> + * Ok because after list delete qe is only accessed by
>> + * ima_lookup_digest_entry().
>> + */
>> + for (i = 0; i < qe->entry->template_desc->num_fields; i++) {
>> + kfree(qe->entry->template_data[i].data);
>> + qe->entry->template_data[i].data = NULL;
>> + qe->entry->template_data[i].len = 0;
>> + }
>> +
>> + list_del(&qe->later);
>> +
>> + /* No leak if !ima_flush_htable, referenced by ima_htable. */
>> + if (ima_flush_htable) {
>> + kfree(qe->entry->digests);
>> + kfree(qe->entry);
>> + kfree(qe);
>> + }
>> + }
>> +
>> + ima_measurements_staged_exist = false;
>> + return 0;
>> +}
>> +
>> int ima_restore_measurement_entry(struct ima_template_entry *entry)
>> {
>> int result = 0;
>
^ permalink raw reply
* Re: [RFC][PATCH v2] ima: Add support for staging measurements for deletion and trimming
From: steven chen @ 2025-12-12 19:41 UTC (permalink / raw)
To: Roberto Sassu, corbet, zohar, dmitry.kasatkin, eric.snowberg,
paul, jmorris, serge
Cc: linux-doc, linux-kernel, linux-integrity, linux-security-module,
gregorylumen, nramas, Roberto Sassu, steven chen
In-Reply-To: <20251212171932.316676-1-roberto.sassu@huaweicloud.com>
On 12/12/2025 9:19 AM, Roberto Sassu wrote:
> From: Roberto Sassu <roberto.sassu@huawei.com>
>
> Introduce the ability of staging the entire (or a portion of the) IMA
> measurement list for deletion. Staging means moving the current content of
> the measurement list to a separate location, and allowing users to read and
> delete it. This causes the measurement list to be atomically truncated
> before new measurements can be added. Staging can be done only once at a
> time. In the event of kexec(), staging is reverted and staged entries will
> be carried over to the new kernel.
>
> User space is responsible to concatenate the staged IMA measurements list
> portions following the temporal order in which the operations were done,
> together with the current measurement list. Then, it can send the collected
> data to the remote verifiers.
>
> Also introduce the ability of trimming N measurements entries from the IMA
> measurements list, provided that user space has already read them. Trimming
> combines staging and deletion in one operation.
>
> The benefit of these solutions is the ability to free precious kernel
> memory, in exchange of delegating user space to reconstruct the full
> measurement list from the chunks. No trust needs to be given to user space,
> since the integrity of the measurement list is protected by the TPM.
>
> By default, staging/trimming the measurements list does not alter the hash
> table. When staging/trimming are done, IMA is still able to detect
> collisions on the staged and later deleted measurement entries, by keeping
> the entry digests (only template data are freed).
>
> However, since during the measurements list serialization only the SHA1
> digest is passed, and since there are no template data to recalculate the
> other digests from, the hash table is currently not populated with digests
> from staged/deleted entries after kexec().
>
> Introduce the new kernel option ima_flush_htable to decide whether or not
> the digests of staged measurement entries are flushed from the hash table.
>
> Then, introduce ascii_runtime_measurements_staged_<algo> and
> binary_runtime_measurement_staged_<algo> interfaces to stage/trim/delete
> the measurements. Use 'echo A > <IMA interface>' and
> 'echo D > <IMA interface>' to respectively stage and delete the entire
> measurements list. Use 'echo N > <IMA interface>', with N between 1 and
> LONG_MAX, to stage the selected portion of the measurements list, and
> 'echo -N > <IMA interface>' to trim N measurements entries.
>
> The ima_measure_users counter (protected by the ima_measure_lock mutex) has
> been introduced to protect access to the measurements list and the staged
> part. The open method of all the measurement interfaces has been extended
> to allow only one writer at a time or, in alternative, multiple readers.
> The write permission is used to stage/trim/delete the measurements, the
> read permission to read them. Write requires also the CAP_SYS_ADMIN
> capability.
>
> Finally, introduce and maintain dedicate counters for the number of
> measurement entries and binary size, for the current measurements list
> (BINARY_SIZE), for the current measurements list plus staged entries
> (BINARY_SIZE_STAGED) useful for kexec() segment allocation, and for the
> entire measurement list without staging/trimming (BINARY_SIZE_FULL) useful
> for the kexec-related critical data records.
Hello Roberto,
I think staged N proposal without one step trim N solution has following
shortages compare
"one step trim N solution":
list lock time longer
UM need to do more work
implementation more complex
more code changed/added
not energy green: cost more to run the function
I appreciate that you have fully incorporated my one-step solution for
trimming N entries
into your RFC. I will now review your proposed roadmap and compare it
with mine.
Roberto’s | Steven’s
|
Version 0: Snapshot (staged) | Trim N entries, one step
(version 1)
Two steps to trim log | One step to trim log
|
|
Version 1: Staged N | Trim N entries, one step
(version 2)
Two steps to trim log | One step to trim log
|
Take “N” from Steven’s |
| Resolve comments (From
Roberto, acked)
| Performance
improvement (From Roberto, acked)
|
|
Version 2: Staged plus | Trim N entries, one step
Two step to trim log | One step to trim log
|
Take “N” from Steven’s |
One step from Steven's |
| will release soon
| Will take good points
from everyone
|
Possible |
Version 3: Trim N entries, one step (please refer to Steven's proposal)
No body will need Staged
because of no value
The follow are differences of two proposals:
The cost of proposal
Staged without "one step trim N" | Trim N entries, one step
|
running cost: 150 cents | 100 cents (for example)
code added: 400+ | 200+
The complex of proposal
Staged without "one step trim N" | Trim N entries, one step
total 6 steps | total 3 steps
|
1. UM reads list without lock | 1. UM reads list without lock
2. UM stages list with lock | 2. UM decides to trim N
entries
3. UM decides to trim N entries | 3. Kernel trim log with lock
4. Kernel trim staged list |
5. kexec save the staged list |
6. kexec restore the staged list|
The lock time of proposal
Staged without "one step trim N" | Trim N entries, one step
|
time 1 ms (for example) | should less than 1 ms
I think everyone knows the Trim N entries one step solution is the best
for now.
If you insist on staged, it is not good for open source community!!!
You did not reply my comments in your version 1 release so I add refer here.
[RFC][PATCH] ima: Add support for staging measurements for deletion
https://lore.kernel.org/linux-integrity/207fd6d7-53c-57bb-36d8-13a0902052d1@linux.microsoft.com/T/#t
I also add my Trim N entries on step version 2 refer here.
[PATCH v2 0/1] Trim N entries of IMA event logs
https://lore.kernel.org/linux-integrity/20251210235314.3341-1-chenste@linux.microsoft.com/T/#t
Thanks,
Steven
> Note: This code derives from the Alt-IMA Huawei project, and is being
> released under the dual license model (GPL-2.0 OR MIT).
>
> Link: https://github.com/linux-integrity/linux/issues/1
> Signed-off-by: Roberto Sassu <roberto.sassu@huawei.com>
> ---
> .../admin-guide/kernel-parameters.txt | 4 +
> security/integrity/ima/ima.h | 18 +-
> security/integrity/ima/ima_fs.c | 240 +++++++++++++++++-
> security/integrity/ima/ima_kexec.c | 42 ++-
> security/integrity/ima/ima_queue.c | 169 +++++++++++-
> 5 files changed, 439 insertions(+), 34 deletions(-)
>
> diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
> index 6c42061ca20e..e5f1e11bd0a2 100644
> --- a/Documentation/admin-guide/kernel-parameters.txt
> +++ b/Documentation/admin-guide/kernel-parameters.txt
> @@ -2215,6 +2215,10 @@
> Use the canonical format for the binary runtime
> measurements, instead of host native format.
>
> + ima_flush_htable [IMA]
> + Flush the IMA hash table when staging for deletion or
> + trimming measurement entries.
> +
> ima_hash= [IMA]
> Format: { md5 | sha1 | rmd160 | sha256 | sha384
> | sha512 | ... }
> diff --git a/security/integrity/ima/ima.h b/security/integrity/ima/ima.h
> index e3d71d8d56e3..8a6be4284210 100644
> --- a/security/integrity/ima/ima.h
> +++ b/security/integrity/ima/ima.h
> @@ -28,6 +28,15 @@ enum ima_show_type { IMA_SHOW_BINARY, IMA_SHOW_BINARY_NO_FIELD_LEN,
> IMA_SHOW_BINARY_OLD_STRING_FMT, IMA_SHOW_ASCII };
> enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
>
> +/*
> + * BINARY_SIZE: size of the current measurements list
> + * BINARY_SIZE_STAGED: size of current measurements list + staged entries
> + * BINARY_SIZE_FULL: size of measurements list since IMA initialization
> + */
> +enum binary_size_types {
> + BINARY_SIZE, BINARY_SIZE_STAGED, BINARY_SIZE_FULL, BINARY__LAST
> +};
> +
> /* digest size for IMA, fits SHA1 or MD5 */
> #define IMA_DIGEST_SIZE SHA1_DIGEST_SIZE
> #define IMA_EVENT_NAME_LEN_MAX 255
> @@ -117,6 +126,8 @@ struct ima_queue_entry {
> struct ima_template_entry *entry;
> };
> extern struct list_head ima_measurements; /* list of all measurements */
> +extern struct list_head ima_measurements_staged; /* list of staged meas. */
> +extern bool ima_measurements_staged_exist; /* If there are staged meas. */
>
> /* Some details preceding the binary serialized measurement list */
> struct ima_kexec_hdr {
> @@ -281,10 +292,12 @@ struct ima_template_desc *ima_template_desc_current(void);
> struct ima_template_desc *ima_template_desc_buf(void);
> struct ima_template_desc *lookup_template_desc(const char *name);
> bool ima_template_has_modsig(const struct ima_template_desc *ima_template);
> +int ima_queue_stage_trim(unsigned long req_value, bool trim);
> +int ima_queue_delete_staged_trimmed(bool staged_moved);
> int ima_restore_measurement_entry(struct ima_template_entry *entry);
> int ima_restore_measurement_list(loff_t bufsize, void *buf);
> int ima_measurements_show(struct seq_file *m, void *v);
> -unsigned long ima_get_binary_runtime_size(void);
> +unsigned long ima_get_binary_runtime_size(enum binary_size_types type);
> int ima_init_template(void);
> void ima_init_template_list(void);
> int __init ima_init_digests(void);
> @@ -298,11 +311,12 @@ int ima_lsm_policy_change(struct notifier_block *nb, unsigned long event,
> extern spinlock_t ima_queue_lock;
>
> struct ima_h_table {
> - atomic_long_t len; /* number of stored measurements in the list */
> + atomic_long_t len[BINARY__LAST]; /* num of stored meas. in the list */
> atomic_long_t violations;
> struct hlist_head queue[IMA_MEASURE_HTABLE_SIZE];
> };
> extern struct ima_h_table ima_htable;
> +extern struct mutex ima_extend_list_mutex;
>
> static inline unsigned int ima_hash_key(u8 *digest)
> {
> diff --git a/security/integrity/ima/ima_fs.c b/security/integrity/ima/ima_fs.c
> index 87045b09f120..a96f7c36b34a 100644
> --- a/security/integrity/ima/ima_fs.c
> +++ b/security/integrity/ima/ima_fs.c
> @@ -24,7 +24,18 @@
>
> #include "ima.h"
>
> +/*
> + * Requests:
> + * 'A\n': stage the entire measurements list
> + * '[1, LONG_MAX]\n' stage N measurements entries
> + * '-[1, LONG_MAX]\n' trim N measurements entries
> + * 'D\n': delete staged measurements
> + */
> +#define STAGED_REQ_LENGTH 21
> +
> static DEFINE_MUTEX(ima_write_mutex);
> +static DEFINE_MUTEX(ima_measure_lock);
> +static long ima_measure_users;
>
> bool ima_canonical_fmt;
> static int __init default_canonical_fmt_setup(char *str)
> @@ -64,7 +75,8 @@ static ssize_t ima_show_measurements_count(struct file *filp,
> char __user *buf,
> size_t count, loff_t *ppos)
> {
> - return ima_show_htable_value(buf, count, ppos, &ima_htable.len);
> + return ima_show_htable_value(buf, count, ppos,
> + &ima_htable.len[BINARY_SIZE]);
>
> }
>
> @@ -74,14 +86,15 @@ static const struct file_operations ima_measurements_count_ops = {
> };
>
> /* returns pointer to hlist_node */
> -static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
> +static void *_ima_measurements_start(struct seq_file *m, loff_t *pos,
> + struct list_head *head)
> {
> loff_t l = *pos;
> struct ima_queue_entry *qe;
>
> /* we need a lock since pos could point beyond last element */
> rcu_read_lock();
> - list_for_each_entry_rcu(qe, &ima_measurements, later) {
> + list_for_each_entry_rcu(qe, head, later) {
> if (!l--) {
> rcu_read_unlock();
> return qe;
> @@ -91,7 +104,18 @@ static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
> return NULL;
> }
>
> -static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
> +static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
> +{
> + return _ima_measurements_start(m, pos, &ima_measurements);
> +}
> +
> +static void *ima_measurements_staged_start(struct seq_file *m, loff_t *pos)
> +{
> + return _ima_measurements_start(m, pos, &ima_measurements_staged);
> +}
> +
> +static void *_ima_measurements_next(struct seq_file *m, void *v, loff_t *pos,
> + struct list_head *head)
> {
> struct ima_queue_entry *qe = v;
>
> @@ -103,7 +127,18 @@ static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
> rcu_read_unlock();
> (*pos)++;
>
> - return (&qe->later == &ima_measurements) ? NULL : qe;
> + return (&qe->later == head) ? NULL : qe;
> +}
> +
> +static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
> +{
> + return _ima_measurements_next(m, v, pos, &ima_measurements);
> +}
> +
> +static void *ima_measurements_staged_next(struct seq_file *m, void *v,
> + loff_t *pos)
> +{
> + return _ima_measurements_next(m, v, pos, &ima_measurements_staged);
> }
>
> static void ima_measurements_stop(struct seq_file *m, void *v)
> @@ -202,16 +237,147 @@ static const struct seq_operations ima_measurments_seqops = {
> .show = ima_measurements_show
> };
>
> +static int _ima_measurements_open(struct inode *inode, struct file *file,
> + const struct seq_operations *seq_ops)
> +{
> + bool write = !!(file->f_mode & FMODE_WRITE);
> + int ret;
> +
> + if (write && !capable(CAP_SYS_ADMIN))
> + return -EPERM;
> +
> + mutex_lock(&ima_measure_lock);
> + if ((write && ima_measure_users != 0) ||
> + (!write && ima_measure_users < 0)) {
> + mutex_unlock(&ima_measure_lock);
> + return -EBUSY;
> + }
> +
> + ret = seq_open(file, seq_ops);
> + if (ret < 0) {
> + mutex_unlock(&ima_measure_lock);
> + return ret;
> + }
> +
> + if (write)
> + ima_measure_users--;
> + else
> + ima_measure_users++;
> +
> + mutex_unlock(&ima_measure_lock);
> + return ret;
> +}
> +
> static int ima_measurements_open(struct inode *inode, struct file *file)
> {
> - return seq_open(file, &ima_measurments_seqops);
> + return _ima_measurements_open(inode, file, &ima_measurments_seqops);
> +}
> +
> +static int ima_measurements_release(struct inode *inode, struct file *file)
> +{
> + bool write = !!(file->f_mode & FMODE_WRITE);
> + int ret;
> +
> + mutex_lock(&ima_measure_lock);
> + ret = seq_release(inode, file);
> + if (!ret) {
> + if (write)
> + ima_measure_users++;
> + else
> + ima_measure_users--;
> + }
> +
> + mutex_unlock(&ima_measure_lock);
> + return ret;
> }
>
> static const struct file_operations ima_measurements_ops = {
> .open = ima_measurements_open,
> .read = seq_read,
> .llseek = seq_lseek,
> - .release = seq_release,
> + .release = ima_measurements_release,
> +};
> +
> +static const struct seq_operations ima_measurments_staged_seqops = {
> + .start = ima_measurements_staged_start,
> + .next = ima_measurements_staged_next,
> + .stop = ima_measurements_stop,
> + .show = ima_measurements_show
> +};
> +
> +static int ima_measurements_staged_open(struct inode *inode, struct file *file)
> +{
> + return _ima_measurements_open(inode, file,
> + &ima_measurments_staged_seqops);
> +}
> +
> +static ssize_t ima_measurements_staged_read(struct file *file, char __user *buf,
> + size_t size, loff_t *ppos)
> +{
> + if (!ima_measurements_staged_exist)
> + return -ENOENT;
> +
> + return seq_read(file, buf, size, ppos);
> +}
> +
> +static ssize_t ima_measurements_staged_write(struct file *file,
> + const char __user *buf,
> + size_t datalen, loff_t *ppos)
> +{
> + char req[STAGED_REQ_LENGTH], *req_ptr = req;
> + unsigned long req_value;
> + bool trim = false;
> + int ret;
> +
> + if (*ppos > 0 || datalen < 2 || datalen > STAGED_REQ_LENGTH)
> + return -EINVAL;
> +
> + if (copy_from_user(req, buf, datalen) != 0)
> + return -EFAULT;
> +
> + if (req[datalen - 1] != '\n')
> + return -EINVAL;
> +
> + req[datalen - 1] = '\0';
> + req_ptr = req;
> +
> + switch (req[0]) {
> + case 'A':
> + if (datalen != 2 || req[1] != '\0')
> + return -EINVAL;
> +
> + ret = ima_queue_stage_trim(LONG_MAX, false);
> + break;
> + case 'D':
> + if (datalen != 2 || req[1] != '\0')
> + return -EINVAL;
> +
> + ret = ima_queue_delete_staged_trimmed(false);
> + break;
> + case '-':
> + trim = true;
> + req_ptr++;
> + fallthrough;
> + default:
> + ret = kstrtoul(req_ptr, 0, &req_value);
> + if (ret < 0)
> + return ret;
> +
> + ret = ima_queue_stage_trim(req_value, trim);
> + }
> +
> + if (ret < 0)
> + return ret;
> +
> + return datalen;
> +}
> +
> +static const struct file_operations ima_measurements_staged_ops = {
> + .open = ima_measurements_staged_open,
> + .read = ima_measurements_staged_read,
> + .write = ima_measurements_staged_write,
> + .llseek = seq_lseek,
> + .release = ima_measurements_release,
> };
>
> void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
> @@ -279,14 +445,37 @@ static const struct seq_operations ima_ascii_measurements_seqops = {
>
> static int ima_ascii_measurements_open(struct inode *inode, struct file *file)
> {
> - return seq_open(file, &ima_ascii_measurements_seqops);
> + return _ima_measurements_open(inode, file,
> + &ima_ascii_measurements_seqops);
> }
>
> static const struct file_operations ima_ascii_measurements_ops = {
> .open = ima_ascii_measurements_open,
> .read = seq_read,
> .llseek = seq_lseek,
> - .release = seq_release,
> + .release = ima_measurements_release,
> +};
> +
> +static const struct seq_operations ima_ascii_measurements_staged_seqops = {
> + .start = ima_measurements_staged_start,
> + .next = ima_measurements_staged_next,
> + .stop = ima_measurements_stop,
> + .show = ima_ascii_measurements_show
> +};
> +
> +static int ima_ascii_measurements_staged_open(struct inode *inode,
> + struct file *file)
> +{
> + return _ima_measurements_open(inode, file,
> + &ima_ascii_measurements_staged_seqops);
> +}
> +
> +static const struct file_operations ima_ascii_measurements_staged_ops = {
> + .open = ima_ascii_measurements_staged_open,
> + .read = ima_measurements_staged_read,
> + .write = ima_measurements_staged_write,
> + .llseek = seq_lseek,
> + .release = ima_measurements_release,
> };
>
> static ssize_t ima_read_policy(char *path)
> @@ -419,6 +608,25 @@ static int __init create_securityfs_measurement_lists(void)
> &ima_measurements_ops);
> if (IS_ERR(dentry))
> return PTR_ERR(dentry);
> +
> + sprintf(file_name, "ascii_runtime_measurements_staged_%s",
> + hash_algo_name[algo]);
> + dentry = securityfs_create_file(file_name,
> + S_IRUSR | S_IRGRP | S_IWUSR | S_IWGRP,
> + ima_dir, (void *)(uintptr_t)i,
> + &ima_ascii_measurements_staged_ops);
> + if (IS_ERR(dentry))
> + return PTR_ERR(dentry);
> +
> + sprintf(file_name, "binary_runtime_measurements_staged_%s",
> + hash_algo_name[algo]);
> + dentry = securityfs_create_file(file_name,
> + S_IRUSR | S_IRGRP |
> + S_IWUSR | S_IWGRP,
> + ima_dir, (void *)(uintptr_t)i,
> + &ima_measurements_staged_ops);
> + if (IS_ERR(dentry))
> + return PTR_ERR(dentry);
> }
>
> return 0;
> @@ -528,6 +736,20 @@ int __init ima_fs_init(void)
> goto out;
> }
>
> + dentry = securityfs_create_symlink("binary_runtime_measurements_staged",
> + ima_dir, "binary_runtime_measurements_staged_sha1", NULL);
> + if (IS_ERR(dentry)) {
> + ret = PTR_ERR(dentry);
> + goto out;
> + }
> +
> + dentry = securityfs_create_symlink("ascii_runtime_measurements_staged",
> + ima_dir, "ascii_runtime_measurements_staged_sha1", NULL);
> + if (IS_ERR(dentry)) {
> + ret = PTR_ERR(dentry);
> + goto out;
> + }
> +
> dentry = securityfs_create_file("runtime_measurements_count",
> S_IRUSR | S_IRGRP, ima_dir, NULL,
> &ima_measurements_count_ops);
> diff --git a/security/integrity/ima/ima_kexec.c b/security/integrity/ima/ima_kexec.c
> index 7362f68f2d8b..13c7e78aeefd 100644
> --- a/security/integrity/ima/ima_kexec.c
> +++ b/security/integrity/ima/ima_kexec.c
> @@ -40,8 +40,8 @@ void ima_measure_kexec_event(const char *event_name)
> long len;
> int n;
>
> - buf_size = ima_get_binary_runtime_size();
> - len = atomic_long_read(&ima_htable.len);
> + buf_size = ima_get_binary_runtime_size(BINARY_SIZE_FULL);
> + len = atomic_long_read(&ima_htable.len[BINARY_SIZE_FULL]);
>
> n = scnprintf(ima_kexec_event, IMA_KEXEC_EVENT_LEN,
> "kexec_segment_size=%lu;ima_binary_runtime_size=%lu;"
> @@ -78,6 +78,17 @@ static int ima_alloc_kexec_file_buf(size_t segment_size)
> return 0;
> }
>
> +static int ima_dump_measurement(struct ima_kexec_hdr *khdr,
> + struct ima_queue_entry *qe)
> +{
> + if (ima_kexec_file.count >= ima_kexec_file.size)
> + return -EINVAL;
> +
> + khdr->count++;
> + ima_measurements_show(&ima_kexec_file, qe);
> + return 0;
> +}
> +
> static int ima_dump_measurement_list(unsigned long *buffer_size, void **buffer,
> unsigned long segment_size)
> {
> @@ -93,17 +104,25 @@ static int ima_dump_measurement_list(unsigned long *buffer_size, void **buffer,
>
> memset(&khdr, 0, sizeof(khdr));
> khdr.version = 1;
> - /* This is an append-only list, no need to hold the RCU read lock */
> - list_for_each_entry_rcu(qe, &ima_measurements, later, true) {
> - if (ima_kexec_file.count < ima_kexec_file.size) {
> - khdr.count++;
> - ima_measurements_show(&ima_kexec_file, qe);
> - } else {
> - ret = -EINVAL;
> +
> + /* It can race with ima_queue_stage_trim(). */
> + mutex_lock(&ima_extend_list_mutex);
> +
> + list_for_each_entry(qe, &ima_measurements_staged, later) {
> + ret = ima_dump_measurement(&khdr, qe);
> + if (ret < 0)
> + break;
> + }
> +
> + list_for_each_entry(qe, &ima_measurements, later) {
> + if (!ret)
> + ret = ima_dump_measurement(&khdr, qe);
> + if (ret < 0)
> break;
> - }
> }
>
> + mutex_unlock(&ima_extend_list_mutex);
> +
> /*
> * fill in reserved space with some buffer details
> * (eg. version, buffer size, number of measurements)
> @@ -157,7 +176,8 @@ void ima_add_kexec_buffer(struct kimage *image)
> else
> extra_memory = CONFIG_IMA_KEXEC_EXTRA_MEMORY_KB * 1024;
>
> - binary_runtime_size = ima_get_binary_runtime_size() + extra_memory;
> + binary_runtime_size = ima_get_binary_runtime_size(BINARY_SIZE_STAGED) +
> + extra_memory;
>
> if (binary_runtime_size >= ULONG_MAX - PAGE_SIZE)
> kexec_segment_size = ULONG_MAX;
> diff --git a/security/integrity/ima/ima_queue.c b/security/integrity/ima/ima_queue.c
> index 590637e81ad1..7dfa24b8ae31 100644
> --- a/security/integrity/ima/ima_queue.c
> +++ b/security/integrity/ima/ima_queue.c
> @@ -22,19 +22,32 @@
>
> #define AUDIT_CAUSE_LEN_MAX 32
>
> +bool ima_flush_htable;
> +static int __init ima_flush_htable_setup(char *str)
> +{
> + ima_flush_htable = true;
> + return 1;
> +}
> +__setup("ima_flush_htable", ima_flush_htable_setup);
> +
> /* pre-allocated array of tpm_digest structures to extend a PCR */
> static struct tpm_digest *digests;
>
> LIST_HEAD(ima_measurements); /* list of all measurements */
> +LIST_HEAD(ima_measurements_staged); /* list of staged measurements */
> +static LIST_HEAD(ima_measurements_trim); /* list of measurements to trim */
> +bool ima_measurements_staged_exist; /* If there are staged measurements */
> #ifdef CONFIG_IMA_KEXEC
> -static unsigned long binary_runtime_size;
> +static unsigned long binary_runtime_size[BINARY__LAST];
> #else
> -static unsigned long binary_runtime_size = ULONG_MAX;
> +static unsigned long binary_runtime_size[BINARY_SIZE] = ULONG_MAX;
> +static unsigned long binary_runtime_size[BINARY_SIZE_FULL] = ULONG_MAX;
> +static unsigned long binary_runtime_size[BINARY_SIZE_STAGED] = ULONG_MAX;
> #endif
>
> /* key: inode (before secure-hashing a file) */
> struct ima_h_table ima_htable = {
> - .len = ATOMIC_LONG_INIT(0),
> + .len = { ATOMIC_LONG_INIT(0) },
> .violations = ATOMIC_LONG_INIT(0),
> .queue[0 ... IMA_MEASURE_HTABLE_SIZE - 1] = HLIST_HEAD_INIT
> };
> @@ -43,7 +56,7 @@ struct ima_h_table ima_htable = {
> * and extending the TPM PCR aggregate. Since tpm_extend can take
> * long (and the tpm driver uses a mutex), we can't use the spinlock.
> */
> -static DEFINE_MUTEX(ima_extend_list_mutex);
> +DEFINE_MUTEX(ima_extend_list_mutex);
>
> /*
> * Used internally by the kernel to suspend measurements.
> @@ -101,7 +114,7 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
> bool update_htable)
> {
> struct ima_queue_entry *qe;
> - unsigned int key;
> + unsigned int i, key;
>
> qe = kmalloc(sizeof(*qe), GFP_KERNEL);
> if (qe == NULL) {
> @@ -113,18 +126,23 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
> INIT_LIST_HEAD(&qe->later);
> list_add_tail_rcu(&qe->later, &ima_measurements);
>
> - atomic_long_inc(&ima_htable.len);
> + for (i = 0; i < BINARY__LAST; i++)
> + atomic_long_inc(&ima_htable.len[i]);
> +
> if (update_htable) {
> key = ima_hash_key(entry->digests[ima_hash_algo_idx].digest);
> hlist_add_head_rcu(&qe->hnext, &ima_htable.queue[key]);
> }
>
> - if (binary_runtime_size != ULONG_MAX) {
> + if (binary_runtime_size[BINARY_SIZE_FULL] != ULONG_MAX) {
> int size;
>
> size = get_binary_runtime_size(entry);
> - binary_runtime_size = (binary_runtime_size < ULONG_MAX - size) ?
> - binary_runtime_size + size : ULONG_MAX;
> +
> + for (i = 0; i < BINARY__LAST; i++)
> + binary_runtime_size[i] =
> + (binary_runtime_size[i] < ULONG_MAX - size) ?
> + binary_runtime_size[i] + size : ULONG_MAX;
> }
> return 0;
> }
> @@ -134,12 +152,18 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
> * entire binary_runtime_measurement list, including the ima_kexec_hdr
> * structure.
> */
> -unsigned long ima_get_binary_runtime_size(void)
> +unsigned long ima_get_binary_runtime_size(enum binary_size_types type)
> {
> - if (binary_runtime_size >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
> + unsigned long val;
> +
> + mutex_lock(&ima_extend_list_mutex);
> + val = binary_runtime_size[type];
> + mutex_unlock(&ima_extend_list_mutex);
> +
> + if (val >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
> return ULONG_MAX;
> else
> - return binary_runtime_size + sizeof(struct ima_kexec_hdr);
> + return val + sizeof(struct ima_kexec_hdr);
> }
>
> static int ima_pcr_extend(struct tpm_digest *digests_arg, int pcr)
> @@ -220,6 +244,127 @@ int ima_add_template_entry(struct ima_template_entry *entry, int violation,
> return result;
> }
>
> +int ima_queue_stage_trim(unsigned long req_value, bool trim)
req_value idea comes from Trim N entries one step proposal
trim idea come from Trim N entries one step proposal
> +{
> + unsigned long req_value_copy = req_value, to_remove = 0;
> + struct list_head *moved = &ima_measurements_staged;
> + struct ima_queue_entry *qe;
> +
> + if (req_value == 0 || req_value > LONG_MAX)
> + return -EINVAL;
> +
> + if (ima_measurements_staged_exist)
> + return -EEXIST;
> +
> + if (trim)
> + moved = &ima_measurements_trim;
> +
> + mutex_lock(&ima_extend_list_mutex);
> + if (list_empty(&ima_measurements)) {
> + mutex_unlock(&ima_extend_list_mutex);
> + return -ENOENT;
> + }
> +
> + if (req_value == LONG_MAX) {
> + list_replace(&ima_measurements, moved);
> + INIT_LIST_HEAD(&ima_measurements);
> + atomic_long_set(&ima_htable.len[BINARY_SIZE], 0);
> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
> + binary_runtime_size[BINARY_SIZE] = 0;
> +
> + if (trim) {
> + atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
> + binary_runtime_size[BINARY_SIZE_STAGED] = 0;
> + }
> + } else {
> + list_for_each_entry(qe, &ima_measurements, later) {
> + to_remove += get_binary_runtime_size(qe->entry);
Trim N entries one step proposal does not need this step, this will save
lock time
> + if (--req_value_copy == 0)
> + break;
> + }
> +
> + if (req_value_copy > 0) {
> + mutex_unlock(&ima_extend_list_mutex);
> + return -ENOENT;
> + }
> +
> + __list_cut_position(moved, &ima_measurements, &qe->later);
> + atomic_long_sub(req_value, &ima_htable.len[BINARY_SIZE]);
> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
> + binary_runtime_size[BINARY_SIZE] -= to_remove;
> +
> + if (trim) {
> + atomic_long_sub(req_value,
> + &ima_htable.len[BINARY_SIZE_STAGED]);
> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
> + binary_runtime_size[BINARY_SIZE_STAGED] -=
> + to_remove;
> + }
> + }
> +
> + if (ima_flush_htable)
> + /* Either staged/trimmed entries are removed from hash table. */
> + list_for_each_entry(qe, moved, later)
> + /* It can race with ima_lookup_digest_entry(). */
> + hlist_del_rcu(&qe->hnext);
> +
> + mutex_unlock(&ima_extend_list_mutex);
> + ima_measurements_staged_exist = true;
> +
> + if (ima_flush_htable)
> + synchronize_rcu();
> +
> + if (trim)
> + return ima_queue_delete_staged_trimmed(true);
> +
> + return 0;
> +}
> +
> +int ima_queue_delete_staged_trimmed(bool staged_moved)
> +{
> + struct ima_queue_entry *qe, *qe_tmp;
> + unsigned int i;
> +
> + if (!ima_measurements_staged_exist)
> + return -ENOENT;
> +
> + if (!staged_moved) {
> + mutex_lock(&ima_extend_list_mutex);
> + list_replace(&ima_measurements_staged, &ima_measurements_trim);
> + INIT_LIST_HEAD(&ima_measurements_staged);
> + atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
> + if (IS_ENABLED(CONFIG_IMA_KEXEC))
> + binary_runtime_size[BINARY_SIZE_STAGED] = 0;
> +
> + mutex_unlock(&ima_extend_list_mutex);
> + }
> +
> + list_for_each_entry_safe(qe, qe_tmp, &ima_measurements_trim, later) {
> + /*
> + * Ok because after list delete qe is only accessed by
> + * ima_lookup_digest_entry().
> + */
> + for (i = 0; i < qe->entry->template_desc->num_fields; i++) {
> + kfree(qe->entry->template_data[i].data);
> + qe->entry->template_data[i].data = NULL;
> + qe->entry->template_data[i].len = 0;
> + }
> +
> + list_del(&qe->later);
> +
> + /* No leak if !ima_flush_htable, referenced by ima_htable. */
> + if (ima_flush_htable) {
> + kfree(qe->entry->digests);
> + kfree(qe->entry);
> + kfree(qe);
> + }
> + }
> +
> + ima_measurements_staged_exist = false;
> + return 0;
> +}
> +
> int ima_restore_measurement_entry(struct ima_template_entry *entry)
> {
> int result = 0;
^ permalink raw reply
* [RFC][PATCH v2] ima: Add support for staging measurements for deletion and trimming
From: Roberto Sassu @ 2025-12-12 17:19 UTC (permalink / raw)
To: corbet, zohar, dmitry.kasatkin, eric.snowberg, paul, jmorris,
serge
Cc: linux-doc, linux-kernel, linux-integrity, linux-security-module,
gregorylumen, chenste, nramas, Roberto Sassu
From: Roberto Sassu <roberto.sassu@huawei.com>
Introduce the ability of staging the entire (or a portion of the) IMA
measurement list for deletion. Staging means moving the current content of
the measurement list to a separate location, and allowing users to read and
delete it. This causes the measurement list to be atomically truncated
before new measurements can be added. Staging can be done only once at a
time. In the event of kexec(), staging is reverted and staged entries will
be carried over to the new kernel.
User space is responsible to concatenate the staged IMA measurements list
portions following the temporal order in which the operations were done,
together with the current measurement list. Then, it can send the collected
data to the remote verifiers.
Also introduce the ability of trimming N measurements entries from the IMA
measurements list, provided that user space has already read them. Trimming
combines staging and deletion in one operation.
The benefit of these solutions is the ability to free precious kernel
memory, in exchange of delegating user space to reconstruct the full
measurement list from the chunks. No trust needs to be given to user space,
since the integrity of the measurement list is protected by the TPM.
By default, staging/trimming the measurements list does not alter the hash
table. When staging/trimming are done, IMA is still able to detect
collisions on the staged and later deleted measurement entries, by keeping
the entry digests (only template data are freed).
However, since during the measurements list serialization only the SHA1
digest is passed, and since there are no template data to recalculate the
other digests from, the hash table is currently not populated with digests
from staged/deleted entries after kexec().
Introduce the new kernel option ima_flush_htable to decide whether or not
the digests of staged measurement entries are flushed from the hash table.
Then, introduce ascii_runtime_measurements_staged_<algo> and
binary_runtime_measurement_staged_<algo> interfaces to stage/trim/delete
the measurements. Use 'echo A > <IMA interface>' and
'echo D > <IMA interface>' to respectively stage and delete the entire
measurements list. Use 'echo N > <IMA interface>', with N between 1 and
LONG_MAX, to stage the selected portion of the measurements list, and
'echo -N > <IMA interface>' to trim N measurements entries.
The ima_measure_users counter (protected by the ima_measure_lock mutex) has
been introduced to protect access to the measurements list and the staged
part. The open method of all the measurement interfaces has been extended
to allow only one writer at a time or, in alternative, multiple readers.
The write permission is used to stage/trim/delete the measurements, the
read permission to read them. Write requires also the CAP_SYS_ADMIN
capability.
Finally, introduce and maintain dedicate counters for the number of
measurement entries and binary size, for the current measurements list
(BINARY_SIZE), for the current measurements list plus staged entries
(BINARY_SIZE_STAGED) useful for kexec() segment allocation, and for the
entire measurement list without staging/trimming (BINARY_SIZE_FULL) useful
for the kexec-related critical data records.
Note: This code derives from the Alt-IMA Huawei project, and is being
released under the dual license model (GPL-2.0 OR MIT).
Link: https://github.com/linux-integrity/linux/issues/1
Signed-off-by: Roberto Sassu <roberto.sassu@huawei.com>
---
.../admin-guide/kernel-parameters.txt | 4 +
security/integrity/ima/ima.h | 18 +-
security/integrity/ima/ima_fs.c | 240 +++++++++++++++++-
security/integrity/ima/ima_kexec.c | 42 ++-
security/integrity/ima/ima_queue.c | 169 +++++++++++-
5 files changed, 439 insertions(+), 34 deletions(-)
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index 6c42061ca20e..e5f1e11bd0a2 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -2215,6 +2215,10 @@
Use the canonical format for the binary runtime
measurements, instead of host native format.
+ ima_flush_htable [IMA]
+ Flush the IMA hash table when staging for deletion or
+ trimming measurement entries.
+
ima_hash= [IMA]
Format: { md5 | sha1 | rmd160 | sha256 | sha384
| sha512 | ... }
diff --git a/security/integrity/ima/ima.h b/security/integrity/ima/ima.h
index e3d71d8d56e3..8a6be4284210 100644
--- a/security/integrity/ima/ima.h
+++ b/security/integrity/ima/ima.h
@@ -28,6 +28,15 @@ enum ima_show_type { IMA_SHOW_BINARY, IMA_SHOW_BINARY_NO_FIELD_LEN,
IMA_SHOW_BINARY_OLD_STRING_FMT, IMA_SHOW_ASCII };
enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
+/*
+ * BINARY_SIZE: size of the current measurements list
+ * BINARY_SIZE_STAGED: size of current measurements list + staged entries
+ * BINARY_SIZE_FULL: size of measurements list since IMA initialization
+ */
+enum binary_size_types {
+ BINARY_SIZE, BINARY_SIZE_STAGED, BINARY_SIZE_FULL, BINARY__LAST
+};
+
/* digest size for IMA, fits SHA1 or MD5 */
#define IMA_DIGEST_SIZE SHA1_DIGEST_SIZE
#define IMA_EVENT_NAME_LEN_MAX 255
@@ -117,6 +126,8 @@ struct ima_queue_entry {
struct ima_template_entry *entry;
};
extern struct list_head ima_measurements; /* list of all measurements */
+extern struct list_head ima_measurements_staged; /* list of staged meas. */
+extern bool ima_measurements_staged_exist; /* If there are staged meas. */
/* Some details preceding the binary serialized measurement list */
struct ima_kexec_hdr {
@@ -281,10 +292,12 @@ struct ima_template_desc *ima_template_desc_current(void);
struct ima_template_desc *ima_template_desc_buf(void);
struct ima_template_desc *lookup_template_desc(const char *name);
bool ima_template_has_modsig(const struct ima_template_desc *ima_template);
+int ima_queue_stage_trim(unsigned long req_value, bool trim);
+int ima_queue_delete_staged_trimmed(bool staged_moved);
int ima_restore_measurement_entry(struct ima_template_entry *entry);
int ima_restore_measurement_list(loff_t bufsize, void *buf);
int ima_measurements_show(struct seq_file *m, void *v);
-unsigned long ima_get_binary_runtime_size(void);
+unsigned long ima_get_binary_runtime_size(enum binary_size_types type);
int ima_init_template(void);
void ima_init_template_list(void);
int __init ima_init_digests(void);
@@ -298,11 +311,12 @@ int ima_lsm_policy_change(struct notifier_block *nb, unsigned long event,
extern spinlock_t ima_queue_lock;
struct ima_h_table {
- atomic_long_t len; /* number of stored measurements in the list */
+ atomic_long_t len[BINARY__LAST]; /* num of stored meas. in the list */
atomic_long_t violations;
struct hlist_head queue[IMA_MEASURE_HTABLE_SIZE];
};
extern struct ima_h_table ima_htable;
+extern struct mutex ima_extend_list_mutex;
static inline unsigned int ima_hash_key(u8 *digest)
{
diff --git a/security/integrity/ima/ima_fs.c b/security/integrity/ima/ima_fs.c
index 87045b09f120..a96f7c36b34a 100644
--- a/security/integrity/ima/ima_fs.c
+++ b/security/integrity/ima/ima_fs.c
@@ -24,7 +24,18 @@
#include "ima.h"
+/*
+ * Requests:
+ * 'A\n': stage the entire measurements list
+ * '[1, LONG_MAX]\n' stage N measurements entries
+ * '-[1, LONG_MAX]\n' trim N measurements entries
+ * 'D\n': delete staged measurements
+ */
+#define STAGED_REQ_LENGTH 21
+
static DEFINE_MUTEX(ima_write_mutex);
+static DEFINE_MUTEX(ima_measure_lock);
+static long ima_measure_users;
bool ima_canonical_fmt;
static int __init default_canonical_fmt_setup(char *str)
@@ -64,7 +75,8 @@ static ssize_t ima_show_measurements_count(struct file *filp,
char __user *buf,
size_t count, loff_t *ppos)
{
- return ima_show_htable_value(buf, count, ppos, &ima_htable.len);
+ return ima_show_htable_value(buf, count, ppos,
+ &ima_htable.len[BINARY_SIZE]);
}
@@ -74,14 +86,15 @@ static const struct file_operations ima_measurements_count_ops = {
};
/* returns pointer to hlist_node */
-static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
+static void *_ima_measurements_start(struct seq_file *m, loff_t *pos,
+ struct list_head *head)
{
loff_t l = *pos;
struct ima_queue_entry *qe;
/* we need a lock since pos could point beyond last element */
rcu_read_lock();
- list_for_each_entry_rcu(qe, &ima_measurements, later) {
+ list_for_each_entry_rcu(qe, head, later) {
if (!l--) {
rcu_read_unlock();
return qe;
@@ -91,7 +104,18 @@ static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
return NULL;
}
-static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
+static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
+{
+ return _ima_measurements_start(m, pos, &ima_measurements);
+}
+
+static void *ima_measurements_staged_start(struct seq_file *m, loff_t *pos)
+{
+ return _ima_measurements_start(m, pos, &ima_measurements_staged);
+}
+
+static void *_ima_measurements_next(struct seq_file *m, void *v, loff_t *pos,
+ struct list_head *head)
{
struct ima_queue_entry *qe = v;
@@ -103,7 +127,18 @@ static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
rcu_read_unlock();
(*pos)++;
- return (&qe->later == &ima_measurements) ? NULL : qe;
+ return (&qe->later == head) ? NULL : qe;
+}
+
+static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
+{
+ return _ima_measurements_next(m, v, pos, &ima_measurements);
+}
+
+static void *ima_measurements_staged_next(struct seq_file *m, void *v,
+ loff_t *pos)
+{
+ return _ima_measurements_next(m, v, pos, &ima_measurements_staged);
}
static void ima_measurements_stop(struct seq_file *m, void *v)
@@ -202,16 +237,147 @@ static const struct seq_operations ima_measurments_seqops = {
.show = ima_measurements_show
};
+static int _ima_measurements_open(struct inode *inode, struct file *file,
+ const struct seq_operations *seq_ops)
+{
+ bool write = !!(file->f_mode & FMODE_WRITE);
+ int ret;
+
+ if (write && !capable(CAP_SYS_ADMIN))
+ return -EPERM;
+
+ mutex_lock(&ima_measure_lock);
+ if ((write && ima_measure_users != 0) ||
+ (!write && ima_measure_users < 0)) {
+ mutex_unlock(&ima_measure_lock);
+ return -EBUSY;
+ }
+
+ ret = seq_open(file, seq_ops);
+ if (ret < 0) {
+ mutex_unlock(&ima_measure_lock);
+ return ret;
+ }
+
+ if (write)
+ ima_measure_users--;
+ else
+ ima_measure_users++;
+
+ mutex_unlock(&ima_measure_lock);
+ return ret;
+}
+
static int ima_measurements_open(struct inode *inode, struct file *file)
{
- return seq_open(file, &ima_measurments_seqops);
+ return _ima_measurements_open(inode, file, &ima_measurments_seqops);
+}
+
+static int ima_measurements_release(struct inode *inode, struct file *file)
+{
+ bool write = !!(file->f_mode & FMODE_WRITE);
+ int ret;
+
+ mutex_lock(&ima_measure_lock);
+ ret = seq_release(inode, file);
+ if (!ret) {
+ if (write)
+ ima_measure_users++;
+ else
+ ima_measure_users--;
+ }
+
+ mutex_unlock(&ima_measure_lock);
+ return ret;
}
static const struct file_operations ima_measurements_ops = {
.open = ima_measurements_open,
.read = seq_read,
.llseek = seq_lseek,
- .release = seq_release,
+ .release = ima_measurements_release,
+};
+
+static const struct seq_operations ima_measurments_staged_seqops = {
+ .start = ima_measurements_staged_start,
+ .next = ima_measurements_staged_next,
+ .stop = ima_measurements_stop,
+ .show = ima_measurements_show
+};
+
+static int ima_measurements_staged_open(struct inode *inode, struct file *file)
+{
+ return _ima_measurements_open(inode, file,
+ &ima_measurments_staged_seqops);
+}
+
+static ssize_t ima_measurements_staged_read(struct file *file, char __user *buf,
+ size_t size, loff_t *ppos)
+{
+ if (!ima_measurements_staged_exist)
+ return -ENOENT;
+
+ return seq_read(file, buf, size, ppos);
+}
+
+static ssize_t ima_measurements_staged_write(struct file *file,
+ const char __user *buf,
+ size_t datalen, loff_t *ppos)
+{
+ char req[STAGED_REQ_LENGTH], *req_ptr = req;
+ unsigned long req_value;
+ bool trim = false;
+ int ret;
+
+ if (*ppos > 0 || datalen < 2 || datalen > STAGED_REQ_LENGTH)
+ return -EINVAL;
+
+ if (copy_from_user(req, buf, datalen) != 0)
+ return -EFAULT;
+
+ if (req[datalen - 1] != '\n')
+ return -EINVAL;
+
+ req[datalen - 1] = '\0';
+ req_ptr = req;
+
+ switch (req[0]) {
+ case 'A':
+ if (datalen != 2 || req[1] != '\0')
+ return -EINVAL;
+
+ ret = ima_queue_stage_trim(LONG_MAX, false);
+ break;
+ case 'D':
+ if (datalen != 2 || req[1] != '\0')
+ return -EINVAL;
+
+ ret = ima_queue_delete_staged_trimmed(false);
+ break;
+ case '-':
+ trim = true;
+ req_ptr++;
+ fallthrough;
+ default:
+ ret = kstrtoul(req_ptr, 0, &req_value);
+ if (ret < 0)
+ return ret;
+
+ ret = ima_queue_stage_trim(req_value, trim);
+ }
+
+ if (ret < 0)
+ return ret;
+
+ return datalen;
+}
+
+static const struct file_operations ima_measurements_staged_ops = {
+ .open = ima_measurements_staged_open,
+ .read = ima_measurements_staged_read,
+ .write = ima_measurements_staged_write,
+ .llseek = seq_lseek,
+ .release = ima_measurements_release,
};
void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
@@ -279,14 +445,37 @@ static const struct seq_operations ima_ascii_measurements_seqops = {
static int ima_ascii_measurements_open(struct inode *inode, struct file *file)
{
- return seq_open(file, &ima_ascii_measurements_seqops);
+ return _ima_measurements_open(inode, file,
+ &ima_ascii_measurements_seqops);
}
static const struct file_operations ima_ascii_measurements_ops = {
.open = ima_ascii_measurements_open,
.read = seq_read,
.llseek = seq_lseek,
- .release = seq_release,
+ .release = ima_measurements_release,
+};
+
+static const struct seq_operations ima_ascii_measurements_staged_seqops = {
+ .start = ima_measurements_staged_start,
+ .next = ima_measurements_staged_next,
+ .stop = ima_measurements_stop,
+ .show = ima_ascii_measurements_show
+};
+
+static int ima_ascii_measurements_staged_open(struct inode *inode,
+ struct file *file)
+{
+ return _ima_measurements_open(inode, file,
+ &ima_ascii_measurements_staged_seqops);
+}
+
+static const struct file_operations ima_ascii_measurements_staged_ops = {
+ .open = ima_ascii_measurements_staged_open,
+ .read = ima_measurements_staged_read,
+ .write = ima_measurements_staged_write,
+ .llseek = seq_lseek,
+ .release = ima_measurements_release,
};
static ssize_t ima_read_policy(char *path)
@@ -419,6 +608,25 @@ static int __init create_securityfs_measurement_lists(void)
&ima_measurements_ops);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
+
+ sprintf(file_name, "ascii_runtime_measurements_staged_%s",
+ hash_algo_name[algo]);
+ dentry = securityfs_create_file(file_name,
+ S_IRUSR | S_IRGRP | S_IWUSR | S_IWGRP,
+ ima_dir, (void *)(uintptr_t)i,
+ &ima_ascii_measurements_staged_ops);
+ if (IS_ERR(dentry))
+ return PTR_ERR(dentry);
+
+ sprintf(file_name, "binary_runtime_measurements_staged_%s",
+ hash_algo_name[algo]);
+ dentry = securityfs_create_file(file_name,
+ S_IRUSR | S_IRGRP |
+ S_IWUSR | S_IWGRP,
+ ima_dir, (void *)(uintptr_t)i,
+ &ima_measurements_staged_ops);
+ if (IS_ERR(dentry))
+ return PTR_ERR(dentry);
}
return 0;
@@ -528,6 +736,20 @@ int __init ima_fs_init(void)
goto out;
}
+ dentry = securityfs_create_symlink("binary_runtime_measurements_staged",
+ ima_dir, "binary_runtime_measurements_staged_sha1", NULL);
+ if (IS_ERR(dentry)) {
+ ret = PTR_ERR(dentry);
+ goto out;
+ }
+
+ dentry = securityfs_create_symlink("ascii_runtime_measurements_staged",
+ ima_dir, "ascii_runtime_measurements_staged_sha1", NULL);
+ if (IS_ERR(dentry)) {
+ ret = PTR_ERR(dentry);
+ goto out;
+ }
+
dentry = securityfs_create_file("runtime_measurements_count",
S_IRUSR | S_IRGRP, ima_dir, NULL,
&ima_measurements_count_ops);
diff --git a/security/integrity/ima/ima_kexec.c b/security/integrity/ima/ima_kexec.c
index 7362f68f2d8b..13c7e78aeefd 100644
--- a/security/integrity/ima/ima_kexec.c
+++ b/security/integrity/ima/ima_kexec.c
@@ -40,8 +40,8 @@ void ima_measure_kexec_event(const char *event_name)
long len;
int n;
- buf_size = ima_get_binary_runtime_size();
- len = atomic_long_read(&ima_htable.len);
+ buf_size = ima_get_binary_runtime_size(BINARY_SIZE_FULL);
+ len = atomic_long_read(&ima_htable.len[BINARY_SIZE_FULL]);
n = scnprintf(ima_kexec_event, IMA_KEXEC_EVENT_LEN,
"kexec_segment_size=%lu;ima_binary_runtime_size=%lu;"
@@ -78,6 +78,17 @@ static int ima_alloc_kexec_file_buf(size_t segment_size)
return 0;
}
+static int ima_dump_measurement(struct ima_kexec_hdr *khdr,
+ struct ima_queue_entry *qe)
+{
+ if (ima_kexec_file.count >= ima_kexec_file.size)
+ return -EINVAL;
+
+ khdr->count++;
+ ima_measurements_show(&ima_kexec_file, qe);
+ return 0;
+}
+
static int ima_dump_measurement_list(unsigned long *buffer_size, void **buffer,
unsigned long segment_size)
{
@@ -93,17 +104,25 @@ static int ima_dump_measurement_list(unsigned long *buffer_size, void **buffer,
memset(&khdr, 0, sizeof(khdr));
khdr.version = 1;
- /* This is an append-only list, no need to hold the RCU read lock */
- list_for_each_entry_rcu(qe, &ima_measurements, later, true) {
- if (ima_kexec_file.count < ima_kexec_file.size) {
- khdr.count++;
- ima_measurements_show(&ima_kexec_file, qe);
- } else {
- ret = -EINVAL;
+
+ /* It can race with ima_queue_stage_trim(). */
+ mutex_lock(&ima_extend_list_mutex);
+
+ list_for_each_entry(qe, &ima_measurements_staged, later) {
+ ret = ima_dump_measurement(&khdr, qe);
+ if (ret < 0)
+ break;
+ }
+
+ list_for_each_entry(qe, &ima_measurements, later) {
+ if (!ret)
+ ret = ima_dump_measurement(&khdr, qe);
+ if (ret < 0)
break;
- }
}
+ mutex_unlock(&ima_extend_list_mutex);
+
/*
* fill in reserved space with some buffer details
* (eg. version, buffer size, number of measurements)
@@ -157,7 +176,8 @@ void ima_add_kexec_buffer(struct kimage *image)
else
extra_memory = CONFIG_IMA_KEXEC_EXTRA_MEMORY_KB * 1024;
- binary_runtime_size = ima_get_binary_runtime_size() + extra_memory;
+ binary_runtime_size = ima_get_binary_runtime_size(BINARY_SIZE_STAGED) +
+ extra_memory;
if (binary_runtime_size >= ULONG_MAX - PAGE_SIZE)
kexec_segment_size = ULONG_MAX;
diff --git a/security/integrity/ima/ima_queue.c b/security/integrity/ima/ima_queue.c
index 590637e81ad1..7dfa24b8ae31 100644
--- a/security/integrity/ima/ima_queue.c
+++ b/security/integrity/ima/ima_queue.c
@@ -22,19 +22,32 @@
#define AUDIT_CAUSE_LEN_MAX 32
+bool ima_flush_htable;
+static int __init ima_flush_htable_setup(char *str)
+{
+ ima_flush_htable = true;
+ return 1;
+}
+__setup("ima_flush_htable", ima_flush_htable_setup);
+
/* pre-allocated array of tpm_digest structures to extend a PCR */
static struct tpm_digest *digests;
LIST_HEAD(ima_measurements); /* list of all measurements */
+LIST_HEAD(ima_measurements_staged); /* list of staged measurements */
+static LIST_HEAD(ima_measurements_trim); /* list of measurements to trim */
+bool ima_measurements_staged_exist; /* If there are staged measurements */
#ifdef CONFIG_IMA_KEXEC
-static unsigned long binary_runtime_size;
+static unsigned long binary_runtime_size[BINARY__LAST];
#else
-static unsigned long binary_runtime_size = ULONG_MAX;
+static unsigned long binary_runtime_size[BINARY_SIZE] = ULONG_MAX;
+static unsigned long binary_runtime_size[BINARY_SIZE_FULL] = ULONG_MAX;
+static unsigned long binary_runtime_size[BINARY_SIZE_STAGED] = ULONG_MAX;
#endif
/* key: inode (before secure-hashing a file) */
struct ima_h_table ima_htable = {
- .len = ATOMIC_LONG_INIT(0),
+ .len = { ATOMIC_LONG_INIT(0) },
.violations = ATOMIC_LONG_INIT(0),
.queue[0 ... IMA_MEASURE_HTABLE_SIZE - 1] = HLIST_HEAD_INIT
};
@@ -43,7 +56,7 @@ struct ima_h_table ima_htable = {
* and extending the TPM PCR aggregate. Since tpm_extend can take
* long (and the tpm driver uses a mutex), we can't use the spinlock.
*/
-static DEFINE_MUTEX(ima_extend_list_mutex);
+DEFINE_MUTEX(ima_extend_list_mutex);
/*
* Used internally by the kernel to suspend measurements.
@@ -101,7 +114,7 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
bool update_htable)
{
struct ima_queue_entry *qe;
- unsigned int key;
+ unsigned int i, key;
qe = kmalloc(sizeof(*qe), GFP_KERNEL);
if (qe == NULL) {
@@ -113,18 +126,23 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
INIT_LIST_HEAD(&qe->later);
list_add_tail_rcu(&qe->later, &ima_measurements);
- atomic_long_inc(&ima_htable.len);
+ for (i = 0; i < BINARY__LAST; i++)
+ atomic_long_inc(&ima_htable.len[i]);
+
if (update_htable) {
key = ima_hash_key(entry->digests[ima_hash_algo_idx].digest);
hlist_add_head_rcu(&qe->hnext, &ima_htable.queue[key]);
}
- if (binary_runtime_size != ULONG_MAX) {
+ if (binary_runtime_size[BINARY_SIZE_FULL] != ULONG_MAX) {
int size;
size = get_binary_runtime_size(entry);
- binary_runtime_size = (binary_runtime_size < ULONG_MAX - size) ?
- binary_runtime_size + size : ULONG_MAX;
+
+ for (i = 0; i < BINARY__LAST; i++)
+ binary_runtime_size[i] =
+ (binary_runtime_size[i] < ULONG_MAX - size) ?
+ binary_runtime_size[i] + size : ULONG_MAX;
}
return 0;
}
@@ -134,12 +152,18 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
* entire binary_runtime_measurement list, including the ima_kexec_hdr
* structure.
*/
-unsigned long ima_get_binary_runtime_size(void)
+unsigned long ima_get_binary_runtime_size(enum binary_size_types type)
{
- if (binary_runtime_size >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
+ unsigned long val;
+
+ mutex_lock(&ima_extend_list_mutex);
+ val = binary_runtime_size[type];
+ mutex_unlock(&ima_extend_list_mutex);
+
+ if (val >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
return ULONG_MAX;
else
- return binary_runtime_size + sizeof(struct ima_kexec_hdr);
+ return val + sizeof(struct ima_kexec_hdr);
}
static int ima_pcr_extend(struct tpm_digest *digests_arg, int pcr)
@@ -220,6 +244,127 @@ int ima_add_template_entry(struct ima_template_entry *entry, int violation,
return result;
}
+int ima_queue_stage_trim(unsigned long req_value, bool trim)
+{
+ unsigned long req_value_copy = req_value, to_remove = 0;
+ struct list_head *moved = &ima_measurements_staged;
+ struct ima_queue_entry *qe;
+
+ if (req_value == 0 || req_value > LONG_MAX)
+ return -EINVAL;
+
+ if (ima_measurements_staged_exist)
+ return -EEXIST;
+
+ if (trim)
+ moved = &ima_measurements_trim;
+
+ mutex_lock(&ima_extend_list_mutex);
+ if (list_empty(&ima_measurements)) {
+ mutex_unlock(&ima_extend_list_mutex);
+ return -ENOENT;
+ }
+
+ if (req_value == LONG_MAX) {
+ list_replace(&ima_measurements, moved);
+ INIT_LIST_HEAD(&ima_measurements);
+ atomic_long_set(&ima_htable.len[BINARY_SIZE], 0);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE] = 0;
+
+ if (trim) {
+ atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE_STAGED] = 0;
+ }
+ } else {
+ list_for_each_entry(qe, &ima_measurements, later) {
+ to_remove += get_binary_runtime_size(qe->entry);
+ if (--req_value_copy == 0)
+ break;
+ }
+
+ if (req_value_copy > 0) {
+ mutex_unlock(&ima_extend_list_mutex);
+ return -ENOENT;
+ }
+
+ __list_cut_position(moved, &ima_measurements, &qe->later);
+ atomic_long_sub(req_value, &ima_htable.len[BINARY_SIZE]);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE] -= to_remove;
+
+ if (trim) {
+ atomic_long_sub(req_value,
+ &ima_htable.len[BINARY_SIZE_STAGED]);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE_STAGED] -=
+ to_remove;
+ }
+ }
+
+ if (ima_flush_htable)
+ /* Either staged/trimmed entries are removed from hash table. */
+ list_for_each_entry(qe, moved, later)
+ /* It can race with ima_lookup_digest_entry(). */
+ hlist_del_rcu(&qe->hnext);
+
+ mutex_unlock(&ima_extend_list_mutex);
+ ima_measurements_staged_exist = true;
+
+ if (ima_flush_htable)
+ synchronize_rcu();
+
+ if (trim)
+ return ima_queue_delete_staged_trimmed(true);
+
+ return 0;
+}
+
+int ima_queue_delete_staged_trimmed(bool staged_moved)
+{
+ struct ima_queue_entry *qe, *qe_tmp;
+ unsigned int i;
+
+ if (!ima_measurements_staged_exist)
+ return -ENOENT;
+
+ if (!staged_moved) {
+ mutex_lock(&ima_extend_list_mutex);
+ list_replace(&ima_measurements_staged, &ima_measurements_trim);
+ INIT_LIST_HEAD(&ima_measurements_staged);
+ atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE_STAGED] = 0;
+
+ mutex_unlock(&ima_extend_list_mutex);
+ }
+
+ list_for_each_entry_safe(qe, qe_tmp, &ima_measurements_trim, later) {
+ /*
+ * Ok because after list delete qe is only accessed by
+ * ima_lookup_digest_entry().
+ */
+ for (i = 0; i < qe->entry->template_desc->num_fields; i++) {
+ kfree(qe->entry->template_data[i].data);
+ qe->entry->template_data[i].data = NULL;
+ qe->entry->template_data[i].len = 0;
+ }
+
+ list_del(&qe->later);
+
+ /* No leak if !ima_flush_htable, referenced by ima_htable. */
+ if (ima_flush_htable) {
+ kfree(qe->entry->digests);
+ kfree(qe->entry);
+ kfree(qe);
+ }
+ }
+
+ ima_measurements_staged_exist = false;
+ return 0;
+}
+
int ima_restore_measurement_entry(struct ima_template_entry *entry)
{
int result = 0;
--
2.43.0
^ permalink raw reply related
* Re: [LTP] [PATCH] ima_violations.sh: Another fix of condition evaluation
From: Petr Vorel @ 2025-12-12 11:20 UTC (permalink / raw)
To: Andrea Cervesato; +Cc: ltp, linux-integrity, Martin Doucha
In-Reply-To: <DEW3YDE8MMBT.DEEW2VO31X0G@suse.com>
> Hi!
> On Thu Dec 11, 2025 at 12:10 PM CET, Petr Vorel wrote:
> > c0c35509f9 was not enough to fix evaluation against empty
> > $expected_violations:
> > ima_violations 1 TINFO: verify open writers violation
> > /opt/ltp/testcases/bin/ima_violations.sh: line 96: [: 0: unary operator expected
> > Therefore split checks into two if.
> > Also improvements (readability)
> > * shorten line length with saving subtraction into variable
> > * evaluate empty variable with ${:-}
> > Fixes: 726ed71905 ("ima_violations.sh: Update validate() to support multiple violations")
> > Reported-by: Martin Doucha <mdoucha@suse.cz>
> > Signed-off-by: Petr Vorel <pvorel@suse.cz>
> > ---
> > NOTE: this was found on old SLES 4.4 based kernel which does not log
> > validations. But missing validations might be just a Secure Boot related
> > setup problem:
> > $ mokutil --sb-state
> > Secure Boot: EFI variables not supported on SUT
> > Events are logged when Secure Boot is off:
> > $ mokutil --sb-state
> > SecureBoot disabled
> > Or maybe violations worked differently on the old kernel (I remember
> > only 6.15 change).
> > Kind regards,
> > Petr
> > .../integrity/ima/tests/ima_violations.sh | 21 ++++++++++++-------
> > 1 file changed, 14 insertions(+), 7 deletions(-)
> > diff --git a/testcases/kernel/security/integrity/ima/tests/ima_violations.sh b/testcases/kernel/security/integrity/ima/tests/ima_violations.sh
> > index 1d2f1d9447..a8476e6b59 100755
> > --- a/testcases/kernel/security/integrity/ima/tests/ima_violations.sh
> > +++ b/testcases/kernel/security/integrity/ima/tests/ima_violations.sh
> > @@ -87,23 +87,30 @@ validate()
> > local search="$3"
> > local expected_violations="$4"
> > local max_attempt=3
> > - local count2 i num_violations_new
> > + local count2 diff i num_violations_new pass
> > for i in $(seq 1 $max_attempt); do
> > read num_violations_new < $IMA_VIOLATIONS
> > count2="$(get_count $search)"
> > - if [ -z "$expected_violations" -a $(($num_violations_new - $num_violations)) -gt 0 ] || \
> > - [ $(($num_violations_new - $num_violations)) -eq $expected_violations ]; then
> > - [ -z "$expected_violations" ] && expected_violations=1
> > + diff=$(($num_violations_new - $num_violations))
> > +
> > + if [ "$expected_violations" ] && [ $diff -eq $expected_violations ]; then
> > + pass=1
> > + fi
> > + if [ -z "$expected_violations" ] && [ $diff -gt 0 ]; then
> > + pass=1
> > + fi
> Maybe readability can be improved (well..shell scripts are pretty ugly
> by nature anyway):
> diff=$((num_violations_new - num_violations))
> if [ "$expected_violations" ]; then
> [ $diff -eq $expected_violations ] && pass=1
> else
> [ $diff -gt 0 ] && pass=1
> fi
Thanks, makes sense, I'll modify it before merge.
Feel free to add your RBT/TBT tags if you wish (as you spent time looking into
this).
Kind regards,
Petr
> > +
> > + if [ "$pass" = 1 ]; then
> > if [ $count2 -gt $count ]; then
> > - tst_res TPASS "$expected_violations $search violation(s) added"
> > + tst_res TPASS "${expected_violations:-1} $search violation(s) added"
> > return
> > else
> > tst_res TINFO "$search not found in $LOG ($i/$max_attempt attempt)..."
> > tst_sleep 1s
> > fi
> > - elif [ $(($num_violations_new - $num_violations)) -gt 0 ]; then
> > - tst_res $IMA_FAIL "$search too many violations added: $num_violations_new - $num_violations"
> > + elif [ $diff -gt 0 ]; then
> > + tst_res $IMA_FAIL "$search too many violations added: $diff ($num_violations_new - $num_violations)"
> > return
> > else
> > tst_res $IMA_FAIL "$search violation not added"
^ permalink raw reply
* Re: [LTP] [PATCH] ima_violations.sh: Another fix of condition evaluation
From: Andrea Cervesato @ 2025-12-12 8:50 UTC (permalink / raw)
To: Petr Vorel, ltp; +Cc: linux-integrity
In-Reply-To: <20251211111046.87297-1-pvorel@suse.cz>
Hi!
On Thu Dec 11, 2025 at 12:10 PM CET, Petr Vorel wrote:
> c0c35509f9 was not enough to fix evaluation against empty
> $expected_violations:
>
> ima_violations 1 TINFO: verify open writers violation
> /opt/ltp/testcases/bin/ima_violations.sh: line 96: [: 0: unary operator expected
>
> Therefore split checks into two if.
>
> Also improvements (readability)
> * shorten line length with saving subtraction into variable
> * evaluate empty variable with ${:-}
>
> Fixes: 726ed71905 ("ima_violations.sh: Update validate() to support multiple violations")
> Reported-by: Martin Doucha <mdoucha@suse.cz>
> Signed-off-by: Petr Vorel <pvorel@suse.cz>
> ---
> NOTE: this was found on old SLES 4.4 based kernel which does not log
> validations. But missing validations might be just a Secure Boot related
> setup problem:
>
> $ mokutil --sb-state
> Secure Boot: EFI variables not supported on SUT
>
> Events are logged when Secure Boot is off:
> $ mokutil --sb-state
> SecureBoot disabled
>
> Or maybe violations worked differently on the old kernel (I remember
> only 6.15 change).
>
> Kind regards,
> Petr
>
> .../integrity/ima/tests/ima_violations.sh | 21 ++++++++++++-------
> 1 file changed, 14 insertions(+), 7 deletions(-)
>
> diff --git a/testcases/kernel/security/integrity/ima/tests/ima_violations.sh b/testcases/kernel/security/integrity/ima/tests/ima_violations.sh
> index 1d2f1d9447..a8476e6b59 100755
> --- a/testcases/kernel/security/integrity/ima/tests/ima_violations.sh
> +++ b/testcases/kernel/security/integrity/ima/tests/ima_violations.sh
> @@ -87,23 +87,30 @@ validate()
> local search="$3"
> local expected_violations="$4"
> local max_attempt=3
> - local count2 i num_violations_new
> + local count2 diff i num_violations_new pass
>
> for i in $(seq 1 $max_attempt); do
> read num_violations_new < $IMA_VIOLATIONS
> count2="$(get_count $search)"
> - if [ -z "$expected_violations" -a $(($num_violations_new - $num_violations)) -gt 0 ] || \
> - [ $(($num_violations_new - $num_violations)) -eq $expected_violations ]; then
> - [ -z "$expected_violations" ] && expected_violations=1
> + diff=$(($num_violations_new - $num_violations))
> +
> + if [ "$expected_violations" ] && [ $diff -eq $expected_violations ]; then
> + pass=1
> + fi
> + if [ -z "$expected_violations" ] && [ $diff -gt 0 ]; then
> + pass=1
> + fi
Maybe readability can be improved (well..shell scripts are pretty ugly
by nature anyway):
diff=$((num_violations_new - num_violations))
if [ "$expected_violations" ]; then
[ $diff -eq $expected_violations ] && pass=1
else
[ $diff -gt 0 ] && pass=1
fi
> +
> + if [ "$pass" = 1 ]; then
> if [ $count2 -gt $count ]; then
> - tst_res TPASS "$expected_violations $search violation(s) added"
> + tst_res TPASS "${expected_violations:-1} $search violation(s) added"
> return
> else
> tst_res TINFO "$search not found in $LOG ($i/$max_attempt attempt)..."
> tst_sleep 1s
> fi
> - elif [ $(($num_violations_new - $num_violations)) -gt 0 ]; then
> - tst_res $IMA_FAIL "$search too many violations added: $num_violations_new - $num_violations"
> + elif [ $diff -gt 0 ]; then
> + tst_res $IMA_FAIL "$search too many violations added: $diff ($num_violations_new - $num_violations)"
> return
> else
> tst_res $IMA_FAIL "$search violation not added"
--
Andrea Cervesato
SUSE QE Automation Engineer Linux
andrea.cervesato@suse.com
^ permalink raw reply
* Re: [PATCH] ima_violations.sh: Another fix of condition evaluation
From: Mimi Zohar @ 2025-12-12 3:42 UTC (permalink / raw)
To: Petr Vorel, ltp; +Cc: linux-integrity, Martin Doucha
In-Reply-To: <20251211111046.87297-1-pvorel@suse.cz>
On Thu, 2025-12-11 at 12:10 +0100, Petr Vorel wrote:
> c0c35509f9 was not enough to fix evaluation against empty
> $expected_violations:
>
> ima_violations 1 TINFO: verify open writers violation
> /opt/ltp/testcases/bin/ima_violations.sh: line 96: [: 0: unary operator expected
>
> Therefore split checks into two if.
>
> Also improvements (readability)
> * shorten line length with saving subtraction into variable
> * evaluate empty variable with ${:-}
>
> Fixes: 726ed71905 ("ima_violations.sh: Update validate() to support multiple violations")
> Reported-by: Martin Doucha <mdoucha@suse.cz>
> Signed-off-by: Petr Vorel <pvorel@suse.cz>
Thanks, Martin, Petr. LGTM
> ---
> NOTE: this was found on old SLES 4.4 based kernel which does not log
> validations. But missing validations might be just a Secure Boot related
> setup problem:
>
> $ mokutil --sb-state
> Secure Boot: EFI variables not supported on SUT
>
> Events are logged when Secure Boot is off:
> $ mokutil --sb-state
> SecureBoot disabled
>
> Or maybe violations worked differently on the old kernel (I remember
> only 6.15 change).
Violations only occur when there are policy rules containing "func=FILE_CHECK"
defined. The secure boot mode should only affects the arch specific policies,
which do not include "func=FILE_CHECK" rules. There is a slight difference
between the builtin the original "ima_tcb" and newer "ima_policy=tcb" policies,
which might affect violations.
--
thanks,
Mimi
^ permalink raw reply
page: next (older) | prev (newer) | latest
- recent:[subjects (threaded)|topics (new)|topics (active)]
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox