Linux Security Modules development
 help / color / mirror / Atom feed
* [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: An opinion about Linux security
From: Casey Schaufler @ 2025-12-12 23:43 UTC (permalink / raw)
  To: Dr. Greg, Timur Chernykh; +Cc: torvalds, linux-security-module, Casey Schaufler
In-Reply-To: <20251212054524.GA23417@wind.enjellic.com>

On 12/11/2025 9:45 PM, Dr. Greg wrote:
> On Wed, Dec 10, 2025 at 03:15:39AM +0300, Timur Chernykh wrote:
>
> Good morning Timur, I hope this note finds your week having gone well.
>
>> Hello Linus,
>>
>> I'm writing to ask for your opinion. What do you think about Linux's
>> current readiness for security-focused commercial products?  I'm
>> particularly interested in several areas.
> I don't expect you will receive an answer.
>
> Based on his previous comments and long standing position on this
> issue, I believe it can be fairly stated that he looks at the LSM as
> an unnecessary evil.
>
> So in his absence, some 'in loco parentis' reflections on the issues
> you raise.
>
> I've been advised, more than once, that in this day and age, no one is
> interested in reading more than a two sentence paragraph, so a short
> response to your issues here and a bit more detail for anyone who
> wants to read more, at the end.
>
> There is active art available to address the shortcomings you outline
> in your post below.  Our TSEM LSM was designed to service the
> realitities of the modern security environment and where it is going.
> In a manner that doesn't provide any restrictions on how 'security'
> can be implemented.
>
> We've done four releases over three years and we believe an unbiased
> observer would conclude they have received no substantive technical
> review that would support interest in upstream integration.

Stop. Really, I mean it. I put significant effort into trying to teach
you how to submit a patch set that could be reviewed. You ignored it.
I can't speak to what an "unbiased observer" would conclude because
your behavior has certainly left me with bias. Rather than writing
full length novels about why you submitted patches the way you've
done it you might consider heeding the advice. Grrr.

> The challenge is that the security gatekeepers view LSM submissions
> through a lens of whether or not the LSM implements security
> consistent with what they believe is security.

While there is some truth to that, we're really quite flexible.
What we need to see is that there is some sort of security model,
and that the proposed code implements it. We also need to be able
to examine the proposed code to see that it implements the model.
You have rejected all suggestions about how to make your proposal
reviewable.

>   Those views are
> inconsistent with the realities of the modern security market,

Oh, stop it. Look at how many LSMs have been added over the past
few years. Sandboxing and application controlled security are
"modern" security concepts that were unheard of when the LSM was
introduced. As I said before, security is a dynamic technology.
If it were not, we'd have a Bell & LaPadula kernel config option
instead of an LSM infrastructure.

>  a
> market that that is now predicated on detection rather than
> enforcement.  A trend that will only accelerate with advancements in
> machine learning and AI.

Without the underlying access controls detection is rather pointless.

> It is worth noting that the history of the technology industry is
> littered with examples of technology incumbents usually missing
> disruptive innovation.

The technology industry is not unique on this. Acme Buggy Whips, inc.

> This restriction on suitability is actually inconsistent with Linus'
> stated position on how Linux sub-systems can be used, as expressed in
> his comment in the following post.
>
> https://lore.kernel.org/lkml/CAHk-=wgLbz1Bm8QhmJ4dJGSmTuV5w_R0Gwvg5kHrYr4Ko9dUHQ@mail.gmail.com/
>
> So the problem is not technical, it is a political eco-system problem.
>
> So, big picture, that is the challenge facing resolution of your
> concerns.
>
> Apologies to everyone about the paragraph/sentence overflow and any
> afront to sensibilities.
>
> More detail below if anyone is interested.
>
>> First, in today's 3rd-party (out-of-tree) EDR development EDR
>> being the most common commercial class of security products eBPF
>> has effectively become the main option. Yet eBPF is extremely
>> restrictive.  It is not possible to write fully expressive real-time
>> analysis code: the verifier is overly strict, non-deterministic
>> loops are not allowed, and older kernels lack BTF support. These
>> issues create real limitations.
>>
>> Second, the removal of the out-of-tree LSM API in the 4.x kernel
>> series caused significant problems for many AV/EDR vendors. I was
>> unable to find an explanation in the mailing lists that convincingly
>> justified that decision.
>>
>> The next closest mechanism, fanotify, was a genuine improvement.
>> However, it does not allow an AV/EDR vendor to protect the integrity
>> of its own product. Is Linux truly expecting modern AV/EDR solutions
>> to rely on fanotify alone?
>>
>> My main question is: what are the future plans? Linux provides very
>> few APIs for security and dynamic analysis. eBPF is still immature,
>> fanotify is insufficient, and driver workarounds that bypass kernel
>> restrictions are risky they introduce both stability and security
>> problems. At the same time, properly implemented in-tree LSMs are not
>> inherently dangerous and remain the safer, supported path for
>> extending security functionality. Without safe, supported interfaces,
>> however, commercial products struggle to be competitive. At the
>> moment, macOS with its Endpoint Security Framework is significantly
>> ahead.
>>
>> Yes, the kernel includes multiple in-tree LSM modules, but in
>> practice SELinux does not simplify operations it often complicates
>> them, despite its long-standing presence. Many of the other LSMs are
>> rarely used in production. As an EDR developer, I seldom encounter
>> them, and when I do, they usually provide little practical
>> value. Across numerous real-world server intrusions, none of these
>> LSM modules have meaningfully prevented attacks, despite many years
>> of kernel development.
>>
>> Perhaps it is time for Linux to focus on more than a theoretical model
>> of security.
> The heart of the political eco-system challenge is best expressed by a
> quote from Kyle Moffett, in which he stated that security should only
> be developed and implemented by experts.  Unfortunately that view is
> inconsistent with the current state of the technology industry.

Glad to hear I'm not an expert! - Not!

> Classical security practititioners will defend complex subject/object
> architectures with: "Google uses SeLinux for Android security".

Yea gads. Subject/Object is about as simple as it gets. Look at Smack.

> Our response to that is that the world doesn't have a security problem
> because Google lacks sufficient resources to implement anything it
> desires to implement, regardless of the development and maintenance
> input costs.
>
> Unfortunately, that luxury is inconsistent with the rest of the
> software development world that doesn't enjoy a 3.8 trillion dollar
> market capitalization.
>
> The world simply lacks enough experts to make the 'security only by
> experts' model work.
>
> Today, the fastest way to a product is to grab Linux and a development
> team and write software for hardware that is now completely
> commoditized.  Everyone knows that security is not one of the
> fundamental project predicates in this model.
>
> Both NIST and DHS/CISA are officially on record as indicating that
> security needs to start with and be baked in through the development
> process.  One of the objectives of TSEM was to provide a framework for
> enabling this concept for the implementation of analysis and mandatory
> behavior controls for software workloads.
>
> A second fundamental problem is that the world has moved, in large
> part, to containerized execution workloads.  The Linux LSM, in its
> current form, doesn't effectively support the application of workload
> specific security policies.
>
> Further complicating this issue is the fact that LSM 'stacking'
> requires reasoning as to what a final security policy will be when
> multiple different security architectures/policies get to decide on
> the outcome of a security event/hook.  The concept of least surprise
> would suggest the need for stacking to have idempotency, in other
> words, the order in which LSM event consumers are called shouldn't
> influence the effective policy, but this is generally acknowledged as
> not being the case with 'stacking'.

Any other approach, and they have been considered, fails miserably
and introduces a host of complications. Not to mention performance
de-optimization.

> So we designed TSEM to provide an alternative, not a replacement, but
> an alternative to how developers and system administrators can develop
> and apply security policy, including integrity controls.
>
> TSEM is an LSM that implements containerized security infrastructure
> rather than security policy.  It is designed around the concept of a
> security orchestrator that can execute security isolated workloads and
> receive the LSM events and their parameters from that workload and
> process them in any manner it wishes.

I shan't repeat the objections that have been raised, but I will
point out that you have done nothing to address them.

> For example: A Docker/Kubernetes container can be run and all of the
> security events by that workload exported up into an OpenSearch or
> ElasticSearch instance for anomaly detection and analysis.
>
> So an EDR implemented on top of this has visibility into all of the
> security events and their characteristics that are deemed security
> relevant by the kernel developers.
>
> One of the pushbacks is that this can lead to asynchronous security
> decisions, but as you note, that is the model that the commercial
> security industry and the consumers of its products has embraced,
> particularly in light of the advancements coming out of the AI
> industry, detection rather than enforcement.
>
> If synchronous enforcement is required TSEM provides that as well,
> including the use of standard kernel modules to implement analysis and
> response to the LSM hooks.  Internally we have implemented other LSM's
> such as Tomoyo and IMA as loadable modules that can support multiple
> and independent workload policies.
>
> If you or other EDR vendors are interested, we would be more than
> happy to engage in conversations as to how to improve the capabilities
> of this type of architecture, as an alternative to what is currently
> available in Linux, which as you note, has significant limitations.
>
>> Everything above reflects only my personal opinion. I would greatly
>> appreciate your response and any criticism you may have.
> As I mentioned at the outset, you are unlikely to hear anything.
>
> For the necessary Linux infrastructure improvements to emerge we
> believe there is the need to develop and engage a community effort
> that independently pursues the advancements that are necessary,
> particularly those that enable Linux to implement first class AI based
> security controls.
>
> We believe that only this will result in sufficient 'market pull' at the
> distribution level to help shape upstreaming decisions.
>
> Absent that, it is likely that Linux will continue to implement what
> has failed to work in the past in the hope that it will somehow work
> in the future.

Wow. calling Linux a failure is a bit of a stretch, don't you think?

> Comments and criticism welcome, we have had plenty of experience with
> the latter.... :-)

We've been over these issues many times. Go back and make some changes to
your approach.

>> Best regards,
>> Timur Chernykh
> Best wishes for the success of your work and a pleasant holiday season.
>
> As always,
> Dr. Greg
>
> The Quixote Project - Flailing at the Travails of Cybersecurity
>               https://github.com/Quixote-Project
>

^ 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: [PATCH v4 1/5] landlock: Implement LANDLOCK_ADD_RULE_NO_INHERIT
From: Justin Suess @ 2025-12-12 22:02 UTC (permalink / raw)
  To: mic; +Cc: gnoack, jack, linux-security-module, m, utilityemal77, xandfury
In-Reply-To: <20251212.Iuracooqu0es@digikod.net>

On 12/12/25 08:27, Mickaël Salaün wrote:
> Thanks for this patch series.  This feature would be useful, but the
> related patches add a lot of new code.  We should try to minimize that
> as much as possible, especially when similar/close logic already exist
> (e.g. path walk).

Agreed. I would like to get this patch much smaller. I'm glad you think the
feature is useful, it was a personal usecase that motivated me to make this
patch originally but I think having it would benefit a lot of downstream
projects.

I appreciate your patience and willingness to work with someone new to
kernel development and landlock. :)

> On Sat, Dec 06, 2025 at 08:51:27PM -0500, Justin Suess wrote:
>> Implements a flag to prevent access grant inheritance within the filesystem
>> hierarchy for landlock rules.
>>
>> If a landlock rule on an inode has this flag, any access grants on parent
>> inodes will be ignored. Moreover, operations that involve altering the
>> ancestors of the subject with LANDLOCK_ADD_RULE_NO_INHERIT will be
>> denied up to the VFS root (new in v4).
>>
>> For example, if /a/b/c/ = read only + LANDLOCK_ADD_RULE_NO_INHERIT and
>> / = read write, writes to files in /a/b/c will be denied. Moreover,
>> moving /a to /bad, removing /a/b/c, or creating links to /a will be
>> prohibited.
>>
>> Parent flag inheritance is automatically suppressed by the permission
>> harvesting logic, which will finish processing early if all relevant
>> layers are tagged with NO_INHERIT.
>>
>> And if / has LANDLOCK_ADD_RULE_QUIET, /a/b/c will still audit (handled)
>> accesses. This is because LANDLOCK_ADD_RULE_NO_INHERIT also
>> suppresses flag inheritance from parent objects.
>>
>> The parent directory restrictions mitigate sandbox-restart attacks. For
>> example, if a sandboxed program is able to move a
>> LANDLOCK_ADD_RULE_NO_INHERIT restricted directory, upon sandbox restart,
>> the policy applied naively on the same filenames would be invalid.
>> Preventing these operations mitigates these attacks.
>>
>
> Your Signed-off-by and Cc should be here, followed by "---", followed by
> the changelog (to exclude it from the git message e.g., when using
> git am).
>

Gotcha. I'll make sure to fix that.

>> v3..v4 changes:
>>
>>   * Rebased on v6 of Tingmao Wang's "quiet flag" series.
>>   * Removed unnecessary mask_no_inherit_descendant_layers and related
>>     code at Tingmao Wang's suggestion, simplifying patch.
>>   * Updated to use new disconnected directory handling.
>>   * Improved WARN_ON_ONCE usage. (Thanks Tingmao Wang!)
>>   * Removed redundant loop for single-layer rulesets (again thanks Tingmao
>>     Wang!)
>>   * Protections now apply up to the VFS root, not just the mountpoint.
>>   * Indentation fixes.
>>   * Removed redundant flag marker blocked_flag_masks.
>>
>> v2..v3 changes:
>>
>>   * Parent directory topology protections now work by lazily
>>     inserting blank rules on parent inodes if they do not
>>     exist. This replaces the previous xarray implementation
>>     with simplified logic.
>>   * Added an optimization to skip further processing if all layers
>>     collected have no inherit.
>>   * Added support to block flag inheritance.
>>
>> Cc: Tingmao Wang <m@maowtm.org>
>> Signed-off-by: Justin Suess <utilityemal77@gmail.com>
>> ---
>>  security/landlock/fs.c      | 389 +++++++++++++++++++++++++++++++++++-
>>  security/landlock/ruleset.c |  19 +-
>>  security/landlock/ruleset.h |  29 ++-
>>  3 files changed, 433 insertions(+), 4 deletions(-)
>>
>> diff --git a/security/landlock/fs.c b/security/landlock/fs.c
>> index 0b589263ea42..7b0b77859778 100644
>> --- a/security/landlock/fs.c
>> +++ b/security/landlock/fs.c
>> @@ -317,6 +317,207 @@ static struct landlock_object *get_inode_object(struct inode *const inode)
>>  	LANDLOCK_ACCESS_FS_IOCTL_DEV)
>>  /* clang-format on */
>>  
>> +static const struct landlock_rule *find_rule(const struct landlock_ruleset *const domain,
>> +					     const struct dentry *const dentry);
>> +
>> +/**
>> + * landlock_domain_layers_mask - Build a mask covering all layers of a domain
>> + * @domain: The ruleset (domain) to inspect.
>> + *
>> + * Return a layer mask with a 1 bit for each existing layer of @domain.
>> + * If @domain has no layers 0 is returned.  If the number of layers is
>> + * greater than or equal to the number of bits in layer_mask_t, all bits
>> + * are set.
>> + */
>> +static layer_mask_t landlock_domain_layers_mask(const struct landlock_ruleset
>> +						*const domain)
>> +{
>> +	if (!domain || !domain->num_layers)
>> +		return 0;
>> +
>> +	if (domain->num_layers >= sizeof(layer_mask_t) * BITS_PER_BYTE)
>> +		return (layer_mask_t)~0ULL;
>> +
>> +	return GENMASK_ULL(domain->num_layers - 1, 0);
>> +}
>> +
>> +/**
>> + * rule_blocks_all_layers_no_inherit - check whether a rule disables inheritance
>> + * @domain_layers_mask: Mask describing the domain's active layers.
>> + * @rule: Rule to inspect.
>> + *
>> + * Return true if every layer present in @rule has its no_inherit flag set
>> + * and the set of layers covered by the rule equals @domain_layers_mask.
>> + * This indicates that the rule prevents inheritance on all layers of the
>> + * domain and thus further walking for inheritance checks can stop.
>> + */
>> +static bool rule_blocks_all_layers_no_inherit(const layer_mask_t domain_layers_mask,
>> +					      const struct landlock_rule *const rule)
>> +{
>> +	layer_mask_t rule_layers = 0;
>> +	u32 layer_index;
>> +
>> +	if (!domain_layers_mask || !rule)
>> +		return false;
>> +
>> +	for (layer_index = 0; layer_index < rule->num_layers; layer_index++) {
>> +		const struct landlock_layer *const layer =
>> +			&rule->layers[layer_index];
>> +		const layer_mask_t layer_bit = BIT_ULL(layer->level - 1);
>> +
>> +		if (!layer->flags.no_inherit)
>> +			return false;
>> +
>> +		rule_layers |= layer_bit;
>> +	}
>> +
>> +	return rule_layers && rule_layers == domain_layers_mask;
>> +}
>> +
>> +/**
>> + * ensure_rule_for_dentry - ensure a ruleset contains a rule entry for dentry,
>> + * inserting a blank rule if needed.
>> + * @ruleset: Ruleset to modify/inspect.  Caller must hold @ruleset->lock.
>> + * @dentry: Dentry to ensure a rule exists for.
>> + *
>> + * If no rule is currently associated with @dentry, insert an empty rule
>> + * (with zero access) tied to the backing inode.  Returns a pointer to the
>> + * rule associated with @dentry on success, NULL when @dentry is negative, or
>> + * an ERR_PTR()-encoded error if the rule cannot be created.
>> + *
>> + * This is useful for LANDLOCK_ADD_RULE_NO_INHERIT processing, where a rule
>> + * may need to be created for an ancestor dentry that does not yet have one
>> + * to properly track no_inherit flags.
>> + *
>> + * The flags are set to zero if a rule is newly created, and the caller
>> + * is responsible for setting them appropriately.
>> + *
>> + * The returned rule pointer's lifetime is tied to @ruleset.
>> + */
>> +static const struct landlock_rule *
>> +ensure_rule_for_dentry(struct landlock_ruleset *const ruleset,
>> +		       struct dentry *const dentry)
>> +{
>> +	struct landlock_id id = {
>> +		.type = LANDLOCK_KEY_INODE,
>> +	};
>> +	const struct landlock_rule *rule;
>> +	int err;
>> +
>> +	if (WARN_ON_ONCE(!ruleset || !dentry || d_is_negative(dentry)))
>> +		return NULL;
>> +
>> +	lockdep_assert_held(&ruleset->lock);
>> +
>> +	rule = find_rule(ruleset, dentry);
>> +	if (rule)
>> +		return rule;
>> +
>> +	id.key.object = get_inode_object(d_backing_inode(dentry));
>> +	if (IS_ERR(id.key.object))
>> +		return ERR_CAST(id.key.object);
>> +
>> +	err = landlock_insert_rule(ruleset, id, 0, 0);
>> +	landlock_put_object(id.key.object);
>> +	if (err)
>> +		return ERR_PTR(err);
>> +
>> +	rule = find_rule(ruleset, dentry);
>> +	if (WARN_ON_ONCE(!rule))
>> +		return ERR_PTR(-ENOENT);
>> +	return rule;
>> +}
>> +
>> +/**
>> + * mark_no_inherit_ancestors - mark ancestors as having no_inherit descendants
>> + * @ruleset: Ruleset to modify.  Caller must hold @ruleset->lock.
>> + * @path: Path representing the descendant that carries no_inherit bits.
>> + * @descendant_layers: Mask of layers from the descendant that should be
>> + *                     advertised to ancestors via has_no_inherit_descendant.
>> + *
>> + * Walks upward from @dentry and ensures that any ancestor rule contains the
>> + * has_no_inherit_descendant marker for the specified @descendant_layers so
>> + * parent lookups can quickly detect descendant no_inherit influence.
>> + *
>> + * Returns 0 on success or a negative errno if ancestor bookkeeping fails.
>> + */
>> +static int mark_no_inherit_ancestors(struct landlock_ruleset *ruleset,
>> +				     const struct path *const path,
>> +				     layer_mask_t descendant_layers)
>> +{
>> +	struct dentry *cursor;
>> +	struct path walk_path;
>> +	int err = 0;
>> +
>> +	if (WARN_ON_ONCE(!ruleset || !path || !path->dentry || !path->mnt ||
>> +			 !descendant_layers))
>> +		return -EINVAL;
>> +
>> +	lockdep_assert_held(&ruleset->lock);
>> +
>> +	walk_path.mnt = path->mnt;
>> +	walk_path.dentry = path->dentry;
>> +	path_get(&walk_path);
>> +
>> +	cursor = dget(walk_path.dentry);
>> +	while (cursor) {
>> +		struct dentry *parent;
>> +		const struct landlock_rule *rule;
>> +
>> +		/* Follow mounts all the way up to the root. */
>> +		if (IS_ROOT(cursor)) {
>> +			dput(cursor);
>> +			if (!follow_up(&walk_path)) {
>
> This path walk is inconsistent and a duplicate of the (correct)
> is_access_to_paths_allowed() one.  Please add a patch to factor out the
> common parts as much as possible.  Ditto for the
> collect_domain_accesses() and collect_topology_sealed_layers().
>

Total agreement from me.

It makes sense to not duplicate the path traversal code. We could do
everything in is_access_to_paths_allowed but that function is already hairy
in my opinion. What do you think about a helper function for traversal?

        enum landlock_walk_result {
	        LANDLOCK_WALK_CONTINUE,
	        LANDLOCK_WALK_STOP_REAL_ROOT,
	        LANDLOCK_WALK_STOP_INTERNAL_ROOT,
        };

        static enum landlock_walk_result landlock_walk_path(struct path *const path)
        {
        jump_up:
        	if (path->dentry == path->mnt->mnt_root) {
        		if (follow_up(path))
        			goto jump_up;
        		return LANDLOCK_WALK_STOP_REAL_ROOT;
        	}
        
        	if (unlikely(IS_ROOT(path->dentry))) {
        		if (likely(path->mnt->mnt_flags & MNT_INTERNAL))
        			return LANDLOCK_WALK_STOP_INTERNAL_ROOT;
        		dput(path->dentry);
        		path->dentry = dget(path->mnt->mnt_root);
        		return LANDLOCK_WALK_CONTINUE;
        	}
        
        	{
        		struct dentry *const parent = dget_parent(path->dentry);
        
        		dput(path->dentry);
        		path->dentry = parent;
        	}
        	return LANDLOCK_WALK_CONTINUE;
        }

The caller gets a readable enum for where they are in the traversal. This
should centralize the logic and make it easier to
understand.

>> +				cursor = NULL;
>> +				continue;
>> +			}
>> +			cursor = dget(walk_path.dentry);
>> +		}
>> +
>> +		parent = dget_parent(cursor);
>> +		dput(cursor);
>> +		if (!parent)
>> +			break;
>> +
>> +		if (WARN_ON_ONCE(d_is_negative(parent))) {
>> +			dput(parent);
>> +			break;
>> +		}
>> +		/*
>> +		 * Ensures a rule exists for the parent dentry,
>> +		 * inserting a blank one if needed.
>> +		 */
>> +		rule = ensure_rule_for_dentry(ruleset, parent);
>> +		if (IS_ERR(rule)) {
>> +			err = PTR_ERR(rule);
>> +			dput(parent);
>> +			cursor = NULL;
>> +			break;
>> +		}
>> +		if (rule) {
>> +			struct landlock_rule *mutable_rule =
>> +				(struct landlock_rule *)rule;
>> +			/*
>> +			 * Unmerged rulesets should only have one layer.
>> +			 */
>> +			if (WARN_ON_ONCE(mutable_rule->num_layers != 1)) {
>> +				dput(parent);
>> +				err = -EINVAL;
>> +				cursor = NULL;
>> +				break;
>> +			}
>> +
>> +			if (descendant_layers & BIT_ULL(0))
>> +				mutable_rule->layers[0]
>> +					.flags.has_no_inherit_descendant = true;
>> +		}
>> +
>> +		cursor = parent;
>> +	}
>> +	path_put(&walk_path);
>> +	return err;
>> +}
>
>> +/**
>> + * collect_topology_sealed_layers - collect layers sealed against topology changes
>> + * @domain: Ruleset to consult.
>> + * @dentry: Starting dentry for the upward walk.
>> + * @override_layers: Optional out parameter filled with layers that are
>> + *                   present on ancestors but considered overrides (not
>> + *                   sealing the topology for descendants).
>> + *
>> + * Walk upwards from @dentry and return a mask of layers where either the
>> + * visited dentry contains a no_inherit rule or ancestors were previously
>> + * marked as having a descendant with no_inherit.  @override_layers, if not
>> + * NULL, is filled with layers that would normally be overridden by more
>> + * specific descendant rules.
>> + *
>> + * Returns a layer mask where set bits indicate layers that are "sealed"
>> + * (topology changes like rename/rmdir are denied) for the subtree rooted at
>> + * @dentry.
>> + *
>> + * Useful for LANDLOCK_ADD_RULE_NO_INHERIT parent directory enforcement to ensure
>> + * that topology changes do not violate the no_inherit constraints.
>> + */
>> +static layer_mask_t
>> +collect_topology_sealed_layers(const struct landlock_ruleset *const domain,
>> +			       struct dentry *dentry,
>> +			       layer_mask_t *const override_layers)
>> +{
>> +	struct dentry *cursor, *parent;
>> +	bool include_descendants = true;
>> +	layer_mask_t sealed_layers = 0;
>> +
>> +	if (override_layers)
>> +		*override_layers = 0;
>> +
>> +	if (WARN_ON_ONCE(!domain || !dentry || d_is_negative(dentry)))
>> +		return 0;
>> +
>> +	cursor = dget(dentry);
>> +	while (cursor) {
>> +		const struct landlock_rule *rule;
>> +		u32 layer_index;
>> +
>> +		rule = find_rule(domain, cursor);
>> +		if (rule) {
>> +			for (layer_index = 0; layer_index < rule->num_layers;
>> +			     layer_index++) {
>> +				const struct landlock_layer *layer =
>> +					&rule->layers[layer_index];
>> +				layer_mask_t layer_bit =
>> +					BIT_ULL(layer->level - 1);
>> +
>> +				if (include_descendants &&
>> +				    (layer->flags.no_inherit ||
>> +				     layer->flags.has_no_inherit_descendant)) {
>> +					sealed_layers |= layer_bit;
>> +				} else if (override_layers) {
>> +					*override_layers |= layer_bit;
>> +				}
>> +			}
>> +		}
>> +
>> +		if (sealed_layers || IS_ROOT(cursor))
>> +			break;
>> +
>> +		parent = dget_parent(cursor);
>> +		dput(cursor);
>> +		if (!parent)
>> +			return sealed_layers;
>> +
>> +		cursor = parent;
>> +		include_descendants = false;
>> +	}
>> +	dput(cursor);
>> +	return sealed_layers;
>> +}

^ permalink raw reply

* Re: [RFC 08/11] security: Hornet LSM
From: Fan Wu @ 2025-12-12 21:00 UTC (permalink / raw)
  To: Blaise Boscaccy
  Cc: Jonathan Corbet, Paul Moore, James Morris, Serge E. Hallyn,
	Mickaël Salaün, Günther Noack,
	Dr. David Alan Gilbert, Andrew Morton, James.Bottomley, dhowells,
	linux-security-module, linux-doc, linux-kernel, bpf
In-Reply-To: <20251211021257.1208712-9-bboscaccy@linux.microsoft.com>

On Wed, Dec 10, 2025 at 6:18 PM Blaise Boscaccy
<bboscaccy@linux.microsoft.com> wrote:
>
> This adds the Hornet Linux Security Module which provides enhanced
> signature verification and data validation for eBPF programs. This
> allows users to continue to maintain an invariant that all code
> running inside of the kernel has actually been signed and verified, by
> the kernel.
>
> This effort builds upon the currently excepted upstream solution. It
> further hardens it by providing deterministic, in-kernel checking of
> map hashes to solidify auditing along with preventing TOCTOU attacks
> against lskel map hashes.
>
> Target map hashes are passed in via PKCS#7 signed attributes. Hornet
> determines the extent which the eBFP program is signed and defers to
> other LSMs for policy decisions.
>
> Signed-off-by: Blaise Boscaccy <bboscaccy@linux.microsoft.com>
> ---
...
> +
> +int hornet_next_map(void *context, size_t hdrlen,
> +                    unsigned char tag,
> +                    const void *value, size_t vlen)
> +{
> +       struct hornet_parse_context *ctx = (struct hornet_parse_context *)value;

I think you wanted to cast context instead?

> +
> +       ctx->hash_count++;
> +       return 0;
> +}
> +
> +
> +int hornet_map_index(void *context, size_t hdrlen,
> +                    unsigned char tag,
> +                    const void *value, size_t vlen)
> +{
> +       struct hornet_parse_context *ctx = (struct hornet_parse_context *)value;

Same above.

> +
> +       ctx->hashes[ctx->hash_count] = *(int *)value;
> +       return 0;
> +}
> +
> +int hornet_map_hash(void *context, size_t hdrlen,
> +                   unsigned char tag,
> +                   const void *value, size_t vlen)
> +
> +{
> +       struct hornet_parse_context *ctx = (struct hornet_parse_context *)value;

Same above.

-Fan

> +
> +       if (vlen != SHA256_DIGEST_SIZE && vlen != 0)
> +               return -EINVAL;
> +
> +       if (vlen != 0) {
> +               ctx->skips[ctx->hash_count] = false;
> +               memcpy(&ctx->hashes[ctx->hash_count * SHA256_DIGEST_SIZE], value, vlen);
> +       } else
> +               ctx->skips[ctx->hash_count] = true;
> +
> +       return 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

* Re: An opinion about Linux security
From: Dr. Greg @ 2025-12-12 18:10 UTC (permalink / raw)
  To: Timur Chernykh; +Cc: Casey Schaufler, torvalds, linux-security-module
In-Reply-To: <CABZOZnRQ=b4K5jpNM8Z=Zr=+66COwLpC8gynzw88==mL0FCrOw@mail.gmail.com>

On Fri, Dec 12, 2025 at 05:47:24PM +0300, Timur Chernykh wrote:

Good morning again to everyone.

> > eBPF has been accepted because of these restrictions. Without them
> > an eBPF program could very easily reek havoc on the system's behavior.
> 
> Unfortunately, these restrictions also make it impossible to use eBPF
> effectively for security. We can certainly discuss the limitations
> themselves if needed, but that???s not the main point I???m trying to make
> here.
> 
> > Yes. That's true for many kernel features.
> 
> Right, and that's a well-known issue that has no clean solution other
> than backporting. I completely agree with that.
> 
> > To the best of my understanding, and I have been working with LSMs
> > and the infrastructure for quite some time, there has never been an
> > out-of-tree LSM API.
> 
> I was under the impression that there was something of that sort.
> For example: https://elixir.bootlin.com/linux/v3.10/source/include/linux/security.h#L1688
> It may not have been 'officially' exported, but people who needed it
> simply resolved the symbol through `kallsyms` or a kprobe and used it.
> I'm not claiming that this is good practice, but it did work.
> 
> > You will need to provide more detail about why you believe that the
> > integrity of an AV/EDR product cannot be protected.
> 
> Consider the case where an attacker already has root access. The first
> thing they typically do is disable or tamper with security tools.
> After that, they establish persistence. Access-control models alone
> are not enough here sometimes they need to be adjusted dynamically,
> based on complex real-time analysis.
> 
> > What APIs do you want? It's possible that some exist that you haven't
> > discovered.

> I'm confident I've studied all the mechanisms available for
> real-time system protection. I've even given talks and published
> material on approaches to securing Linux.  I may not have covered
> every LSM module in depth, but in practice they simply don't provide
> the capabilities required for modern security workloads.
>
> And I don't want to sound overly categorical, but the current path of
> security development feels like a dead end to me, for several reasons.
> Modern security relies on analyzing hundreds of thousands of events
> per second. eBPF isn't particularly fast to begin with, and on top of
> that it imposes strict technological limitations that prevent
> meaningful in-kernel analysis. Every EDR vendor ends up doing the same
> thing: collecting raw data (which is already difficult) and pushing it
> into userspace for processing. That adds transport overhead on top of
> everything else.
> 
> Or, of course, writes a dirty and unsafe kernel module. For me in the
> perfect world seems to it's better to provide an API for userspace.
> It's safe enough and doesn't contain a restriction that eBPF has.

You may be cooking a response to my previous e-mail so a quick comment
to perhaps constructively shape forward conversations.

We looked at the ESF implementation and if we understand the Mac/Apple
approach an API is supplied to register for security events of
interest.

With TSEM we came at the problem from a framework of supporting the
mathematical modeling of security behavior, a 'y = mx + b' type of
approach.  With an objective of providing complete flexibility with
respect to how the functional definition for security is generated.

The most universal method of doing this, at least in our view, was to
supply the stream of LSM events and their parameters and let a
modeling engine, either in the kernel or userspace, decide how to
filter for and process the events in order to create the functional
definition.

A userspace orchestrator receives a JSON encoded record for each LSM
event to do with as it pleases.  If you feed that into something like
an Elastic or Open Search instance you have a complete compliance
record as to every event that the kernel deemed to have security
implications.

Obviously a lot of events can be generated.  We currently support
policy specific screening of events with standard kernel modules and
doing this with eBPF is our next step.  From an eBPF perspective this
is much more of a lightweight approach than attempting to code for
specific security analytics or behavior analysis.

For example, we implemented the rough equivalent of userspace IMA by
in kernel filtering for security_file_open events invoked with
administrative privileges.

The LSM API isn't considered stable but the reality of security
telemetry in this day and age is that security vendors have to code
for specific LTS kernel releases.  Even with a 'stable' release there
are issues with telemetry acquisition, CrowdStike ended up blue
screening RHEL not too long ago on one of their kernel point releases.

We would be interested as to what you see to be the challenges, from
an EDR vendor perspective, with this approach.

FWIW.  If you namespace the security event stream you end up with the
ability to much more precisely model whether or not a workload is
exhibiting aberrant behavior, while decreasing the event flux rate.

> > Please propose the interfaces you want. An API definition would be
> > good, and patches even better.
> 
> I'm lucky enough to have already built a working prototype, which I
> once offered for review:
> 
> https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
> https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
> 
> Less lucky was the reaction I received. Paul Moore was strongly
> opposed, as far as I remember. Dr. Greg once said that heat death of
> the universe is more likely than this approach being accepted into the
> kernel.

> I don't want to 'poke old wounds', but the design I proposed was
> largely inspired by Apple's Endpoint Security Framework
> (originally 'mac policies'):
> https://developer.apple.com/documentation/endpointsecurity

> In my view, it is an exemplary model. The kernel provides a
> consistent stream of events to userspace, hides the complexity of
> data collection and transport, and ensures fault-tolerance if
> userspace fails to process events quickly enough.  Audit, for
> comparison, simply hangs the system if its buffer overflows. ESF
> does not have that problem and even lets userspace control the event
> stream.

> > There are numerous cases where LSMs have mitigated attacks. One case:
> 
> And there are thousands of cases where LSMs did not. Most companies
> never disclose successful breaches because of NDAs and fear of
> investor backlash. The few disclosures we see typically appear only
> when it???s safe for the company, or when they specifically want to
> appear transparent.
> 
> > Your assertion that LSMs don't provide "real" value is not substantiated
> > in the literature.
> 
> Which literature do you mean?
> As I mentioned above, public reports about successful attacks are rare.
> 
> Maybe I poorly delivered my point. I'll try again.
> 
> The strongest protection on Linux today is provided by proprietary
> security vendors. Unfortunately, they often achieve this using
> kernel-module ???hacks??? rather than LSMs. It???s not because they prefer
> hacks ??? it???s because Linux doesn???t offer proper APIs to implement the
> required functionality.
> 
> > Each of the existing LSMs addresses one or more real world issues. I would
> > hardly call any of the Linux security mechanisms, from mode bits and setuid
> > through SELinux, landlock and EVM, "theoretical".
> 
> In practice, most LSM modules are either disabled or misconfigured on
> real servers, and the responsibility falls on AV/EDR vendors. As
> someone who has been building such systems professionally for years, I
> can say with confidence: there is no clean, reliable mechanism
> available today.
> As much as I love Linux, its security and its friendliness toward
> security vendors are its weak side.
> 
> In the real world, deploying a modern security product means dealing
> with endless pain: missing kernel headers (sometimes there isn???t even
> Internet access to download them), unstable kernel APIs, lack of BTF,
> constant fights with the eBPF verifier, and all the other limitations
> of eBPF.
> 
> To be honest, many developers ??? and I???m taking the liberty to speak
> broadly here ??? would simply like to see something similar to Apple???s
> ESF available on Linux.
> 
> Best regards,
> Timur Chernykh
> 
> On Wed, Dec 10, 2025 at 11:08???PM Casey Schaufler <casey@schaufler-ca.com> wrote:
> >
> > On 12/9/2025 4:15 PM, Timur Chernykh wrote:
> > > Hello Linus,
> > >
> > > I???m writing to ask for your opinion. What do you think about Linux???s
> > > current readiness for security-focused commercial products? I???m
> > > particularly interested in several areas.
> > >
> > > First, in today???s 3rd-party (out-of-tree) EDR development ??? EDR being
> > > the most common commercial class of security products ??? eBPF has
> > > effectively become the main option. Yet eBPF is extremely restrictive.
> >
> > eBPF has been accepted because of these restrictions. Without them
> > an eBPF program could very easily reek havoc on the system's behavior.
> >
> > > It is not possible to write fully expressive real-time analysis code:
> > > the verifier is overly strict,
> >
> > This is of necessity. It is the only protection against malicious and
> > badly written eBPF programs.
> >
> > > non-deterministic loops are not
> > > allowed,
> >
> > Without this restriction denial of service attacks become trivial.
> >
> > >  and older kernels lack BTF support.
> >
> > Yes. That's true for many kernel features.
> >
> > > These issues create real
> > > limitations.
> > >
> > > Second, the removal of the out-of-tree LSM API in the 4.x kernel
> > > series caused significant problems for many AV/EDR vendors. I was
> > > unable to find an explanation in the mailing lists that convincingly
> > > justified that decision.
> >
> > To the best of my understanding, and I have been working with LSMs
> > and the infrastructure for quite some time, there has never been an
> > out-of-tree LSM API. We have been very clear that the LSM interfaces
> > are fluid. We have also been very clear that supporting out-of-tree
> > security modules is not a requirement. There are members of the
> > community who would prefer that they be completely prohibited.
> >
> >
> > > The next closest mechanism, fanotify, was a genuine improvement.
> > > However, it does not allow an AV/EDR vendor to protect the integrity
> > > of its own product. Is Linux truly expecting modern AV/EDR solutions
> > > to rely on fanotify alone?
> >
> > You will need to provide more detail about why you believe that the
> > integrity of an AV/EDR product cannot be protected.
> >
> > > My main question is: what are the future plans?
> >
> > Security remains a dynamic technology. There are quite a few plans,
> > from a variety of sources, with no shortage of security goals. Trying
> > to keep up with the concern/crisis of the day is more than sufficient
> > to consume the resources committed to Linux security.
> >
> > >  Linux provides very
> > > few APIs for security and dynamic analysis.
> >
> > What APIs do you want? It's possible that some exist that you haven't
> > discovered.
> >
> > >  eBPF is still immature,
> >
> > And it will be for some time. That is, until it is mature.
> >
> > > fanotify is insufficient,
> >
> > Without specifics it is quite difficult to do anything about that.
> > And, as we like to say, patches are welcome.
> >
> > >  and driver workarounds that bypass kernel
> > > restrictions are risky ??? they introduce both stability and security
> > > problems.
> >
> > Yes. Don't do that.
> >
> > >  At the same time, properly implemented in-tree LSMs are not
> > > inherently dangerous and remain the safer, supported path for
> > > extending security functionality. Without safe, supported interfaces,
> > > however, commercial products struggle to be competitive. At the
> > > moment, macOS with its Endpoint Security Framework is significantly
> > > ahead.
> >
> > Please propose the interfaces you want. An API definition would be
> > good, and patches even better.
> >
> > > Yes, the kernel includes multiple in-tree LSM modules, but in practice
> > > SELinux does not simplify operations ??? it often complicates them,
> > > despite its long-standing presence. Many of the other LSMs are rarely
> > > used in production. As an EDR developer, I seldom encounter them, and
> > > when I do, they usually provide little practical value. Across
> > > numerous real-world server intrusions, none of these LSM modules have
> > > meaningfully prevented attacks, despite many years of kernel
> > > development.
> >
> > There are numerous cases where LSMs have mitigated attacks. One case:
> >
> > https://mihail-milev.medium.com/mitigating-malware-risks-with-selinux-e37cf1db7c56
> >
> > Your assertion that LSMs don't provide "real" value is not substantiated
> > in the literature.
> >
> > > Perhaps it is time for Linux to focus on more than a theoretical model
> > > of security.
> >
> > Each of the existing LSMs addresses one or more real world issues. I would
> > hardly call any of the Linux security mechanisms, from mode bits and setuid
> > through SELinux, landlock and EVM, "theoretical".
> >
> > > P.S.
> > > Everything above reflects only my personal opinion. I would greatly
> > > appreciate your response and any criticism you may have.
> >
> > We are always ready to improve the security infrastructure of Linux.
> > If it does not meet your needs, help us improve it. The best way to
> > accomplish this is to provide the changes required.
> >
> > > Best regards,
> > > Timur Chernykh

Have a good weekend.

As always,
Dr. Greg

The Quixote Project - Flailing at the Travails of Cybersecurity
              https://github.com/Quixote-Project

^ permalink raw reply

* Re: An opinion about Linux security
From: Paul Moore @ 2025-12-12 18:30 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Timur Chernykh, Casey Schaufler, torvalds, linux-security-module,
	greg
In-Reply-To: <CAEjxPJ5O2YTPaD9S=UXw-KzTtQyXPuvZ_WXDHGX1Of1oxjw9rQ@mail.gmail.com>

On Fri, Dec 12, 2025 at 12:37 PM Stephen Smalley
<stephen.smalley.work@gmail.com> wrote:
> On Fri, Dec 12, 2025 at 12:22 PM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
> >
> > > While Timur was
> > > added to the conversation by someone, I don't see any mail from him in
> > > that thread.
> >
> > I probably missed this thread.
> >
> > > Beyond that, I'm a bit lost.  As far as I can remember, and both lore
> > > and my own sent mail folder appear to support this, I've never
> > > commented on ESF.  At this point I think Timur may be mistaken
> > > regarding my commenting on ESF, but if I am wrong please provide a
> > > lore link so I can refresh my memory.
> >
> > Sorry for misleading you. My mistake, I should have checked the thread
> > first instead of relying on my memory.
> >
> > > In this post Timur provides links to his ESF project on GitHub, but no
> > > patches.
> >
> > Am I correct in understanding that any proposals and questions I'd
> > like to discuss with the maintainers and the community should start
> > with patches? Even if the goal isn't to implement a change right away,
> > but merely to evaluate the idea.
> >
> > When I proposed the prototype, it seemed excessive to me to prepare
> > patches for something that could be "finished" at the idea stage.
>
> It doesn't seem to require much more effort than creating the
> prototype and publishing it on GitHub. "Write for maximum efficiency
> of reading" includes avoiding the need to follow links to adequately
> evaluate a proposal. Just provide enough code to show what it is you
> want to do and why that can't be done (well) today.

To add to what Stephen already said, if you are serious about
submitting a new LSM upstream, we do have some documented guidance
linked off the "SECURITY SUBSYSTEM" entry in the MAINTAINERS file.  To
save some time/searching, the direct link is below:

https://github.com/LinuxSecurityModule/kernel/blob/main/README.md#new-lsms

-- 
paul-moore.com

^ permalink raw reply

* Re: An opinion about Linux security
From: Stephen Smalley @ 2025-12-12 17:37 UTC (permalink / raw)
  To: Timur Chernykh
  Cc: Paul Moore, Casey Schaufler, torvalds, linux-security-module,
	greg
In-Reply-To: <CABZOZnRgYd687neqk5e8vQu5y7cwPwbht2SHS-4=q0y3MWU=mg@mail.gmail.com>

On Fri, Dec 12, 2025 at 12:22 PM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
>
> > While Timur was
> > added to the conversation by someone, I don't see any mail from him in
> > that thread.
>
> I probably missed this thread.
>
> > Beyond that, I'm a bit lost.  As far as I can remember, and both lore
> > and my own sent mail folder appear to support this, I've never
> > commented on ESF.  At this point I think Timur may be mistaken
> > regarding my commenting on ESF, but if I am wrong please provide a
> > lore link so I can refresh my memory.
>
> Sorry for misleading you. My mistake, I should have checked the thread
> first instead of relying on my memory.
>
> > In this post Timur provides links to his ESF project on GitHub, but no
> > patches.
>
> Am I correct in understanding that any proposals and questions I'd
> like to discuss with the maintainers and the community should start
> with patches? Even if the goal isn't to implement a change right away,
> but merely to evaluate the idea.
>
> When I proposed the prototype, it seemed excessive to me to prepare
> patches for something that could be "finished" at the idea stage.

It doesn't seem to require much more effort than creating the
prototype and publishing it on GitHub. "Write for maximum efficiency
of reading" includes avoiding the need to follow links to adequately
evaluate a proposal. Just provide enough code to show what it is you
want to do and why that can't be done (well) today.

^ permalink raw reply

* Re: An opinion about Linux security
From: Timur Chernykh @ 2025-12-12 17:22 UTC (permalink / raw)
  To: Paul Moore
  Cc: Stephen Smalley, Casey Schaufler, torvalds, linux-security-module,
	greg
In-Reply-To: <CAHC9VhSU5yLQkCchCMUx+OLk+_2YY=1fjzth4s+_ELwgXg5t-A@mail.gmail.com>

> While Timur was
> added to the conversation by someone, I don't see any mail from him in
> that thread.

I probably missed this thread.

> Beyond that, I'm a bit lost.  As far as I can remember, and both lore
> and my own sent mail folder appear to support this, I've never
> commented on ESF.  At this point I think Timur may be mistaken
> regarding my commenting on ESF, but if I am wrong please provide a
> lore link so I can refresh my memory.

Sorry for misleading you. My mistake, I should have checked the thread
first instead of relying on my memory.

> In this post Timur provides links to his ESF project on GitHub, but no
> patches.

Am I correct in understanding that any proposals and questions I'd
like to discuss with the maintainers and the community should start
with patches? Even if the goal isn't to implement a change right away,
but merely to evaluate the idea.

When I proposed the prototype, it seemed excessive to me to prepare
patches for something that could be "finished" at the idea stage.

On Fri, Dec 12, 2025 at 8:06 PM Paul Moore <paul@paul-moore.com> wrote:
>
> On Fri, Dec 12, 2025 at 11:12 AM Stephen Smalley
> <stephen.smalley.work@gmail.com> wrote:
> > On Fri, Dec 12, 2025 at 9:47 AM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
> > >
> > > I’m lucky enough to have already built a working prototype, which I
> > > once offered for review:
> > >
> > > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
> > > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
> > >
> > > Less lucky was the reaction I received. Paul Moore was strongly
> > > opposed, as far as I remember. Dr. Greg once said that heat death of
> > > the universe is more likely than this approach being accepted into the
> > > kernel.
> >
> > Not seeing an actual response from Paul in the archives, but did you
> > ever actually post patches to the list?
>
> I was wondering about this too.  I searched through my sent mail and
> while it's possible I'm missing some mail, the only conversation I see
> with Timur is an off-list discussion from 2024 regarding changes in
> the upstream kernel to support out-of-tree LSMs.  While Timur was
> added to the conversation by someone, I don't see any mail from him in
> that thread.  My comments in that thread are consistent with my
> comments in on-list threads from around that same time when
> out-of-tree code was discussed.  Here is a snippet from one of my
> responses, which still holds true as far as I'm concerned:
>
>  "As stated many times in the past, the LSM framework as
>   well as the Linux kernel in general, does not provide the
>   same level of consideration to out-of-tree code that it does
>   to upstream, mainline code.  My policy on this remains the
>   same as last time we talked: while I have no goal to make
>   things difficult for out-of-tree code, I will not sacrifice
>   the continued development and maintenance of existing
>   upstream code in favor of out-of-tree code."
>
> Searching for "Timur Chernykh" in all of the lore archives shows some
> BPF related threads and the following LSM thread from June 2024:
>
> https://lore.kernel.org/all/CABZOZnS13-KscVQY0YqqWZsBwmQaKyRO_G=kzCL8zc9jHxAC=A@mail.gmail.com
>
> In this post Timur provides links to his ESF project on GitHub, but no
> patches.  I see comments from Stephen, Tetsuo, Casey, and Dr. Greg; I
> did not comment on that thread.
>
> Beyond that, I'm a bit lost.  As far as I can remember, and both lore
> and my own sent mail folder appear to support this, I've never
> commented on ESF.  At this point I think Timur may be mistaken
> regarding my commenting on ESF, but if I am wrong please provide a
> lore link so I can refresh my memory.
>
> --
> paul-moore.com

^ 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: An opinion about Linux security
From: Paul Moore @ 2025-12-12 17:06 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Timur Chernykh, Casey Schaufler, torvalds, linux-security-module,
	greg
In-Reply-To: <CAEjxPJ6CbZC-=onSGgELygnt_hsqaN0JS_jJFxWn+hYt90s2Ng@mail.gmail.com>

On Fri, Dec 12, 2025 at 11:12 AM Stephen Smalley
<stephen.smalley.work@gmail.com> wrote:
> On Fri, Dec 12, 2025 at 9:47 AM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
> >
> > I’m lucky enough to have already built a working prototype, which I
> > once offered for review:
> >
> > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
> > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
> >
> > Less lucky was the reaction I received. Paul Moore was strongly
> > opposed, as far as I remember. Dr. Greg once said that heat death of
> > the universe is more likely than this approach being accepted into the
> > kernel.
>
> Not seeing an actual response from Paul in the archives, but did you
> ever actually post patches to the list?

I was wondering about this too.  I searched through my sent mail and
while it's possible I'm missing some mail, the only conversation I see
with Timur is an off-list discussion from 2024 regarding changes in
the upstream kernel to support out-of-tree LSMs.  While Timur was
added to the conversation by someone, I don't see any mail from him in
that thread.  My comments in that thread are consistent with my
comments in on-list threads from around that same time when
out-of-tree code was discussed.  Here is a snippet from one of my
responses, which still holds true as far as I'm concerned:

 "As stated many times in the past, the LSM framework as
  well as the Linux kernel in general, does not provide the
  same level of consideration to out-of-tree code that it does
  to upstream, mainline code.  My policy on this remains the
  same as last time we talked: while I have no goal to make
  things difficult for out-of-tree code, I will not sacrifice
  the continued development and maintenance of existing
  upstream code in favor of out-of-tree code."

Searching for "Timur Chernykh" in all of the lore archives shows some
BPF related threads and the following LSM thread from June 2024:

https://lore.kernel.org/all/CABZOZnS13-KscVQY0YqqWZsBwmQaKyRO_G=kzCL8zc9jHxAC=A@mail.gmail.com

In this post Timur provides links to his ESF project on GitHub, but no
patches.  I see comments from Stephen, Tetsuo, Casey, and Dr. Greg; I
did not comment on that thread.

Beyond that, I'm a bit lost.  As far as I can remember, and both lore
and my own sent mail folder appear to support this, I've never
commented on ESF.  At this point I think Timur may be mistaken
regarding my commenting on ESF, but if I am wrong please provide a
lore link so I can refresh my memory.

-- 
paul-moore.com

^ permalink raw reply

* [RFC PATCH v3 1/8] landlock: Minor reword of docs for TCP access rights
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

- Move ABI requirement next to each access right to prepare adding more
  access rights;
- Mention the possibility to remove the random component of a socket's
  ephemeral port choice within the netns-wide ephemeral port range,
  since it allows choosing the "random" ephemeral port.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 include/uapi/linux/landlock.h | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h
index f030adc462ee..efb383af40b2 100644
--- a/include/uapi/linux/landlock.h
+++ b/include/uapi/linux/landlock.h
@@ -182,11 +182,13 @@ struct landlock_net_port_attr {
 	 * It should be noted that port 0 passed to :manpage:`bind(2)` will bind
 	 * to an available port from the ephemeral port range.  This can be
 	 * configured with the ``/proc/sys/net/ipv4/ip_local_port_range`` sysctl
-	 * (also used for IPv6).
+	 * (also used for IPv6), and within that range, on a per-socket basis
+	 * with ``setsockopt(IP_LOCAL_PORT_RANGE)``.
 	 *
-	 * A Landlock rule with port 0 and the ``LANDLOCK_ACCESS_NET_BIND_TCP``
+	 * A Landlock rule with port 0 and the %LANDLOCK_ACCESS_NET_BIND_TCP
 	 * right means that requesting to bind on port 0 is allowed and it will
-	 * automatically translate to binding on the related port range.
+	 * automatically translate to binding on a kernel-assigned ephemeral
+	 * port.
 	 */
 	__u64 port;
 };
@@ -332,13 +334,12 @@ struct landlock_net_port_attr {
  * These flags enable to restrict a sandboxed process to a set of network
  * actions.
  *
- * This is supported since Landlock ABI version 4.
- *
  * The following access rights apply to TCP port numbers:
  *
- * - %LANDLOCK_ACCESS_NET_BIND_TCP: Bind a TCP socket to a local port.
- * - %LANDLOCK_ACCESS_NET_CONNECT_TCP: Connect an active TCP socket to
- *   a remote port.
+ * - %LANDLOCK_ACCESS_NET_BIND_TCP: Bind TCP sockets to the given local
+ *   port. Support added in Landlock ABI version 4.
+ * - %LANDLOCK_ACCESS_NET_CONNECT_TCP: Connect TCP sockets to the given
+ *   remote port. Support added in Landlock ABI version 4.
  */
 /* clang-format off */
 #define LANDLOCK_ACCESS_NET_BIND_TCP			(1ULL << 0)
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 3/8] landlock: Add UDP bind+connect access control
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

If a process doesn't need to be able to open UDP sockets, it should be
denied the right to create UDP sockets altogether. For processes using
UDP, add support for two more fine-grained access rights:

- LANDLOCK_ACCESS_NET_CONNECT_UDP, to gate the possibility to connect()
  a UDP socket. For client apps (those which want to avoid specifying a
  destination for each datagram they send), and for a few servers (those
  creating per-client sockets, which want to receive traffic only from a
  specific address)

- LANDLOCK_ACCESS_NET_BIND_UDP, to gate the possibility to bind() a UDP
  socket. For most servers (to start receiving datagrams), and some
  clients that need to use a specific source port (e.g. mDNS requires to
  use port 5353)

Access control is only enforced when trying to set the local or remote
end of a UDP socket. So, nothing prevents a client with the right to
send datagrams to use it to get an automatically bound socket and
receive datagrams on an ephemeral port of their choice, without having
LANDLOCK_ACCESS_NET_BIND_UDP. Restricting send/recv semantics is left
for a future patch, as it would require tagging sockets or a netfilter
hook.

Bump ABI to v8 to allow userland to detect and use these new access
rights.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 include/uapi/linux/landlock.h | 20 ++++++++++++++---
 security/landlock/audit.c     |  2 ++
 security/landlock/limits.h    |  2 +-
 security/landlock/net.c       | 41 ++++++++++++++++++++++-------------
 security/landlock/syscalls.c  |  2 +-
 5 files changed, 47 insertions(+), 20 deletions(-)

diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h
index efb383af40b2..8f748fcf79dd 100644
--- a/include/uapi/linux/landlock.h
+++ b/include/uapi/linux/landlock.h
@@ -186,9 +186,9 @@ struct landlock_net_port_attr {
 	 * with ``setsockopt(IP_LOCAL_PORT_RANGE)``.
 	 *
 	 * A Landlock rule with port 0 and the %LANDLOCK_ACCESS_NET_BIND_TCP
-	 * right means that requesting to bind on port 0 is allowed and it will
-	 * automatically translate to binding on a kernel-assigned ephemeral
-	 * port.
+	 * or %LANDLOCK_ACCESS_NET_BIND_UDP right means that requesting to bind
+	 * on port 0 is allowed and it will automatically translate to binding
+	 * on a kernel-assigned ephemeral port.
 	 */
 	__u64 port;
 };
@@ -340,10 +340,24 @@ struct landlock_net_port_attr {
  *   port. Support added in Landlock ABI version 4.
  * - %LANDLOCK_ACCESS_NET_CONNECT_TCP: Connect TCP sockets to the given
  *   remote port. Support added in Landlock ABI version 4.
+ *
+ * And similarly for UDP port numbers:
+ *
+ * - %LANDLOCK_ACCESS_NET_BIND_UDP: Bind UDP sockets to the given local
+ *   port. Support added in Landlock ABI version 8.
+ *   Note: this access right is not required if your program sends
+ *   datagrams and just uses the implicitly bound port assigned by the
+ *   kernel to reply. Conversely, denying this right only blocks a
+ *   program from binding to non-ephemeral ports if it can send datagrams.
+ * - %LANDLOCK_ACCESS_NET_CONNECT_UDP: Connect UDP sockets to remote
+ *   addresses with the given remote port. Support added in Landlock ABI
+ *   version 8.
  */
 /* clang-format off */
 #define LANDLOCK_ACCESS_NET_BIND_TCP			(1ULL << 0)
 #define LANDLOCK_ACCESS_NET_CONNECT_TCP			(1ULL << 1)
+#define LANDLOCK_ACCESS_NET_BIND_UDP			(1ULL << 2)
+#define LANDLOCK_ACCESS_NET_CONNECT_UDP			(1ULL << 3)
 /* clang-format on */
 
 /**
diff --git a/security/landlock/audit.c b/security/landlock/audit.c
index e899995f1fd5..23d8dee320ef 100644
--- a/security/landlock/audit.c
+++ b/security/landlock/audit.c
@@ -44,6 +44,8 @@ static_assert(ARRAY_SIZE(fs_access_strings) == LANDLOCK_NUM_ACCESS_FS);
 static const char *const net_access_strings[] = {
 	[BIT_INDEX(LANDLOCK_ACCESS_NET_BIND_TCP)] = "net.bind_tcp",
 	[BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_TCP)] = "net.connect_tcp",
+	[BIT_INDEX(LANDLOCK_ACCESS_NET_BIND_UDP)] = "net.bind_udp",
+	[BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_UDP)] = "net.connect_udp",
 };
 
 static_assert(ARRAY_SIZE(net_access_strings) == LANDLOCK_NUM_ACCESS_NET);
diff --git a/security/landlock/limits.h b/security/landlock/limits.h
index 65b5ff051674..13dd5503e471 100644
--- a/security/landlock/limits.h
+++ b/security/landlock/limits.h
@@ -23,7 +23,7 @@
 #define LANDLOCK_MASK_ACCESS_FS		((LANDLOCK_LAST_ACCESS_FS << 1) - 1)
 #define LANDLOCK_NUM_ACCESS_FS		__const_hweight64(LANDLOCK_MASK_ACCESS_FS)
 
-#define LANDLOCK_LAST_ACCESS_NET	LANDLOCK_ACCESS_NET_CONNECT_TCP
+#define LANDLOCK_LAST_ACCESS_NET	LANDLOCK_ACCESS_NET_CONNECT_UDP
 #define LANDLOCK_MASK_ACCESS_NET	((LANDLOCK_LAST_ACCESS_NET << 1) - 1)
 #define LANDLOCK_NUM_ACCESS_NET		__const_hweight64(LANDLOCK_MASK_ACCESS_NET)
 
diff --git a/security/landlock/net.c b/security/landlock/net.c
index 59438285e73b..9bddcf466ce9 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -68,28 +68,31 @@ static int current_check_access_socket(struct socket *const sock,
 
 	switch (address->sa_family) {
 	case AF_UNSPEC:
-		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
+		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
 			/*
 			 * Connecting to an address with AF_UNSPEC dissolves
-			 * the TCP association, which have the same effect as
-			 * closing the connection while retaining the socket
-			 * object (i.e., the file descriptor).  As for dropping
-			 * privileges, closing connections is always allowed.
-			 *
-			 * For a TCP access control system, this request is
-			 * legitimate. Let the network stack handle potential
+			 * the remote association while retaining the socket
+			 * object (i.e., the file descriptor). For TCP, it has
+			 * the same effect as closing the connection. For UDP,
+			 * it removes any preset remote address. As for
+			 * dropping privileges, these actions are always
+			 * allowed.
+			 * Let the network stack handle potential
 			 * inconsistencies and return -EINVAL if needed.
 			 */
 			return 0;
-		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP) {
+		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
+			   access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
 			/*
 			 * Binding to an AF_UNSPEC address is treated
 			 * differently by IPv4 and IPv6 sockets. The socket's
 			 * family may change under our feet due to
 			 * setsockopt(IPV6_ADDRFORM), but that's ok: we either
 			 * reject entirely or require
-			 * %LANDLOCK_ACCESS_NET_BIND_TCP for the given port, so
-			 * it cannot be used to bypass the policy.
+			 * %LANDLOCK_ACCESS_NET_BIND_TCP or
+			 * %LANDLOCK_ACCESS_NET_BIND_UDP for the given port,
+			 * so it cannot be used to bypass the policy.
 			 *
 			 * IPv4 sockets map AF_UNSPEC to AF_INET for
 			 * retrocompatibility for bind accesses, only if the
@@ -132,10 +135,12 @@ static int current_check_access_socket(struct socket *const sock,
 		addr4 = (struct sockaddr_in *)address;
 		port = addr4->sin_port;
 
-		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
+		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
 			audit_net.dport = port;
 			audit_net.v4info.daddr = addr4->sin_addr.s_addr;
-		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP) {
+		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
+			   access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
 			audit_net.sport = port;
 			audit_net.v4info.saddr = addr4->sin_addr.s_addr;
 		} else {
@@ -154,10 +159,12 @@ static int current_check_access_socket(struct socket *const sock,
 		addr6 = (struct sockaddr_in6 *)address;
 		port = addr6->sin6_port;
 
-		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
+		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
 			audit_net.dport = port;
 			audit_net.v6info.daddr = addr6->sin6_addr;
-		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP) {
+		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
+			   access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
 			audit_net.sport = port;
 			audit_net.v6info.saddr = addr6->sin6_addr;
 		} else {
@@ -215,6 +222,8 @@ static int hook_socket_bind(struct socket *const sock,
 
 	if (sk_is_tcp(sock->sk))
 		access_request = LANDLOCK_ACCESS_NET_BIND_TCP;
+	else if (sk_is_udp(sock->sk))
+		access_request = LANDLOCK_ACCESS_NET_BIND_UDP;
 	else
 		return 0;
 
@@ -230,6 +239,8 @@ static int hook_socket_connect(struct socket *const sock,
 
 	if (sk_is_tcp(sock->sk))
 		access_request = LANDLOCK_ACCESS_NET_CONNECT_TCP;
+	else if (sk_is_udp(sock->sk))
+		access_request = LANDLOCK_ACCESS_NET_CONNECT_UDP;
 	else
 		return 0;
 
diff --git a/security/landlock/syscalls.c b/security/landlock/syscalls.c
index 0116e9f93ffe..66fd196be85a 100644
--- a/security/landlock/syscalls.c
+++ b/security/landlock/syscalls.c
@@ -161,7 +161,7 @@ static const struct file_operations ruleset_fops = {
  * Documentation/userspace-api/landlock.rst should be updated to reflect the
  * UAPI change.
  */
-const int landlock_abi_version = 7;
+const int landlock_abi_version = 8;
 
 /**
  * sys_landlock_create_ruleset - Create a new ruleset
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 0/8] landlock: Add UDP access control support
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet

Hi Mickaël, Günther, Mikhail, Konstantin,

Here is v3 of UDP support for Landlock. My apologies for the delay, I've
had to deal with unrelated problems. All feedback from v1/v2 should be
merged, thanks again for taking the time to review them.

I based these patches on linux-mic/next commit 1a3cedbdc156 ("landlock:
Fix wrong type usage") plus my previous patch "landlock: Fix TCP
handling of short AF_UNSPEC addresses" to avoid adding UDP with already
known bugs, duplicated from TCP. I waited a bit to get feedback on that
patch and no one yelled, so I hope it's acceptable, tell me if it's not.
Link: https://lore.kernel.org/linux-security-module/20251027190726.626244-4-matthieu@buffet.re/

Changes since v2
================
Link: https://lore.kernel.org/all/20241214184540.3835222-1-matthieu@buffet.re/
- removed support for sending datagrams with explicit destination
  address of family AF_UNSPEC, which allowed to bypass restrictions with
  a race condition
- rebased on linux-mic/next => add support for auditing
- fixed mistake in selftests when using unspec_srv variables, which were
  implicitly of type SOCK_STREAM and did not actually test UDP code
- add tests for IPPROTO_IP
- improved docs, split off TCP-related refactoring into another commit

Changes since v1
================
Link: https://lore.kernel.org/all/20240916122230.114800-1-matthieu@buffet.re/
- recvmsg hook is gone and sendmsg hook doesn't apply to connected
  sockets anymore, to improve performance
- don't add a get_addr_port() helper function, which required a weird
  "am I in IPv4 or IPv6 context" to avoid a addrlen > sizeof(struct
  sockaddr_in) check in connect(AF_UNSPEC) IPv6 context. A helper was
  useful when ports also needed to be read in a recvmsg() hook, now it
  is just a simple switch case in the sendmsg() hook, more readable
- rename sendmsg access right to LANDLOCK_ACCESS_NET_UDP_SENDTO
- reorder hook prologue for consistency: check domain, then type and
  family
- add additional selftests cases around minimal address length
- update documentation

All important cases should have a selftest now. lcov gives me net.c
going from 91.9% lines/82.5% branches to 93.4% lines/87% branches.
Thank you for taking the time to read this!

Closes: https://github.com/landlock-lsm/linux/issues/10

Matthieu Buffet (8):
  landlock: Minor reword of docs for TCP access rights
  landlock: Refactor TCP socket type check
  landlock: Add UDP bind+connect access control
  selftests/landlock: Add UDP bind/connect tests
  landlock: Add UDP sendmsg access control
  selftests/landlock: Add tests for UDP sendmsg
  samples/landlock: Add sandboxer UDP access control
  landlock: Add documentation for UDP support

 Documentation/userspace-api/landlock.rst     |  94 ++-
 include/uapi/linux/landlock.h                |  46 +-
 samples/landlock/sandboxer.c                 |  58 +-
 security/landlock/audit.c                    |   3 +
 security/landlock/limits.h                   |   2 +-
 security/landlock/net.c                      | 119 +++-
 security/landlock/syscalls.c                 |   2 +-
 tools/testing/selftests/landlock/base_test.c |   2 +-
 tools/testing/selftests/landlock/net_test.c  | 691 ++++++++++++++++---
 9 files changed, 869 insertions(+), 148 deletions(-)


base-commit: 1a3cedbdc156e100eb1a5208a8562a3265c35d87
prerequisite-patch-id: 22051d5d4076a87481b22798c127ce84e219ca97
prerequisite-patch-id: 37a1b44596a2d861ba91989edb1d7aac005931d6
prerequisite-patch-id: c7be1c906699a2590ab7112cdf2ab6892178ec07
-- 
2.47.3


^ permalink raw reply

* [RFC PATCH v3 2/8] landlock: Refactor TCP socket type check
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

Move the socket type check earlier, so that we will later be able to add
elseifs for other types. Ordering of checks (socket is of a type we
enforce restrictions on) / (current creds have landlock restrictions)
should not change anything.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 security/landlock/net.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/security/landlock/net.c b/security/landlock/net.c
index e6367e30e5b0..59438285e73b 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -62,9 +62,6 @@ static int current_check_access_socket(struct socket *const sock,
 	if (!subject)
 		return 0;
 
-	if (!sk_is_tcp(sock->sk))
-		return 0;
-
 	/* Checks for minimal header length to safely read sa_family. */
 	if (addrlen < offsetofend(typeof(*address), sa_family))
 		return -EINVAL;
@@ -214,16 +211,30 @@ static int current_check_access_socket(struct socket *const sock,
 static int hook_socket_bind(struct socket *const sock,
 			    struct sockaddr *const address, const int addrlen)
 {
+	access_mask_t access_request;
+
+	if (sk_is_tcp(sock->sk))
+		access_request = LANDLOCK_ACCESS_NET_BIND_TCP;
+	else
+		return 0;
+
 	return current_check_access_socket(sock, address, addrlen,
-					   LANDLOCK_ACCESS_NET_BIND_TCP);
+					   access_request);
 }
 
 static int hook_socket_connect(struct socket *const sock,
 			       struct sockaddr *const address,
 			       const int addrlen)
 {
+	access_mask_t access_request;
+
+	if (sk_is_tcp(sock->sk))
+		access_request = LANDLOCK_ACCESS_NET_CONNECT_TCP;
+	else
+		return 0;
+
 	return current_check_access_socket(sock, address, addrlen,
-					   LANDLOCK_ACCESS_NET_CONNECT_TCP);
+					   access_request);
 }
 
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 8/8] landlock: Add documentation for UDP support
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

Add example of UDP usage, without detailing each access right, but with
an explicit note about the need to handle both SENDTO and CONNECT to
completely block sending (which could otherwise be overlooked).

Slightly change the example used in code blocks: build a ruleset for a
DNS client, so that it uses both TCP and UDP. Also consider an opaque
implementation so that we get to introduce both the right to connect()
and sendmsg(addr != NULL) within the same example.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 Documentation/userspace-api/landlock.rst | 94 ++++++++++++++++++------
 1 file changed, 72 insertions(+), 22 deletions(-)

diff --git a/Documentation/userspace-api/landlock.rst b/Documentation/userspace-api/landlock.rst
index 1d0c2c15c22e..758217c2b260 100644
--- a/Documentation/userspace-api/landlock.rst
+++ b/Documentation/userspace-api/landlock.rst
@@ -8,7 +8,7 @@ Landlock: unprivileged access control
 =====================================
 
 :Author: Mickaël Salaün
-:Date: March 2025
+:Date: October 2025
 
 The goal of Landlock is to enable restriction of ambient rights (e.g. global
 filesystem or network access) for a set of processes.  Because Landlock
@@ -40,8 +40,8 @@ Filesystem rules
     and the related filesystem actions are defined with
     `filesystem access rights`.
 
-Network rules (since ABI v4)
-    For these rules, the object is a TCP port,
+Network rules (since ABI v4 for TCP and v8 for UDP)
+    For these rules, the object is a TCP or UDP port,
     and the related actions are defined with `network access rights`.
 
 Defining and enforcing a security policy
@@ -49,11 +49,11 @@ Defining and enforcing a security policy
 
 We first need to define the ruleset that will contain our rules.
 
-For this example, the ruleset will contain rules that only allow filesystem
-read actions and establish a specific TCP connection. Filesystem write
-actions and other TCP actions will be denied.
+For this example, the ruleset will contain rules that only allow some
+filesystem read actions and some specific UDP and TCP accesses. Filesystem
+write actions and other TCP/UDP actions will be denied.
 
-The ruleset then needs to handle both these kinds of actions.  This is
+The ruleset then needs to handle all these kinds of actions.  This is
 required for backward and forward compatibility (i.e. the kernel and user
 space may not know each other's supported restrictions), hence the need
 to be explicit about the denied-by-default access rights.
@@ -80,7 +80,10 @@ to be explicit about the denied-by-default access rights.
             LANDLOCK_ACCESS_FS_IOCTL_DEV,
         .handled_access_net =
             LANDLOCK_ACCESS_NET_BIND_TCP |
-            LANDLOCK_ACCESS_NET_CONNECT_TCP,
+            LANDLOCK_ACCESS_NET_CONNECT_TCP |
+            LANDLOCK_ACCESS_NET_BIND_UDP |
+            LANDLOCK_ACCESS_NET_CONNECT_UDP |
+            LANDLOCK_ACCESS_NET_SENDTO_UDP,
         .scoped =
             LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
             LANDLOCK_SCOPE_SIGNAL,
@@ -127,6 +130,14 @@ version, and only use the available subset of access rights:
         /* Removes LANDLOCK_SCOPE_* for ABI < 6 */
         ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
                                  LANDLOCK_SCOPE_SIGNAL);
+        __attribute__((fallthrough));
+    case 6:
+    case 7:
+        /* Removes LANDLOCK_ACCESS_*_UDP for ABI < 8 */
+        ruleset_attr.handled_access_net &=
+            ~(LANDLOCK_ACCESS_NET_BIND_UDP |
+              LANDLOCK_ACCESS_NET_CONNECT_UDP |
+              LANDLOCK_ACCESS_NET_SENDTO_UDP);
     }
 
 This enables the creation of an inclusive ruleset that will contain our rules.
@@ -175,26 +186,53 @@ descriptor.
 
 It may also be required to create rules following the same logic as explained
 for the ruleset creation, by filtering access rights according to the Landlock
-ABI version.  In this example, this is not required because all of the requested
-``allowed_access`` rights are already available in ABI 1.
+ABI version.  So far, this was not required because all of the requested
+``allowed_access`` rights have always been available, from ABI 1.
 
-For network access-control, we can add a set of rules that allow to use a port
-number for a specific action: HTTPS connections.
+For network access-control, we will add a set of rules to allow DNS
+queries, which requires both UDP and TCP. For TCP, we need to allow
+outbound connections to port 53, which can be handled and granted starting
+with ABI 4:
 
 .. code-block:: c
 
-    struct landlock_net_port_attr net_port = {
-        .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
-        .port = 443,
-    };
+    if (ruleset_attr.handled_access_net & LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+        struct landlock_net_port_attr net_port = {
+            .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+            .port = 53,
+        };
 
-    err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-                            &net_port, 0);
+        err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+                                &net_port, 0);
+
+We also need to be able to send UDP datagrams to port 53: we don't know if
+the client will call e.g. :manpage:`sendto(2)` with an explicit destination
+address, or :manpage:`connect(2)` then e.g. :manpage:`send(2)`, so we
+allow both. Note that granting ``LANDLOCK_ACCESS_NET_BIND_UDP`` is not
+necessary here because the client's socket will be automatically bound to
+an ephemeral port by the kernel.  Also note that we need to handle both
+``LANDLOCK_ACCESS_NET_CONNECT_UDP`` and ``LANDLOCK_ACCESS_NET_SENDTO_UDP``
+to effectively block sending UDP datagrams to arbitrary ports.
+
+.. code-block:: c
+
+    if ((ruleset_attr.handled_access_net & (LANDLOCK_ACCESS_NET_CONNECT_UDP |
+                                            LANDLOCK_ACCESS_NET_SENDTO_UDP)) ==
+                                           (LANDLOCK_ACCESS_NET_CONNECT_UDP |
+                                            LANDLOCK_ACCESS_NET_SENDTO_UDP)) {
+        struct landlock_net_port_attr net_port = {
+            .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_UDP |
+                              LANDLOCK_ACCESS_NET_SENDTO_UDP,
+            .port = 53,
+        };
+
+        err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+                                &net_port, 0);
 
 The next step is to restrict the current thread from gaining more privileges
 (e.g. through a SUID binary).  We now have a ruleset with the first rule
 allowing read access to ``/usr`` while denying all other handled accesses for
-the filesystem, and a second rule allowing HTTPS connections.
+the filesystem, and two more rules allowing DNS queries.
 
 .. code-block:: c
 
@@ -604,6 +642,18 @@ Landlock audit events with the ``LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF``,
 sys_landlock_restrict_self().  See Documentation/admin-guide/LSM/landlock.rst
 for more details on audit.
 
+UDP networking (ABI < 8)
+------------------------
+
+Starting with the Landlock ABI version 8, it is possible to restrict
+setting the local/remote ports of UDP sockets to specific values. Restrictions
+are now enforced at :manpage:`bind(2)` time with the new
+``LANDLOCK_ACCESS_NET_BIND_UDP`` access right, and at :manpage:`connect(2)`
+time with ``LANDLOCK_ACCESS_NET_CONNECT_UDP``. Finally,
+``LANDLOCK_ACCESS_NET_SENDTO_UDP`` also restricts sending datagrams with
+an explicit destination address (e.g. with :manpage:`sendmsg(2)`) to only some
+specific remote ports.
+
 .. _kernel_support:
 
 Kernel support
@@ -666,10 +716,10 @@ the boot loader.
 Network support
 ---------------
 
-To be able to explicitly allow TCP operations (e.g., adding a network rule with
-``LANDLOCK_ACCESS_NET_BIND_TCP``), the kernel must support TCP
+To be able to explicitly allow TCP or UDP operations (e.g., adding a network rule with
+``LANDLOCK_ACCESS_NET_BIND_TCP``), the kernel must support the TCP/IP protocol suite
 (``CONFIG_INET=y``).  Otherwise, sys_landlock_add_rule() returns an
-``EAFNOSUPPORT`` error, which can safely be ignored because this kind of TCP
+``EAFNOSUPPORT`` error, which can safely be ignored because this kind of TCP or UDP
 operation is already not possible.
 
 Questions and answers
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 7/8] samples/landlock: Add sandboxer UDP access control
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

Add environment variables to control associated access rights:
- LL_UDP_BIND
- LL_UDP_CONNECT
- LL_UDP_SENDTO

Each one takes a list of ports separated by colons, like other list
options.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 samples/landlock/sandboxer.c | 58 ++++++++++++++++++++++++++++++++++--
 1 file changed, 56 insertions(+), 2 deletions(-)

diff --git a/samples/landlock/sandboxer.c b/samples/landlock/sandboxer.c
index e7af02f98208..65accc095926 100644
--- a/samples/landlock/sandboxer.c
+++ b/samples/landlock/sandboxer.c
@@ -62,6 +62,9 @@ static inline int landlock_restrict_self(const int ruleset_fd,
 #define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT"
 #define ENV_SCOPED_NAME "LL_SCOPED"
 #define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"
+#define ENV_UDP_BIND_NAME "LL_UDP_BIND"
+#define ENV_UDP_CONNECT_NAME "LL_UDP_CONNECT"
+#define ENV_UDP_SENDTO_NAME "LL_UDP_SENDTO"
 #define ENV_DELIMITER ":"
 
 static int str2num(const char *numstr, __u64 *num_dst)
@@ -299,7 +302,7 @@ static bool check_ruleset_scope(const char *const env_var,
 
 /* clang-format on */
 
-#define LANDLOCK_ABI_LAST 7
+#define LANDLOCK_ABI_LAST 8
 
 #define XSTR(s) #s
 #define STR(s) XSTR(s)
@@ -322,6 +325,12 @@ static const char help[] =
 	"means an empty list):\n"
 	"* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n"
 	"* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n"
+	"* " ENV_UDP_BIND_NAME ": local UDP ports allowed to bind (server: "
+	"prepare to receive on port / client: set as source port)\n"
+	"* " ENV_UDP_CONNECT_NAME ": remote UDP ports allowed to connect "
+	"(client: set as destination port / server: receive only from it)\n"
+	"* " ENV_UDP_SENDTO_NAME ": remote UDP ports allowed to send to "
+	"without prior connect()\n"
 	"* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n"
 	"  - \"a\" to restrict opening abstract unix sockets\n"
 	"  - \"s\" to restrict sending signals\n"
@@ -334,6 +343,8 @@ static const char help[] =
 	ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
 	ENV_TCP_BIND_NAME "=\"9418\" "
 	ENV_TCP_CONNECT_NAME "=\"80:443\" "
+	ENV_UDP_CONNECT_NAME "=\"53\" "
+	ENV_UDP_SENDTO_NAME "=\"53\" "
 	ENV_SCOPED_NAME "=\"a:s\" "
 	"%1$s bash -i\n"
 	"\n"
@@ -354,7 +365,10 @@ int main(const int argc, char *const argv[], char *const *const envp)
 	struct landlock_ruleset_attr ruleset_attr = {
 		.handled_access_fs = access_fs_rw,
 		.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-				      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+				      LANDLOCK_ACCESS_NET_CONNECT_TCP |
+				      LANDLOCK_ACCESS_NET_BIND_UDP |
+				      LANDLOCK_ACCESS_NET_CONNECT_UDP |
+				      LANDLOCK_ACCESS_NET_SENDTO_UDP,
 		.scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
 			  LANDLOCK_SCOPE_SIGNAL,
 	};
@@ -436,6 +450,13 @@ int main(const int argc, char *const argv[], char *const *const envp)
 		/* Removes LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON for ABI < 7 */
 		supported_restrict_flags &=
 			~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
+		__attribute__((fallthrough));
+	case 7:
+		/* Removes UDP support for ABI < 8 */
+		ruleset_attr.handled_access_net &=
+			~(LANDLOCK_ACCESS_NET_BIND_UDP |
+			  LANDLOCK_ACCESS_NET_CONNECT_UDP |
+			  LANDLOCK_ACCESS_NET_SENDTO_UDP);
 
 		/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */
 		fprintf(stderr,
@@ -468,6 +489,27 @@ int main(const int argc, char *const argv[], char *const *const envp)
 		ruleset_attr.handled_access_net &=
 			~LANDLOCK_ACCESS_NET_CONNECT_TCP;
 	}
+	/* Removes UDP bind access control if not supported by a user. */
+	env_port_name = getenv(ENV_UDP_BIND_NAME);
+	if (!env_port_name) {
+		ruleset_attr.handled_access_net &=
+			~LANDLOCK_ACCESS_NET_BIND_UDP;
+	}
+	/* Removes UDP connect access control if not supported by a user. */
+	env_port_name = getenv(ENV_UDP_CONNECT_NAME);
+	if (!env_port_name) {
+		ruleset_attr.handled_access_net &=
+			~LANDLOCK_ACCESS_NET_CONNECT_UDP;
+	}
+	/*
+	 * Removes UDP send with explicit address access control if not
+	 * supported by a user.
+	 */
+	env_port_name = getenv(ENV_UDP_SENDTO_NAME);
+	if (!env_port_name) {
+		ruleset_attr.handled_access_net &=
+			~LANDLOCK_ACCESS_NET_SENDTO_UDP;
+	}
 
 	if (check_ruleset_scope(ENV_SCOPED_NAME, &ruleset_attr))
 		return 1;
@@ -512,6 +554,18 @@ int main(const int argc, char *const argv[], char *const *const envp)
 				 LANDLOCK_ACCESS_NET_CONNECT_TCP)) {
 		goto err_close_ruleset;
 	}
+	if (populate_ruleset_net(ENV_UDP_BIND_NAME, ruleset_fd,
+				 LANDLOCK_ACCESS_NET_BIND_UDP)) {
+		goto err_close_ruleset;
+	}
+	if (populate_ruleset_net(ENV_UDP_CONNECT_NAME, ruleset_fd,
+				 LANDLOCK_ACCESS_NET_CONNECT_UDP)) {
+		goto err_close_ruleset;
+	}
+	if (populate_ruleset_net(ENV_UDP_SENDTO_NAME, ruleset_fd,
+				 LANDLOCK_ACCESS_NET_SENDTO_UDP)) {
+		goto err_close_ruleset;
+	}
 
 	if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
 		perror("Failed to restrict privileges");
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 6/8] selftests/landlock: Add tests for UDP sendmsg
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

Add tests specific to UDP sendmsg(), orthogonal to whether the process
is allowed to bind()/connect(). Make this part of the protocol_*
variants to ensure behaviour is consistent across AF_INET, AF_INET6 and
AF_UNIX.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 tools/testing/selftests/landlock/net_test.c | 306 +++++++++++++++++++-
 1 file changed, 299 insertions(+), 7 deletions(-)

diff --git a/tools/testing/selftests/landlock/net_test.c b/tools/testing/selftests/landlock/net_test.c
index 977d82eb9934..79ce52907ef3 100644
--- a/tools/testing/selftests/landlock/net_test.c
+++ b/tools/testing/selftests/landlock/net_test.c
@@ -268,9 +268,68 @@ static int connect_variant(const int sock_fd,
 	return connect_variant_addrlen(sock_fd, srv, get_addrlen(srv, false));
 }
 
+static int sendto_variant_addrlen(const int sock_fd,
+				  const struct service_fixture *const srv,
+				  const socklen_t addrlen, void *buf,
+				  size_t len, size_t flags)
+{
+	const struct sockaddr *dst = NULL;
+	ssize_t ret;
+
+	/*
+	 * We never want our processes to be killed by SIGPIPE: we check
+	 * return codes and errno, so that we have actual error messages.
+	 */
+	flags |= MSG_NOSIGNAL;
+
+	if (srv != NULL) {
+		switch (srv->protocol.domain) {
+		case AF_UNSPEC:
+		case AF_INET:
+			dst = (const struct sockaddr *)&srv->ipv4_addr;
+			break;
+
+		case AF_INET6:
+			dst = (const struct sockaddr *)&srv->ipv6_addr;
+			break;
+
+		case AF_UNIX:
+			dst = (const struct sockaddr *)&srv->unix_addr;
+			break;
+
+		default:
+			errno = -EAFNOSUPPORT;
+			return -errno;
+		}
+	}
+
+	ret = sendto(sock_fd, buf, len, flags, dst, addrlen);
+	if (ret < 0)
+		return -errno;
+
+	/* errno is not set in cases of partial writes. */
+	if (ret != len)
+		return -EINTR;
+
+	return 0;
+}
+
+static int sendto_variant(const int sock_fd,
+			  const struct service_fixture *const srv, void *buf,
+			  size_t len, size_t flags)
+{
+	socklen_t addrlen = 0;
+
+	if (srv != NULL)
+		addrlen = get_addrlen(srv, false);
+
+	return sendto_variant_addrlen(sock_fd, srv, addrlen, buf, len, flags);
+}
+
 FIXTURE(protocol)
 {
-	struct service_fixture srv0, srv1, srv2, unspec_any0, unspec_srv0;
+	struct service_fixture srv0, srv1, srv2;
+	struct service_fixture unspec_any0, unspec_srv0, unspec_srv1;
 };
 
 FIXTURE_VARIANT(protocol)
@@ -292,6 +351,7 @@ FIXTURE_SETUP(protocol)
 	ASSERT_EQ(0, set_service(&self->srv2, variant->prot, 2));
 
 	ASSERT_EQ(0, set_service(&self->unspec_srv0, prot_unspec, 0));
+	ASSERT_EQ(0, set_service(&self->unspec_srv1, prot_unspec, 1));
 
 	ASSERT_EQ(0, set_service(&self->unspec_any0, prot_unspec, 0));
 	self->unspec_any0.ipv4_addr.sin_addr.s_addr = htonl(INADDR_ANY);
@@ -1075,6 +1135,185 @@ TEST_F(protocol, connect_unspec)
 	EXPECT_EQ(0, close(bind_fd));
 }
 
+TEST_F(protocol, sendmsg)
+{
+	/* Arbitrary value just to not block other tests indefinitely. */
+	const struct timeval read_timeout = {
+		.tv_sec = 0,
+		.tv_usec = 100000,
+	};
+	const bool sandboxed = variant->sandbox == UDP_SANDBOX &&
+			       (variant->prot.domain == AF_INET ||
+				variant->prot.domain == AF_INET6);
+	int res, srv1_fd, srv0_fd, client_fd;
+	char read_buf[1] = { 0 };
+
+	if (variant->prot.type != SOCK_DGRAM)
+		return;
+
+	disable_caps(_metadata);
+
+	/* Prepare server on port #0 to be denied */
+	ASSERT_EQ(0, set_service(&self->srv0, variant->prot, 0));
+	srv0_fd = socket_variant(&self->srv0);
+	ASSERT_LE(0, srv0_fd);
+	ASSERT_EQ(0, bind_variant(srv0_fd, &self->srv0));
+
+	/* And another server on port #1 to be allowed */
+	ASSERT_EQ(0, set_service(&self->srv1, variant->prot, 1));
+	srv1_fd = socket_variant(&self->srv1);
+	ASSERT_LE(0, srv1_fd);
+	ASSERT_EQ(0, bind_variant(srv1_fd, &self->srv1));
+
+	EXPECT_EQ(0, setsockopt(srv0_fd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout,
+				sizeof(read_timeout)));
+	EXPECT_EQ(0, setsockopt(srv1_fd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout,
+				sizeof(read_timeout)));
+
+	client_fd = socket_variant(&self->srv0);
+	ASSERT_LE(0, client_fd);
+
+	if (sandboxed) {
+		const struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = LANDLOCK_ACCESS_NET_SENDTO_UDP |
+					      LANDLOCK_ACCESS_NET_BIND_UDP,
+		};
+		const struct landlock_net_port_attr allow_one_server = {
+			.allowed_access = LANDLOCK_ACCESS_NET_SENDTO_UDP,
+			.port = self->srv1.port,
+		};
+		const int ruleset_fd = landlock_create_ruleset(
+			&ruleset_attr, sizeof(ruleset_attr), 0);
+		ASSERT_LE(0, ruleset_fd);
+		ASSERT_EQ(0,
+			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+					    &allow_one_server, 0));
+		enforce_ruleset(_metadata, ruleset_fd);
+		EXPECT_EQ(0, close(ruleset_fd));
+	}
+
+	/* No connect(), NULL address */
+	EXPECT_EQ(-1, write(client_fd, "A", 1));
+	if (variant->prot.domain == AF_UNIX) {
+		EXPECT_EQ(ENOTCONN, errno);
+	} else {
+		EXPECT_EQ(EDESTADDRREQ, errno);
+	}
+
+	/* No connect(), non-NULL but too small explicit address */
+	EXPECT_EQ(-EINVAL,
+		  sendto_variant_addrlen(client_fd, &self->srv0,
+					 get_addrlen(&self->srv0, true) - 1,
+					 "B", 1, 0));
+
+	/* No connect(), explicit denied port */
+	res = sendto_variant(client_fd, &self->srv0, "C", 1, 0);
+	if (sandboxed) {
+		EXPECT_EQ(-EACCES, res);
+	} else {
+		EXPECT_EQ(0, res);
+		EXPECT_EQ(1, read(srv0_fd, read_buf, 1));
+		EXPECT_EQ(read_buf[0], 'C');
+	}
+
+	/* No connect(), explicit allowed port */
+	EXPECT_EQ(0, sendto_variant(client_fd, &self->srv1, "D", 1, 0));
+	EXPECT_EQ(1, read(srv1_fd, read_buf, 1));
+	EXPECT_EQ(read_buf[0], 'D');
+
+	/* Explicit AF_UNSPEC address but truncated */
+	EXPECT_EQ(-EINVAL, sendto_variant_addrlen(
+				   client_fd, &self->unspec_srv0,
+				   get_addrlen(&self->unspec_srv0, true) - 1,
+				   "E", 1, 0));
+
+	/* Explicit AF_UNSPEC address, should always be denied */
+	res = sendto_variant(client_fd, &self->unspec_srv1, "F", 1, 0);
+	if (sandboxed) {
+		EXPECT_EQ(-EACCES, res);
+	} else {
+		if (variant->prot.domain == AF_INET) {
+			/* IPv4 sockets treat AF_UNSPEC as AF_INET */
+			EXPECT_EQ(0, res);
+			EXPECT_EQ(1, read(srv1_fd, read_buf, 1))
+			{
+				TH_LOG("read() failed: %s", strerror(errno));
+			}
+			EXPECT_EQ(read_buf[0], 'F');
+		} else if (variant->prot.domain == AF_INET6) {
+			/* IPv6 sockets treat AF_UNSPEC as a NULL address */
+			EXPECT_EQ(-EDESTADDRREQ, res);
+		} else {
+			/* Unix sockets don't accept AF_UNSPEC */
+			EXPECT_EQ(-EINVAL, res);
+		}
+	}
+
+	/* With connect() on an allowed explicit port, no explicit address */
+	ASSERT_EQ(0, connect_variant(client_fd, &self->srv1));
+	EXPECT_EQ(0, sendto_variant(client_fd, NULL, "G", 1, 0));
+	EXPECT_EQ(1, read(srv1_fd, read_buf, 1));
+	EXPECT_EQ(read_buf[0], 'G');
+
+	/* With connect() on a denied explicit port, no explicit address */
+	ASSERT_EQ(0, connect_variant(client_fd, &self->srv0));
+	EXPECT_EQ(0, sendto_variant(client_fd, NULL, "H", 1, 0));
+	EXPECT_EQ(1, read(srv0_fd, read_buf, 1));
+	EXPECT_EQ(read_buf[0], 'H');
+
+	/* Explicit AF_UNSPEC minimal address (just the sa_family_t field) */
+	res = sendto_variant_addrlen(client_fd, &self->unspec_srv0,
+				     get_addrlen(&self->unspec_srv0, true), "I",
+				     1, 0);
+	if (sandboxed) {
+		EXPECT_EQ(-EACCES, res);
+	} else if (variant->prot.domain == AF_INET6) {
+		/*
+		 * IPv6 sockets treat AF_UNSPEC as a NULL address,
+		 * falling back to the connected address
+		 */
+		EXPECT_EQ(0, res);
+		EXPECT_EQ(1, read(srv0_fd, read_buf, 1));
+		EXPECT_EQ(read_buf[0], 'I');
+	} else {
+		/*
+		 * IPv4 socket will expect a struct sockaddr_in, our address
+		 * is considered truncated.
+		 * And Unix sockets don't accept AF_UNSPEC at all.
+		 */
+		EXPECT_EQ(-EINVAL, res);
+	}
+
+	/* Explicit AF_UNSPEC address, should always be denied */
+	res = sendto_variant(client_fd, &self->unspec_srv1, "J", 1, 0);
+	if (sandboxed) {
+		EXPECT_EQ(-EACCES, res);
+	} else if (variant->prot.domain == AF_INET ||
+		   variant->prot.domain == AF_INET6) {
+		int read_fd;
+
+		EXPECT_EQ(0, res);
+		if (variant->prot.domain == AF_INET) {
+			/* IPv4 sockets treat AF_UNSPEC as AF_INET */
+			read_fd = srv1_fd;
+		} else {
+			/*
+			 * IPv6 sockets treat AF_UNSPEC as a NULL address,
+			 * falling back to the connected address
+			 */
+			read_fd = srv0_fd;
+		}
+		EXPECT_EQ(1, read(read_fd, read_buf, 1))
+		{
+			TH_LOG("read failed: %s", strerror(errno));
+		}
+		EXPECT_EQ(read_buf[0], 'J');
+	} else {
+		/* Unix sockets don't accept AF_UNSPEC */
+		EXPECT_EQ(-EINVAL, res);
+	}
+}
+
 FIXTURE(ipv4)
 {
 	struct service_fixture srv0, srv1;
@@ -1470,13 +1709,14 @@ FIXTURE_TEARDOWN(mini)
 
 /* clang-format off */
 
-#define ACCESS_LAST LANDLOCK_ACCESS_NET_CONNECT_UDP
+#define ACCESS_LAST LANDLOCK_ACCESS_NET_SENDTO_UDP
 
 #define ACCESS_ALL ( \
 	LANDLOCK_ACCESS_NET_BIND_TCP | \
 	LANDLOCK_ACCESS_NET_CONNECT_TCP | \
 	LANDLOCK_ACCESS_NET_BIND_UDP | \
-	LANDLOCK_ACCESS_NET_CONNECT_UDP)
+	LANDLOCK_ACCESS_NET_CONNECT_UDP | \
+	LANDLOCK_ACCESS_NET_SENDTO_UDP)
 
 /* clang-format on */
 
@@ -2078,19 +2318,26 @@ static int matches_log_prot(const int audit_fd, const char *const blockers,
 			    const char *const dir_addr, const char *const addr,
 			    const char *const dir_port)
 {
-	static const char log_template[] = REGEX_LANDLOCK_PREFIX
+	static const char tmpl_with_addr_port[] = REGEX_LANDLOCK_PREFIX
 		" blockers=%s %s=%s %s=1024$";
+	static const char tmpl_no_addr_port[] = REGEX_LANDLOCK_PREFIX
+		" blockers=%s$";
 	/*
 	 * Max strlen(blockers): 16
 	 * Max strlen(dir_addr): 5
 	 * Max strlen(addr): 12
 	 * Max strlen(dir_port): 4
 	 */
-	char log_match[sizeof(log_template) + 37];
+	char log_match[sizeof(tmpl_with_addr_port) + 37];
 	int log_match_len;
 
-	log_match_len = snprintf(log_match, sizeof(log_match), log_template,
-				 blockers, dir_addr, addr, dir_port);
+	if (addr != NULL)
+		log_match_len = snprintf(log_match, sizeof(log_match), tmpl_with_addr_port,
+					 blockers, dir_addr, addr, dir_port);
+	else
+		log_match_len = snprintf(log_match, sizeof(log_match), tmpl_no_addr_port,
+					 blockers);
+
 	if (log_match_len > sizeof(log_match))
 		return -E2BIG;
 
@@ -2101,6 +2348,7 @@ static int matches_log_prot(const int audit_fd, const char *const blockers,
 FIXTURE(audit)
 {
 	struct service_fixture srv0;
+	struct service_fixture unspec_srv0;
 	struct audit_filter audit_filter;
 	int audit_fd;
 };
@@ -2153,7 +2401,13 @@ FIXTURE_VARIANT_ADD(audit, ipv6_udp) {
 
 FIXTURE_SETUP(audit)
 {
+	struct protocol_variant prot_unspec = variant->prot;
+
+	prot_unspec.domain = AF_UNSPEC;
+
 	ASSERT_EQ(0, set_service(&self->srv0, variant->prot, 0));
+	ASSERT_EQ(0, set_service(&self->unspec_srv0, prot_unspec, 0));
+
 	setup_loopback(_metadata);
 
 	set_cap(_metadata, CAP_AUDIT_CONTROL);
@@ -2241,4 +2495,42 @@ TEST_F(audit, connect)
 	EXPECT_EQ(0, close(sock_fd));
 }
 
+TEST_F(audit, sendmsg)
+{
+	const struct landlock_ruleset_attr ruleset_attr = {
+		.handled_access_net = LANDLOCK_ACCESS_NET_SENDTO_UDP,
+	};
+	struct audit_records records;
+	int ruleset_fd, sock_fd;
+
+	if (variant->prot.type != SOCK_DGRAM)
+		return;
+
+	ruleset_fd =
+		landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+	ASSERT_LE(0, ruleset_fd);
+	enforce_ruleset(_metadata, ruleset_fd);
+	EXPECT_EQ(0, close(ruleset_fd));
+
+	sock_fd = socket_variant(&self->srv0);
+	ASSERT_LE(0, sock_fd);
+	EXPECT_EQ(-EACCES, sendto_variant(sock_fd, &self->srv0, "A", 1, 0));
+	EXPECT_EQ(0, matches_log_prot(self->audit_fd, "net.sendto_udp", "daddr",
+				      variant->addr, "dest"));
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);
+	EXPECT_EQ(1, records.domain);
+
+	EXPECT_EQ(-EACCES, sendto_variant(sock_fd, &self->unspec_srv0, "B", 1, 0));
+	EXPECT_EQ(0, matches_log_prot(self->audit_fd, "net.sendto_udp", "daddr",
+				      NULL, "dest"));
+
+	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+	EXPECT_EQ(0, records.access);
+	EXPECT_EQ(0, records.domain);
+
+	EXPECT_EQ(0, close(sock_fd));
+}
+
 TEST_HARNESS_MAIN
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 4/8] selftests/landlock: Add UDP bind/connect tests
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

Make basic changes to the existing bind() and connect() test suite to
also encompass testing UDP access control.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 tools/testing/selftests/landlock/base_test.c |   2 +-
 tools/testing/selftests/landlock/net_test.c  | 389 ++++++++++++++-----
 2 files changed, 303 insertions(+), 88 deletions(-)

diff --git a/tools/testing/selftests/landlock/base_test.c b/tools/testing/selftests/landlock/base_test.c
index 7b69002239d7..f4b1a275d8d9 100644
--- a/tools/testing/selftests/landlock/base_test.c
+++ b/tools/testing/selftests/landlock/base_test.c
@@ -76,7 +76,7 @@ TEST(abi_version)
 	const struct landlock_ruleset_attr ruleset_attr = {
 		.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE,
 	};
-	ASSERT_EQ(7, landlock_create_ruleset(NULL, 0,
+	ASSERT_EQ(8, landlock_create_ruleset(NULL, 0,
 					     LANDLOCK_CREATE_RULESET_VERSION));
 
 	ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,
diff --git a/tools/testing/selftests/landlock/net_test.c b/tools/testing/selftests/landlock/net_test.c
index b34b139b3f89..977d82eb9934 100644
--- a/tools/testing/selftests/landlock/net_test.c
+++ b/tools/testing/selftests/landlock/net_test.c
@@ -35,6 +35,7 @@ enum sandbox_type {
 	NO_SANDBOX,
 	/* This may be used to test rules that allow *and* deny accesses. */
 	TCP_SANDBOX,
+	UDP_SANDBOX,
 };
 
 static int set_service(struct service_fixture *const srv,
@@ -93,11 +94,20 @@ static bool prot_is_tcp(const struct protocol_variant *const prot)
 	       (prot->protocol == IPPROTO_TCP || prot->protocol == IPPROTO_IP);
 }
 
+static bool prot_is_udp(const struct protocol_variant *const prot)
+{
+	return (prot->domain == AF_INET || prot->domain == AF_INET6) &&
+	       prot->type == SOCK_DGRAM &&
+	       (prot->protocol == IPPROTO_UDP || prot->protocol == IPPROTO_IP);
+}
+
 static bool is_restricted(const struct protocol_variant *const prot,
 			  const enum sandbox_type sandbox)
 {
 	if (sandbox == TCP_SANDBOX)
 		return prot_is_tcp(prot);
+	else if (sandbox == UDP_SANDBOX)
+		return prot_is_udp(prot);
 	return false;
 }
 
@@ -271,10 +281,9 @@ FIXTURE_VARIANT(protocol)
 
 FIXTURE_SETUP(protocol)
 {
-	const struct protocol_variant prot_unspec = {
-		.domain = AF_UNSPEC,
-		.type = SOCK_STREAM,
-	};
+	struct protocol_variant prot_unspec = variant->prot;
+
+	prot_unspec.domain = AF_UNSPEC;
 
 	disable_caps(_metadata);
 
@@ -510,6 +519,92 @@ FIXTURE_VARIANT_ADD(protocol, tcp_sandbox_with_unix_datagram) {
 	},
 };
 
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv4_udp1) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET,
+		.type = SOCK_DGRAM,
+		.protocol = IPPROTO_UDP,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv4_udp2) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET,
+		.type = SOCK_DGRAM,
+		/* IPPROTO_IP == 0 */
+		.protocol = IPPROTO_IP,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv6_udp1) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET6,
+		.type = SOCK_DGRAM,
+		.protocol = IPPROTO_UDP,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv6_udp2) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET6,
+		.type = SOCK_DGRAM,
+		/* IPPROTO_IP == 0 */
+		.protocol = IPPROTO_IP,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv4_tcp) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET,
+		.type = SOCK_STREAM,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv6_tcp) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET6,
+		.type = SOCK_STREAM,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_unix_stream) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_UNIX,
+		.type = SOCK_STREAM,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_unix_datagram) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_UNIX,
+		.type = SOCK_DGRAM,
+	},
+};
+
 static void test_bind_and_connect(struct __test_metadata *const _metadata,
 				  const struct service_fixture *const srv,
 				  const bool deny_bind, const bool deny_connect)
@@ -602,7 +697,7 @@ static void test_bind_and_connect(struct __test_metadata *const _metadata,
 		ret = connect_variant(connect_fd, srv);
 		if (deny_connect) {
 			EXPECT_EQ(-EACCES, ret);
-		} else if (deny_bind) {
+		} else if (deny_bind && srv->protocol.type == SOCK_STREAM) {
 			/* No listening server. */
 			EXPECT_EQ(-ECONNREFUSED, ret);
 		} else {
@@ -641,18 +736,25 @@ static void test_bind_and_connect(struct __test_metadata *const _metadata,
 
 TEST_F(protocol, bind)
 {
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
+		const __u64 bind_access =
+			(variant->sandbox == TCP_SANDBOX ?
+				 LANDLOCK_ACCESS_NET_BIND_TCP :
+				 LANDLOCK_ACCESS_NET_BIND_UDP);
+		const __u64 connect_access =
+			(variant->sandbox == TCP_SANDBOX ?
+				 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+				 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 		const struct landlock_ruleset_attr ruleset_attr = {
-			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-					      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+			.handled_access_net = bind_access | connect_access,
 		};
-		const struct landlock_net_port_attr tcp_bind_connect_p0 = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
-					  LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		const struct landlock_net_port_attr bind_connect_p0 = {
+			.allowed_access = bind_access | connect_access,
 			.port = self->srv0.port,
 		};
-		const struct landlock_net_port_attr tcp_connect_p1 = {
-			.allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		const struct landlock_net_port_attr connect_p1 = {
+			.allowed_access = connect_access,
 			.port = self->srv1.port,
 		};
 		int ruleset_fd;
@@ -664,12 +766,12 @@ TEST_F(protocol, bind)
 		/* Allows connect and bind for the first port.  */
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind_connect_p0, 0));
+					    &bind_connect_p0, 0));
 
 		/* Allows connect and denies bind for the second port. */
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_connect_p1, 0));
+					    &connect_p1, 0));
 
 		enforce_ruleset(_metadata, ruleset_fd);
 		EXPECT_EQ(0, close(ruleset_fd));
@@ -691,18 +793,25 @@ TEST_F(protocol, bind)
 
 TEST_F(protocol, connect)
 {
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
+		const __u64 bind_access =
+			(variant->sandbox == TCP_SANDBOX ?
+				 LANDLOCK_ACCESS_NET_BIND_TCP :
+				 LANDLOCK_ACCESS_NET_BIND_UDP);
+		const __u64 connect_access =
+			(variant->sandbox == TCP_SANDBOX ?
+				 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+				 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 		const struct landlock_ruleset_attr ruleset_attr = {
-			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-					      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+			.handled_access_net = bind_access | connect_access,
 		};
-		const struct landlock_net_port_attr tcp_bind_connect_p0 = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
-					  LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		const struct landlock_net_port_attr bind_connect_p0 = {
+			.allowed_access = bind_access | connect_access,
 			.port = self->srv0.port,
 		};
-		const struct landlock_net_port_attr tcp_bind_p1 = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
+		const struct landlock_net_port_attr bind_p1 = {
+			.allowed_access = bind_access,
 			.port = self->srv1.port,
 		};
 		int ruleset_fd;
@@ -714,12 +823,12 @@ TEST_F(protocol, connect)
 		/* Allows connect and bind for the first port. */
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind_connect_p0, 0));
+					    &bind_connect_p0, 0));
 
 		/* Allows bind and denies connect for the second port. */
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind_p1, 0));
+					    &bind_p1, 0));
 
 		enforce_ruleset(_metadata, ruleset_fd);
 		EXPECT_EQ(0, close(ruleset_fd));
@@ -737,16 +846,24 @@ TEST_F(protocol, connect)
 
 TEST_F(protocol, bind_unspec)
 {
-	const struct landlock_ruleset_attr ruleset_attr = {
-		.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP,
-	};
-	const struct landlock_net_port_attr tcp_bind = {
-		.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
-		.port = self->srv0.port,
-	};
+	const int bind_access_right = (variant->sandbox == TCP_SANDBOX ?
+					       LANDLOCK_ACCESS_NET_BIND_TCP :
+					       LANDLOCK_ACCESS_NET_BIND_UDP);
 	int bind_fd, ret;
 
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
+		const struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = bind_access_right,
+		};
+		const struct landlock_net_port_attr bind = {
+			.allowed_access =
+				(variant->sandbox == TCP_SANDBOX ?
+					 LANDLOCK_ACCESS_NET_BIND_TCP :
+					 LANDLOCK_ACCESS_NET_BIND_UDP),
+			.port = self->srv0.port,
+		};
+
 		const int ruleset_fd = landlock_create_ruleset(
 			&ruleset_attr, sizeof(ruleset_attr), 0);
 		ASSERT_LE(0, ruleset_fd);
@@ -754,7 +871,7 @@ TEST_F(protocol, bind_unspec)
 		/* Allows bind. */
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind, 0));
+					    &bind, 0));
 		enforce_ruleset(_metadata, ruleset_fd);
 		EXPECT_EQ(0, close(ruleset_fd));
 	}
@@ -782,7 +899,11 @@ TEST_F(protocol, bind_unspec)
 	}
 	EXPECT_EQ(0, close(bind_fd));
 
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
+		const struct landlock_ruleset_attr ruleset_attr = {
+			.handled_access_net = bind_access_right,
+		};
 		const int ruleset_fd = landlock_create_ruleset(
 			&ruleset_attr, sizeof(ruleset_attr), 0);
 		ASSERT_LE(0, ruleset_fd);
@@ -829,10 +950,12 @@ TEST_F(protocol, bind_unspec)
 TEST_F(protocol, connect_unspec)
 {
 	const struct landlock_ruleset_attr ruleset_attr = {
-		.handled_access_net = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		.handled_access_net = LANDLOCK_ACCESS_NET_CONNECT_TCP |
+				      LANDLOCK_ACCESS_NET_CONNECT_UDP,
 	};
-	const struct landlock_net_port_attr tcp_connect = {
-		.allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+	const struct landlock_net_port_attr connect = {
+		.allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP |
+				  LANDLOCK_ACCESS_NET_CONNECT_UDP,
 		.port = self->srv0.port,
 	};
 	int bind_fd, client_fd, status;
@@ -865,7 +988,8 @@ TEST_F(protocol, connect_unspec)
 			EXPECT_EQ(0, ret);
 		}
 
-		if (variant->sandbox == TCP_SANDBOX) {
+		if (variant->sandbox == TCP_SANDBOX ||
+		    variant->sandbox == UDP_SANDBOX) {
 			const int ruleset_fd = landlock_create_ruleset(
 				&ruleset_attr, sizeof(ruleset_attr), 0);
 			ASSERT_LE(0, ruleset_fd);
@@ -873,7 +997,7 @@ TEST_F(protocol, connect_unspec)
 			/* Allows connect. */
 			ASSERT_EQ(0, landlock_add_rule(ruleset_fd,
 						       LANDLOCK_RULE_NET_PORT,
-						       &tcp_connect, 0));
+						       &connect, 0));
 			enforce_ruleset(_metadata, ruleset_fd);
 			EXPECT_EQ(0, close(ruleset_fd));
 		}
@@ -896,7 +1020,8 @@ TEST_F(protocol, connect_unspec)
 			EXPECT_EQ(0, ret);
 		}
 
-		if (variant->sandbox == TCP_SANDBOX) {
+		if (variant->sandbox == TCP_SANDBOX ||
+		    variant->sandbox == UDP_SANDBOX) {
 			const int ruleset_fd = landlock_create_ruleset(
 				&ruleset_attr, sizeof(ruleset_attr), 0);
 			ASSERT_LE(0, ruleset_fd);
@@ -975,6 +1100,13 @@ FIXTURE_VARIANT_ADD(ipv4, tcp_sandbox_with_tcp) {
 	.type = SOCK_STREAM,
 };
 
+/* clang-format off */
+FIXTURE_VARIANT_ADD(ipv4, udp_sandbox_with_tcp) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.type = SOCK_STREAM,
+};
+
 /* clang-format off */
 FIXTURE_VARIANT_ADD(ipv4, no_sandbox_with_udp) {
 	/* clang-format on */
@@ -989,6 +1121,13 @@ FIXTURE_VARIANT_ADD(ipv4, tcp_sandbox_with_udp) {
 	.type = SOCK_DGRAM,
 };
 
+/* clang-format off */
+FIXTURE_VARIANT_ADD(ipv4, udp_sandbox_with_udp) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.type = SOCK_DGRAM,
+};
+
 FIXTURE_SETUP(ipv4)
 {
 	const struct protocol_variant prot = {
@@ -1010,16 +1149,21 @@ FIXTURE_TEARDOWN(ipv4)
 
 TEST_F(ipv4, from_unix_to_inet)
 {
+	const int access_rights =
+		(variant->sandbox == TCP_SANDBOX ?
+			 LANDLOCK_ACCESS_NET_BIND_TCP |
+				 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+			 LANDLOCK_ACCESS_NET_BIND_UDP |
+				 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 	int unix_stream_fd, unix_dgram_fd;
 
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
 		const struct landlock_ruleset_attr ruleset_attr = {
-			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-					      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+			.handled_access_net = access_rights,
 		};
-		const struct landlock_net_port_attr tcp_bind_connect_p0 = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
-					  LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		const struct landlock_net_port_attr bind_connect_p0 = {
+			.allowed_access = access_rights,
 			.port = self->srv0.port,
 		};
 		int ruleset_fd;
@@ -1032,7 +1176,7 @@ TEST_F(ipv4, from_unix_to_inet)
 		/* Allows connect and bind for srv0.  */
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind_connect_p0, 0));
+					    &bind_connect_p0, 0));
 
 		enforce_ruleset(_metadata, ruleset_fd);
 		EXPECT_EQ(0, close(ruleset_fd));
@@ -1326,11 +1470,13 @@ FIXTURE_TEARDOWN(mini)
 
 /* clang-format off */
 
-#define ACCESS_LAST LANDLOCK_ACCESS_NET_CONNECT_TCP
+#define ACCESS_LAST LANDLOCK_ACCESS_NET_CONNECT_UDP
 
 #define ACCESS_ALL ( \
 	LANDLOCK_ACCESS_NET_BIND_TCP | \
-	LANDLOCK_ACCESS_NET_CONNECT_TCP)
+	LANDLOCK_ACCESS_NET_CONNECT_TCP | \
+	LANDLOCK_ACCESS_NET_BIND_UDP | \
+	LANDLOCK_ACCESS_NET_CONNECT_UDP)
 
 /* clang-format on */
 
@@ -1697,7 +1843,7 @@ FIXTURE_VARIANT_ADD(port_specific, no_sandbox_with_ipv4) {
 };
 
 /* clang-format off */
-FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv4) {
+FIXTURE_VARIANT_ADD(port_specific, tcp_sandbox_with_ipv4) {
 	/* clang-format on */
 	.sandbox = TCP_SANDBOX,
 	.prot = {
@@ -1706,6 +1852,16 @@ FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv4) {
 	},
 };
 
+/* clang-format off */
+FIXTURE_VARIANT_ADD(port_specific, udp_sandbox_with_ipv4) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET,
+		.type = SOCK_DGRAM,
+	},
+};
+
 /* clang-format off */
 FIXTURE_VARIANT_ADD(port_specific, no_sandbox_with_ipv6) {
 	/* clang-format on */
@@ -1717,7 +1873,7 @@ FIXTURE_VARIANT_ADD(port_specific, no_sandbox_with_ipv6) {
 };
 
 /* clang-format off */
-FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv6) {
+FIXTURE_VARIANT_ADD(port_specific, tcp_sandbox_with_ipv6) {
 	/* clang-format on */
 	.sandbox = TCP_SANDBOX,
 	.prot = {
@@ -1726,6 +1882,16 @@ FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv6) {
 	},
 };
 
+/* clang-format off */
+FIXTURE_VARIANT_ADD(port_specific, udp_sandbox_with_ipv6) {
+	/* clang-format on */
+	.sandbox = UDP_SANDBOX,
+	.prot = {
+		.domain = AF_INET6,
+		.type = SOCK_DGRAM,
+	},
+};
+
 FIXTURE_SETUP(port_specific)
 {
 	disable_caps(_metadata);
@@ -1745,14 +1911,19 @@ TEST_F(port_specific, bind_connect_zero)
 	uint16_t port;
 
 	/* Adds a rule layer with bind and connect actions. */
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
+		const int access_rights =
+			(variant->sandbox == TCP_SANDBOX ?
+				 LANDLOCK_ACCESS_NET_BIND_TCP |
+					 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+				 LANDLOCK_ACCESS_NET_BIND_UDP |
+					 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 		const struct landlock_ruleset_attr ruleset_attr = {
-			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-					      LANDLOCK_ACCESS_NET_CONNECT_TCP
+			.handled_access_net = access_rights,
 		};
 		const struct landlock_net_port_attr tcp_bind_connect_zero = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
-					  LANDLOCK_ACCESS_NET_CONNECT_TCP,
+			.allowed_access = access_rights,
 			.port = 0,
 		};
 		int ruleset_fd;
@@ -1785,11 +1956,13 @@ TEST_F(port_specific, bind_connect_zero)
 	ret = bind_variant(bind_fd, &self->srv0);
 	EXPECT_EQ(0, ret);
 
-	EXPECT_EQ(0, listen(bind_fd, backlog));
+	if (variant->prot.type == SOCK_STREAM) {
+		EXPECT_EQ(0, listen(bind_fd, backlog));
 
-	/* Connects on port 0. */
-	ret = connect_variant(connect_fd, &self->srv0);
-	EXPECT_EQ(-ECONNREFUSED, ret);
+		/* Connects on port 0. */
+		ret = connect_variant(connect_fd, &self->srv0);
+		EXPECT_EQ(-ECONNREFUSED, ret);
+	}
 
 	/* Sets binded port for both protocol families. */
 	port = get_binded_port(bind_fd, &variant->prot);
@@ -1813,21 +1986,25 @@ TEST_F(port_specific, bind_connect_1023)
 	int bind_fd, connect_fd, ret;
 
 	/* Adds a rule layer with bind and connect actions. */
-	if (variant->sandbox == TCP_SANDBOX) {
+	if (variant->sandbox == TCP_SANDBOX ||
+	    variant->sandbox == UDP_SANDBOX) {
+		const int access_rights =
+			(variant->sandbox == TCP_SANDBOX ?
+				 LANDLOCK_ACCESS_NET_BIND_TCP |
+					 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+				 LANDLOCK_ACCESS_NET_BIND_UDP |
+					 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 		const struct landlock_ruleset_attr ruleset_attr = {
-			.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-					      LANDLOCK_ACCESS_NET_CONNECT_TCP
+			.handled_access_net = access_rights,
 		};
 		/* A rule with port value less than 1024. */
-		const struct landlock_net_port_attr tcp_bind_connect_low_range = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
-					  LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		const struct landlock_net_port_attr bind_connect_low_range = {
+			.allowed_access = access_rights,
 			.port = 1023,
 		};
 		/* A rule with 1024 port. */
-		const struct landlock_net_port_attr tcp_bind_connect = {
-			.allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
-					  LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		const struct landlock_net_port_attr bind_connect = {
+			.allowed_access = access_rights,
 			.port = 1024,
 		};
 		int ruleset_fd;
@@ -1838,10 +2015,10 @@ TEST_F(port_specific, bind_connect_1023)
 
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind_connect_low_range, 0));
+					    &bind_connect_low_range, 0));
 		ASSERT_EQ(0,
 			  landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
-					    &tcp_bind_connect, 0));
+					    &bind_connect, 0));
 
 		enforce_ruleset(_metadata, ruleset_fd);
 		EXPECT_EQ(0, close(ruleset_fd));
@@ -1865,7 +2042,8 @@ TEST_F(port_specific, bind_connect_1023)
 	ret = bind_variant(bind_fd, &self->srv0);
 	clear_cap(_metadata, CAP_NET_BIND_SERVICE);
 	EXPECT_EQ(0, ret);
-	EXPECT_EQ(0, listen(bind_fd, backlog));
+	if (variant->prot.type == SOCK_STREAM)
+		EXPECT_EQ(0, listen(bind_fd, backlog));
 
 	/* Connects on the binded port 1023. */
 	ret = connect_variant(connect_fd, &self->srv0);
@@ -1885,7 +2063,8 @@ TEST_F(port_specific, bind_connect_1023)
 	/* Binds on port 1024. */
 	ret = bind_variant(bind_fd, &self->srv0);
 	EXPECT_EQ(0, ret);
-	EXPECT_EQ(0, listen(bind_fd, backlog));
+	if (variant->prot.type == SOCK_STREAM)
+		EXPECT_EQ(0, listen(bind_fd, backlog));
 
 	/* Connects on the binded port 1024. */
 	ret = connect_variant(connect_fd, &self->srv0);
@@ -1895,9 +2074,9 @@ TEST_F(port_specific, bind_connect_1023)
 	EXPECT_EQ(0, close(bind_fd));
 }
 
-static int matches_log_tcp(const int audit_fd, const char *const blockers,
-			   const char *const dir_addr, const char *const addr,
-			   const char *const dir_port)
+static int matches_log_prot(const int audit_fd, const char *const blockers,
+			    const char *const dir_addr, const char *const addr,
+			    const char *const dir_port)
 {
 	static const char log_template[] = REGEX_LANDLOCK_PREFIX
 		" blockers=%s %s=%s %s=1024$";
@@ -1933,7 +2112,7 @@ FIXTURE_VARIANT(audit)
 };
 
 /* clang-format off */
-FIXTURE_VARIANT_ADD(audit, ipv4) {
+FIXTURE_VARIANT_ADD(audit, ipv4_tcp) {
 	/* clang-format on */
 	.addr = "127\\.0\\.0\\.1",
 	.prot = {
@@ -1943,7 +2122,17 @@ FIXTURE_VARIANT_ADD(audit, ipv4) {
 };
 
 /* clang-format off */
-FIXTURE_VARIANT_ADD(audit, ipv6) {
+FIXTURE_VARIANT_ADD(audit, ipv4_udp) {
+	/* clang-format on */
+	.addr = "127\\.0\\.0\\.1",
+	.prot = {
+		.domain = AF_INET,
+		.type = SOCK_DGRAM,
+	},
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(audit, ipv6_tcp) {
 	/* clang-format on */
 	.addr = "::1",
 	.prot = {
@@ -1952,6 +2141,16 @@ FIXTURE_VARIANT_ADD(audit, ipv6) {
 	},
 };
 
+/* clang-format off */
+FIXTURE_VARIANT_ADD(audit, ipv6_udp) {
+	/* clang-format on */
+	.addr = "::1",
+	.prot = {
+		.domain = AF_INET6,
+		.type = SOCK_DGRAM,
+	},
+};
+
 FIXTURE_SETUP(audit)
 {
 	ASSERT_EQ(0, set_service(&self->srv0, variant->prot, 0));
@@ -1972,9 +2171,17 @@ FIXTURE_TEARDOWN(audit)
 
 TEST_F(audit, bind)
 {
+	const char *audit_evt = (variant->prot.type == SOCK_STREAM ?
+					 "net\\.bind_tcp" :
+					 "net\\.bind_udp");
+	const int access_rights =
+		(variant->prot.type == SOCK_STREAM ?
+			 LANDLOCK_ACCESS_NET_BIND_TCP |
+				 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+			 LANDLOCK_ACCESS_NET_BIND_UDP |
+				 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 	const struct landlock_ruleset_attr ruleset_attr = {
-		.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-				      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		.handled_access_net = access_rights,
 	};
 	struct audit_records records;
 	int ruleset_fd, sock_fd;
@@ -1988,8 +2195,8 @@ TEST_F(audit, bind)
 	sock_fd = socket_variant(&self->srv0);
 	ASSERT_LE(0, sock_fd);
 	EXPECT_EQ(-EACCES, bind_variant(sock_fd, &self->srv0));
-	EXPECT_EQ(0, matches_log_tcp(self->audit_fd, "net\\.bind_tcp", "saddr",
-				     variant->addr, "src"));
+	EXPECT_EQ(0, matches_log_prot(self->audit_fd, audit_evt, "saddr",
+				      variant->addr, "src"));
 
 	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
 	EXPECT_EQ(0, records.access);
@@ -2000,9 +2207,17 @@ TEST_F(audit, bind)
 
 TEST_F(audit, connect)
 {
+	const char *audit_evt = (variant->prot.type == SOCK_STREAM ?
+					 "net\\.connect_tcp" :
+					 "net\\.connect_udp");
+	const int access_rights =
+		(variant->prot.type == SOCK_STREAM ?
+			 LANDLOCK_ACCESS_NET_BIND_TCP |
+				 LANDLOCK_ACCESS_NET_CONNECT_TCP :
+			 LANDLOCK_ACCESS_NET_BIND_UDP |
+				 LANDLOCK_ACCESS_NET_CONNECT_UDP);
 	const struct landlock_ruleset_attr ruleset_attr = {
-		.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
-				      LANDLOCK_ACCESS_NET_CONNECT_TCP,
+		.handled_access_net = access_rights,
 	};
 	struct audit_records records;
 	int ruleset_fd, sock_fd;
@@ -2016,8 +2231,8 @@ TEST_F(audit, connect)
 	sock_fd = socket_variant(&self->srv0);
 	ASSERT_LE(0, sock_fd);
 	EXPECT_EQ(-EACCES, connect_variant(sock_fd, &self->srv0));
-	EXPECT_EQ(0, matches_log_tcp(self->audit_fd, "net\\.connect_tcp",
-				     "daddr", variant->addr, "dest"));
+	EXPECT_EQ(0, matches_log_prot(self->audit_fd, audit_evt, "daddr",
+				      variant->addr, "dest"));
 
 	EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
 	EXPECT_EQ(0, records.access);
-- 
2.47.3


^ permalink raw reply related

* [RFC PATCH v3 5/8] landlock: Add UDP sendmsg access control
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
  To: Mickaël Salaün
  Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
	konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>

Add support for a LANDLOCK_ACCESS_NET_SENDTO_UDP access right, providing
control over specifying a UDP datagram's destination address explicitly
in sendto(), sendmsg(), and sendmmsg().
This complements the previous control of connect() via
LANDLOCK_ACCESS_NET_CONNECT_UDP.

Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
 include/uapi/linux/landlock.h | 13 ++++++++
 security/landlock/audit.c     |  1 +
 security/landlock/limits.h    |  2 +-
 security/landlock/net.c       | 61 +++++++++++++++++++++++++++++++++--
 4 files changed, 74 insertions(+), 3 deletions(-)

diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h
index 8f748fcf79dd..c43586e02216 100644
--- a/include/uapi/linux/landlock.h
+++ b/include/uapi/linux/landlock.h
@@ -352,12 +352,25 @@ struct landlock_net_port_attr {
  * - %LANDLOCK_ACCESS_NET_CONNECT_UDP: Connect UDP sockets to remote
  *   addresses with the given remote port. Support added in Landlock ABI
  *   version 8.
+ * - %LANDLOCK_ACCESS_NET_SENDTO_UDP: Send datagrams on UDP sockets with
+ *   an explicit destination address set to the given remote port.
+ *   Support added in Landlock ABI version 8. Note: this access right
+ *   does not control sending datagrams with no explicit destination
+ *   (e.g. via :manpage:`send(2)` or ``sendto(..., NULL, 0)``, so this
+ *   access right is not necessary when specifying a destination address
+ *   once and for all in :manpage:`connect(2)`.
+ *
+ *   Note: sending datagrams to an explicit ``AF_UNSPEC`` destination
+ *   address family is not supported. For IPv4 sockets, you will need to
+ *   use an ``AF_INET`` address instead, and for IPv6 sockets, you will
+ *   need to use a ``NULL`` address.
  */
 /* clang-format off */
 #define LANDLOCK_ACCESS_NET_BIND_TCP			(1ULL << 0)
 #define LANDLOCK_ACCESS_NET_CONNECT_TCP			(1ULL << 1)
 #define LANDLOCK_ACCESS_NET_BIND_UDP			(1ULL << 2)
 #define LANDLOCK_ACCESS_NET_CONNECT_UDP			(1ULL << 3)
+#define LANDLOCK_ACCESS_NET_SENDTO_UDP			(1ULL << 4)
 /* clang-format on */
 
 /**
diff --git a/security/landlock/audit.c b/security/landlock/audit.c
index 23d8dee320ef..e0c030727dab 100644
--- a/security/landlock/audit.c
+++ b/security/landlock/audit.c
@@ -46,6 +46,7 @@ static const char *const net_access_strings[] = {
 	[BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_TCP)] = "net.connect_tcp",
 	[BIT_INDEX(LANDLOCK_ACCESS_NET_BIND_UDP)] = "net.bind_udp",
 	[BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_UDP)] = "net.connect_udp",
+	[BIT_INDEX(LANDLOCK_ACCESS_NET_SENDTO_UDP)] = "net.sendto_udp",
 };
 
 static_assert(ARRAY_SIZE(net_access_strings) == LANDLOCK_NUM_ACCESS_NET);
diff --git a/security/landlock/limits.h b/security/landlock/limits.h
index 13dd5503e471..b6d26bc5c49e 100644
--- a/security/landlock/limits.h
+++ b/security/landlock/limits.h
@@ -23,7 +23,7 @@
 #define LANDLOCK_MASK_ACCESS_FS		((LANDLOCK_LAST_ACCESS_FS << 1) - 1)
 #define LANDLOCK_NUM_ACCESS_FS		__const_hweight64(LANDLOCK_MASK_ACCESS_FS)
 
-#define LANDLOCK_LAST_ACCESS_NET	LANDLOCK_ACCESS_NET_CONNECT_UDP
+#define LANDLOCK_LAST_ACCESS_NET	LANDLOCK_ACCESS_NET_SENDTO_UDP
 #define LANDLOCK_MASK_ACCESS_NET	((LANDLOCK_LAST_ACCESS_NET << 1) - 1)
 #define LANDLOCK_NUM_ACCESS_NET		__const_hweight64(LANDLOCK_MASK_ACCESS_NET)
 
diff --git a/security/landlock/net.c b/security/landlock/net.c
index 9bddcf466ce9..061a531339de 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -121,6 +121,34 @@ static int current_check_access_socket(struct socket *const sock,
 				else
 					return -EAFNOSUPPORT;
 			}
+		} else if (access_request == LANDLOCK_ACCESS_NET_SENDTO_UDP) {
+			/*
+			 * We cannot allow LANDLOCK_ACCESS_NET_SENDTO_UDP on an
+			 * explicit AF_UNSPEC address. That's because semantics
+			 * of AF_UNSPEC change between socket families (e.g.
+			 * IPv6 treat it as "no address" in the sendmsg()
+			 * syscall family, so we should always allow, whilst
+			 * IPv4 treat it as AF_INET, so we should filter based
+			 * on port, and future address families might even do
+			 * something else), and the socket's family can change
+			 * under our feet due to setsockopt(IPV6_ADDRFORM).
+			 */
+			audit_net.family = AF_UNSPEC;
+			landlock_init_layer_masks(subject->domain,
+						  access_request, &layer_masks,
+						  LANDLOCK_KEY_NET_PORT);
+			landlock_log_denial(
+				subject,
+				&(struct landlock_request){
+					.type = LANDLOCK_REQUEST_NET_ACCESS,
+					.audit.type = LSM_AUDIT_DATA_NET,
+					.audit.u.net = &audit_net,
+					.access = access_request,
+					.layer_masks = &layer_masks,
+					.layer_masks_size =
+						ARRAY_SIZE(layer_masks),
+				});
+			return -EACCES;
 		} else {
 			WARN_ON_ONCE(1);
 		}
@@ -136,7 +164,8 @@ static int current_check_access_socket(struct socket *const sock,
 		port = addr4->sin_port;
 
 		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
-		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
+		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP ||
+		    access_request == LANDLOCK_ACCESS_NET_SENDTO_UDP) {
 			audit_net.dport = port;
 			audit_net.v4info.daddr = addr4->sin_addr.s_addr;
 		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
@@ -160,7 +189,8 @@ static int current_check_access_socket(struct socket *const sock,
 		port = addr6->sin6_port;
 
 		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
-		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
+		    access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP ||
+		    access_request == LANDLOCK_ACCESS_NET_SENDTO_UDP) {
 			audit_net.dport = port;
 			audit_net.v6info.daddr = addr6->sin6_addr;
 		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
@@ -248,9 +278,36 @@ static int hook_socket_connect(struct socket *const sock,
 					   access_request);
 }
 
+static int hook_socket_sendmsg(struct socket *const sock,
+			       struct msghdr *const msg, const int size)
+{
+	struct sockaddr *const address = msg->msg_name;
+	const int addrlen = msg->msg_namelen;
+	access_mask_t access_request;
+
+	/*
+	 * If there is no explicit address in the message, we have no
+	 * policy to enforce here because either:
+	 * - the socket has a remote address assigned, so the appropriate
+	 *   access check has already been done back then at assignment time;
+	 * - or, we can let the networking stack reply -EDESTADDRREQ.
+	 */
+	if (!address)
+		return 0;
+
+	if (sk_is_udp(sock->sk))
+		access_request = LANDLOCK_ACCESS_NET_SENDTO_UDP;
+	else
+		return 0;
+
+	return current_check_access_socket(sock, address, addrlen,
+					   access_request);
+}
+
 static struct security_hook_list landlock_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(socket_bind, hook_socket_bind),
 	LSM_HOOK_INIT(socket_connect, hook_socket_connect),
+	LSM_HOOK_INIT(socket_sendmsg, hook_socket_sendmsg),
 };
 
 __init void landlock_add_net_hooks(void)
-- 
2.47.3


^ permalink raw reply related


This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox