Skip to contentSkip to conversation

module: Introduce hash-based integrity checking

PATCH In review Thomas Weißschuh 7 participants 34 messages May 5 – Aug 4

Subsystems (11)
Documentation Kbuild BPF Crypto API +7 more subsystems
lore
Share & tools
lore
#0 lore raw

v5 cover module: Introduce hash-based integrity checking

The current signature-based module integrity checking has some drawbacks in combination with reproducible builds. Either the module signing key is generated at build time, which makes the build unreproducible, or a static signing key is used, which precludes rebuilds by third parties and makes the whole build and packaging process much more complicated.

The goal is to reach bit-for-bit reproducibility. Excluding certain parts of the build output from the reproducibility analysis would be error-prone and force each downstream consumer to introduce new tooling.

Introduce a new mechanism to ensure only well-known modules are loaded by embedding a merkle tree root of all modules built as part of the full kernel build into vmlinux.

Interest has been proclaimed by Arch Linux, Debian, Proxmox, SUSE, NixOS and the general reproducible builds community.

Compatibility with IMA modsig is not provided yet. It is still unclear to me if it should be hooked up transparently without any changes to the policy or it should require new policy options.

BPF/BTF folks, please take a look at patch 1.

Further improvements:
* Use MODULE_SIG_HASH for configuration
* UAPI for discovery?

To: Nathan Chancellor <[email protected]>
To: Nicolas Schier <[email protected]>
To: Arnd Bergmann <[email protected]>
To: Luis Chamberlain <[email protected]>
To: Petr Pavlu <[email protected]>
To: Sami Tolvanen <[email protected]>
To: Daniel Gomez <[email protected]>
To: Paul Moore <[email protected]>
To: James Morris <[email protected]>
To: Serge E. Hallyn <[email protected]>
To: Jonathan Corbet <[email protected]>
To: Madhavan Srinivasan <[email protected]>
To: Michael Ellerman <[email protected]>
To: Nicholas Piggin <[email protected]>
To: Christophe Leroy <[email protected]>
To: Naveen N Rao <[email protected]>
To: Mimi Zohar <[email protected]>
To: Roberto Sassu <[email protected]>
To: Dmitry Kasatkin <[email protected]>
To: Eric Snowberg <[email protected]>
To: Nicolas Schier <[email protected]>
To: Daniel Gomez <[email protected]>
To: Aaron Tomlin <[email protected]>
To: Christophe Leroy (CS GROUP) <[email protected]>
To: Nicolas Schier <[email protected]>
To: Nicolas Bouchinet <[email protected]>
To: Xiu Jianfeng <[email protected]>

---
Changes in v5:
- Document tree layout.
- Make scripts/module-merkle-tree more robust.
- Remove all changes to link-vmlinux.sh, use vmlinux.unstripped instead.
- Clean up types and logic in modules-merkle-tree.c.
- Use "auth" over "integrity" naming scheme.
- Reduce the changes to the existing authentication flow.
- Explicitly send the series to BTF folks for review of BTF changes.
- Link to v4: https://patch.msgid.link/[email protected]

Changes in v4:
- Use as Merkle tree over a linera list of hashes.
- Provide compatibilith with INSTALL_MOD_STRIP
- Rework commit messages.
- Use vmlinux.unstripped over plain "vmlinux".
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Rebase on v6.15-rc1
- Use openssl to calculate hash
- Avoid warning if no modules are built
- Simplify module_integrity_check() a bit
- Make incompatibility with INSTALL_MOD_STRIP explicit
- Update docs
- Add IMA cleanups
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Drop RFC state
- Mention interested parties in cover letter
- Expand Kconfig description
- Add compatibility with CONFIG_MODULE_SIG
- Parallelize module-hashes.sh
- Update Documentation/kbuild/reproducible-builds.rst
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Thomas Weißschuh (14):
kbuild: generate module BTF based on vmlinux.unstripped
lockdown: Make the relationship to MODULE_SIG a dependency
kbuild: rename the strip_relocs command
module: Drop pointless debugging message
module: Make mod_verify_sig() static
module: Switch load_info::len to size_t
module: Make module authentication usable without MODULE_SIG
module: Move authentication logic into dedicated new file
module: Move signature type check out of mod_check_sig()
module: Prepare for additional module authentication mechanisms
module: update timestamp of modules.order after modules are built
module: Introduce hash-based integrity checking
kbuild: move handling of module stripping to Makefile.lib
kbuild: make CONFIG_MODULE_HASHES compatible with module stripping

 .gitignore                                   |   2 +
 Documentation/kbuild/reproducible-builds.rst |   5 +-
 Makefile                                     |   7 +-
 crypto/algapi.c                              |   4 +-
 include/asm-generic/vmlinux.lds.h            |  11 +
 include/linux/module.h                       |  18 +-
 include/linux/module_hashes.h                |  29 ++
 include/uapi/linux/module_signature.h        |   1 +
 kernel/module/Kconfig                        |  29 +-
 kernel/module/Makefile                       |   2 +
 kernel/module/auth.c                         | 139 +++++++++
 kernel/module/hashes.c                       |  95 ++++++
 kernel/module/hashes_root.c                  |   6 +
 kernel/module/internal.h                     |  18 +-
 kernel/module/main.c                         |  16 +-
 kernel/module/signing.c                      | 113 +-------
 kernel/module_signature.c                    |   8 +-
 scripts/.gitignore                           |   1 +
 scripts/Makefile                             |   4 +
 scripts/Makefile.lib                         |  32 +++
 scripts/Makefile.modfinal                    |  28 +-
 scripts/Makefile.modinst                     |  44 +--
 scripts/Makefile.vmlinux                     |  40 ++-
 scripts/include/xalloc.h                     |  29 ++
 scripts/link-vmlinux.sh                      |   3 +-
 scripts/modules-merkle-tree.c                | 416 +++++++++++++++++++++++++++
 security/integrity/ima/ima_modsig.c          |   5 +
 security/lockdown/Kconfig                    |   2 +-
 tools/include/uapi/linux/module_signature.h  |   1 +
 29 files changed, 919 insertions(+), 189 deletions(-)

---
base-commit: 585c2e775b12ef45bdf9cef5f679dcb1220e0d65
change-id: 20241225-module-hashes-7a50a7cc2a30

Best regards,

Signature · 1 line
Thomas Weißschuh <[email protected]>
#1 lore raw

PATCH v5 1/14 kbuild: generate module BTF based on vmlinux.unstripped

The upcoming module hashes functionality will build the modules in between the generation of the BTF data and the final link of vmlinux. At this point vmlinux is not yet built and therefore can't be used for module BTF generation. vmlinux.unstripped however is usable and sufficient for BTF generation.

---
 scripts/Makefile.modfinal | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
scripts/Makefile.modfinal +7 -5
index adcbcde16a07..b09040ccddd2 100644
@@ -38,12 +38,14 @@ quiet_cmd_ld_ko_o = LD [M]  $@
 		$(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE)		\
 		-T $(objtree)/scripts/module.lds -o $@ $(filter %.o, $^)
 
+btf-vmlinux := $(if $(KBUILD_EXTMOD),vmlinux,vmlinux.unstripped)
+
 quiet_cmd_btf_ko = BTF [M] $@
       cmd_btf_ko = 							\
-	if [ ! -f $(objtree)/vmlinux ]; then				\
-		printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \
+	if [ ! -f $(objtree)/$(btf-vmlinux) ]; then				\
+		printf "Skipping BTF generation for %s due to unavailability of $(btf-vmlinux)\n" $@ 1>&2; \
 	else	\
-		$(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \
+		$(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/$(btf-vmlinux) $@; \
 	fi;
 
 # Same as newer-prereqs, but allows to exclude specified extra dependencies
@@ -55,8 +57,8 @@ if_changed_except = $(if $(call newer_prereqs_except,$(2))$(cmd-check),      \
 	printf '%s\n' 'savedcmd_$@ := $(make-cmd)' > $(dot-target).cmd, @:)
 
 # Re-generate module BTFs if either module's .ko or vmlinux changed
-%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/vmlinux) FORCE
-	+$(call if_changed_except,ld_ko_o,$(objtree)/vmlinux)
+%.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/$(btf-vmlinux)) FORCE
+	+$(call if_changed_except,ld_ko_o,$(objtree)/$(btf-vmlinux))
 ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 	+$(if $(newer-prereqs),$(call cmd,btf_ko))
 endif
Signature · 1 line
2.54.0
#2 lore raw

PATCH v5 2/14 lockdown: Make the relationship to MODULE_SIG a dependency

In reply to Thomas Weißschuh

The new hash-based module integrity checking will also be able to satisfy the requirements of lockdown.
Such an alternative is not representable with "select", so use "depends on" instead.

---
 security/lockdown/Kconfig | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
security/lockdown/Kconfig +1 -1
index e84ddf484010..155959205b8e 100644
@@ -1,7 +1,7 @@
 config SECURITY_LOCKDOWN_LSM
 	bool "Basic module for enforcing kernel lockdown"
 	depends on SECURITY
-	select MODULE_SIG if MODULES
+	depends on !MODULES || MODULE_SIG
 	help
 	  Build support for an LSM that enforces a coarse kernel lockdown
 	  behaviour.
Signature · 1 line
2.54.0
#3 lore raw

Re: [PATCH v5 02/14] lockdown: Make the relationship to MODULE_SIG a dependency

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Replacing `select` with `depends on` silently disables Kernel Lockdown…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Replacing select with depends on silently disables Kernel Lockdown (CONFIG_SECURITY_LOCKDOWN_LSM) in existing defconfigs. --

commit fc97135b538c64bfcbf058cc70c9665d00e5bb18
Author: Thomas Weißschuh <[email protected]>

lockdown: Make the relationship to MODULE_SIG a dependency

This commit changes the relationship between SECURITY_LOCKDOWN_LSM and MODULE_SIG from a select to a depends on. This is intended to allow for future hash-based module integrity checking alternatives.

security/lockdown/Kconfig line 4

Quoted 10 lines
security/lockdown/Kconfig +1 -1
index e84ddf4840101..155959205b8ea 100644
@@ -1,7 +1,7 @@
 config SECURITY_LOCKDOWN_LSM
 	bool "Basic module for enforcing kernel lockdown"
 	depends on SECURITY
-	select MODULE_SIG if MODULES
+	depends on !MODULES || MODULE_SIG

Will this change silently disable CONFIG_SECURITY_LOCKDOWN_LSM in existing defconfigs?

Because Kconfig's savedefconfig strips out automatically selected symbols, many in-tree defconfigs contain CONFIG_SECURITY_LOCKDOWN_LSM=y but omit CONFIG_MODULE_SIG=y. Since CONFIG_MODULE_SIG has no default y, it will initialize to n.

With CONFIG_MODULES=y and CONFIG_MODULE_SIG=n, this new dependency evaluates to n. As a result, Kconfig will drop CONFIG_SECURITY_LOCKDOWN_LSM from the final configuration without any warnings, leaving the kernel unprotected by lockdown. This also degrades discoverability, hiding the Lockdown LSM in menuconfig unless a user explicitly enables MODULE_SIG first.

Could this be handled with a conditional select instead to avoid breaking existing configurations while still supporting the upcoming MODULE_HASHES feature? For example:

select MODULE_SIG if MODULES && !MODULE_HASHES

Quoted 3 lines
security/lockdown/Kconfig +0 -0
 	help
 	  Build support for an LSM that enforces a coarse kernel lockdown
 	  behaviour.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#4 lore raw

Re: [PATCH v5 02/14] lockdown: Make the relationship to MODULE_SIG a dependency

Quoted 19 lines

security/lockdown/Kconfig line 4

Quoted 10 lines
security/lockdown/Kconfig +1 -1
index e84ddf4840101..155959205b8ea 100644
@@ -1,7 +1,7 @@
 config SECURITY_LOCKDOWN_LSM
 	bool "Basic module for enforcing kernel lockdown"
 	depends on SECURITY
-	select MODULE_SIG if MODULES
+	depends on !MODULES || MODULE_SIG

Will this change silently disable CONFIG_SECURITY_LOCKDOWN_LSM in existing defconfigs?

Because Kconfig's savedefconfig strips out automatically selected symbols, many in-tree defconfigs contain CONFIG_SECURITY_LOCKDOWN_LSM=y but omit CONFIG_MODULE_SIG=y. Since CONFIG_MODULE_SIG has no default y, it will initialize to n.

Quoted 5 lines

With CONFIG_MODULES=y and CONFIG_MODULE_SIG=n, this new dependency evaluates to n. As a result, Kconfig will drop CONFIG_SECURITY_LOCKDOWN_LSM from the final configuration without any warnings, leaving the kernel unprotected by lockdown. This also degrades discoverability, hiding the Lockdown LSM in menuconfig unless a user explicitly enables MODULE_SIG first.

I think the bot is correct, powerpc/configs/skiroot_defconfig, powerpc/configs/ppc64_defconfig, s390/configs/debug_defconfig and s390/configs/defconfig all set CONFIG_SECURITY_LOCKDOWN_LSM{,_EARLY}=y. They also set CONFIG_MODULE_SIG_FORCE=y but do not set CONFIG_MODULE_SIG directly. The new 'depends on' condition will thus evict CONFIG_SECURITY_LOCKDOWN_LSM{,_EARLY} from the generated .config.

Nicolas

#5 lore raw

PATCH v5 3/14 kbuild: rename the strip_relocs command

In reply to Thomas Weißschuh

This command is doing more than just stripping relocations. With the introduction of CONFIG_MODULE_HASHES it will do even more.

Use a more generic name for the variable.

---
 scripts/Makefile.vmlinux | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
scripts/Makefile.vmlinux +4 -4
index fcae1e432d9a..6cc661e5292b 100644
@@ -91,13 +91,13 @@ remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*'
 
 # To avoid warnings: "empty loadable segment detected at ..." from GNU objcopy,
 # it is necessary to remove the PT_LOAD flag from the segment.
-quiet_cmd_strip_relocs = OBJCOPY $@
-      cmd_strip_relocs = $(OBJCOPY) $(patsubst %,--set-section-flags %=noload,$(remove-section-y)) $< $@; \
-                         $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $@
+quiet_cmd_objcopy_vmlinux = OBJCOPY $@
+      cmd_objcopy_vmlinux = $(OBJCOPY) $(patsubst %,--set-section-flags %=noload,$(remove-section-y)) $< $@; \
+                            $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $@
 
 targets += vmlinux
 vmlinux: vmlinux.unstripped FORCE
-	$(call if_changed,strip_relocs)
+	$(call if_changed,objcopy_vmlinux)
 
 # modules.builtin.modinfo
 # ---------------------------------------------------------------------------
Signature · 1 line
2.54.0
#6 lore raw

PATCH v5 4/14 module: Drop pointless debugging message

In reply to Thomas Weißschuh

This is the only instance of pr_devel() in the whole module subsystem and essentially useless.

Drop it.

---
 kernel/module/signing.c | 2 --
 1 file changed, 2 deletions(-)
kernel/module/signing.c +0 -2
index 590ba29c85ab..4a5e4eef250d 100644
@@ -46,8 +46,6 @@ int mod_verify_sig(const void *mod, struct load_info *info)
 	size_t sig_len, modlen = info->len;
 	int ret;
 
-	pr_devel("==>%s(,%zu)\n", __func__, modlen);
-
 	if (modlen <= sizeof(ms))
 		return -EBADMSG;
 
Signature · 1 line
2.54.0
#7 lore raw

PATCH v5 5/14 module: Make mod_verify_sig() static

In reply to Thomas Weißschuh

It is not used outside of signing.c.

---
 kernel/module/internal.h | 1 -
 kernel/module/signing.c  | 2 +-
 2 files changed, 1 insertion(+), 2 deletions(-)
kernel/module/internal.h +0 -1
index 061161cc79d9..071999743341 100644
@@ -117,7 +117,6 @@ struct module_use {
 	struct module *source, *target;
 };
 
-int mod_verify_sig(const void *mod, struct load_info *info);
 int try_to_force_load(struct module *mod, const char *reason);
 bool find_symbol(struct find_symbol_arg *fsa);
 struct module *find_module_all(const char *name, size_t len, bool even_unformed);
kernel/module/signing.c +1 -1
index 4a5e4eef250d..69d4b1758540 100644
@@ -40,7 +40,7 @@ void set_module_sig_enforced(void)
 /*
  * Verify the signature on a module.
  */
-int mod_verify_sig(const void *mod, struct load_info *info)
+static int mod_verify_sig(const void *mod, struct load_info *info)
 {
 	struct module_signature ms;
 	size_t sig_len, modlen = info->len;
Signature · 1 line
2.54.0
#8 lore raw

PATCH v5 6/14 module: Switch load_info::len to size_t

In reply to Thomas Weißschuh

Switching the types will make some later changes cleaner. size_t is also the semantically correct type for this field.

As both 'size_t' and 'unsigned long' are always the same size, this should be risk-free.

---
 kernel/module/internal.h | 2 +-
 kernel/module/main.c     | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
kernel/module/internal.h +1 -1
index 071999743341..006ada7d4e6e 100644
@@ -64,7 +64,7 @@ struct load_info {
 	/* pointer to module in temporary copy, freed at end of load_module() */
 	struct module *mod;
 	Elf_Ehdr *hdr;
-	unsigned long len;
+	size_t len;
 	Elf_Shdr *sechdrs;
 	char *secstrings, *strtab;
 	unsigned long symoffs, stroffs, init_typeoffs, core_typeoffs;
kernel/module/main.c +1 -1
index 46dd8d25a605..17a352198016 100644
@@ -1898,7 +1898,7 @@ static int validate_section_offset(const struct load_info *info, Elf_Shdr *shdr)
 static int elf_validity_ehdr(const struct load_info *info)
 {
 	if (info->len < sizeof(*(info->hdr))) {
-		pr_err("Invalid ELF header len %lu\n", info->len);
+		pr_err("Invalid ELF header len %zu\n", info->len);
 		return -ENOEXEC;
 	}
 	if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
Signature · 1 line
2.54.0
maintainer
#9 lore raw

Re: [PATCH v5 06/14] module: Switch load_info::len to size_t

Quoted 1 line · Thomas Weißschuh

Switching the types will make some later changes cleaner.

Since the updated version drops the patch "module: Deduplicate signature extraction", I believe this change is no longer necessary.

Quoted 4 lines

size_t is also the semantically correct type for this field.

As both 'size_t' and 'unsigned long' are always the same size, this should be risk-free.

The module 'len' would now start in init_module() as 'unsigned long', then change in copy_module_from_user() to size_t, and then back to 'unsigned long' when calling copy_chunked_from_user(). The current code is more consistent and mostly uses 'unsigned long', matching the syscall interface.

Signature · 2 lines
Thanks,
Petr
#10 lore raw

Re: [PATCH v5 06/14] module: Switch load_info::len to size_t

Quoted 5 lines · Petr Pavlu
Quoted 1 line · Thomas Weißschuh

Switching the types will make some later changes cleaner.

Since the updated version drops the patch "module: Deduplicate signature extraction", I believe this change is no longer necessary.

Ack.

(...)

Thomas

#11 lore raw

PATCH v5 7/14 module: Make module authentication usable without MODULE_SIG

In reply to Thomas Weißschuh

The module authentication functionality will also be used by the hash-based module authentication. Split it out from CONFIG_MODULE_SIG so it is usable by both.

---
 crypto/algapi.c          |  4 ++--
 include/linux/module.h   | 18 +++++++++---------
 kernel/module/Kconfig    |  5 ++++-
 kernel/module/Makefile   |  1 +
 kernel/module/auth.c     | 32 ++++++++++++++++++++++++++++++++
 kernel/module/internal.h |  2 +-
 kernel/module/main.c     |  8 ++++----
 kernel/module/signing.c  | 23 +----------------------
 8 files changed, 54 insertions(+), 39 deletions(-)
crypto/algapi.c +2 -2
index 37de377719ae..14252b780266 100644
@@ -24,8 +24,8 @@ static LIST_HEAD(crypto_template_list);
 
 static inline void crypto_check_module_sig(struct module *mod)
 {
-	if (fips_enabled && mod && !module_sig_ok(mod))
-		panic("Module %s signature verification failed in FIPS mode\n",
+	if (fips_enabled && mod && !module_auth_ok(mod))
+		panic("Module %s authentication failed in FIPS mode\n",
 		      module_name(mod));
 }
 
include/linux/module.h +9 -9
index 7566815fabbe..b4760777daad 100644
@@ -437,9 +437,9 @@ struct module {
 	/* GPL-only exported symbols. */
 	bool using_gplonly_symbols;
 
-#ifdef CONFIG_MODULE_SIG
-	/* Signature was verified. */
-	bool sig_ok;
+#ifdef CONFIG_MODULE_AUTH
+	/* Module was authenticated. */
+	bool auth_ok;
 #endif
 
 	bool async_probe_requested;
@@ -918,16 +918,16 @@ static inline bool retpoline_module_ok(bool has_retpoline)
 }
 #endif
 
-#ifdef CONFIG_MODULE_SIG
+#ifdef CONFIG_MODULE_AUTH
 bool is_module_sig_enforced(void);
 
 void set_module_sig_enforced(void);
 
-static inline bool module_sig_ok(struct module *module)
+static inline bool module_auth_ok(struct module *module)
 {
-	return module->sig_ok;
+	return module->auth_ok;
 }
-#else	/* !CONFIG_MODULE_SIG */
+#else	/* !CONFIG_MODULE_AUTH */
 static inline bool is_module_sig_enforced(void)
 {
 	return false;
@@ -937,11 +937,11 @@ static inline void set_module_sig_enforced(void)
 {
 }
 
-static inline bool module_sig_ok(struct module *module)
+static inline bool module_auth_ok(struct module *module)
 {
 	return true;
 }
-#endif	/* CONFIG_MODULE_SIG */
+#endif	/* CONFIG_MODULE_AUTH */
 
 #if defined(CONFIG_MODULES) && defined(CONFIG_KALLSYMS)
 int module_kallsyms_on_each_symbol(const char *modname,
kernel/module/Kconfig +4 -1
index f535181e0d98..84297da666ff 100644
@@ -271,9 +271,12 @@ config MODULE_SIG
 	  debuginfo strip done by some packagers (such as rpmbuild) and
 	  inclusion into an initramfs that wants the module size reduced.
 
+config MODULE_AUTH
+	def_bool MODULE_SIG
+
 config MODULE_SIG_FORCE
 	bool "Require modules to be validly signed"
-	depends on MODULE_SIG
+	depends on MODULE_AUTH
 	help
 	  Reject unsigned modules or signed modules for which we don't have a
 	  key.  Without this, such modules will simply taint the kernel.
kernel/module/Makefile +1 -0
index d9e8759a7b05..c7200e293d04 100644
@@ -14,6 +14,7 @@ obj-y += strict_rwx.o
 obj-y += kmod.o
 obj-$(CONFIG_MODULE_DEBUG_AUTOLOAD_DUPS) += dups.o
 obj-$(CONFIG_MODULE_DECOMPRESS) += decompress.o
+obj-$(CONFIG_MODULE_AUTH) += auth.o
 obj-$(CONFIG_MODULE_SIG) += signing.o
 obj-$(CONFIG_LIVEPATCH) += livepatch.o
 obj-$(CONFIG_MODULES_TREE_LOOKUP) += tree_lookup.o
kernel/module/auth.c new file +32 -0
new file mode 100644
index 000000000000..956ac63d9d33
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/* Module authentication checker
+ *
+ * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
+ * Written by David Howells ([email protected])
+ */
+
+#include <linux/export.h>
+#include <linux/module.h>
+#include <linux/moduleparam.h>
+#include <linux/types.h>
+
+#undef MODULE_PARAM_PREFIX
+#define MODULE_PARAM_PREFIX "module."
+
+static bool sig_enforce = IS_ENABLED(CONFIG_MODULE_SIG_FORCE);
+module_param(sig_enforce, bool_enable_only, 0644);
+
+/*
+ * Export sig_enforce kernel cmdline parameter to allow other subsystems rely
+ * on that instead of directly to CONFIG_MODULE_SIG_FORCE config.
+ */
+bool is_module_sig_enforced(void)
+{
+	return sig_enforce;
+}
+EXPORT_SYMBOL(is_module_sig_enforced);
+
+void set_module_sig_enforced(void)
+{
+	sig_enforce = true;
+}
kernel/module/internal.h +1 -1
index 006ada7d4e6e..f8f425b167f1 100644
@@ -68,7 +68,7 @@ struct load_info {
 	Elf_Shdr *sechdrs;
 	char *secstrings, *strtab;
 	unsigned long symoffs, stroffs, init_typeoffs, core_typeoffs;
-	bool sig_ok;
+	bool auth_ok;
 #ifdef CONFIG_KALLSYMS
 	unsigned long mod_kallsyms_init_off;
 #endif
kernel/module/main.c +4 -4
index 17a352198016..cd8a74df117e 100644
@@ -2601,10 +2601,10 @@ static void module_augment_kernel_taints(struct module *mod, struct load_info *i
 				mod->name);
 		add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
 	}
-#ifdef CONFIG_MODULE_SIG
-	mod->sig_ok = info->sig_ok;
-	if (!mod->sig_ok) {
-		pr_notice_once("%s: module verification failed: signature "
+#ifdef CONFIG_MODULE_AUTH
+	mod->auth_ok = info->auth_ok;
+	if (!mod->auth_ok) {
+		pr_notice_once("%s: module authentication failed: signature "
 			       "and/or required key missing - tainting "
 			       "kernel\n", mod->name);
 		add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
kernel/module/signing.c +1 -22
index 69d4b1758540..07a786723221 100644
@@ -16,27 +16,6 @@
 #include <uapi/linux/module.h>
 #include "internal.h"
 
-#undef MODULE_PARAM_PREFIX
-#define MODULE_PARAM_PREFIX "module."
-
-static bool sig_enforce = IS_ENABLED(CONFIG_MODULE_SIG_FORCE);
-module_param(sig_enforce, bool_enable_only, 0644);
-
-/*
- * Export sig_enforce kernel cmdline parameter to allow other subsystems rely
- * on that instead of directly to CONFIG_MODULE_SIG_FORCE config.
- */
-bool is_module_sig_enforced(void)
-{
-	return sig_enforce;
-}
-EXPORT_SYMBOL(is_module_sig_enforced);
-
-void set_module_sig_enforced(void)
-{
-	sig_enforce = true;
-}
-
 /*
  * Verify the signature on a module.
  */
@@ -84,7 +63,7 @@ int module_sig_check(struct load_info *info, int flags)
 		info->len -= markerlen;
 		err = mod_verify_sig(mod, info);
 		if (!err) {
-			info->sig_ok = true;
+			info->auth_ok = true;
 			return 0;
 		}
 	}
Signature · 1 line
2.54.0
#12 lore raw

Re: [PATCH v5 07/14] module: Make module authentication usable without MODULE_SIG

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Misleading error message for generic authentication failures. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Misleading error message for generic authentication failures.
--

commit bd4ac969635e030618b66220b18c93b8a3a287e1
Author: Thomas Weißschuh <[email protected]>
Subject: module: Make module authentication usable without MODULE_SIG

This commit splits module authentication functionality out from CONFIG_MODULE_SIG into a more generic CONFIG_MODULE_AUTH. This change makes the authentication functionality usable by both signature-based and the upcoming hash-based module authentication.

Quoted 8 lines
kernel/module/main.c +0 -0
index 17a352198016a..cd8a74df117e7 100644
@@ -2601,10 +2601,10 @@ static void module_augment_kernel_taints(struct module *mod, struct load_info *i
 				mod->name);
 		add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
 	}

kernel/module/main.c static void module_augment_kernel_taints(struct module *mod, struct load_info *i · line 2609

Quoted 10 lines
kernel/module/main.c +4 -4
-#ifdef CONFIG_MODULE_SIG
-	mod->sig_ok = info->sig_ok;
-	if (!mod->sig_ok) {
-		pr_notice_once("%s: module verification failed: signature "
+#ifdef CONFIG_MODULE_AUTH
+	mod->auth_ok = info->auth_ok;
+	if (!mod->auth_ok) {
+		pr_notice_once("%s: module authentication failed: signature "
 			       "and/or required key missing - tainting "
 			       "kernel\n", mod->name);

Since this infrastructure is being generalized to support hash-based authentication, will this error message be misleading for modules that fail hash verification where no PKCS7 signature or key is involved?

Could this be updated to reflect a more generic authentication failure?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
maintainer
#13 lore raw

Re: [PATCH v5 07/14] module: Make module authentication usable without MODULE_SIG

In reply to Thomas Weißschuh
Quoted 14 lines · Thomas Weißschuh

The module authentication functionality will also be used by the hash-based module authentication. Split it out from CONFIG_MODULE_SIG so it is usable by both.

kernel/module/Kconfig +0 -0
index f535181e0d98..84297da666ff 100644
@@ -271,9 +271,12 @@ config MODULE_SIG
 	  debuginfo strip done by some packagers (such as rpmbuild) and
 	  inclusion into an initramfs that wants the module size reduced.
 

kernel/module/Kconfig config MODULE_SIG · line 282

Quoted 10 lines
kernel/module/Kconfig +4 -1
+config MODULE_AUTH
+	def_bool MODULE_SIG
+
 config MODULE_SIG_FORCE
 	bool "Require modules to be validly signed"
-	depends on MODULE_SIG
+	depends on MODULE_AUTH
 	help
 	  Reject unsigned modules or signed modules for which we don't have a
 	  key.  Without this, such modules will simply taint the kernel.

Should MODULE_SIG_FORCE be renamed to MODULE_AUTH_FORCE, along with renaming the sig_enforce functionality in kernel/module/auth.c to auth_enforce?

Signature · 2 lines
Thanks,
Petr
#14 lore raw

Re: [PATCH v5 07/14] module: Make module authentication usable without MODULE_SIG

Quoted 15 lines · Petr Pavlu
Quoted 14 lines · Thomas Weißschuh

The module authentication functionality will also be used by the hash-based module authentication. Split it out from CONFIG_MODULE_SIG so it is usable by both.

kernel/module/Kconfig +0 -0
index f535181e0d98..84297da666ff 100644
@@ -271,9 +271,12 @@ config MODULE_SIG
 	  debuginfo strip done by some packagers (such as rpmbuild) and
 	  inclusion into an initramfs that wants the module size reduced.
 
Quoted 14 lines

kernel/module/Kconfig config MODULE_SIG · line 282

Quoted 10 lines
kernel/module/Kconfig +4 -1
+config MODULE_AUTH
+	def_bool MODULE_SIG
+
 config MODULE_SIG_FORCE
 	bool "Require modules to be validly signed"
-	depends on MODULE_SIG
+	depends on MODULE_AUTH
 	help
 	  Reject unsigned modules or signed modules for which we don't have a
 	  key.  Without this, such modules will simply taint the kernel.

Should MODULE_SIG_FORCE be renamed to MODULE_AUTH_FORCE, along with renaming the sig_enforce functionality in kernel/module/auth.c to auth_enforce?

Given that it is a user-visible symbol we'll need to be a bit careful not to break existing configurations.
I'll try to use the new "transitional" kconfig attribute.

Thomas

#15 lore raw

Re: [PATCH v5 07/14] module: Make module authentication usable without MODULE_SIG

Quoted 8 lines · Thomas Weißschuh
Quoted 3 lines · Petr Pavlu

Should MODULE_SIG_FORCE be renamed to MODULE_AUTH_FORCE, along with renaming the sig_enforce functionality in kernel/module/auth.c to auth_enforce?

Given that it is a user-visible symbol we'll need to be a bit careful not to break existing configurations.
I'll try to use the new "transitional" kconfig attribute.

A slightly softer worded alternative (yet semantically equivalent) name could be MODULE_AUTH_REQUIRE. No strong opinion though, I think MODULE_AUTH_* does make sense.

I initially shared the concern about renaming well established config options, but the transitional feature does seem to be a good fit for this.

Sincerely,
kpcyrd

#16 lore raw

PATCH v5 8/14 module: Move authentication logic into dedicated new file

In reply to Thomas Weißschuh

The module authentication functionality will also be used by the hash-based module authentication. To make it usable even if CONFIG_MODULE_SIG is disabled, move it to a new file.

---
 kernel/module/auth.c     | 85 +++++++++++++++++++++++++++++++++++++++++++++
 kernel/module/internal.h | 14 ++++++--
 kernel/module/main.c     |  6 ++--
 kernel/module/signing.c  | 90 ++----------------------------------------------
 4 files changed, 103 insertions(+), 92 deletions(-)
kernel/module/auth.c +85 -0
index 956ac63d9d33..831a13eb0c9b 100644
@@ -5,10 +5,16 @@
  * Written by David Howells ([email protected])
  */
 
+#include <linux/errno.h>
 #include <linux/export.h>
 #include <linux/module.h>
+#include <linux/module_signature.h>
 #include <linux/moduleparam.h>
+#include <linux/security.h>
+#include <linux/string.h>
 #include <linux/types.h>
+#include <uapi/linux/module.h>
+#include "internal.h"
 
 #undef MODULE_PARAM_PREFIX
 #define MODULE_PARAM_PREFIX "module."
@@ -30,3 +36,82 @@ void set_module_sig_enforced(void)
 {
 	sig_enforce = true;
 }
+
+static int mod_verify_sig(const void *mod, struct load_info *info)
+{
+	struct module_signature ms;
+	size_t sig_len, modlen = info->len;
+	int ret;
+
+	if (modlen <= sizeof(ms))
+		return -EBADMSG;
+
+	memcpy(&ms, mod + (modlen - sizeof(ms)), sizeof(ms));
+
+	ret = mod_check_sig(&ms, modlen, "module");
+	if (ret)
+		return ret;
+
+	sig_len = be32_to_cpu(ms.sig_len);
+	modlen -= sig_len + sizeof(ms);
+	info->len = modlen;
+
+	return module_sig_check(mod, modlen, mod + modlen, sig_len);
+}
+
+int module_auth_check(struct load_info *info, int flags)
+{
+	int err = -ENODATA;
+	const unsigned long markerlen = sizeof(MODULE_SIGNATURE_MARKER) - 1;
+	const char *reason;
+	const void *mod = info->hdr;
+	bool mangled_module = flags & (MODULE_INIT_IGNORE_MODVERSIONS |
+				       MODULE_INIT_IGNORE_VERMAGIC);
+	/*
+	 * Do not allow mangled modules as a module with version information
+	 * removed is no longer the module that was signed.
+	 */
+	if (!mangled_module &&
+	    info->len > markerlen &&
+	    memcmp(mod + info->len - markerlen, MODULE_SIGNATURE_MARKER, markerlen) == 0) {
+		/* We truncate the module to discard the signature */
+		info->len -= markerlen;
+		err = mod_verify_sig(mod, info);
+		if (!err) {
+			info->auth_ok = true;
+			return 0;
+		}
+	}
+
+	/*
+	 * We don't permit modules to be loaded into the trusted kernels
+	 * without a valid signature on them, but if we're not enforcing,
+	 * certain errors are non-fatal.
+	 */
+	switch (err) {
+	case -ENODATA:
+		reason = "unsigned module";
+		break;
+	case -ENOPKG:
+		reason = "module with unsupported crypto";
+		break;
+	case -ENOKEY:
+		reason = "module with unavailable key";
+		break;
+
+	default:
+		/*
+		 * All other errors are fatal, including lack of memory,
+		 * unparseable signatures, and signature check failures --
+		 * even if signatures aren't required.
+		 */
+		return err;
+	}
+
+	if (is_module_sig_enforced()) {
+		pr_notice("Loading of %s is rejected\n", reason);
+		return -EKEYREJECTED;
+	}
+
+	return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
+}
kernel/module/internal.h +12 -2
index f8f425b167f1..d923e31a5d8e 100644
@@ -336,14 +336,24 @@ void module_mark_ro_after_init(const Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
 			       const char *secstrings);
 
 #ifdef CONFIG_MODULE_SIG
-int module_sig_check(struct load_info *info, int flags);
+int module_sig_check(const void *mod, size_t mod_len, const void *sig, size_t sig_len);
 #else /* !CONFIG_MODULE_SIG */
-static inline int module_sig_check(struct load_info *info, int flags)
+static inline int module_sig_check(const void *mod, size_t mod_len,
+				   const void *sig, size_t sig_len)
 {
 	return 0;
 }
 #endif /* !CONFIG_MODULE_SIG */
 
+#ifdef CONFIG_MODULE_AUTH
+int module_auth_check(struct load_info *info, int flags);
+#else /* !CONFIG_MODULE_AUTH */
+static inline int module_auth_check(struct load_info *info, int flags)
+{
+	return 0;
+}
+#endif /* !CONFIG_MODULE_AUTH */
+
 #ifdef CONFIG_DEBUG_KMEMLEAK
 void kmemleak_load_module(const struct module *mod, const struct load_info *info);
 #else /* !CONFIG_DEBUG_KMEMLEAK */
kernel/module/main.c +3 -3
index cd8a74df117e..55a010383a8d 100644
@@ -3428,8 +3428,8 @@ static int load_module(struct load_info *info, const char __user *uargs,
 	char *after_dashes;
 
 	/*
-	 * Do the signature check (if any) first. All that
-	 * the signature check needs is info->len, it does
+	 * Do the authentication checks (if any) first. All that
+	 * the authentication checks need is info->len, it does
 	 * not need any of the section info. That can be
 	 * set up later. This will minimize the chances
 	 * of a corrupt module causing problems before
@@ -3439,7 +3439,7 @@ static int load_module(struct load_info *info, const char __user *uargs,
 	 * off the sig length at the end of the module, making
 	 * checks against info->len more correct.
 	 */
-	err = module_sig_check(info, flags);
+	err = module_auth_check(info, flags);
 	if (err)
 		goto free_copy;
 
kernel/module/signing.c +3 -87

101 lines not on this page · raw message

Signature · 1 line
2.54.0
maintainer Reviewed-by on v5 8/14
#17 lore raw

Re: [PATCH v5 08/14] module: Move authentication logic into dedicated new file

Quoted 101 lines · Thomas Weißschuh

The module authentication functionality will also be used by the hash-based module authentication. To make it usable even if CONFIG_MODULE_SIG is disabled, move it to a new file.

---
[...]

kernel/module/auth.c +75 -0
index 956ac63d9d33..831a13eb0c9b 100644
@@ -5,10 +5,16 @@
  * Written by David Howells ([email protected])
  */
 
+#include <linux/errno.h>
 #include <linux/export.h>
 #include <linux/module.h>
+#include <linux/module_signature.h>
 #include <linux/moduleparam.h>
+#include <linux/security.h>
+#include <linux/string.h>
 #include <linux/types.h>
+#include <uapi/linux/module.h>
+#include "internal.h"
 
 #undef MODULE_PARAM_PREFIX
 #define MODULE_PARAM_PREFIX "module."
@@ -30,3 +36,82 @@ void set_module_sig_enforced(void)
 {
 	sig_enforce = true;
 }
+
+static int mod_verify_sig(const void *mod, struct load_info *info)
+{
+	struct module_signature ms;
+	size_t sig_len, modlen = info->len;
+	int ret;
+
+	if (modlen <= sizeof(ms))
+		return -EBADMSG;
+
+	memcpy(&ms, mod + (modlen - sizeof(ms)), sizeof(ms));
+
+	ret = mod_check_sig(&ms, modlen, "module");
+	if (ret)
+		return ret;
+
+	sig_len = be32_to_cpu(ms.sig_len);
+	modlen -= sig_len + sizeof(ms);
+	info->len = modlen;
+
+	return module_sig_check(mod, modlen, mod + modlen, sig_len);
+}
+
+int module_auth_check(struct load_info *info, int flags)
+{
+	int err = -ENODATA;
+	const unsigned long markerlen = sizeof(MODULE_SIGNATURE_MARKER) - 1;
+	const char *reason;
+	const void *mod = info->hdr;
+	bool mangled_module = flags & (MODULE_INIT_IGNORE_MODVERSIONS |
+				       MODULE_INIT_IGNORE_VERMAGIC);
+	/*
+	 * Do not allow mangled modules as a module with version information
+	 * removed is no longer the module that was signed.
+	 */
+	if (!mangled_module &&
+	    info->len > markerlen &&
+	    memcmp(mod + info->len - markerlen, MODULE_SIGNATURE_MARKER, markerlen) == 0) {
+		/* We truncate the module to discard the signature */
+		info->len -= markerlen;
+		err = mod_verify_sig(mod, info);
+		if (!err) {
+			info->auth_ok = true;
+			return 0;
+		}
+	}
+
+	/*
+	 * We don't permit modules to be loaded into the trusted kernels
+	 * without a valid signature on them, but if we're not enforcing,
+	 * certain errors are non-fatal.
+	 */
+	switch (err) {
+	case -ENODATA:
+		reason = "unsigned module";
+		break;
+	case -ENOPKG:
+		reason = "module with unsupported crypto";
+		break;
+	case -ENOKEY:
+		reason = "module with unavailable key";
+		break;
+
+	default:
+		/*
+		 * All other errors are fatal, including lack of memory,
+		 * unparseable signatures, and signature check failures --
+		 * even if signatures aren't required.
+		 */

kernel/module/auth.c void set_module_sig_enforced(void) · line 117

Quoted 10 lines
kernel/module/auth.c +10 -0
+		return err;
+	}
+
+	if (is_module_sig_enforced()) {
+		pr_notice("Loading of %s is rejected\n", reason);
+		return -EKEYREJECTED;
+	}
+
+	return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
+}

The resulting call chain of the module authentication/signature functions is as follows:

ima_read_modsig() -----------------------------,
v
module_auth_check() -> mod_verify_sig() -> mod_check_sig()

                             |
                             |-> module_sig_check()
                             '-> module_hash_check()

I think this logic is quite hard to follow because mod_verify_sig(), mod_check_sig() and module_sig_check() have very similar names.

The naming of module_auth_check(), module_sig_check() and module_hash_check() looks good to me, but I would prefer to rename mod_check_sig() and mod_verify_sig(). Perhaps mod_check_sig() could be renamed to mod_check_sig_header(), and mod_verify_sig() to mod_dispatch_auth_check()?

Otherwise, the patch looks ok to me. Feel free to add:

Signature · 2 lines
Thanks,
Petr
#18 lore raw

PATCH v5 9/14 module: Move signature type check out of mod_check_sig()

In reply to Thomas Weißschuh

Additional signature types are about to be added.
As each caller of mod_check_sig() can have different support for these, move the type validation into the callers.

---
 kernel/module/auth.c                | 5 +++++
 kernel/module_signature.c           | 8 +-------
 security/integrity/ima/ima_modsig.c | 5 +++++
 3 files changed, 11 insertions(+), 7 deletions(-)
kernel/module/auth.c +5 -0
index 831a13eb0c9b..21e49eb4967c 100644
@@ -48,6 +48,11 @@ static int mod_verify_sig(const void *mod, struct load_info *info)
 
 	memcpy(&ms, mod + (modlen - sizeof(ms)), sizeof(ms));
 
+	if (ms.id_type != MODULE_SIGNATURE_TYPE_PKCS7) {
+		pr_err("module: not signed with expected PKCS#7 message\n");
+		return -ENOPKG;
+	}
+
 	ret = mod_check_sig(&ms, modlen, "module");
 	if (ret)
 		return ret;
kernel/module_signature.c +1 -7
index a0eee2fe4368..4d0476bcdb72 100644
@@ -24,12 +24,6 @@ int mod_check_sig(const struct module_signature *ms, size_t file_len,
 	if (be32_to_cpu(ms->sig_len) >= file_len - sizeof(*ms))
 		return -EBADMSG;
 
-	if (ms->id_type != MODULE_SIGNATURE_TYPE_PKCS7) {
-		pr_err("%s: not signed with expected PKCS#7 message\n",
-		       name);
-		return -ENOPKG;
-	}
-
 	if (ms->algo != 0 ||
 	    ms->hash != 0 ||
 	    ms->signer_len != 0 ||
@@ -37,7 +31,7 @@ int mod_check_sig(const struct module_signature *ms, size_t file_len,
 	    ms->__pad[0] != 0 ||
 	    ms->__pad[1] != 0 ||
 	    ms->__pad[2] != 0) {
-		pr_err("%s: PKCS#7 signature info has unexpected non-zero params\n",
+		pr_err("%s: signature info has unexpected non-zero params\n",
 		       name);
 		return -EBADMSG;
 	}
security/integrity/ima/ima_modsig.c +5 -0
index 632c746fd81e..ebfcdd368a2a 100644
@@ -57,6 +57,11 @@ int ima_read_modsig(enum ima_hooks func, const void *buf, loff_t buf_len,
 	buf_len -= marker_len;
 	sig = (const struct module_signature *)(p - sizeof(*sig));
 
+	if (sig->id_type != MODULE_SIGNATURE_TYPE_PKCS7) {
+		pr_err("%s: not signed with expected PKCS#7 message\n", func_tokens[func]);
+		return -ENOPKG;
+	}
+
 	rc = mod_check_sig(sig, buf_len, func_tokens[func]);
 	if (rc)
 		return rc;
Signature · 1 line
2.54.0
maintainer Reviewed-by on v5 9/14
#19 lore raw

Re: [PATCH v5 09/14] module: Move signature type check out of mod_check_sig()

Quoted 5 lines · Thomas Weißschuh

Additional signature types are about to be added.
As each caller of mod_check_sig() can have different support for these, move the type validation into the callers.

-- Petr

#20 lore raw

PATCH v5 10/14 module: Prepare for additional module authentication mechanisms

In reply to Thomas Weißschuh

Reorganize the code to make it easier to add the new hash-based module authentication.

Also drop the now unnecessary stub for module_sig_check().

---
 kernel/module/auth.c     | 17 ++++++++++++++---
 kernel/module/internal.h |  8 --------
 2 files changed, 14 insertions(+), 11 deletions(-)
kernel/module/auth.c +14 -3
index 21e49eb4967c..2ee512d26790 100644
@@ -37,6 +37,14 @@ void set_module_sig_enforced(void)
 	sig_enforce = true;
 }
 
+static __always_inline bool mod_sig_type_valid(enum module_signature_type id_type)
+{
+	if (id_type == MODULE_SIGNATURE_TYPE_PKCS7 && IS_ENABLED(CONFIG_MODULE_SIG))
+		return true;
+
+	return false;
+}
+
 static int mod_verify_sig(const void *mod, struct load_info *info)
 {
 	struct module_signature ms;
@@ -48,8 +56,8 @@ static int mod_verify_sig(const void *mod, struct load_info *info)
 
 	memcpy(&ms, mod + (modlen - sizeof(ms)), sizeof(ms));
 
-	if (ms.id_type != MODULE_SIGNATURE_TYPE_PKCS7) {
-		pr_err("module: not signed with expected PKCS#7 message\n");
+	if (!mod_sig_type_valid(ms.id_type)) {
+		pr_err("module: not signed with expected signature\n");
 		return -ENOPKG;
 	}
 
@@ -61,7 +69,10 @@ static int mod_verify_sig(const void *mod, struct load_info *info)
 	modlen -= sig_len + sizeof(ms);
 	info->len = modlen;
 
-	return module_sig_check(mod, modlen, mod + modlen, sig_len);
+	if (ms.id_type == MODULE_SIGNATURE_TYPE_PKCS7 && IS_ENABLED(CONFIG_MODULE_SIG))
+		return module_sig_check(mod, modlen, mod + modlen, sig_len);
+
+	return 0;
 }
 
 int module_auth_check(struct load_info *info, int flags)
kernel/module/internal.h +0 -8
index d923e31a5d8e..aabe7f8e1af4 100644
@@ -335,15 +335,7 @@ int module_enforce_rwx_sections(const Elf_Ehdr *hdr, const Elf_Shdr *sechdrs,
 void module_mark_ro_after_init(const Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
 			       const char *secstrings);
 
-#ifdef CONFIG_MODULE_SIG
 int module_sig_check(const void *mod, size_t mod_len, const void *sig, size_t sig_len);
-#else /* !CONFIG_MODULE_SIG */
-static inline int module_sig_check(const void *mod, size_t mod_len,
-				   const void *sig, size_t sig_len)
-{
-	return 0;
-}
-#endif /* !CONFIG_MODULE_SIG */
 
 #ifdef CONFIG_MODULE_AUTH
 int module_auth_check(struct load_info *info, int flags);
Signature · 1 line
2.54.0
maintainer Reviewed-by on v5 10/14
#21 lore raw

Re: [PATCH v5 10/14] module: Prepare for additional module authentication mechanisms

Quoted 6 lines · Thomas Weißschuh

Reorganize the code to make it easier to add the new hash-based module authentication.

Also drop the now unnecessary stub for module_sig_check().

-- Petr

#22 lore raw

PATCH v5 11/14 module: update timestamp of modules.order after modules are built

In reply to Thomas Weißschuh

Make sure that modules.order is always newer than the module .ko files. Other rules can then use modules.order as a prerequisite and rerun if any module is (re-)built.

---
 scripts/Makefile.modfinal | 7 +++++++
 1 file changed, 7 insertions(+)
scripts/Makefile.modfinal +7 -0
index b09040ccddd2..44a382689a5a 100644
@@ -66,6 +66,13 @@ endif
 
 targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
 
+# Update modules.order when a module is (re-)built.
+# Allow using it as target dependency.
+targets += modules.order
+__modfinal: modules.order
+modules.order: $(modules:%.o=%.ko)
+	@touch $@
+
 # Add FORCE to the prerequisites of a target to force it to be always rebuilt.
 # ---------------------------------------------------------------------------
 
Signature · 1 line
2.54.0
#23 lore raw

Re: [PATCH v5 11/14] module: update timestamp of modules.order after modules are built

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Touching `modules.order` in `Makefile.modfinal` causes unnecessary rebuilds of `Module.symvers` on…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Touching modules.order in Makefile.modfinal causes unnecessary rebuilds of Module.symvers on subsequent make invocations. --

commit c15348209a95736a85efe8f0905f610fb5def492
Author: Thomas Weißschuh <[email protected]>

module: update timestamp of modules.order after modules are built

This commit ensures modules.order is always newer than the module .ko files by touching it after modules are built, allowing other rules to use it as a prerequisite.

Quoted 5 lines
scripts/Makefile.modfinal +0 -0
index b09040ccddd2b..44a382689a5aa 100644

scripts/Makefile.modfinal endif · line 74

Quoted 9 lines
scripts/Makefile.modfinal +6 -0
@@ -66,6 +66,13 @@ endif
 
 targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
 
+# Update modules.order when a module is (re-)built.
+# Allow using it as target dependency.
+targets += modules.order
+__modfinal: modules.order
+modules.order: $(modules:%.o=%.ko)
+	@touch $@

Does this cause an unnecessary rebuild of Module.symvers on subsequent make invocations?

In scripts/Makefile.modpost, Module.symvers depends on modules.order. During a build, Makefile.modpost is executed strictly before Makefile.modfinal.

When a module is rebuilt, touching modules.order here updates its modification time to be newer than the previously generated Module.symvers. On the next make invocation, even without source changes, Makefile.modpost will see modules.order as newer than Module.symvers.

Will this trigger modpost to execute unnecessarily, degrading incremental build performance by forcing an extra settling build to reach a clean state?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#24 lore raw

PATCH v5 12/14 module: Introduce hash-based integrity checking

In reply to Thomas Weißschuh

The current signature-based module integrity checking has some drawbacks in combination with reproducible builds. Either the module signing key is generated at build time, which makes the build unreproducible, or a static signing key is used, which precludes rebuilds by third parties and makes the whole build and packaging process much more complicated.

The goal is to reach bit-for-bit reproducibility. Excluding certain parts of the build output from the reproducibility analysis would be error-prone and force each downstream consumer to introduce new tooling.

Introduce a new mechanism to ensure only well-known modules are loaded by embedding a merkle tree root of all modules built as part of the full kernel build into vmlinux.

Out-of-tree modules can be validated as before through signatures.

Normally the .ko module files depend on a fully built vmlinux to be available for modpost validation and BTF generation. With CONFIG_MODULE_HASHES, vmlinux now depends on the modules
to build a merkle tree. This introduces a dependency cycle which is impossible to satisfy. Work around this by building the modules during link-vmlinux.sh, after vmlinux is complete enough for modpost and BTF but before the final module hashes are

The PKCS7 format which is used for regular module signatures can not represent Merkle proofs, so a new kind of module signature is introduced. As this signature type is only ever used for builtin modules, no compatibility issues can arise.

---
 .gitignore                                   |   1 +
 Documentation/kbuild/reproducible-builds.rst |   5 +-
 Makefile                                     |   7 +-
 include/asm-generic/vmlinux.lds.h            |  11 +
 include/linux/module_hashes.h                |  29 ++
 include/uapi/linux/module_signature.h        |   1 +
 kernel/module/Kconfig                        |  21 +-
 kernel/module/Makefile                       |   1 +
 kernel/module/auth.c                         |   6 +
 kernel/module/hashes.c                       |  95 ++++++
 kernel/module/hashes_root.c                  |   6 +
 kernel/module/internal.h                     |   1 +
 scripts/.gitignore                           |   1 +
 scripts/Makefile                             |   4 +
 scripts/Makefile.modinst                     |  11 +
 scripts/Makefile.vmlinux                     |  32 +++
 scripts/include/xalloc.h                     |  29 ++
 scripts/link-vmlinux.sh                      |   3 +-
 scripts/modules-merkle-tree.c                | 416 +++++++++++++++++++++++++++
 security/lockdown/Kconfig                    |   2 +-
 tools/include/uapi/linux/module_signature.h  |   1 +
 21 files changed, 677 insertions(+), 6 deletions(-)
.gitignore +1 -0
index 3044b9590f05..78cf799401e6 100644
@@ -36,6 +36,7 @@
 *.lz4
 *.lzma
 *.lzo
+*.merkle
 *.mod
 *.mod.c
 *.o
Documentation/kbuild/reproducible-builds.rst +4 -1
index bc1eb82211df..b15019678aae 100644
@@ -84,7 +84,10 @@ generate a different temporary key for each build, resulting in the
 modules being unreproducible.  However, including a signing key with
 your source would presumably defeat the purpose of signing modules.
 
-One approach to this is to divide up the build process so that the
+Instead ``CONFIG_MODULE_HASHES`` can be used to embed a static list
+of valid modules to load.
+
+Another approach to this is to divide up the build process so that the
 unreproducible parts can be treated as sources:
 
 1. Generate a persistent signing key.  Add the certificate for the key
Makefile +6 -1
index e27c91ea56fc..def4a2413c43 100644
@@ -1650,7 +1650,9 @@ ifdef CONFIG_MODULES
 
 # By default, build modules as well
 
+ifndef CONFIG_MODULE_HASHES
 all: modules
+endif
 
 # When we're building modules with modversions, we need to consider
 # the built-in objects during the descend as well, in order to
@@ -1666,8 +1668,10 @@ endif
 # is an exception.
 ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 KBUILD_BUILTIN := y
+ifndef CONFIG_MODULE_HASHES
 modules: vmlinux
 endif
+endif
 
 modules: modules_prepare
 
@@ -2068,7 +2072,7 @@ modules.order: $(build-dir)
 # KBUILD_MODPOST_NOFINAL can be set to skip the final link of modules.
 # This is solely useful to speed up test compiles.
 modules: modpost
-ifneq ($(KBUILD_MODPOST_NOFINAL),1)
+ifneq ($(CONFIG_MODULE_HASHES)|$(KBUILD_MODPOST_NOFINAL),|1)
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modfinal
 endif
 
@@ -2162,6 +2166,7 @@ clean: $(clean-dirs)
 		-o -name '*.c.[012]*.*' \
 		-o -name '*.ll' \
 		-o -name '*.gcno' \
+		-o -name '*.merkle' \
 		\) -type f -print \
 		-o -name '.tmp_*' -print \
 		| xargs rm -rf
include/asm-generic/vmlinux.lds.h +11 -0
index 60c8c22fd3e4..661881e5ef96 100644
@@ -508,6 +508,8 @@
 									\
 	PRINTK_INDEX							\
 									\
+	MODULE_HASHES							\
+									\
 	/* Kernel symbol table */					\
 	__ksymtab         : AT(ADDR(__ksymtab) - LOAD_OFFSET) {		\
 		__start___ksymtab = .;					\
@@ -913,6 +915,15 @@
 #define PRINTK_INDEX
 #endif
 
+#ifdef CONFIG_MODULE_HASHES
+#define MODULE_HASHES							\
+	.module_hashes : AT(ADDR(.module_hashes) - LOAD_OFFSET) {	\
+		KEEP(*(SORT(.module_hashes)))				\
+	}
+#else
+#define MODULE_HASHES
+#endif
+
 /*
  * Discard .note.GNU-stack, which is emitted as PROGBITS by the compiler.
  * Otherwise, the type of .notes section would become PROGBITS instead of NOTES.
include/linux/module_hashes.h new file +29 -0
new file mode 100644
index 000000000000..53b34fa12f2d
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#ifndef _LINUX_MODULE_HASHES_H
+#define _LINUX_MODULE_HASHES_H
+
+#include <linux/compiler_attributes.h>
+#include <linux/types.h>
+#include <crypto/sha2.h>
+
+#define __module_hashes_section __section(".module_hashes")
+#define MODULE_HASHES_HASH_SIZE SHA256_DIGEST_SIZE
+
+struct module_hash {
+	u8 h[MODULE_HASHES_HASH_SIZE];
+};
+
+struct module_hashes_proof {
+	__be32 pos;
+	struct module_hash hash_sigs[];
+} __packed;
+
+struct module_hashes_root {
+	u32 levels;
+	struct module_hash hash;
+};
+
+extern const struct module_hashes_root module_hashes_root;
+
+#endif /* _LINUX_MODULE_HASHES_H */
include/uapi/linux/module_signature.h +1 -0
index 634c9f1c8fc2..78e206996eed 100644
@@ -16,6 +16,7 @@
 
 enum module_signature_type {
 	MODULE_SIGNATURE_TYPE_PKCS7 = 2,	/* Signature in PKCS#7 message */
+	MODULE_SIGNATURE_TYPE_MERKLE = 3,	/* Merkle proof for modules, opaque structure */
 };
 
 /*
kernel/module/Kconfig +19 -2
index 84297da666ff..acbbda58e7c8 100644
@@ -272,7 +272,7 @@ config MODULE_SIG
 	  inclusion into an initramfs that wants the module size reduced.
 
 config MODULE_AUTH
-	def_bool MODULE_SIG
+	def_bool MODULE_SIG || MODULE_HASHES
 
 config MODULE_SIG_FORCE
 	bool "Require modules to be validly signed"
@@ -291,7 +291,7 @@ config MODULE_SIG_ALL
 	  modules must be signed manually, using the scripts/sign-file tool.
 
 comment "Do not forget to sign required modules with scripts/sign-file"
-	depends on MODULE_SIG_FORCE && !MODULE_SIG_ALL
+	depends on MODULE_SIG_FORCE && !MODULE_SIG_ALL && !MODULE_HASHES
 
 choice
 	prompt "Hash algorithm to sign modules"
@@ -406,6 +406,23 @@ config MODULE_DECOMPRESS
 
 endif # MODULE_COMPRESS
 
+config MODULE_HASHES
+	bool "Hash-based module authentication"
+	depends on !MODULE_SIG_ALL
+	depends on !IMA_APPRAISE_MODSIG
+	select MODULE_SIG_FORMAT
+	select CRYPTO_LIB_SHA256
+	help
+	  Validate modules by their hashes.
+	  Only modules built together with the main kernel image can be
+	  validated that way.
+
+	  This is a reproducible-build compatible alternative to a build-time
+	  generated module keyring, as enabled by
+	  CONFIG_MODULE_SIG_KEY=certs/signing_key.pem.
+
+	  Also see the warning in MODULE_SIG about stripping modules.
+
 config MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
 	bool "Allow loading of modules with missing namespace imports"
 	help
kernel/module/Makefile +1 -0
index c7200e293d04..da9420f140e9 100644
@@ -26,3 +26,4 @@ obj-$(CONFIG_KGDB_KDB) += kdb.o
 obj-$(CONFIG_MODVERSIONS) += version.o
 obj-$(CONFIG_MODULE_UNLOAD_TAINT_TRACKING) += tracking.o
 obj-$(CONFIG_MODULE_STATS) += stats.o
+obj-$(CONFIG_MODULE_HASHES) += hashes.o hashes_root.o
kernel/module/auth.c +6 -0
index 2ee512d26790..cf3fe3f8bd89 100644
@@ -42,6 +42,9 @@ static __always_inline bool mod_sig_type_valid(enum module_signature_type id_typ
 	if (id_type == MODULE_SIGNATURE_TYPE_PKCS7 && IS_ENABLED(CONFIG_MODULE_SIG))
 		return true;
 
+	if (id_type == MODULE_SIGNATURE_TYPE_MERKLE && IS_ENABLED(CONFIG_MODULE_HASHES))
+		return true;
+
 	return false;
 }
 
@@ -72,6 +75,9 @@ static int mod_verify_sig(const void *mod, struct load_info *info)
 	if (ms.id_type == MODULE_SIGNATURE_TYPE_PKCS7 && IS_ENABLED(CONFIG_MODULE_SIG))
 		return module_sig_check(mod, modlen, mod + modlen, sig_len);
 
+	if (ms.id_type == MODULE_SIGNATURE_TYPE_MERKLE && IS_ENABLED(CONFIG_MODULE_HASHES))
+		return module_hash_check(mod, modlen, mod + modlen, sig_len);
+
 	return 0;
 }
 
kernel/module/hashes.c new file +95 -0

95 lines not on this page · raw message

kernel/module/hashes_root.c new file +6 -0
new file mode 100644
index 000000000000..ffb6adfc2193
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <linux/module_hashes.h>
+
+/* Blank dummy data. Will be replaced by the read data during the build */
+const struct module_hashes_root module_hashes_root __module_hashes_section = {};
kernel/module/internal.h +1 -0
index aabe7f8e1af4..259e8ca5cb25 100644
@@ -336,6 +336,7 @@ void module_mark_ro_after_init(const Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
 			       const char *secstrings);
 
 int module_sig_check(const void *mod, size_t mod_len, const void *sig, size_t sig_len);
+int module_hash_check(const void *mod, size_t mod_len, const void *sig, size_t sig_len);
 
 #ifdef CONFIG_MODULE_AUTH
 int module_auth_check(struct load_info *info, int flags);
scripts/.gitignore +1 -0
index 4215c2208f7e..8dad9b0d3b2d 100644
@@ -5,6 +5,7 @@
 /insert-sys-cert
 /kallsyms
 /module.lds
+/modules-merkle-tree
 /recordmcount
 /rustdoc_test_builder
 /rustdoc_test_gen
scripts/Makefile +4 -0
index c983e09be78c..b6291595d9e8 100644
@@ -11,6 +11,7 @@ hostprogs-always-y					+= sign-file
 hostprogs-always-$(CONFIG_SYSTEM_EXTRA_CERTIFICATE)	+= insert-sys-cert
 hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_builder
 hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS)		+= rustdoc_test_gen
+hostprogs-always-$(CONFIG_MODULE_HASHES)		+= modules-merkle-tree
 hostprogs-always-$(CONFIG_TRACEPOINTS)			+= tracepoint-update
 
 sorttable-objs := sorttable.o elf-parse.o
@@ -37,6 +38,9 @@ HOSTCFLAGS_asn1_compiler.o = -I$(srctree)/include
 HOSTCFLAGS_sign-file.o = $(shell $(HOSTPKG_CONFIG) --cflags libcrypto 2> /dev/null)
 HOSTCFLAGS_sign-file.o += -I$(srctree)/tools/include/uapi/
 HOSTLDLIBS_sign-file = $(shell $(HOSTPKG_CONFIG) --libs libcrypto 2> /dev/null || echo -lcrypto)
+HOSTCFLAGS_modules-merkle-tree.o = $(shell $(HOSTPKG_CONFIG) --cflags libcrypto 2> /dev/null)
+HOSTCFLAGS_modules-merkle-tree.o += -I$(srctree)/tools/include/uapi/
+HOSTLDLIBS_modules-merkle-tree = $(shell $(HOSTPKG_CONFIG) --libs libcrypto 2> /dev/null || echo -lcrypto)
 
 ifdef CONFIG_UNWINDER_ORC
 ifeq ($(ARCH),x86_64)
scripts/Makefile.modinst +11 -0
index 9ba45e5b32b1..68708a039a62 100644
@@ -79,6 +79,12 @@ quiet_cmd_install = INSTALL $@
 # as the options to the strip command.
 ifdef INSTALL_MOD_STRIP
 
+ifdef CONFIG_MODULE_HASHES
+ifeq ($(KBUILD_EXTMOD),)
+$(error CONFIG_MODULE_HASHES and INSTALL_MOD_STRIP are mutually exclusive)
+endif
+endif
+
 ifeq ($(INSTALL_MOD_STRIP),1)
 strip-option := --strip-debug
 else
@@ -116,6 +122,11 @@ quiet_cmd_sign :=
       cmd_sign := :
 endif
 
+ifeq ($(KBUILD_EXTMOD)|$(CONFIG_MODULE_HASHES),|y)
+quiet_cmd_sign = MERKLE [M] $@
+      cmd_sign = cat $(objtree)/$*.merkle >> $@
+endif
+
 # Create necessary directories
 $(foreach dir, $(sort $(dir $(install-y))), $(shell mkdir -p $(dir)))
 
scripts/Makefile.vmlinux +32 -0
index 6cc661e5292b..a0332c06bde1 100644
@@ -78,6 +78,33 @@ ifdef CONFIG_BUILDTIME_TABLE_SORT
 vmlinux.unstripped: scripts/sorttable
 endif
 
+ifdef CONFIG_MODULE_HASHES
+targets += .tmp_module_hashes.c
+
+modules.order: vmlinux.unstripped FORCE
+	$(Q)echo "  MAKE    modules"
+	$(Q)$(MAKE) -f $(srctree)/Makefile modules
+
+quiet_cmd_modules_merkle_tree = MERKLE  $@
+      cmd_modules_merkle_tree = $< $@ .ko
+
+targets += .tmp_module_hashes.c
+.tmp_module_hashes.c: $(objtree)/scripts/modules-merkle-tree modules.order FORCE
+	$(call if_changed,modules_merkle_tree)
+
+targets += .tmp_module_hashes.o
+.tmp_module_hashes.o: .tmp_module_hashes.c FORCE
+
+quiet_cmd_modules_merkle_tree_root = GEN     $@
+      cmd_modules_merkle_tree_root = $(OBJCOPY) --dump-section .module_hashes=$@ $<
+
+targets += .tmp_module_hashes.bin
+.tmp_module_hashes.bin: .tmp_module_hashes.o FORCE
+	$(call if_changed,modules_merkle_tree_root)
+
+vmlinux: .tmp_module_hashes.bin
+endif
+
 # vmlinux
 # ---------------------------------------------------------------------------
 
@@ -95,6 +122,11 @@ quiet_cmd_objcopy_vmlinux = OBJCOPY $@
       cmd_objcopy_vmlinux = $(OBJCOPY) $(patsubst %,--set-section-flags %=noload,$(remove-section-y)) $< $@; \
                             $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $@
 
+ifdef CONFIG_MODULE_HASHES
+# Patch module hashes root into vmlinux after modules have been built.
+      cmd_objcopy_vmlinux += ; $(OBJCOPY) --update-section .module_hashes=.tmp_module_hashes.bin $@
+endif
+
 targets += vmlinux
 vmlinux: vmlinux.unstripped FORCE
 	$(call if_changed,objcopy_vmlinux)
scripts/include/xalloc.h +29 -0
index cdadb07d0592..8294bc0b836f 100644
@@ -3,6 +3,7 @@
 #ifndef XALLOC_H
 #define XALLOC_H
 
+#include <stdarg.h>
 #include <stdlib.h>
 #include <string.h>
 
@@ -50,4 +51,32 @@ static inline char *xstrndup(const char *s, size_t n)
 	return p;
 }
 
+static inline void *xreallocarray(void *oldp, size_t n, size_t size)
+{
+	void *p;
+
+	p = reallocarray(oldp, n, size);
+	if (!p)
+		exit(1);
+
+	return p;
+}
+
+#ifdef _GNU_SOURCE
+static inline char *xasprintf(const char *fmt, ...)
+{
+	va_list ap;
+	char *strp;
+	int ret;
+
+	va_start(ap, fmt);
+	ret = vasprintf(&strp, fmt, ap);
+	va_end(ap);
+	if (ret == -1)
+		exit(1);
+
+	return strp;
+}
+#endif /* _GNU_SOURCE */
+
 #endif /* XALLOC_H */
scripts/link-vmlinux.sh +2 -1
index f99e196abeea..0edec5ee34dc 100755
@@ -103,7 +103,7 @@ vmlinux_link()
 	${ld} ${ldflags} -o ${output}					\
 		${wl}--whole-archive ${objs} ${wl}--no-whole-archive	\
 		${wl}--start-group ${libs} ${wl}--end-group		\
-		${kallsymso} ${btf_vmlinux_bin_o} ${arch_vmlinux_o} ${ldlibs}
+		${kallsymso} ${btf_vmlinux_bin_o} ${module_hashes_o} ${arch_vmlinux_o} ${ldlibs}
 }
 
 # Create ${2}.o file with all symbols from the ${1} object file
@@ -183,6 +183,7 @@ fi
 btf_vmlinux_bin_o=
 btfids_vmlinux=
 kallsymso=
+module_hashes_o=
 strip_debug=
 generate_map=
 
scripts/modules-merkle-tree.c new file +416 -0

416 lines not on this page · raw message

security/lockdown/Kconfig +1 -1
index 155959205b8e..60b240e3ef1f 100644
@@ -1,7 +1,7 @@
 config SECURITY_LOCKDOWN_LSM
 	bool "Basic module for enforcing kernel lockdown"
 	depends on SECURITY
-	depends on !MODULES || MODULE_SIG
+	depends on !MODULES || MODULE_SIG || MODULE_HASHES
 	help
 	  Build support for an LSM that enforces a coarse kernel lockdown
 	  behaviour.
tools/include/uapi/linux/module_signature.h +1 -0
index 634c9f1c8fc2..78e206996eed 100644
@@ -16,6 +16,7 @@
 
 enum module_signature_type {
 	MODULE_SIGNATURE_TYPE_PKCS7 = 2,	/* Signature in PKCS#7 message */
+	MODULE_SIGNATURE_TYPE_MERKLE = 3,	/* Merkle proof for modules, opaque structure */
 };
 
 /*
Signature · 1 line
2.54.0
#25 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Build corruption due to concurrent Kbuild executions of the `modules` target. - [High] Standalone…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Build corruption due to concurrent Kbuild executions of the modules target.
- [High] Standalone module builds and installations are fundamentally broken.
- [Low] Memory leak in the modules-merkle-tree host utility.
--

commit 199906bc761e41bbeca38213843237f79baf0aaf
Author: Thomas Weißschuh <[email protected]>

module: Introduce hash-based integrity checking

This commit introduces a hash-based integrity checking mechanism to support reproducible builds. It embeds a Merkle tree root of all builtin modules into vmlinux, while out-of-tree modules continue to be validated through signatures.

Quoted 4 lines
scripts/Makefile.modinst +0 -0
index 9ba45e5b32b18..68708a039a621 100644

[ ... ]

scripts/Makefile.modinst quiet_cmd_sign := · line 128

Quoted 8 lines
scripts/Makefile.modinst +4 -0
@@ -116,6 +122,11 @@ quiet_cmd_sign :=
       cmd_sign := :
 endif
 
+ifeq ($(KBUILD_EXTMOD)|$(CONFIG_MODULE_HASHES),|y)
+quiet_cmd_sign = MERKLE [M] $@
+      cmd_sign = cat $(objtree)/$*.merkle >> $@
+endif

If modules are built and installed independently of a full vmlinux compilation using make modules followed by make modules_install, will this cat command abort with a missing file error?

The .merkle files appear to only be generated by scripts/modules-merkle-tree during the vmlinux link stage, which might leave standalone module builds without the required proof files.

Quoted 4 lines
scripts/Makefile.vmlinux +0 -0
index 6cc661e5292b0..a0332c06bde1d 100644

[ ... ]

scripts/Makefile.vmlinux ifdef CONFIG_BUILDTIME_TABLE_SORT · line 86

Quoted 10 lines
scripts/Makefile.vmlinux +6 -0
@@ -78,6 +78,33 @@ ifdef CONFIG_BUILDTIME_TABLE_SORT
 vmlinux.unstripped: scripts/sorttable
 endif
 
+ifdef CONFIG_MODULE_HASHES
+targets += .tmp_module_hashes.c
+
+modules.order: vmlinux.unstripped FORCE
+	$(Q)echo "  MAKE    modules"
+	$(Q)$(MAKE) -f $(srctree)/Makefile modules

Can this recursive make invocation race with the top-level modules target if a user runs make -j vmlinux modules?

Since both targets share the modpost prerequisite, it seems Kbuild could evaluate both concurrently. This might cause two independent instances of scripts/Makefile.modfinal to compile and link the exact same .mod.o and .ko files at the same time, leading to unpredictable file truncations.

Quoted 5 lines
scripts/modules-merkle-tree.c new file +0 -0
new file mode 100644
index 0000000000000..10e3455d5d7af

[ ... ]

Quoted 7 lines
scripts/modules-merkle-tree.c new file +7 -0
+	mt = build_merkle(fh_list, num_files);
+	write_merkle_root(mt, argv[1]);
+	for (size_t i = 0; i < num_files; i++) {
+		char *signame;
+		int fd;
+
+		signame = xstrdup_replace_suffix(fh_list[i].name, kmod_suffix, ".merkle");

scripts/modules-merkle-tree.c line 407

Quoted 10 lines
scripts/modules-merkle-tree.c new file +10 -0
+
+		fd = open(signame, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+		if (fd < 0)
+			err(1, "Can't create %s", signame);
+
+		build_proof(mt, i, fd);
+		append_module_signature_magic(fd, lseek(fd, 0, SEEK_CUR));
+		if (close(fd))
+			err(1, "Can't write %s", signame);
+	}

Does this code leak the signame string? The xstrdup_replace_suffix helper allocates memory that does not appear to be freed before the end of the loop, which might leave memory stranded for each kernel module processed.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#26 lore raw

PATCH v5 13/14 kbuild: move handling of module stripping to Makefile.lib

In reply to Thomas Weißschuh

To allow CONFIG_MODULE_HASHES in combination with INSTALL_MOD_STRIP, this logc will also be used by Makefile.modfinal.

Move it to a shared location to enable reuse.

---
 scripts/Makefile.lib     | 32 ++++++++++++++++++++++++++++++++
 scripts/Makefile.modinst | 37 +++++--------------------------------
 2 files changed, 37 insertions(+), 32 deletions(-)
scripts/Makefile.lib +32 -0
index 0718e39cedda..bb713a1a11be 100644
@@ -484,6 +484,38 @@ define sed-offsets
 	s:->::; p;}'
 endef
 
+#
+# Module Installation
+#
+quiet_cmd_install_mod = INSTALL $@
+      cmd_install_mod = cp $< $@
+
+# Module Strip
+# ---------------------------------------------------------------------------
+#
+# INSTALL_MOD_STRIP, if defined, will cause modules to be stripped after they
+# are installed. If INSTALL_MOD_STRIP is '1', then the default option
+# --strip-debug will be used. Otherwise, INSTALL_MOD_STRIP value will be used
+# as the options to the strip command.
+ifeq ($(INSTALL_MOD_STRIP),1)
+mod-strip-option := --strip-debug
+else
+mod-strip-option := $(INSTALL_MOD_STRIP)
+endif
+
+# Strip
+ifdef INSTALL_MOD_STRIP
+
+quiet_cmd_strip_mod = STRIP   $@
+      cmd_strip_mod = $(STRIP) $(mod-strip-option) $@
+
+else
+
+quiet_cmd_strip_mod =
+      cmd_strip_mod = :
+
+endif
+
 # Use filechk to avoid rebuilds when a header changes, but the resulting file
 # does not
 define filechk_offsets
scripts/Makefile.modinst +5 -32
index 68708a039a62..b95f613e23c8 100644
@@ -8,6 +8,7 @@ __modinst:
 
 include $(objtree)/include/config/auto.conf
 include $(srctree)/scripts/Kbuild.include
+include $(srctree)/scripts/Makefile.lib
 
 install-y :=
 
@@ -36,7 +37,7 @@ install-y += $(addprefix $(MODLIB)/, modules.builtin modules.builtin.modinfo)
 install-$(CONFIG_BUILTIN_MODULE_RANGES) += $(MODLIB)/modules.builtin.ranges
 
 $(addprefix $(MODLIB)/, modules.builtin modules.builtin.modinfo modules.builtin.ranges): $(MODLIB)/%: % FORCE
-	$(call cmd,install)
+	$(call cmd,install_mod)
 
 endif
 
@@ -65,40 +66,12 @@ install-$(CONFIG_MODULES) += $(modules)
 __modinst: $(install-y)
 	@:
 
-#
-# Installation
-#
-quiet_cmd_install = INSTALL $@
-      cmd_install = cp $< $@
-
-# Strip
-#
-# INSTALL_MOD_STRIP, if defined, will cause modules to be stripped after they
-# are installed. If INSTALL_MOD_STRIP is '1', then the default option
-# --strip-debug will be used. Otherwise, INSTALL_MOD_STRIP value will be used
-# as the options to the strip command.
-ifdef INSTALL_MOD_STRIP
-
 ifdef CONFIG_MODULE_HASHES
 ifeq ($(KBUILD_EXTMOD),)
+ifdef INSTALL_MOD_STRIP
 $(error CONFIG_MODULE_HASHES and INSTALL_MOD_STRIP are mutually exclusive)
 endif
 endif
-
-ifeq ($(INSTALL_MOD_STRIP),1)
-strip-option := --strip-debug
-else
-strip-option := $(INSTALL_MOD_STRIP)
-endif
-
-quiet_cmd_strip = STRIP   $@
-      cmd_strip = $(STRIP) $(strip-option) $@
-
-else
-
-quiet_cmd_strip =
-      cmd_strip = :
-
 endif
 
 #
@@ -131,8 +104,8 @@ endif
 $(foreach dir, $(sort $(dir $(install-y))), $(shell mkdir -p $(dir)))
 
 $(dst)/%.ko: %.ko FORCE
-	$(call cmd,install)
-	$(call cmd,strip)
+	$(call cmd,install_mod)
+	$(call cmd,strip_mod)
 	$(call cmd,sign)
 
 ifdef CONFIG_MODULES
Signature · 1 line
2.54.0
#27 lore raw

Re: [PATCH v5 13/14] kbuild: move handling of module stripping to Makefile.lib

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Reusing `INSTALL_MOD_STRIP` in the build phase violates the separation of build and install…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Reusing INSTALL_MOD_STRIP in the build phase violates the separation of build and install phases, breaking standard user workflows and core kernel packaging scripts. --

commit 82e978c8789922dfed0ff25bf7970d67d952508d
Author: Thomas Weißschuh <[email protected]>

kbuild: move handling of module stripping to Makefile.lib

This commit moves the INSTALL_MOD_STRIP logic to Makefile.lib so that it can be reused by Makefile.modfinal, allowing CONFIG_MODULE_HASHES in combination with module stripping.

Quoted 2 lines

To allow CONFIG_MODULE_HASHES in combination with INSTALL_MOD_STRIP, this logc will also be used by Makefile.modfinal.

This isn't a bug, but there's a typo (logc) in the commit message.

More importantly, does evaluating INSTALL_MOD_STRIP during the build phase (Makefile.modfinal) violate the separation of the build and install phases?

INSTALL_MOD_STRIP is traditionally an install-phase variable passed strictly to make modules_install (e.g., make INSTALL_MOD_STRIP=1 modules_install).

Core kernel packaging scripts heavily rely on passing INSTALL_MOD_STRIP only during the install phase. For example, scripts/package/builddeb executes:
make -f Makefile INSTALL_MOD_PATH="..." INSTALL_MOD_STRIP=1 modules_install during debian/rules binary, while the build phase runs without this variable. Similar logic exists in Arch PKGBUILD and RPM kernel.spec.

If build tools do not export INSTALL_MOD_STRIP during the build phase, relying on it during Makefile.modfinal will mean the build phase and install phase have different views of the variable. If a subsequent commit enforces that the build-time and install-time values of INSTALL_MOD_STRIP must match, wouldn't this break package build targets like make bindeb-pkg or make rpm-pkg?

If build-phase module stripping is required to support hashes, should this be governed by a dedicated build-time Kconfig option, rather than repurposing an install-time Kbuild environment variable?

Quoted 3 lines
scripts/Makefile.lib +0 -0

[ ... ]

scripts/Makefile.lib define sed-offsets · line 504

Quoted 12 lines
scripts/Makefile.lib +12 -0
+# Module Strip
+# ---------------------------------------------------------------------------
+#
+# INSTALL_MOD_STRIP, if defined, will cause modules to be stripped after they
+# are installed. If INSTALL_MOD_STRIP is '1', then the default option
+# --strip-debug will be used. Otherwise, INSTALL_MOD_STRIP value will be used
+# as the options to the strip command.
+ifeq ($(INSTALL_MOD_STRIP),1)
+mod-strip-option := --strip-debug
+else
+mod-strip-option := $(INSTALL_MOD_STRIP)
+endif

Since this is now in Makefile.lib and evaluated during both build and install, can this cause inconsistencies if users run a standard workflow like:

make
sudo make INSTALL_MOD_STRIP=1 modules_install

Will the build phase have generated hashes based on unstripped modules, rendering the hashes invalid when the modules are later stripped during installation?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
maintainer Reviewed-by on v5 13/14
#28 lore raw

Re: [PATCH v5 13/14] kbuild: move handling of module stripping to Makefile.lib

In reply to Thomas Weißschuh
Quoted 2 lines · Thomas Weißschuh

To allow CONFIG_MODULE_HASHES in combination with INSTALL_MOD_STRIP, this logc will also be used by Makefile.modfinal.

s/logc/logic/

Quoted 8 lines

Move it to a shared location to enable reuse.

---
 scripts/Makefile.lib     | 32 ++++++++++++++++++++++++++++++++
 scripts/Makefile.modinst | 37 +++++--------------------------------
 2 files changed, 37 insertions(+), 32 deletions(-)

For kbuild:

Signature · 1 line
Nicolas
#29 lore raw

PATCH v5 14/14 kbuild: make CONFIG_MODULE_HASHES compatible with module stripping

In reply to Thomas Weißschuh

CONFIG_MODULE_HASHES needs to process the modules at build time in the exact form they will be loaded at runtime. If the modules are stripped afterwards they will not be loadable anymore.

Also evaluate INSTALL_MOD_STRIP at build time and build the hashes based on modules stripped this way.

If users specify inconsistent values of INSTALL_MOD_STRIP between build and installation time, an error is reported.

---
 .gitignore                | 1 +
 kernel/module/Kconfig     | 5 +++++
 scripts/Makefile.modfinal | 9 +++++++++
 scripts/Makefile.modinst  | 4 ++--
 scripts/Makefile.vmlinux  | 2 +-
 5 files changed, 18 insertions(+), 3 deletions(-)
.gitignore +1 -0
index 78cf799401e6..6ce10623c5a3 100644
@@ -30,6 +30,7 @@
 *.gz
 *.i
 *.ko
+*.ko.stripped
 *.lex.c
 *.ll
 *.lst
kernel/module/Kconfig +5 -0
index acbbda58e7c8..48be498a4452 100644
@@ -423,6 +423,11 @@ config MODULE_HASHES
 
 	  Also see the warning in MODULE_SIG about stripping modules.
 
+# To validate the consistency of INSTALL_MOD_STRIP for MODULE_HASHES
+config MODULE_INSTALL_STRIP
+	string
+	default "$(INSTALL_MOD_STRIP)"
+
 config MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
 	bool "Allow loading of modules with missing namespace imports"
 	help
scripts/Makefile.modfinal +9 -0
index 44a382689a5a..9924a7bb73c5 100644
@@ -64,7 +64,16 @@ ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 endif
 	+$(call cmd,check_tracepoint)
 
+%.ko.stripped: %.ko $(wildcard include/config/MODULE_INSTALL_STRIP)
+	$(call cmd,install_mod)
+	$(call cmd,strip_mod)
+
+ifneq ($(CONFIG_MODULE_INSTALL_STRIP),)
+modules.order: $(modules:%.o=%.ko.stripped)
+endif
+
 targets += $(modules:%.o=%.ko) $(modules:%.o=%.mod.o) .module-common.o
+targets += $(modules:%.o=%.ko.stripped)
 
 # Update modules.order when a module is (re-)built.
 # Allow using it as target dependency.
scripts/Makefile.modinst +2 -2
index b95f613e23c8..fd1fb89bb0bd 100644
@@ -68,8 +68,8 @@ __modinst: $(install-y)
 
 ifdef CONFIG_MODULE_HASHES
 ifeq ($(KBUILD_EXTMOD),)
-ifdef INSTALL_MOD_STRIP
-$(error CONFIG_MODULE_HASHES and INSTALL_MOD_STRIP are mutually exclusive)
+ifneq ($(INSTALL_MOD_STRIP),$(CONFIG_MODULE_INSTALL_STRIP))
+$(error Inconsistent values for INSTALL_MOD_STRIP between build and installation)
 endif
 endif
 endif
scripts/Makefile.vmlinux +1 -1
index a0332c06bde1..a2d170241a2f 100644
@@ -86,7 +86,7 @@ modules.order: vmlinux.unstripped FORCE
 	$(Q)$(MAKE) -f $(srctree)/Makefile modules
 
 quiet_cmd_modules_merkle_tree = MERKLE  $@
-      cmd_modules_merkle_tree = $< $@ .ko
+      cmd_modules_merkle_tree = $< $@ $(if $(CONFIG_MODULE_INSTALL_STRIP),.ko.stripped,.ko)
 
 targets += .tmp_module_hashes.c
 .tmp_module_hashes.c: $(objtree)/scripts/modules-merkle-tree modules.order FORCE
Signature · 1 line
2.54.0
#30 lore raw

Re: [PATCH v5 14/14] kbuild: make CONFIG_MODULE_HASHES compatible with module stripping

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] The string comparison in `scripts/Makefile.modinst` unconditionally fails, completely breaking…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] The string comparison in scripts/Makefile.modinst unconditionally fails, completely breaking make modules_install when CONFIG_MODULE_HASHES is enabled.
- [High] Module hashes are calculated on unstripped modules if INSTALL_MOD_STRIP is not explicitly passed during the build phase (make modules), leading to unbootable modules.
- [Medium] The build system unconditionally generates redundant .ko.stripped files for every module, even if CONFIG_MODULE_HASHES is disabled or no stripping is requested. --

commit c60e91b7cfcdafd6de940881990bcbadd0ee0179
Author: Thomas Weißschuh <[email protected]>

kbuild: make CONFIG_MODULE_HASHES compatible with module stripping

This commit aims to fix module loading when CONFIG_MODULE_HASHES is used alongside module stripping. It records the INSTALL_MOD_STRIP value in Kconfig and validates consistency between build and install time. It also introduces stripped module variants during compilation to ensure the generated hashes match the final installed files.

Quoted 4 lines
kernel/module/Kconfig +0 -0
index 99482fac07018..a5b3807e2304d 100644

[ ... ]

kernel/module/Kconfig config MODULE_HASHES · line 430

Quoted 9 lines
kernel/module/Kconfig +5 -0
@@ -423,6 +423,11 @@ config MODULE_HASHES
 
 	  Also see the warning in MODULE_SIG about stripping modules.
 
+# To validate the consistency of INSTALL_MOD_STRIP for MODULE_HASHES
+config MODULE_INSTALL_STRIP
+	string
+	default "$(INSTALL_MOD_STRIP)"
+

Is it intended for config MODULE_INSTALL_STRIP to lack a depends on MODULE_HASHES statement? Without it, the config appears to be evaluated and saved as a quoted string even when hashes are not used.

[ ... ]

Quoted 4 lines
scripts/Makefile.modfinal +0 -0
index 44a382689a5aa..9924a7bb73c5e 100644

[ ... ]

scripts/Makefile.modfinal ifdef CONFIG_DEBUG_INFO_BTF_MODULES · line 69

Quoted 3 lines

+%.ko.stripped: %.ko $(wildcard include/config/MODULE_INSTALL_STRIP)

scripts/Makefile.modfinal +2 -0
+	$(call cmd,install_mod)
+	$(call cmd,strip_mod)

Does cmd_strip_mod evaluate to a no-op during the build phase if INSTALL_MOD_STRIP is not explicitly passed to the build command?

Since users typically pass INSTALL_MOD_STRIP=1 only during the module installation step and not during compilation, this might cause hashes to be calculated on unstripped modules during the build. If the modules are then properly stripped during installation, could this result in a hash mismatch that prevents module loading?

scripts/Makefile.modfinal ifdef CONFIG_DEBUG_INFO_BTF_MODULES · line 73

Quoted 4 lines
scripts/Makefile.modfinal +4 -0
+
+ifneq ($(CONFIG_MODULE_INSTALL_STRIP),)
+modules.order: $(modules:%.o=%.ko.stripped)
+endif

Since Kconfig strings are exported to Make with quotes, won't this check evaluate to true even if the string is empty, as the value will be "" rather than completely empty?

This looks like it would force the generation of .ko.stripped targets for all modules, adding unnecessary overhead to the build even if module hashes are disabled or no stripping is requested.

[ ... ]

scripts/Makefile.modinst __modinst: $(install-y) · line 73

Quoted 13 lines
scripts/Makefile.modinst +2 -2
index b95f613e23c89..fd1fb89bb0bd7 100644
@@ -68,8 +68,8 @@ __modinst: $(install-y)
 
 ifdef CONFIG_MODULE_HASHES
 ifeq ($(KBUILD_EXTMOD),)
-ifdef INSTALL_MOD_STRIP
-$(error CONFIG_MODULE_HASHES and INSTALL_MOD_STRIP are mutually exclusive)
+ifneq ($(INSTALL_MOD_STRIP),$(CONFIG_MODULE_INSTALL_STRIP))
+$(error Inconsistent values for INSTALL_MOD_STRIP between build and installation)
 endif

Kconfig string options are exported to Make with literal double quotes, such as CONFIG_MODULE_INSTALL_STRIP="1", while the INSTALL_MOD_STRIP variable passed via the command line or environment is typically unquoted.

Will this literal comparison always evaluate as unequal, meaning 1 != "1", and therefore prevent module installation when CONFIG_MODULE_HASHES is enabled?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
maintainer Reviewed-by on v5 14/14
#31 lore raw

Re: [PATCH v5 14/14] kbuild: make CONFIG_MODULE_HASHES compatible with module stripping

In reply to Thomas Weißschuh
Quoted 10 lines · Thomas Weißschuh

CONFIG_MODULE_HASHES needs to process the modules at build time in the exact form they will be loaded at runtime. If the modules are stripped afterwards they will not be loadable anymore.

Also evaluate INSTALL_MOD_STRIP at build time and build the hashes based on modules stripped this way.

If users specify inconsistent values of INSTALL_MOD_STRIP between build and installation time, an error is reported.

Quoted 9 lines
---
 .gitignore                | 1 +
 kernel/module/Kconfig     | 5 +++++
 scripts/Makefile.modfinal | 9 +++++++++
 scripts/Makefile.modinst  | 4 ++--
 scripts/Makefile.vmlinux  | 2 +-
 5 files changed, 18 insertions(+), 3 deletions(-)

For kbuild:

Signature · 1 line
Nicolas
maintainer
#32 lore raw
In reply to Thomas Weißschuh

Hi Thomas,

Quoted 6 lines · Thomas Weißschuh

The current signature-based module integrity checking has some drawbacks in combination with reproducible builds. Either the module signing key is generated at build time, which makes the build unreproducible, or a static signing key is used, which precludes rebuilds by third parties and makes the whole build and packaging process much more complicated.

Quoted 7 lines

The goal is to reach bit-for-bit reproducibility. Excluding certain parts of the build output from the reproducibility analysis would be error-prone and force each downstream consumer to introduce new tooling.

Introduce a new mechanism to ensure only well-known modules are loaded by embedding a merkle tree root of all modules built as part of the full kernel build into vmlinux.

I noticed Sashiko had a few concerns about the build changes. Would you mind taking a look to see if they're valid?

https://sashiko.dev/#/patchset/20260505-module-hashes-v5-0-e174a5a49fce%40weissschuh.net

Sami

#33 lore raw

Hi Sami,

Quoted 11 lines · Sami Tolvanen
Quoted 10 lines · Thomas Weißschuh

The current signature-based module integrity checking has some drawbacks in combination with reproducible builds. Either the module signing key is generated at build time, which makes the build unreproducible, or a static signing key is used, which precludes rebuilds by third parties and makes the whole build and packaging process much more complicated.

The goal is to reach bit-for-bit reproducibility. Excluding certain parts of the build output from the reproducibility analysis would be error-prone and force each downstream consumer to introduce new tooling.

Quoted 8 lines
Quoted 3 lines

Introduce a new mechanism to ensure only well-known modules are loaded by embedding a merkle tree root of all modules built as part of the full kernel build into vmlinux.

I noticed Sashiko had a few concerns about the build changes. Would you mind taking a look to see if they're valid?

https://sashiko.dev/#/patchset/20260505-module-hashes-v5-0-e174a5a49fce%40weissschuh.net

I definitively have these on my list. Unfortunately I am busy with something else right now. But this series and the Sashiko comments are next.

Thomas