Skip to contentSkip to conversation

Verify BPF signed loader at load time

PATCH Applied Daniel Borkmann 4 participants 18 messages Jul 8

Subsystems (8)
lore
Share & tools
lore

Daniel Borkmann

author maintainer
#0 lore raw

v6 cover Verify BPF signed loader at load time

The BPF signing scheme signs a light skeleton's loader program and lets the loader vouch for everything else: bpftool bakes the SHA256 of the metadata map into the loader's instructions, signs the instructions, and the loader compares the (frozen, exclusive) map against that hash from within BPF once it runs. The construction is sound as a trusted hash chain, but the kernel itself never attests the metadata, and that split has been the recurring objection from the LSM / integrity side since the scheme was proposed.

This proposal closes both gaps by having the kernel verify the metadata at BPF_PROG_LOAD time, before the LSM admission hook and before the verifier, /without/ growing the UAPI. A signed loader binds its metadata map(s) through the existing fd_array/fd_array_cnt, and exclusive maps are already bound to the loader's digest via excl_prog_hash. When a signature is present, the kernel collects the exclusive maps from the fd_array and appends their frozen contents to the instructions before PKCS#7 verification, so the signature covers ...

    insns || metadata_0 || metadata_1 || [...]

... in fd_array order. The in-loader hash check is dropped from the gen_loader entirely: generated loaders carry no verification logic anymore, and signing or verifying a skeleton becomes an ordinary CMS operation over bytes that sit verbatim in the skeleton, reproducible offline. A signed program is either BPF_SIG_UNSIGNED or BPF_SIG_VERIFIED with nothing in between.

There is no new UAPI, we now have a single signature scheme, no LSM code reaching into BPF internals, no new LSM hook, and unsigned loads are completely unaffected. It is also less complex since the loader does not need to deal with BTF, an extra kfunc, etc, as proposed in an earlier series [0]. Tested against full BPF CI which came back green. For more details and examples, see the documentation patch in this series.

[0] https://lore.kernel.org/bpf/[email protected]/

v5 -> v6:
- Added bpf_map_write_active check to close potential race on

    arm64 (sashiko)

- Rebased & rest stays as-is
v4 -> v5:
- Squashed patch 2/9 and 3/9 together and dropped Nack (Paul)
- Added Anton's Acked-by on the fd_array cache patch
- Add !attr->signature_size test to reject invalid param and added BPF selftest for this case
v3 -> v4:
- Fix upper limit in MAX_FD_ARRAY_CNT (Anton)
- Reject !fd_array && attr->fd_array_cnt (Anton)
- Add bpftool patch wrt ignored return value of EVP_Digest() (sashiko)
- Fix setting of gen_loader_fixture_init (sashiko)
- Fix unused map_fd cleanup branch in selftest (bot+bpf-ci)
- Remove now unused map->excl member and adjust selftests
- Added more BPF signed_loader corner case selftest coverage
- Added Paul's Nack wrt bpf_prog_load LSM hook dispute
- Added patch 2 to move bigger allocations below fd_array resolution (Paul)
v2 -> v3:
- Added first commit to cache and work on objects in fd_array which was the most recent issue sashiko rightfully complained
- Added more BPF signed_loader selftest coverage to cover that usage of sparse fd_array or map fds gets rejected
- I left the security_bpf_prog_load as in v2 given preference from BPF side over adding new hook
v1 -> v2:
- Addressed both sashiko complaints, the TOCTOU bug regarding fd_array processing, as well as exclusive map checking to only allow array maps. The validation is now moved into the verifier before the main verification work happens. This also gives the opportunity to utilize the verifier log.

Daniel Borkmann (8):
bpf: Resolve and cache fd_array objects at load time
bpf: Verify signed loader metadata at load time
libbpf: Drop in-loader metadata check for load-time verification
bpftool: Check EVP_Digest when computing excl_prog_hash
bpftool: Cover loader metadata with the program signature selftests/bpf: Adjust bpf_map layout in verifier_map_ptr selftests/bpf: Verify load-time signed loader metadata Documentation/bpf: Add BPF signing and enforcement doc

 Documentation/bpf/index.rst                   |    1 +
 Documentation/bpf/signing.rst                 |  497 ++++++++
 include/linux/bpf.h                           |    1 -
 include/linux/bpf_verifier.h                  |   23 +-
 kernel/bpf/syscall.c                          |   83 +-
 kernel/bpf/verifier.c                         |  457 ++++++--
 tools/bpf/bpftool/gen.c                       |    2 +
 tools/bpf/bpftool/sign.c                      |   24 +-
 tools/lib/bpf/bpf_gen_internal.h              |    1 -
 tools/lib/bpf/gen_loader.c                    |   76 +-
 tools/lib/bpf/libbpf_internal.h               |    1 -
 tools/lib/bpf/skel_internal.h                 |   31 +-
 .../selftests/bpf/prog_tests/signed_loader.c  | 1025 ++++++++++++++---
 .../selftests/bpf/progs/test_signed_loader.c  |    9 +-
 .../selftests/bpf/progs/verifier_map_ptr.c    |   23 +-
 15 files changed, 1815 insertions(+), 439 deletions(-)
 create mode 100644 Documentation/bpf/signing.rst
Signature · 1 line
2.43.0
author maintainer
#1 lore raw

PATCH v6 1/8 bpf: Resolve and cache fd_array objects at load time

The fd_array passed to BPF_PROG_LOAD carries the map and module BTF file descriptors a program binds. The verifier reads it more than once during a load: process_fd_array() walks it to bind the maps and BTFs, and check_and_resolve_insns() and the kfunc BTF resolver later read it again to resolve the program's BPF_PSEUDO_MAP_IDX* and module kfunc refs.

For signed BPF, we need these upfront in memory, thus resolve each fd to its object once and cache it by fd_array index, then bind that cached object for the rest of the load. env->fd_array becomes a small per-slot {map, btf} cache rather than a bpfptr_t; every later reference is then an in-bounds lookup of an already-resolved object, and an index outside the cache is rejected instead of read from user memory:

- continuous (fd_array_cnt given): the caller declares the length and every entry is resolved and bound up front (used also by the BPF signed loader)

- sparse (no fd_array_cnt): left as the legacy path with no fd_array cache; each reference reads its fd from the caller's fd_array and resolves it on the spot. Deduplication in used_maps and the kfunc BTF table keeps this correct, and only unsigned programs use this shape.

Split these into separate helpers to make it easier to follow.

---
 include/linux/bpf_verifier.h |  22 +++-
 kernel/bpf/verifier.c        | 223 +++++++++++++++++++++++++++--------
 2 files changed, 193 insertions(+), 52 deletions(-)
include/linux/bpf_verifier.h +21 -1
index 76b8b7627a10..bb57773cde37 100644
@@ -898,6 +898,14 @@ struct bpf_scc_info {
 
 struct bpf_liveness;
 
+struct bpf_fd_array {
+	union {
+		struct bpf_map *map;
+		struct btf *btf;
+		unsigned long val;
+	};
+};
+
 /* single container for all structs
  * one verifier_env per bpf_check() call
  */
@@ -989,7 +997,19 @@ struct bpf_verifier_env {
 	u32 free_list_size;
 	u32 explored_states_size;
 	u32 num_backedges;
-	bpfptr_t fd_array;
+	/*
+	 * The program's fd_array comes in two shapes, told apart by whether
+	 * the caller passed fd_array_cnt. They are mutually exclusive:
+	 *  - continuous (fd_array_cnt given): ->fd_array holds every entry
+	 *    resolved to its object up front, indexed by fd_array position,
+	 *    with ->fd_array_cnt slots; ->fd_array_raw is unused.
+	 *  - sparse (no fd_array_cnt): ->fd_array is NULL, and entries are
+	 *    read from ->fd_array_raw (the caller's fd_array) and resolved
+	 *    on the spot at each reference.
+	 */
+	struct bpf_fd_array *fd_array;
+	u32 fd_array_cnt;
+	bpfptr_t fd_array_raw;
 
 	/* bit mask to keep track of whether a register has been accessed
 	 * since the last time the function state was printed
kernel/bpf/verifier.c +172 -51

305 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#2 lore raw

PATCH v6 2/8 bpf: Verify signed loader metadata at load time

In reply to Daniel Borkmann

A signed gen_loader program carries the programs, maps and relocations it installs in a metadata array map. The loader instructions are covered by the PKCS#7 signature, but the metadata map is not: Today the loader compares the map contents from within BPF against a hash baked into its (signed) instructions, using the kernel-cached map hash. The kernel itself never actually attests that the metadata the loader installs is the metadata that was signed.

This split is the core of the long-standing objection to the BPF signing scheme from the LSM / integrity side: the integrity check of a light skeleton only completes once the loader program runs, that is, after the security_bpf_prog_load() hook, so at admission time an LSM observes a program whose payload has not yet been verified. Auditing the chain link is also not a purely cryptographic operation: whoever signs or reviews an lskel has to disassemble the loader's preamble to convince themselves that the embedded hash check is present and correct [0][1]. Two acceptable fixes were identified in those threads: Complete the integrity check before the admission hook fires, or add a second hook that collects the verification result after the loader ran [2]. Covering both the loader and its maps directly with the PKCS#7 signature is what Blaise Boscaccy's patchsets proposed in several forms. Let's implement the former, without growing the UAPI, and in particular as a single unified scheme where the signature spans the raw bytes rather than derived hashes.

A signed loader binds its metadata map(s) through the existing fd_array, and an exclusive map is already bound to a program digest (excl_prog_hash). So when a signature is present, collect the exclusive maps from fd_array and append their frozen contents to the instructions before verification:
The signature now covers insns || metadata_0 || metadata_1 || [...] in the fd_array order, and verification completes in bpf_check(), once the fd_array maps are resolved into used_maps, before the LSM admission hook and the rest of verification. A program is either BPF_SIG_UNSIGNED or BPF_SIG_VERIFIED, with nothing in between. While folding the fd_array maps, a non-exclusive map bound to a signed program is rejected, so every map folded into the signature is exclusive. A signed loader that fails to cover its metadata thus does not load, and BPF_SIG_VERIFIED always means the instructions and every exclusive map are authentic. The maps must be frozen so the hashed bytes cannot change before the loader runs; the map <-> program digest binding is enforced by the verifier for every used map. Binding maps through fd_array_cnt makes the verifier resolve and excl-check them (excl_prog_sha vs prog->digest) before it would otherwise compute the digest, so compute prog->digest up front in bpf_check(), over the unmodified instructions the signature covers, for a load that folds metadata.

Unsigned programs are not affected by the signature path; for them the LSM admission hook merely moves below fd_array resolution, with minimal bounded work in between. Note, signed loaders generated by older libbpf/ bpftool versions need to be regenerated; some of the recent fixes we've had on the signed loader side require the latter already to close gaps.

Finally, some remarks around the security_bpf_prog_load() placement given there was discussion on whether a new hook is needed or the existing security_bpf_prog() hook should be reused [3]: For a new hook it would mean that just for loading a single BPF program it has to pass through four layers of LSM hooks:

1) security_bpf (cmd=PROG_LOAD): for gating various bpf subcmds
2) security_bpf_prog_load: historical admission hook (CAP/token, prog_type, attach point), pre-verification
3) security_bpf_prog_verify_signature: newly asked admission hook, same role as 2), plus the BPF signature verdict
4) security_bpf_prog: gate handing the prog fd back to userspace, verification done & signature verified

The use-cases of 2) and 3) conflate, thus BPF community prefers to just keep a total of 3 LSM hooks (as-is today): 3) makes 2) incoherent given they are the /same class/ of hook, that is, access-control admission on the load and split only by _what_ they can see. Worse, with the split, for a signed BPF program security_bpf_prog_load 2) admits a program whose signature has not been checked, so a policy gating at 2) is structurally unable to express "admit only verified" and every such policy is forced onto 3) *anyway*. In other words, one doesn't get two complementary hooks, but rather, one real admission hook aka 3) plus a now-degraded /legacy/ hook 2) that can't answer the question operators actually want to ask.

Reusing security_bpf_prog() 4) for admission is no alternative either:
it fires only after the entire verifier (and JIT) pipeline ran, so denying a not-yet-verified program at that point burns exactly the work a denial is supposed to avoid, and by then the program has an id assigned and the kallsyms/perf/audit load events fired. Policies are free to also consume the signature verdict at 4), but admission control belongs into security_bpf_prog_load(). Hence the latter remains the only admission hook, merely moved past signature verification; with moving large allocations further down into the BPF verifier, there is now only minimal work between the old and new location: The preparation work in bpf_check() is reordered such that only the minimally necessary setup happens up front: Allocating the env, initializing the verifier log and resolving the fd_array that a signed BPF metadata map needs. The worst case allocation up until security_bpf_prog_load() is ~90K which is the env itself (~54K) plus the continuous fd_array cache (at most 32K). The insn_aux_data array is moved into a later stage in the verification.

---
 include/linux/bpf_verifier.h |   1 +
 kernel/bpf/syscall.c         |  76 +-----------
 kernel/bpf/verifier.c        | 234 +++++++++++++++++++++++++++++++----
 3 files changed, 215 insertions(+), 96 deletions(-)
include/linux/bpf_verifier.h +1 -0
index bb57773cde37..317e99b9acc0 100644
@@ -947,6 +947,7 @@ struct bpf_verifier_env {
 	bool bypass_spec_v4;
 	bool seen_direct_write;
 	bool seen_exception;
+	bool signature;
 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
 	const struct bpf_line_info *prev_linfo;
 	struct bpf_verifier_log log;
kernel/bpf/syscall.c +2 -74

100 lines not on this page · raw message

kernel/bpf/verifier.c +212 -22

312 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#3 lore raw

PATCH v6 3/8 libbpf: Drop in-loader metadata check for load-time verification

In reply to Daniel Borkmann

The signed gen_loader used to police its own metadata map from within
BPF: emit_signature_match() read the kernel-cached map->sha[] back through hardcoded struct bpf_map offsets and compared it against a hash that compute_sha_update_offsets() baked into the signed instructions, after a BPF_OBJ_GET_INFO_BY_FD round-trip to populate map->sha[].

The kernel now verifies the metadata at BPF_PROG_LOAD time by folding the frozen contents of the loader's exclusive fd_array maps into the signature, so the loader no longer checks anything itself. Generated loaders thus carry no verification logic of their own anymore: Nothing in the signing chain depends on emitted loader bytecode doing the right thing.

On the loading side, skel_internal.h now sets fd_array_cnt for a signed load so the kernel scans fd_array for the exclusive metadata map - still frozen, as the kernel requires - and the BPF_OBJ_GET_INFO_BY_FD round-trip to populate map->sha[] is gone. The struct bpf_map layout BUILD_BUG_ON()s on the kernel side are removed as well: they only pinned the ABI for the in-BPF read of map->sha[] that is no longer needed. Same for the map->excl member. Note: gen_hash is retained; it still marks a loader as signed so an untrusted host cannot re-dimension maps or override initial values now covered by the signature.

---
 include/linux/bpf.h              |  1 -
 kernel/bpf/syscall.c             |  7 ---
 tools/lib/bpf/bpf_gen_internal.h |  1 -
 tools/lib/bpf/gen_loader.c       | 76 +++-----------------------------
 tools/lib/bpf/libbpf_internal.h  |  1 -
 tools/lib/bpf/skel_internal.h    | 31 +------------
 6 files changed, 9 insertions(+), 108 deletions(-)
include/linux/bpf.h +0 -1
index adf53f7edf28..c1a98fa36738 100644
@@ -299,7 +299,6 @@ struct bpf_map_owner {
 
 struct bpf_map {
 	u8 sha[SHA256_DIGEST_SIZE];
-	u32 excl;
 	const struct bpf_map_ops *ops;
 	struct bpf_map *inner_map_meta;
 #ifdef CONFIG_SECURITY
kernel/bpf/syscall.c +0 -7
index e898fad01aaf..358f2b0ce2bd 100644
@@ -1598,13 +1598,6 @@ static int map_create_alloc(union bpf_attr *attr, bpfptr_t uattr, struct bpf_ver
 			err = -EFAULT;
 			goto free_map;
 		}
-
-		/* See libbpf: emit_signature_match() */
-		BUILD_BUG_ON(offsetof(struct bpf_map, excl) != SHA256_DIGEST_SIZE);
-		BUILD_BUG_ON(!__same_type(map->excl, u32));
-		BUILD_BUG_ON(offsetof(struct bpf_map, sha)  != 0);
-		BUILD_BUG_ON(!__same_type(map->sha, u8[SHA256_DIGEST_SIZE]));
-		map->excl = 1;
 	} else if (attr->excl_prog_hash_size) {
 		bpf_log(log, "Invalid excl_prog_hash_size.\n");
 		err = -EINVAL;
tools/lib/bpf/bpf_gen_internal.h +0 -1
index 49af4260b8e6..042569187752 100644
@@ -51,7 +51,6 @@ struct bpf_gen {
 	__u32 nr_ksyms;
 	int fd_array;
 	int nr_fd_array;
-	int hash_insn_offset[SHA256_DWORD_SIZE];
 };
 
 void bpf_gen__init(struct bpf_gen *gen, int log_level, int nr_progs, int nr_maps);
tools/lib/bpf/gen_loader.c +7 -69

124 lines not on this page · raw message

tools/lib/bpf/libbpf_internal.h +0 -1
index 04cd303fb5a8..d5b7db703b3f 100644
@@ -768,7 +768,6 @@ int elf_resolve_pattern_offsets(const char *binary_path, const char *pattern,
 int probe_fd(int fd);
 
 #define SHA256_DIGEST_LENGTH 32
-#define SHA256_DWORD_SIZE SHA256_DIGEST_LENGTH / sizeof(__u64)
 
 void libbpf_sha256(const void *data, size_t len, __u8 out[SHA256_DIGEST_LENGTH]);
 int probe_sys_bpf_ext(void);
tools/lib/bpf/skel_internal.h +2 -29
index 74503d358bc8..53fee53d36d5 100644
@@ -18,10 +18,6 @@
 #include "bpf.h"
 #endif
 
-#ifndef SHA256_DIGEST_LENGTH
-#define SHA256_DIGEST_LENGTH 32
-#endif
-
 #ifndef __NR_bpf
 # if defined(__mips__) && defined(_ABIO32)
 #  define __NR_bpf 4355
@@ -320,25 +316,6 @@ static inline int skel_link_create(int prog_fd, int target_fd,
 	return skel_sys_bpf(BPF_LINK_CREATE, &attr, attr_sz);
 }
 
-static inline int skel_obj_get_info_by_fd(int fd)
-{
-	const size_t attr_sz = offsetofend(union bpf_attr, info);
-	__u8 sha[SHA256_DIGEST_LENGTH];
-	struct bpf_map_info info;
-	__u32 info_len = sizeof(info);
-	union bpf_attr attr;
-
-	memset(&info, 0, sizeof(info));
-	info.hash = (long) &sha;
-	info.hash_size = SHA256_DIGEST_LENGTH;
-
-	memset(&attr, 0, attr_sz);
-	attr.info.bpf_fd = fd;
-	attr.info.info = (long) &info;
-	attr.info.info_len = info_len;
-	return skel_sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, attr_sz);
-}
-
 static inline int skel_map_freeze(int fd)
 {
 	const size_t attr_sz = offsetofend(union bpf_attr, map_fd);
@@ -384,12 +361,6 @@ static inline int bpf_load_and_run(struct bpf_load_and_run_opts *opts)
 		set_err;
 		goto out;
 	}
-	err = skel_obj_get_info_by_fd(map_fd);
-	if (err < 0) {
-		opts->errstr = "failed to fetch obj info";
-		set_err;
-		goto out;
-	}
 #endif
 
 	memset(&attr, 0, prog_load_attr_sz);
@@ -400,6 +371,8 @@ static inline int bpf_load_and_run(struct bpf_load_and_run_opts *opts)
 #ifndef __KERNEL__
 	attr.signature = (long) opts->signature;
 	attr.signature_size = opts->signature_sz;
+	if (opts->signature)
+		attr.fd_array_cnt = 1;
 #else
 	if (opts->signature || opts->signature_sz)
 		pr_warn("signatures are not supported from bpf_preload\n");
Signature · 1 line
2.43.0
#4 lore raw

Re: [PATCH bpf-next v6 3/8] libbpf: Drop in-loader metadata check for load-time verification

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] bpftool does not include the map contents when generating the PKCS#7 signature, which causes the…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] bpftool does not include the map contents when generating the PKCS#7 signature, which causes the kernel to always reject signed loaders.
- [High] The run_gen_loader function in the selftest does not set attr.fd_array_cnt, causing the verifier to reject the loader program with -EACCES. --

--- Patch [3]: [PATCH bpf-next v6 3/8] libbpf: Drop in-loader metadata check for load-time verification --- commit 7b60178a5e722682c8474b704e91ce40e0fc21ed
Author: Daniel Borkmann <[email protected]>

libbpf: Drop in-loader metadata check for load-time verification

This patch removes the in-BPF verification logic from the signed loader, relying on the kernel to verify the metadata at BPF_PROG_LOAD time. It also sets fd_array_cnt in skel_internal.h for signed loads so the kernel can scan fd_array for the exclusive metadata map.

Quoted 11 lines

libbpf: Drop in-loader metadata check for load-time verification

The signed gen_loader used to police its own metadata map from within
BPF: emit_signature_match() read the kernel-cached map->sha[] back through hardcoded struct bpf_map offsets and compared it against a hash that compute_sha_update_offsets() baked into the signed instructions, after a BPF_OBJ_GET_INFO_BY_FD round-trip to populate map->sha[].

The kernel now verifies the metadata at BPF_PROG_LOAD time by folding the frozen contents of the loader's exclusive fd_array maps into the signature, so the loader no longer checks anything itself. Generated

[Severity: High]
Since the kernel now concatenates the map contents to the signed payload during signature verification in bpf_prog_verify_signature(), does bpftool need a corresponding update?

Currently, bpftool_prog_sign() in tools/bpf/bpftool/sign.c only signs the BPF instructions (opts->insns) without including the map contents (opts->data). Won't this cause the kernel to consistently reject loaders signed by bpftool with -EKEYREJECTED?

Quoted 3 lines

loaders thus carry no verification logic of their own anymore: Nothing in the signing chain depends on emitted loader bytecode doing the right thing.

[ ... ]

Quoted 4 lines
tools/lib/bpf/skel_internal.h +0 -0
index 74503d358bc8a..53fee53d36d51 100644

[ ... ]

tools/lib/bpf/skel_internal.h static inline int bpf_load_and_run(struct bpf_load_and_run_opts *opts) · line 375

Quoted 6 lines
tools/lib/bpf/skel_internal.h +2 -0
@@ -400,6 +371,8 @@ static inline int bpf_load_and_run(struct bpf_load_and_run_opts *opts)
 #ifndef __KERNEL__
 	attr.signature = (long) opts->signature;
 	attr.signature_size = opts->signature_sz;
+	if (opts->signature)
+		attr.fd_array_cnt = 1;

[Severity: High]
Does run_gen_loader() in tools/testing/selftests/bpf/prog_tests/signed_loader.c need a similar update to set attr.fd_array_cnt = 1?

Without this, when run_gen_loader() loads the signed program, fd_array_cnt remains 0. The verifier's fd_array_get_map_idx() will then see env->signature is set but env->fd_array is missing, which causes the load to abort with -EACCES and breaks the selftest.

Quoted 3 lines
tools/lib/bpf/skel_internal.h +0 -0
 #else
 	if (opts->signature || opts->signature_sz)
 		pr_warn("signatures are not supported from bpf_preload\n");
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#5 lore raw

Re: [PATCH bpf-next v6 3/8] libbpf: Drop in-loader metadata check for load-time verification

Quoted 3 lines · On 7/8/26 10:15 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] bpftool does not include the map contents when generating the PKCS#7 signature, which causes the kernel to always reject signed loaders.
- [High] The run_gen_loader function in the selftest does not set attr.fd_array_cnt, causing the verifier to reject the loader program with -EACCES.

Both invalid as these are addressed in the patches of this series, just split among libbpf, bpftool, selftest.

author maintainer
#6 lore raw

PATCH v6 4/8 bpftool: Check EVP_Digest when computing excl_prog_hash

In reply to Daniel Borkmann

bpftool_prog_sign() ignores the return value of EVP_Digest(). If the digest computation fails (context allocation failure, or a digest fetch failure under OpenSSL), EVP_Digest() returns 0 and leaves the output buffer untouched, but the function still reports success.

Fixes 40863f4d6ef2 ("bpftool: Add support for signing BPF programs")
---
 tools/bpf/bpftool/sign.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
tools/bpf/bpftool/sign.c +5 -2
index f9b742f4bb10..1257dba8ef2f 100644
@@ -175,8 +175,11 @@ int bpftool_prog_sign(struct bpf_load_and_run_opts *opts)
 		goto cleanup;
 	}
 
-	EVP_Digest(opts->insns, opts->insns_sz, opts->excl_prog_hash,
-		   &opts->excl_prog_hash_sz, EVP_sha256(), NULL);
+	if (EVP_Digest(opts->insns, opts->insns_sz, opts->excl_prog_hash,
+		       &opts->excl_prog_hash_sz, EVP_sha256(), NULL) != 1) {
+		err = -EIO;
+		goto cleanup;
+	}
 
 		bd_out = BIO_new(BIO_s_mem());
 	if (!bd_out) {
Signature · 1 line
2.43.0
maintainer Reviewed-by on v6 4/8
#7 lore raw

Re: [PATCH bpf-next v6 4/8] bpftool: Check EVP_Digest when computing excl_prog_hash

Quoted 7 lines · Daniel Borkmann

bpftool_prog_sign() ignores the return value of EVP_Digest(). If the digest computation fails (context allocation failure, or a digest fetch failure under OpenSSL), EVP_Digest() returns 0 and leaves the output buffer untouched, but the function still reports success.

Fixes 40863f4d6ef2 ("bpftool: Add support for signing BPF programs")

Bpftool changes look good to me, thanks for the fix.

author maintainer
#8 lore raw

PATCH v6 5/8 bpftool: Cover loader metadata with the program signature

In reply to Daniel Borkmann

bpftool_prog_sign() signed only the loader instructions. The metadata blob the loader installs was left to an in-loader hash check, which the kernel now performs at load time over insns || metadata.

Sign that same concatenation: pass the metadata blob (gen_loader_opts data) through to bpftool_prog_sign() and feed insns || metadata to CMS_final(). The excl_prog_hash stays a digest of the instructions alone; it binds the metadata map to the loader and is matched against prog->digest by the verifier, independent of what the signature covers.

The signed artifact is now plain data: both bytes the signature covers are embedded verbatim in the generated skeleton, so signing and verifying an lskel is an ordinary CMS operation that a signer or auditor can perform (or reproduce) offline, without analyzing loader bytecode to establish what the signature actually attests to.

---
 tools/bpf/bpftool/gen.c  |  2 ++
 tools/bpf/bpftool/sign.c | 17 +++++++++++++++--
 2 files changed, 17 insertions(+), 2 deletions(-)
tools/bpf/bpftool/gen.c +2 -0
index 6ae7262ebe0c..a01d06d22d1a 100644
@@ -793,6 +793,8 @@ static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *h
 	if (sign_progs) {
 		sopts.insns = opts.insns;
 		sopts.insns_sz = opts.insns_sz;
+		sopts.data = opts.data;
+		sopts.data_sz = opts.data_sz;
 		sopts.excl_prog_hash = prog_sha;
 		sopts.excl_prog_hash_sz = sizeof(prog_sha);
 		sopts.signature = sig_buf;
tools/bpf/bpftool/sign.c +15 -2
index 1257dba8ef2f..88726a6db6d0 100644
@@ -135,9 +135,21 @@ int bpftool_prog_sign(struct bpf_load_and_run_opts *opts)
 	CMS_ContentInfo *cms = NULL;
 	long actual_sig_len = 0;
 	X509 *x509 = NULL;
+	void *data = NULL;
+	size_t data_sz;
 	int err = 0;
 
-	bd_in = BIO_new_mem_buf(opts->insns, opts->insns_sz);
+	data_sz = (size_t)opts->insns_sz + opts->data_sz;
+	data = malloc(data_sz);
+	if (!data) {
+		err = -ENOMEM;
+		goto cleanup;
+	}
+	memcpy(data, opts->insns, opts->insns_sz);
+	if (opts->data_sz)
+		memcpy((char *)data + opts->insns_sz, opts->data, opts->data_sz);
+
+	bd_in = BIO_new_mem_buf(data, data_sz);
 	if (!bd_in) {
 		err = -ENOMEM;
 		goto cleanup;
@@ -181,7 +193,7 @@ int bpftool_prog_sign(struct bpf_load_and_run_opts *opts)
 		goto cleanup;
 	}
 
-		bd_out = BIO_new(BIO_s_mem());
+	bd_out = BIO_new(BIO_s_mem());
 	if (!bd_out) {
 		err = -ENOMEM;
 		goto cleanup;
@@ -215,6 +227,7 @@ int bpftool_prog_sign(struct bpf_load_and_run_opts *opts)
 	X509_free(x509);
 	EVP_PKEY_free(private_key);
 	BIO_free(bd_in);
+	free(data);
 	DISPLAY_OSSL_ERR(err < 0);
 	return err;
 }
Signature · 1 line
2.43.0
maintainer Reviewed-by on v6 5/8
#9 lore raw

Re: [PATCH bpf-next v6 5/8] bpftool: Cover loader metadata with the program signature

Quoted 10 lines · Daniel Borkmann

bpftool_prog_sign() signed only the loader instructions. The metadata blob the loader installs was left to an in-loader hash check, which the kernel now performs at load time over insns || metadata.

Sign that same concatenation: pass the metadata blob (gen_loader_opts data) through to bpftool_prog_sign() and feed insns || metadata to CMS_final(). The excl_prog_hash stays a digest of the instructions alone; it binds the metadata map to the loader and is matched against prog->digest by the verifier, independent of what the signature covers.

Quoted 7 lines

The signed artifact is now plain data: both bytes the signature covers are embedded verbatim in the generated skeleton, so signing and verifying an lskel is an ordinary CMS operation that a signer or auditor can perform (or reproduce) offline, without analyzing loader bytecode to establish what the signature actually attests to.

Thanks!

author maintainer
#10 lore raw

PATCH v6 6/8 selftests/bpf: Adjust bpf_map layout in verifier_map_ptr

In reply to Daniel Borkmann

With write-only excl member removed from struct bpf_map, ops moves to offset 32 and inner_map_meta to offset 40. Update the expected verifier message for the former and retarget the latter at the sha byte array, so the beyond-member-end rejection path stays covered:

# LDLIBS=-static PKG_CONFIG='pkg-config --static' ./vmtest.sh -- ./test_progs -t verifier_map_ptr [...]

  #619/5   verifier_map_ptr/bpf_map_ptr: read non-existent field rejected:OK
  #619/6   verifier_map_ptr/bpf_map_ptr: read non-existent field rejected @unpriv:OK
  #619/7   verifier_map_ptr/bpf_map_ptr: read beyond sha field rejected:OK
  #619/8   verifier_map_ptr/bpf_map_ptr: read beyond sha field rejected @unpriv:OK
  #619/9   verifier_map_ptr/bpf_map_ptr: read ops field accepted:OK
  #619/10  verifier_map_ptr/bpf_map_ptr: read ops field accepted @unpriv:OK

[...]
#620 verifier_map_ptr_mixing:OK
Summary: 2/20 PASSED, 0 SKIPPED, 0 FAILED

---
 .../selftests/bpf/progs/verifier_map_ptr.c    | 23 ++++++++++---------
 1 file changed, 12 insertions(+), 11 deletions(-)
tools/testing/selftests/bpf/progs/verifier_map_ptr.c +12 -11
index 166193659870..e0a65835c861 100644
@@ -72,14 +72,15 @@ __naked void bpf_map_ptr_write_rejected(void)
 
 /*
  * struct bpf_map starts with the SHA256 hash sha[32] at offset 0 (a readable
- * byte array), the u32 excl field at offset 32, and the ops pointer at offset
- * 40. Reading a u32 at offset 41 reaches into the middle of the ops pointer,
- * i.e. a partial pointer access, which is rejected.
+ * byte array), followed by the ops pointer at offset 32 and the inner_map_meta
+ * pointer at offset 40. Reading a u32 at offset 41 reaches into the middle of
+ * the inner_map_meta pointer, i.e. a partial pointer access, which is
+ * rejected.
  */
 SEC("socket")
 __description("bpf_map_ptr: read non-existent field rejected")
 __failure
-__msg("cannot access ptr member ops with moff 40 in struct bpf_map with off 41 size 4")
+__msg("cannot access ptr member inner_map_meta with moff 40 in struct bpf_map with off 41 size 4")
 __failure_unpriv
 __msg_unpriv("access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN")
 __flag(BPF_F_ANY_ALIGNMENT)
@@ -97,23 +98,23 @@ __naked void read_non_existent_field_rejected(void)
 }
 
 /*
- * The u32 excl field spans offsets 32..35 (mend 36). Reading a u32 at offset
- * 33 starts inside excl but extends past its end, which the verifier rejects
+ * The sha byte array spans offsets 0..31 (mend 32). Reading a u32 at offset
+ * 30 starts inside sha but extends past its end, which the verifier rejects
  * as an out-of-bounds scalar access.
  */
 SEC("socket")
-__description("bpf_map_ptr: read beyond excl field rejected")
+__description("bpf_map_ptr: read beyond sha field rejected")
 __failure
-__msg("access beyond the end of member excl (mend:36) in struct bpf_map with off 33 size 4")
+__msg("access beyond the end of member sha (mend:32) in struct bpf_map with off 30 size 4")
 __failure_unpriv
 __msg_unpriv("access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN")
 __flag(BPF_F_ANY_ALIGNMENT)
-__naked void read_beyond_excl_field_rejected(void)
+__naked void read_beyond_sha_field_rejected(void)
 {
 	asm volatile ("					\
 	r6 = 0;						\
 	r1 = %[map_array_48b] ll;			\
-	r6 = *(u32*)(r1 + 33);				\
+	r6 = *(u32*)(r1 + 30);				\
 	r0 = 1;						\
 	exit;						\
 "	:
@@ -131,7 +132,7 @@ __naked void ptr_read_ops_field_accepted(void)
 	asm volatile ("					\
 	r6 = 0;						\
 	r1 = %[map_array_48b] ll;			\
-	r6 = *(u64*)(r1 + 40);				\
+	r6 = *(u64*)(r1 + 32);				\
 	r0 = 1;						\
 	exit;						\
 "	:
Signature · 1 line
2.43.0
#11 lore raw

Re: [PATCH bpf-next v6 6/8] selftests/bpf: Adjust bpf_map layout in verifier_map_ptr

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Stale test logic in `signed_loader.c` causes selftest suite failure due to removed in-loader…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Stale test logic in signed_loader.c causes selftest suite failure due to removed in-loader metadata checks. --

--- Patch [6]: [PATCH bpf-next v6 6/8] selftests/bpf: Adjust bpf_map layout in verifier_map_ptr --- commit 57fd96aa0d68880807526c20a038bd95f1762aa4
Author: Daniel Borkmann <[email protected]>

selftests/bpf: Adjust bpf_map layout in verifier_map_ptr

This patch adjusts the selftest verifier expectations for bpf_map's memory layout. It updates tests to reflect the removal of the write-only excl member, moving ops to offset 32 and inner_map_meta to offset 40.

Quoted 4 lines
tools/testing/selftests/bpf/progs/verifier_map_ptr.c +0 -0
index 1661936598703..e0a65835c861b 100644

[ ... ]

tools/testing/selftests/bpf/progs/verifier_map_ptr.c __naked void read_non_existent_field_rejected(void) · line 101

Quoted 7 lines
tools/testing/selftests/bpf/progs/verifier_map_ptr.c +1 -2
@@ -97,23 +98,23 @@ __naked void read_non_existent_field_rejected(void)
 }
 
 /*
- * The u32 excl field spans offsets 32..35 (mend 36). Reading a u32 at offset
- * 33 starts inside excl but extends past its end, which the verifier rejects
+ * The sha byte array spans offsets 0..31 (mend 32). Reading a u32 at offset

[Severity: Medium]
Since this series removes the excl field and emit_signature_match(), did we miss updating tools/testing/selftests/bpf/prog_tests/signed_loader.c?

When running test_progs, test_signed_loader() calls metadata_check_shape(), which fails here because it still expects the loader to read the removed excl field at offset 32 and relies on emit_signature_match():

check_sig_match_shape() {
	...
	if (!ASSERT_GE(a, 0, "emit_signature_match present"))
		return;
	...
	/* excl check: r2 = *(u32 *)(map + 32); if r2 != 1 goto cleanup */
	ASSERT_EQ(in[a + 2].code, (BPF_LDX | BPF_MEM | BPF_W), "excl load width");
	ASSERT_EQ(in[a + 2].off, SHA256_DIGEST_LENGTH, "excl field offset");
	...
}

Tests like metadata_sha_mismatch also seem to rely on the removed in-loader hash check to reject tampered maps, meaning they might now unexpectedly run successfully and fail their ASSERT_EQ(r, -EINVAL) verifications. Can this cause the selftests suite to fail?

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

Re: [PATCH bpf-next v6 6/8] selftests/bpf: Adjust bpf_map layout in verifier_map_ptr

Quoted 2 lines · On 7/8/26 10:14 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Stale test logic in signed_loader.c causes selftest suite failure due to removed in-loader metadata checks.

Same comment as last time, this is done in patch 7/8.

author maintainer
#13 lore raw

PATCH v6 7/8 selftests/bpf: Verify load-time signed loader metadata

In reply to Daniel Borkmann

The signed gen_loader no longer checks its metadata map from within BPF; the kernel does it at BPF_PROG_LOAD by folding the loader's frozen exclusive fd_array maps into the signature. Exercise that path end to end. Extend with more test cases (e.g. map-less program, asserting the LSM admission hook observes BPF_SIG_UNSIGNED and BPF_SIG_VERIFIED), and retire the subtests that asserted the old in-loader check, which no longer exists.

# LDLIBS=-static PKG_CONFIG='pkg-config --static' ./vmtest.sh -- ./test_progs -t signed_loader [...]

  #412/1   signed_loader/loadtime_no_map:OK
  #412/2   signed_loader/loadtime_with_map:OK
  #412/3   signed_loader/metadata_match:OK
  #412/4   signed_loader/signature_enforced:OK
  #412/5   signed_loader/signed_nonexcl_fd_array_rejected:OK
  #412/6   signed_loader/signed_unfrozen_fd_array_rejected:OK
  #412/7   signed_loader/signed_nonarray_fd_array_rejected:OK
  #412/8   signed_loader/signed_btf_fd_array_rejected:OK
  #412/9   signed_loader/signed_module_kfunc_rejected:OK
  #412/10  signed_loader/signature_failure_logs:OK
  #412/11  signed_loader/signature_too_large:OK
  #412/12  signed_loader/signature_zero_size:OK
  #412/13  signed_loader/signature_bad_keyring:OK
  #412/14  signed_loader/metadata_ctx_max_entries_ignored:OK
  #412/15  signed_loader/metadata_ctx_initial_value_ignored:OK
  #412/16  signed_loader/signature_authenticates_insns:OK
  #412/17  signed_loader/signature_authenticates_metadata:OK
  #412/18  signed_loader/hash_requires_frozen:OK
  #412/19  signed_loader/no_update_after_freeze:OK
  #412/20  signed_loader/freeze_writable_mmap:OK
  #412/21  signed_loader/no_writable_mmap_frozen:OK
  #412/22  signed_loader/map_hash_matches_libbpf:OK
  #412/23  signed_loader/map_hash_multi_element:OK
  #412/24  signed_loader/map_hash_bad_size:OK
  #412/25  signed_loader/map_hash_unsupported_type:OK
  #412/26  signed_loader/lsm_signature_verdict:OK
  #412/27  signed_loader/signed_no_fd_array:OK
  #412/28  signed_loader/signed_map_by_fd_rejected:OK
  #412/29  signed_loader/signed_sparse_fd_array_rejected:OK
  #412     signed_loader:OK

Summary: 1/29 PASSED, 0 SKIPPED, 0 FAILED

---
 .../selftests/bpf/prog_tests/signed_loader.c  | 1025 ++++++++++++++---
 .../selftests/bpf/progs/test_signed_loader.c  |    9 +-
 2 files changed, 866 insertions(+), 168 deletions(-)
tools/testing/selftests/bpf/prog_tests/signed_loader.c +861 -164
index 5fc417e31fc6..0019492cf07a 100644
@@ -11,6 +11,8 @@
 #include <linux/keyctl.h>
 #include <linux/bpf.h>
 
+#include <bpf/btf.h>
+
 #include "bpf/libbpf_internal.h" /* for libbpf_sha256() */
 #include "bpf/skel_internal.h"	 /* for loader ctx layout (bpf_loader_ctx etc) */
 
@@ -19,8 +21,6 @@
 #include "test_signed_loader_data.skel.h"
 #include "test_signed_loader_lsm.skel.h"
 
-#define SIG_MATCH_INSNS 33 /* excl (5) + 4 * sha-dword (7) */
-
 enum {
 	BPF_SIG_UNSIGNED = 0,
 	BPF_SIG_VERIFIED,
@@ -35,7 +35,8 @@ enum {
 };
 
 static int load_loader(const void *insns, __u32 insns_sz, int map_fd,
-		       const void *sig, __u32 sig_sz, __s32 keyring_id)
+		       const void *sig, __u32 sig_sz, __s32 keyring_id,
+		       __u32 fd_array_cnt)
 {
 	union bpf_attr attr;
 	int fd;
@@ -52,6 +53,7 @@ static int load_loader(const void *insns, __u32 insns_sz, int map_fd,
 		attr.signature_size = sig_sz;
 		attr.keyring_id = keyring_id;
 	}
+	attr.fd_array_cnt = fd_array_cnt;
 	memcpy(attr.prog_name, "__loader.prog", sizeof("__loader.prog"));
 	fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
 		     offsetofend(union bpf_attr, keyring_id));
@@ -62,14 +64,12 @@ static int run_gen_loader(const void *insns, __u32 insns_sz,
 			  const void *data, __u32 data_sz,
 			  const void *excl, __u32 excl_sz,
 			  const void *sig, __u32 sig_sz,
-			  bool get_hash, void *ctx, __u32 ctx_sz, bool *loader_ran)
+			  void *ctx, __u32 ctx_sz, bool *loader_ran)
 {
 	LIBBPF_OPTS(bpf_map_create_opts, mopts,
 		    .excl_prog_hash = excl,
 		    .excl_prog_hash_size = excl_sz);
-	__u8 hbuf[SHA256_DIGEST_LENGTH];
-	struct bpf_map_info info;
-	__u32 ilen = sizeof(info), key = 0;
+	__u32 key = 0;
 	union bpf_attr attr;
 	int map_fd, prog_fd, ret;
 
@@ -87,15 +87,6 @@ static int run_gen_loader(const void *insns, __u32 insns_sz,
 		ret = -errno;
 		goto out_map;
 	}
-	if (get_hash) {
-		memset(&info, 0, sizeof(info));
-		info.hash = ptr_to_u64(hbuf);
-		info.hash_size = sizeof(hbuf);
-		if (bpf_map_get_info_by_fd(map_fd, &info, &ilen)) {
-			ret = -errno;
-			goto out_map;
-		}
-	}
 
 	memset(&attr, 0, sizeof(attr));
 	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
@@ -108,6 +99,7 @@ static int run_gen_loader(const void *insns, __u32 insns_sz,
 		attr.signature = ptr_to_u64(sig);
 		attr.signature_size = sig_sz;
 		attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+		attr.fd_array_cnt = 1;
 	}
 	memcpy(attr.prog_name, "__loader.prog", sizeof("__loader.prog"));
 	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
@@ -236,79 +228,6 @@ static int sign_buf(const char *dir, const void *buf, __u32 len,
 	return ret;
 }
 
-static void check_sig_match_shape(const struct bpf_insn *in, int n)
-{
-	int a = -1, cleanup = -1, i, base, t, br[5], nb = 0;
-
-	/* BPF_PSEUDO_MAP_IDX (the struct bpf_map * form) is used only here. */
-	for (i = 0; i + 1 < n; i++) {
-		if (in[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
-		    in[i].src_reg == BPF_PSEUDO_MAP_IDX) {
-			a = i;
-			break;
-		}
-	}
-	if (!ASSERT_GE(a, 0, "emit_signature_match present"))
-		return;
-	if (!ASSERT_LE(a + SIG_MATCH_INSNS, n, "block fits in program"))
-		return;
-
-	/* excl check: r2 = *(u32 *)(map + 32); if r2 != 1 goto cleanup */
-	ASSERT_EQ(in[a + 2].code, (BPF_LDX | BPF_MEM | BPF_W), "excl load width");
-	ASSERT_EQ(in[a + 2].off, SHA256_DIGEST_LENGTH, "excl field offset");
-	ASSERT_EQ(in[a + 4].code, (BPF_JMP | BPF_JNE | BPF_K), "excl branch op");
-	ASSERT_EQ(in[a + 4].imm, 1, "excl compared to 1");
-	br[nb++] = a + 4;
-
-	/* 4 sha-dword checks: r2 = *(u64 *)(map + i*8); if r2 != r3 goto cleanup */
-	for (i = 0; i < 4; i++) {
-		base = a + 5 + i * 7;
-		ASSERT_EQ(in[base + 2].code, (BPF_LDX | BPF_MEM | BPF_DW), "sha load width");
-		ASSERT_EQ(in[base + 2].off, i * 8, "sha dword offset");
-		ASSERT_EQ(in[base + 3].code, (BPF_LD | BPF_IMM | BPF_DW), "sha imm64 (H_meta)");
-		ASSERT_EQ(in[base + 6].code, (BPF_JMP | BPF_JNE | BPF_X), "sha branch op");
-		br[nb++] = base + 6;
-	}
-
-	/*
-	 * Locate the real cleanup label so we can pin the exact jump target,
-	 * not just "some backward label". bpf_gen__init() emits the cleanup
-	 * block as a prog-fd close loop whose first instruction is the label
-	 * every error branch jumps to.
-	 */
-	for (i = 0; i + 2 < a; i++) {
-		if (in[i].code == (BPF_LDX | BPF_MEM | BPF_W) &&
-		    in[i].dst_reg == BPF_REG_1 && in[i].src_reg == BPF_REG_10 &&
-		    in[i + 1].code == (BPF_JMP | BPF_JSLE | BPF_K) &&
-		    in[i + 1].dst_reg == BPF_REG_1 && in[i + 1].imm == 0 &&
-		    in[i + 1].off == 1 &&
-		    in[i + 2].code == (BPF_JMP | BPF_CALL) &&
-		    in[i + 2].imm == BPF_FUNC_sys_close) {
-			cleanup = i;
-			break;
-		}
-	}
-	if (!ASSERT_GE(cleanup, 0, "cleanup label located"))
-		return;
-	for (i = 0; i < nb; i++) {
-		t = br[i] + 1 + in[br[i]].off;
-		ASSERT_EQ(t, cleanup, "sig-match lands on cleanup");
-	}
-	/*
-	 * Same invariant for every other cleanup-bound jump in the program:
-	 * emit_check_err() is the only source of "if (r7 < 0) goto cleanup",
-	 * so each of those must also resolve exactly to cleanup.
-	 */
-	for (i = 0, t = 0; i < n; i++) {
-		if (in[i].code != (BPF_JMP | BPF_JSLT | BPF_K) ||
-		    in[i].dst_reg != BPF_REG_7 || in[i].imm != 0 || in[i].off >= 0)
-			continue;
-		ASSERT_EQ(i + 1 + in[i].off, cleanup, "err-check lands on cleanup");
-		t++;
-	}
-	ASSERT_GT(t, 0, "found emit_check_err jumps");
-}
-
 struct gen_loader_fixture {
 	struct test_signed_loader *skel;
 	struct gen_loader_opts gopts;
@@ -372,16 +291,6 @@ static void gen_loader_fixture_fini(struct gen_loader_fixture *f)
 	test_signed_loader__destroy(f->skel);
 }
 
-static void metadata_check_shape(void)
-{
-	struct gen_loader_fixture f;
-
-	if (gen_loader_fixture_init(&f) == 0)
-		check_sig_match_shape((const struct bpf_insn *)f.gopts.insns,
-				      f.gopts.insns_sz / sizeof(struct bpf_insn));
-	gen_loader_fixture_fini(&f);
-}
-
 static void metadata_match(void)
 {
 	struct gen_loader_fixture f;
@@ -391,94 +300,263 @@ static void metadata_match(void)
 	if (gen_loader_fixture_init(&f) == 0) {
 		r = run_gen_loader(f.gopts.insns, f.gopts.insns_sz, f.blob,
 				   f.data_sz, f.excl, sizeof(f.excl), NULL, 0,
-				   true, f.ctx, f.ctx_sz, &ran);
+				   f.ctx, f.ctx_sz, &ran);
 		ASSERT_TRUE(ran, "loader ran");
 		ASSERT_EQ(r, 0, "honest loader retval");
 	}
 	gen_loader_fixture_fini(&f);
 }
 
-static void metadata_sha_mismatch(void)
+static void signature_enforced(void)
 {
+	static const __u8 junk[64] = { 0x30, 0x42, 0x13, 0x37, };
 	struct gen_loader_fixture f;
-	bool ran;
-	int r;
+	int fd;
 
 	if (gen_loader_fixture_init(&f) == 0) {
 		/*
-		 * blob[0] lives in the loader's fd_array scratch (first add_data in
-		 * bpf_gen__init); a 0-map program never reads it, so flipping it
-		 * changes only map->sha. The metadata check is the only thing that
-		 * can notice -> isolates emit_signature_match.
+		 * A present-but-invalid signature (the cert bytes are not a
+		 * PKCS#7 signature) must be rejected at load: the signature
+		 * path is honored, not ignored. (The valid path is covered by
+		 * the signed lskels.) Pin -EBADMSG, the PKCS#7 parse failure:
+		 * a looser fd < 0 check could also be satisfied by the sparse
+		 * fd_array rejection (-EACCES) that the loader's map reference
+		 * would trip even if the signature were silently ignored.
 		 */
-		f.blob[0] ^= 0xff;
-		r = run_gen_loader(f.gopts.insns, f.gopts.insns_sz, f.blob,
-				   f.data_sz, f.excl, sizeof(f.excl), NULL, 0,
-				   true, f.ctx, f.ctx_sz, &ran);
-		ASSERT_TRUE(ran, "loader ran");
-		ASSERT_EQ(r, -EINVAL, "tampered blob rejected by emit_signature_match");
+		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
+				 sizeof(junk), KEY_SPEC_SESSION_KEYRING, 0);
+		ASSERT_EQ(fd, -EBADMSG, "invalid signature rejected at load");
 	}
 	gen_loader_fixture_fini(&f);
 }
 
-static void metadata_not_exclusive(void)
+static void signed_nonexcl_fd_array_rejected(void)
 {
+	static const __u8 junk[64] = { 0x30, 0x42, 0x13, 0x37, };
 	struct gen_loader_fixture f;
-	bool ran;
-	int r;
+	int map_fd, fd;
 
 	if (gen_loader_fixture_init(&f) == 0) {
 		/*
-		 * Correct blob but a non-exclusive metadata map: the verifier does
-		 * not reject (excl_prog_sha unset), so the runtime map->excl == 1
-		 * check in the loader must.
+		 * A signed program may only bind exclusive maps through fd_array
+		 * (their contents are folded into the signature). Binding a
+		 * non-exclusive map is rejected, before the signature is even
+		 * examined.
 		 */
-		r = run_gen_loader(f.gopts.insns, f.gopts.insns_sz, f.blob,
-				   f.data_sz, NULL, 0, NULL, 0, true, f.ctx,
-				   f.ctx_sz, &ran);
-		ASSERT_TRUE(ran, "loader ran");
-		ASSERT_EQ(r, -EINVAL, "non-exclusive metadata map rejected");
+		map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "nonexcl", 4,
+					f.data_sz, 1, NULL);
+		if (ASSERT_OK_FD(map_fd, "nonexcl_map")) {
+			if (ASSERT_OK(bpf_map_freeze(map_fd), "freeze")) {
+				fd = load_loader(f.gopts.insns, f.gopts.insns_sz,
+						 map_fd, junk, sizeof(junk),
+						 KEY_SPEC_SESSION_KEYRING, 1);
+				ASSERT_EQ(fd, -EPERM,
+					  "non-exclusive map in signed fd_array rejected");
+				if (fd >= 0)
+					close(fd);
+			}
+			close(map_fd);
+		}
 	}
 	gen_loader_fixture_fini(&f);
 }
 
-static void metadata_hash_not_computed(void)
+static void signed_unfrozen_fd_array_rejected(void)
 {
+	static const __u8 junk[64] = { 0x30, 0x42, 0x13, 0x37, };
+	LIBBPF_OPTS(bpf_map_create_opts, mopts);
 	struct gen_loader_fixture f;
-	bool ran;
-	int r;
+	__u32 key = 0;
+	int map_fd, fd;
 
 	if (gen_loader_fixture_init(&f) == 0) {
 		/*
-		 * Correct, exclusive, frozen map, but its hash was never computed
-		 * (no OBJ_GET_INFO_BY_FD), so map->sha stays zero. The loader must
-		 * fail closed rather than treat an unset hash as a match.
+		 * The metadata map must be frozen before a signed load so the
+		 * folded bytes cannot change afterwards. Bind an exclusive map
+		 * with matching contents but skip the freeze: the load must be
+		 * rejected by the frozen check with -EPERM. The exclusivity
+		 * check right after it would pass, so the errno uniquely pins
+		 * the freeze requirement.
 		 */
-		r = run_gen_loader(f.gopts.insns, f.gopts.insns_sz, f.blob,
-				   f.data_sz, f.excl, sizeof(f.excl), NULL, 0,
-				   false, f.ctx, f.ctx_sz, &ran);
-		ASSERT_TRUE(ran, "loader ran");
-		ASSERT_EQ(r, -EINVAL, "uncomputed metadata hash rejected");
+		mopts.excl_prog_hash = f.excl;
+		mopts.excl_prog_hash_size = sizeof(f.excl);
+		map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "unfrozen", 4,
+					f.data_sz, 1, &mopts);
+		if (ASSERT_OK_FD(map_fd, "unfrozen_map")) {
+			if (ASSERT_OK(bpf_map_update_elem(map_fd, &key, f.blob, 0),
+				      "update")) {
+				fd = load_loader(f.gopts.insns, f.gopts.insns_sz,
+						 map_fd, junk, sizeof(junk),
+						 KEY_SPEC_SESSION_KEYRING, 1);
+				ASSERT_EQ(fd, -EPERM,
+					  "unfrozen map in signed fd_array rejected");
+				if (fd >= 0)
+					close(fd);
+			}
+			close(map_fd);
+		}
 	}
 	gen_loader_fixture_fini(&f);
 }
 
-static void signature_enforced(void)
+static void signed_nonarray_fd_array_rejected(void)
+{
+	static const __u8 junk[64] = { 0x30, 0x42, 0x13, 0x37, };
+	LIBBPF_OPTS(bpf_map_create_opts, mopts);
+	struct gen_loader_fixture f;
+	int map_fd, fd;
+
+	if (gen_loader_fixture_init(&f) == 0) {
+		/*
+		 * Only a plain BPF_MAP_TYPE_ARRAY may be folded into the
+		 * signature. An exclusive map of any other type is rejected
+		 * (-EINVAL) rather than folded - this is the type gate that
+		 * keeps arena maps (map_direct_value_addr() returns a user
+		 * address) and insn-array maps (buffer smaller than value_size)
+		 * out of the hashed region, where the old code would have
+		 * memcpy()'d from them. A hash map stands in here: it is
+		 * exclusive (bound to the loader digest) but not an array.
+		 */
+		mopts.excl_prog_hash = f.excl;
+		mopts.excl_prog_hash_size = sizeof(f.excl);
+		map_fd = bpf_map_create(BPF_MAP_TYPE_HASH, "excl_hash", 4, 4, 1,
+					&mopts);
+		if (ASSERT_OK_FD(map_fd, "excl_hash_map")) {
+			fd = load_loader(f.gopts.insns, f.gopts.insns_sz, map_fd,
+					 junk, sizeof(junk),
+					 KEY_SPEC_SESSION_KEYRING, 1);
+			ASSERT_EQ(fd, -EINVAL,
+				  "non-array map in signed fd_array rejected");
+			if (fd >= 0)
+				close(fd);
+			close(map_fd);
+		}
+	}
+	gen_loader_fixture_fini(&f);
+}
+
+static int setup_meta_map(const struct gen_loader_fixture *f);
+
+static void signed_btf_fd_array_rejected(void)
+{
+	char dir_tmpl[] = "/tmp/signed_loader_btfXXXXXX", *dir = NULL;
+	__u32 sig_sz = 8192;
+	int map_fd = -1, prog_fd = -1;
+	unsigned char *buf = NULL;
+	struct gen_loader_fixture f;
+	bool have_fixture = false;
+	struct btf *btf = NULL;
+	union bpf_attr attr;
+	int fds[2];
+	__u8 sig[8192];
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		return;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		return;
+	}
+	have_fixture = true;
+	if (gen_loader_fixture_init(&f) != 0)
+		goto out;
+
+	/*
+	 * fd_array binds maps and BTFs alike, but only exclusive array maps are
+	 * folded into the signature. Build an otherwise genuinely signed load -
+	 * insns || metadata, exclusive frozen map at fd_array[0] - then smuggle
+	 * an extra BTF into fd_array[1]. A signed program may not bind any BTF,
+	 * so resolving the fd_array entries rejects the BTF with -EACCES (in
+	 * __add_used_btf(), before the signature is even verified).
+	 */
+	buf = malloc((size_t)f.gopts.insns_sz + f.data_sz);
+	if (!ASSERT_OK_PTR(buf, "signbuf"))
+		goto out;
+	memcpy(buf, f.gopts.insns, f.gopts.insns_sz);
+	memcpy(buf + f.gopts.insns_sz, f.blob, f.data_sz);
+	if (!ASSERT_OK(sign_buf(dir, buf, f.gopts.insns_sz + f.data_sz, sig,
+			       &sig_sz), "sign insns||metadata"))
+		goto out;
+
+	map_fd = setup_meta_map(&f);
+	if (!ASSERT_OK_FD(map_fd, "meta_map"))
+		goto out;
+	btf = btf__new_empty();
+	if (!ASSERT_OK_PTR(btf, "btf_new_empty"))
+		goto out;
+	btf__add_int(btf, "int", 4, BTF_INT_SIGNED);
+	if (!ASSERT_OK(btf__load_into_kernel(btf), "btf_load"))
+		goto out;
+
+	fds[0] = map_fd;
+	fds[1] = btf__fd(btf);
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+	attr.insns = ptr_to_u64(f.gopts.insns);
+	attr.insn_cnt = f.gopts.insns_sz / sizeof(struct bpf_insn);
+	attr.license = ptr_to_u64("Dual BSD/GPL");
+	attr.prog_flags = BPF_F_SLEEPABLE;
+	attr.fd_array = ptr_to_u64(fds);
+	attr.fd_array_cnt = 2;
+	attr.signature = ptr_to_u64(sig);
+	attr.signature_size = sig_sz;
+	attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+	memcpy(attr.prog_name, "__loader.prog", sizeof("__loader.prog"));
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	ASSERT_EQ(prog_fd < 0 ? -errno : prog_fd, -EACCES,
+		  "BTF in signed fd_array rejected");
+	if (prog_fd >= 0)
+		close(prog_fd);
+out:
+	if (btf)
+		btf__free(btf);
+	if (map_fd >= 0)
+		close(map_fd);
+	if (have_fixture)
+		gen_loader_fixture_fini(&f);
+	if (dir)
+		run_setup("cleanup", dir);
+	free(buf);
+}
+
+static void signature_failure_logs(void)
 {
 	static const __u8 junk[64] = { 0x30, 0x42, 0x13, 0x37, };
+	char log_buf[1024] = {};
 	struct gen_loader_fixture f;
+	union bpf_attr attr;
 	int fd;
 
 	if (gen_loader_fixture_init(&f) == 0) {
 		/*
-		 * A present-but-invalid signature (the cert bytes are not a
-		 * PKCS#7 signature) must be rejected at load: the signature
-		 * path is honored, not ignored. (The valid path is covered by
-		 * the signed lskels.)
+		 * Signature verification now runs inside bpf_check(), so a
+		 * failure is reported through the verifier log. A present-but-
+		 * invalid signature is rejected and the log says why.
 		 */
-		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
-				 sizeof(junk), KEY_SPEC_SESSION_KEYRING);
+		memset(&attr, 0, sizeof(attr));
+		attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+		attr.insns = ptr_to_u64(f.gopts.insns);
+		attr.insn_cnt = f.gopts.insns_sz / sizeof(struct bpf_insn);
+		attr.license = ptr_to_u64("Dual BSD/GPL");
+		attr.prog_flags = BPF_F_SLEEPABLE;
+		attr.signature = ptr_to_u64(junk);
+		attr.signature_size = sizeof(junk);
+		attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+		attr.log_level = 1;
+		attr.log_buf = ptr_to_u64(log_buf);
+		attr.log_size = sizeof(log_buf);
+		memcpy(attr.prog_name, "__loader.prog", sizeof("__loader.prog"));
+
+		fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			     offsetofend(union bpf_attr, keyring_id));
 		ASSERT_LT(fd, 0, "invalid signature rejected at load");
+		if (fd >= 0)
+			close(fd);
+		ASSERT_HAS_SUBSTR(log_buf, "signature verification failed",
+				  "verifier logs signature failure");
 	}
 	gen_loader_fixture_fini(&f);
 }
@@ -495,12 +573,31 @@ static void signature_too_large(void)
 		 * is rejected before the buffer is read.
 		 */
 		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
-				 64 << 20, KEY_SPEC_SESSION_KEYRING);
+				 64 << 20, KEY_SPEC_SESSION_KEYRING, 0);
 		ASSERT_EQ(fd, -EINVAL, "oversized signature rejected");
 	}
 	gen_loader_fixture_fini(&f);
 }
 
+static void signature_zero_size(void)
+{
+	static const __u8 junk[64] = {};
+	struct gen_loader_fixture f;
+	int fd;
+
+	if (gen_loader_fixture_init(&f) == 0) {
+		/*
+		 * A present signature with signature_size == 0 is rejected
+		 * up front, before the keyring is resolved or the signature
+		 * buffer is read.
+		 */
+		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
+				 0, KEY_SPEC_SESSION_KEYRING, 0);
+		ASSERT_EQ(fd, -EINVAL, "zero-size signature rejected");
+	}
+	gen_loader_fixture_fini(&f);
+}
+
 static void signature_bad_keyring(void)
 {
 	static const __u8 junk[64] = {};
@@ -515,7 +612,7 @@ static void signature_bad_keyring(void)
 		 * large positive serial takes the user-keyring path and won't exist.
 		 */
 		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
-				 sizeof(junk), INT_MAX);
+				 sizeof(junk), INT_MAX, 0);
 		ASSERT_EQ(fd, -EINVAL, "signature with bad keyring_id rejected");
 	}
 	gen_loader_fixture_fini(&f);
@@ -575,7 +672,7 @@ static void metadata_ctx_max_entries_ignored(void)
 	memcpy(blob, gopts.data, data_sz);
 
 	r = run_gen_loader(gopts.insns, gopts.insns_sz, blob, data_sz,
-			   excl, sizeof(excl), NULL, 0, true, ctx, ctx_sz, &ran);
+			   excl, sizeof(excl), NULL, 0, ctx, ctx_sz, &ran);
 	if (!ASSERT_TRUE(ran, "loader ran") ||
 	    !ASSERT_EQ(r, 0, "loader retval"))
 		goto free_blob;
@@ -661,7 +758,7 @@ static void metadata_ctx_initial_value_ignored(void)
 	memcpy(blob, gopts.data, data_sz);
 
 	r = run_gen_loader(gopts.insns, gopts.insns_sz, blob, data_sz,
-			   excl, sizeof(excl), NULL, 0, true, ctx, ctx_sz, &ran);
+			   excl, sizeof(excl), NULL, 0, ctx, ctx_sz, &ran);
 	if (!ASSERT_TRUE(ran, "loader ran") ||
 	    !ASSERT_EQ(r, 0, "loader retval"))
 		goto free_blob;
@@ -714,6 +811,7 @@ static void signature_authenticates_insns(void)
 	__u8 excl[SHA256_DIGEST_LENGTH], sig[8192];
 	__u32 sig_sz = sizeof(sig), insns_sz, data_sz, ctx_sz;
 	unsigned char *insns = NULL, *tampered = NULL, *blob = NULL;
+	unsigned char *signbuf = NULL;
 	int nr_maps = 0, nr_progs = 0, r;
 	struct bpf_program *p;
 	struct bpf_map *m;
@@ -760,29 +858,141 @@ static void signature_authenticates_insns(void)
 	memcpy(blob, gopts.data, data_sz);
 	libbpf_sha256(insns, insns_sz, excl);
 
-	if (!ASSERT_OK(sign_buf(dir, insns, insns_sz, sig, &sig_sz), "sign-file"))
+	signbuf = malloc((size_t)insns_sz + data_sz);
+	if (!ASSERT_OK_PTR(signbuf, "signbuf"))
+		goto cleanup;
+	memcpy(signbuf, insns, insns_sz);
+	memcpy(signbuf + insns_sz, blob, data_sz);
+	if (!ASSERT_OK(sign_buf(dir, signbuf, insns_sz + data_sz, sig, &sig_sz),
+		       "sign-file"))
 		goto cleanup;
 
 	memset(ctx, 0, ctx_sz);
 	((struct bpf_loader_ctx *)ctx)->sz = ctx_sz;
 	r = run_gen_loader(insns, insns_sz, blob, data_sz, excl, sizeof(excl),
-			   sig, sig_sz, true, ctx, ctx_sz, &ran);
+			   sig, sig_sz, ctx, ctx_sz, &ran);
 	ASSERT_TRUE(ran, "valid signature: loader loaded and ran");
 	ASSERT_EQ(r, 0, "valid signature accepted");
 	close_loader_ctx_fds(ctx, nr_maps, nr_progs);
 
 	memcpy(tampered, insns, insns_sz);
 	tampered[insns_sz / 2] ^= 0xff;
+	/*
+	 * Bind the metadata map to the tampered loader's own digest, so the
+	 * verifier's exclusive-map check (excl_prog_sha == prog->digest) passes
+	 * and the signature - verified after the maps are resolved - is what
+	 * rejects the load. This is the attacker's best case: even after
+	 * re-binding the exclusive map to their tampered loader, the signature
+	 * over the original insns || metadata still fails. (Leaving the map
+	 * bound to the original digest would instead trip the excl check first.)
+	 */
+	libbpf_sha256(tampered, insns_sz, excl);
 	memset(ctx, 0, ctx_sz);
 	((struct bpf_loader_ctx *)ctx)->sz = ctx_sz;
 	r = run_gen_loader(tampered, insns_sz, blob, data_sz, excl, sizeof(excl),
-			   sig, sig_sz, true, ctx, ctx_sz, &ran);
+			   sig, sig_sz, ctx, ctx_sz, &ran);
 	ASSERT_FALSE(ran, "tampered loader rejected before run");
 	ASSERT_EQ(r, -EKEYREJECTED, "signature is bound to the instructions");
 cleanup:
 	free(insns);
 	free(tampered);
 	free(blob);
+	free(signbuf);
+	free(ctx);
+	test_signed_loader__destroy(skel);
+	run_setup("cleanup", dir);
+}
+
+static void signature_authenticates_metadata(void)
+{
+	LIBBPF_OPTS(gen_loader_opts, gopts, .gen_hash = true);
+	char dir_tmpl[] = "/tmp/signed_loaderXXXXXX", *dir;
+	struct test_signed_loader *skel = NULL;
+	__u8 excl[SHA256_DIGEST_LENGTH], sig[8192];
+	__u32 sig_sz = sizeof(sig), insns_sz, data_sz, ctx_sz;
+	unsigned char *insns = NULL, *blob = NULL;
+	unsigned char *signbuf = NULL;
+	int nr_maps = 0, nr_progs = 0, r;
+	struct bpf_program *p;
+	struct bpf_map *m;
+	void *ctx = NULL;
+	bool ran;
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		return;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		return;
+	}
+
+	skel = test_signed_loader__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		goto cleanup;
+	if (!ASSERT_OK(bpf_object__gen_loader(skel->obj, &gopts), "gen_loader"))
+		goto cleanup;
+	if (!ASSERT_OK(bpf_object__load(skel->obj), "gen_load"))
+		goto cleanup;
+
+	bpf_object__for_each_program(p, skel->obj)
+		nr_progs++;
+	bpf_object__for_each_map(m, skel->obj)
+		nr_maps++;
+	ctx_sz = sizeof(struct bpf_loader_ctx) +
+		 nr_maps * sizeof(struct bpf_map_desc) +
+		 nr_progs * sizeof(struct bpf_prog_desc);
+	insns_sz = gopts.insns_sz;
+	data_sz = gopts.data_sz;
+	ctx = calloc(1, ctx_sz);
+	insns = malloc(insns_sz);
+	blob = malloc(data_sz);
+	if (!ASSERT_OK_PTR(ctx, "ctx") ||
+	    !ASSERT_OK_PTR(insns, "insns") ||
+	    !ASSERT_OK_PTR(blob, "blob"))
+		goto cleanup;
+	memcpy(insns, gopts.insns, insns_sz);
+	memcpy(blob, gopts.data, data_sz);
+	libbpf_sha256(insns, insns_sz, excl);
+
+	signbuf = malloc((size_t)insns_sz + data_sz);
+	if (!ASSERT_OK_PTR(signbuf, "signbuf"))
+		goto cleanup;
+	memcpy(signbuf, insns, insns_sz);
+	memcpy(signbuf + insns_sz, blob, data_sz);
+	if (!ASSERT_OK(sign_buf(dir, signbuf, insns_sz + data_sz, sig, &sig_sz),
+		       "sign-file"))
+		goto cleanup;
+
+	memset(ctx, 0, ctx_sz);
+	((struct bpf_loader_ctx *)ctx)->sz = ctx_sz;
+	r = run_gen_loader(insns, insns_sz, blob, data_sz, excl, sizeof(excl),
+			   sig, sig_sz, ctx, ctx_sz, &ran);
+	ASSERT_TRUE(ran, "valid signature: loader loaded and ran");
+	ASSERT_EQ(r, 0, "valid signature accepted");
+	close_loader_ctx_fds(ctx, nr_maps, nr_progs);
+
+	/*
+	 * Tamper the metadata after signing while leaving the instructions
+	 * and thus the exclusive hash binding untouched: the map freezes
+	 * fine and excl_prog_sha still matches the loader's digest, so the
+	 * load reaches signature verification, which folds the live frozen
+	 * map bytes into the checked payload and must reject the modified
+	 * blob. A kernel folding anything but the map contents themselves
+	 * would wrongly accept this load.
+	 */
+	blob[data_sz / 2] ^= 0xff;
+	memset(ctx, 0, ctx_sz);
+	((struct bpf_loader_ctx *)ctx)->sz = ctx_sz;
+	r = run_gen_loader(insns, insns_sz, blob, data_sz, excl, sizeof(excl),
+			   sig, sig_sz, ctx, ctx_sz, &ran);
+	ASSERT_FALSE(ran, "tampered metadata rejected before run");
+	ASSERT_EQ(r, -EKEYREJECTED, "signature is bound to the metadata");
+cleanup:
+	free(insns);
+	free(blob);
+	free(signbuf);
 	free(ctx);
 	test_signed_loader__destroy(skel);
 	run_setup("cleanup", dir);
@@ -1007,10 +1217,11 @@ static void lsm_signature_verdict(void)
 {
 	char dir_tmpl[] = "/tmp/signed_loader_lsmXXXXXX", *dir = NULL;
 	struct test_signed_loader_lsm *lsm = NULL;
+	__u32 sig_sz = 8192, msig_sz = 8192;
 	int map_fd = -1, prog_fd = -1;
 	bool have_fixture = false;
 	struct gen_loader_fixture f;
-	__u32 sig_sz = 8192;
+	unsigned char *buf;
 	__s32 ses_serial;
 	__u8 sig[8192];
 
@@ -1029,7 +1240,7 @@ static void lsm_signature_verdict(void)
 	if (!ASSERT_OK_FD(map_fd, "meta_map_unsigned"))
 		goto out;
 	lsm->bss->seen = 0;
-	prog_fd = load_loader(f.gopts.insns, f.gopts.insns_sz, map_fd, NULL, 0, 0);
+	prog_fd = load_loader(f.gopts.insns, f.gopts.insns_sz, map_fd, NULL, 0, 0, 0);
 	close(map_fd);
 	map_fd = -1;
 	if (!ASSERT_OK_FD(prog_fd, "unsigned loader load"))
@@ -1062,22 +1273,51 @@ static void lsm_signature_verdict(void)
 		goto out;
 	lsm->bss->seen = 0;
 	prog_fd = load_loader(f.gopts.insns, f.gopts.insns_sz, map_fd, sig,
-			      sig_sz, KEY_SPEC_SESSION_KEYRING);
+			      sig_sz, KEY_SPEC_SESSION_KEYRING, 0);
 	close(map_fd);
 	map_fd = -1;
-	if (!ASSERT_OK_FD(prog_fd, "signed loader load"))
-		goto out;
-	close(prog_fd);
+	ASSERT_EQ(prog_fd, -EACCES, "unfolded metadata rejected");
+	if (prog_fd >= 0)
+		close(prog_fd);
 	prog_fd = -1;
 
 	ses_serial = syscall(__NR_keyctl, KEYCTL_GET_KEYRING_ID,
 			     KEY_SPEC_SESSION_KEYRING, 0);
 	ASSERT_EQ(lsm->bss->seen, 1, "signed: one observed load");
-	ASSERT_EQ(lsm->bss->sig_verdict, BPF_SIG_VERIFIED, "signed verdict");
+	ASSERT_EQ(lsm->bss->sig_verdict, BPF_SIG_VERIFIED,
+		  "admission saw a valid signature");
 	ASSERT_EQ(lsm->bss->sig_keyring_type, BPF_SIG_KEYRING_USER, "signed keyring type");
 	ASSERT_GT(ses_serial, 0, "session keyring serial resolved");
 	ASSERT_EQ(lsm->bss->sig_keyring_serial, ses_serial,
 		  "signed: validated against session keyring");
+
+	buf = malloc((size_t)f.gopts.insns_sz + f.data_sz);
+	if (!ASSERT_OK_PTR(buf, "meta_signbuf"))
+		goto out;
+	memcpy(buf, f.gopts.insns, f.gopts.insns_sz);
+	memcpy(buf + f.gopts.insns_sz, f.blob, f.data_sz);
+	if (!ASSERT_OK(sign_buf(dir, buf, f.gopts.insns_sz + f.data_sz,
+				sig, &msig_sz), "sign insns||metadata")) {
+		free(buf);
+		goto out;
+	}
+	free(buf);
+
+	map_fd = setup_meta_map(&f);
+	if (!ASSERT_OK_FD(map_fd, "meta_map_bound"))
+		goto out;
+	lsm->bss->seen = 0;
+	prog_fd = load_loader(f.gopts.insns, f.gopts.insns_sz, map_fd, sig,
+			      msig_sz, KEY_SPEC_SESSION_KEYRING, 1);
+	close(map_fd);
+	map_fd = -1;
+	if (!ASSERT_OK_FD(prog_fd, "metadata-bound loader load"))
+		goto out;
+	close(prog_fd);
+	prog_fd = -1;
+	ASSERT_EQ(lsm->bss->seen, 1, "metadata: one observed load");
+	ASSERT_EQ(lsm->bss->sig_verdict, BPF_SIG_VERIFIED,
+		  "metadata-bound verdict");
 out:
 	if (map_fd >= 0)
 		close(map_fd);
@@ -1090,22 +1330,471 @@ static void lsm_signature_verdict(void)
 	test_signed_loader_lsm__destroy(lsm);
 }
 
+/*
+ * Load-time metadata verification: the kernel folds the frozen metadata map
+ * into the signature (insns || metadata) and checks it at BPF_PROG_LOAD via
+ * fd_array_cnt, rather than the loader checking from within BPF. Sign that
+ * concatenation, hand the kernel the map, and confirm the signed loader loads,
+ * runs, and installs its target.
+ */
+static int loadtime_drive(const char *dir, const void *insns, __u32 insns_sz,
+			  const void *data, __u32 data_sz, const __u8 *excl,
+			  void *ctx, __u32 ctx_sz, int *load_ret, bool *ran)
+{
+	LIBBPF_OPTS(bpf_map_create_opts, mopts,
+		    .excl_prog_hash = excl,
+		    .excl_prog_hash_size = SHA256_DIGEST_LENGTH);
+	__u32 sig_sz = 8192, key = 0;
+	unsigned char *buf = NULL;
+	int map_fd, prog_fd, ret = 0;
+	union bpf_attr attr;
+	__u8 sig[8192];
+
+	*ran = false;
+	*load_ret = 0;
+
+	/*
+	 * Metadata map, bound to the loader digest and frozen, exactly as
+	 * skel_internal.h's bpf_load_and_run() sets it up.
+	 */
+	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "__loader.map", 4,
+				data_sz, 1, &mopts);
+	if (map_fd < 0) {
+		ret = -errno;
+		goto out_load;
+	}
+	if (bpf_map_update_elem(map_fd, &key, data, 0) || bpf_map_freeze(map_fd)) {
+		ret = -errno;
+		goto out_load;
+	}
+
+	/* Sign insns || metadata, the same bytes the kernel reconstructs. */
+	buf = malloc((size_t)insns_sz + data_sz);
+	if (!buf) {
+		ret = -ENOMEM;
+		goto out_load;
+	}
+	memcpy(buf, insns, insns_sz);
+	memcpy(buf + insns_sz, data, data_sz);
+	ret = sign_buf(dir, buf, insns_sz + data_sz, sig, &sig_sz);
+	if (ret)
+		goto out_load;
+
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+	attr.insns = ptr_to_u64(insns);
+	attr.insn_cnt = insns_sz / sizeof(struct bpf_insn);
+	attr.license = ptr_to_u64("Dual BSD/GPL");
+	attr.prog_flags = BPF_F_SLEEPABLE;
+	attr.fd_array = ptr_to_u64(&map_fd);
+	attr.signature = ptr_to_u64(sig);
+	attr.signature_size = sig_sz;
+	attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+	attr.fd_array_cnt = 1;
+	memcpy(attr.prog_name, "__loader.prog", sizeof("__loader.prog"));
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	if (prog_fd < 0) {
+		ret = -errno;
+		goto out_load;
+	}
+
+	memset(&attr, 0, sizeof(attr));
+	attr.test.prog_fd = prog_fd;
+	attr.test.ctx_in = ptr_to_u64(ctx);
+	attr.test.ctx_size_in = ctx_sz;
+	if (syscall(__NR_bpf, BPF_PROG_RUN, &attr,
+		    offsetofend(union bpf_attr, test)) < 0) {
+		ret = -errno;
+		goto out_prog;
+	}
+	*ran = true;
+	ret = (int)attr.test.retval;
+out_prog:
+	close(prog_fd);
+	goto out_map;
+out_load:
+	*load_ret = ret;
+out_map:
+	free(buf);
+	if (map_fd >= 0)
+		close(map_fd);
+	return ret;
+}
+
+static void loadtime_verify(struct bpf_object *obj, int expect_maps)
+{
+	LIBBPF_OPTS(gen_loader_opts, gopts, .gen_hash = true);
+	char dir_tmpl[] = "/tmp/signed_loader_ltXXXXXX", *dir = NULL;
+	int nr_maps = 0, nr_progs = 0, load_ret = 0, r;
+	__u8 excl[SHA256_DIGEST_LENGTH];
+	struct bpf_prog_desc *pd;
+	struct bpf_map_desc *md;
+	unsigned char *blob = NULL;
+	struct bpf_program *p;
+	struct bpf_map *m;
+	__u32 ctx_sz, data_sz;
+	void *ctx = NULL;
+	bool ran = false;
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		return;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		return;
+	}
+
+	if (!ASSERT_OK(bpf_object__gen_loader(obj, &gopts), "gen_loader"))
+		goto out;
+	if (!ASSERT_OK(bpf_object__load(obj), "gen_load"))
+		goto out;
+
+	bpf_object__for_each_program(p, obj)
+		nr_progs++;
+	bpf_object__for_each_map(m, obj)
+		nr_maps++;
+	if (!ASSERT_EQ(nr_maps, expect_maps, "fixture map count"))
+		goto out;
+
+	ctx_sz = sizeof(struct bpf_loader_ctx) +
+		 nr_maps * sizeof(struct bpf_map_desc) +
+		 nr_progs * sizeof(struct bpf_prog_desc);
+	ctx = calloc(1, ctx_sz);
+	if (!ASSERT_OK_PTR(ctx, "ctx_alloc"))
+		goto out;
+	((struct bpf_loader_ctx *)ctx)->sz = ctx_sz;
+
+	data_sz = gopts.data_sz;
+	blob = malloc(data_sz);
+	if (!ASSERT_OK_PTR(blob, "blob_alloc"))
+		goto out;
+	memcpy(blob, gopts.data, data_sz);
+
+	/* excl_prog_hash = SHA256(loader insns) == the loader's prog->digest. */
+	libbpf_sha256(gopts.insns, gopts.insns_sz, excl);
+
+	r = loadtime_drive(dir, gopts.insns, gopts.insns_sz, blob, data_sz,
+			   excl, ctx, ctx_sz, &load_ret, &ran);
+	ASSERT_OK(load_ret, "signed loader loaded (insns || metadata)");
+	ASSERT_TRUE(ran, "loader ran");
+	ASSERT_EQ(r, 0, "loader installed its target");
+
+	md = (struct bpf_map_desc *)((char *)ctx + sizeof(struct bpf_loader_ctx));
+	pd = (struct bpf_prog_desc *)(md + nr_maps);
+	ASSERT_GT(pd[0].prog_fd, 0, "target program installed");
+	if (nr_maps)
+		ASSERT_GT(md[0].map_fd, 0, "target map installed");
+
+	close_loader_ctx_fds(ctx, nr_maps, nr_progs);
+out:
+	free(blob);
+	free(ctx);
+	if (dir)
+		run_setup("cleanup", dir);
+}
+
+static void loadtime_no_map(void)
+{
+	struct test_signed_loader *skel = test_signed_loader__open();
+
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+	loadtime_verify(skel->obj, 0);
+	test_signed_loader__destroy(skel);
+}
+
+static void loadtime_with_map(void)
+{
+	struct test_signed_loader_map *skel = test_signed_loader_map__open();
+
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+	loadtime_verify(skel->obj, 1);
+	test_signed_loader_map__destroy(skel);
+}
+
+/*
+ * A signed program need not bind any map. A plain BPF_PROG_TYPE_SYSCALL
+ * program with no fd_array is signed over its instructions alone: the kernel
+ * verifies the signature, folds no metadata, and the program loads. Exercise
+ * the fd_array == NULL / fd_array_cnt == 0 path, and confirm the signature
+ * still authenticates the instructions (a tampered copy is rejected).
+ */
+static void signed_no_fd_array(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	char dir_tmpl[] = "/tmp/signed_loaderXXXXXX", *dir;
+	__u32 sig_sz = 8192;
+	union bpf_attr attr;
+	__u8 sig[8192];
+	int prog_fd, err;
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		return;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		return;
+	}
+
+	/* No metadata map: the signed payload is the instructions alone. */
+	if (!ASSERT_OK(sign_buf(dir, insns, sizeof(insns), sig, &sig_sz),
+		       "sign-file"))
+		goto cleanup;
+
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+	attr.insns = ptr_to_u64(insns);
+	attr.insn_cnt = ARRAY_SIZE(insns);
+	attr.license = ptr_to_u64("Dual BSD/GPL");
+	attr.prog_flags = BPF_F_SLEEPABLE;
+	attr.signature = ptr_to_u64(sig);
+	attr.signature_size = sig_sz;
+	attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+	/* fd_array and fd_array_cnt deliberately left NULL/0. */
+	memcpy(attr.prog_name, "signed_nomap", sizeof("signed_nomap"));
+
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	if (!ASSERT_GE(prog_fd, 0, "map-less signed program loaded")) {
+		if (prog_fd >= 0)
+			close(prog_fd);
+		goto cleanup;
+	}
+	close(prog_fd);
+
+	/* The signature covers the instructions, so tampering must be rejected. */
+	insns[0].imm = 1;
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	err = prog_fd < 0 ? -errno : prog_fd;
+	ASSERT_EQ(err, -EKEYREJECTED, "tampered map-less program rejected");
+	if (prog_fd >= 0)
+		close(prog_fd);
+cleanup:
+	run_setup("cleanup", dir);
+}
+
+/*
+ * A signed program may reach maps only through fd_array indices, so the kernel
+ * folds (and thus attests) them. A direct BPF_PSEUDO_MAP_FD reference - a raw,
+ * unfolded fd baked into the signed instructions - is rejected by the verifier.
+ */
+static void signed_map_by_fd_rejected(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_LD_MAP_FD(BPF_REG_1, 0),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	char dir_tmpl[] = "/tmp/signed_loaderXXXXXX", *dir;
+	__u32 sig_sz = 8192;
+	union bpf_attr attr;
+	__u8 sig[8192];
+	int map_fd, prog_fd, err;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "sig_mapfd", 4, 4, 1, NULL);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+	insns[0].imm = map_fd;	/* bake the raw map fd into the ld_imm64 */
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		goto out_map;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		goto out_map;
+	}
+
+	/* Sign the instructions, raw map fd and all. */
+	if (!ASSERT_OK(sign_buf(dir, insns, sizeof(insns), sig, &sig_sz),
+		       "sign-file"))
+		goto cleanup;
+
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+	attr.insns = ptr_to_u64(insns);
+	attr.insn_cnt = ARRAY_SIZE(insns);
+	attr.license = ptr_to_u64("Dual BSD/GPL");
+	attr.prog_flags = BPF_F_SLEEPABLE;
+	attr.signature = ptr_to_u64(sig);
+	attr.signature_size = sig_sz;
+	attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+	/* No fd_array: the map is reached by a raw fd in the instructions. */
+	memcpy(attr.prog_name, "signed_mapfd", sizeof("signed_mapfd"));
+
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	err = prog_fd < 0 ? -errno : prog_fd;
+	ASSERT_EQ(err, -EINVAL, "signed program referencing a map by fd rejected");
+	if (prog_fd >= 0)
+		close(prog_fd);
+cleanup:
+	run_setup("cleanup", dir);
+out_map:
+	close(map_fd);
+}
+
+/*
+ * A signed program may reach maps only through the continuous fd_array, so the
+ * kernel folds (and thus attests) them. Referencing a map by fd_array *index*
+ * while leaving fd_array_cnt at 0 selects the sparse path, which resolves a map
+ * the signature never covered; the verifier rejects it up front with -EACCES.
+ */
+static void signed_sparse_fd_array_rejected(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_LD_IMM64_RAW(BPF_REG_1, BPF_PSEUDO_MAP_IDX, 0),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	char dir_tmpl[] = "/tmp/signed_loader_spXXXXXX", *dir;
+	__u32 sig_sz = 8192;
+	union bpf_attr attr;
+	__u8 sig[8192];
+	int map_fd, prog_fd, err;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "sig_sparse", 4, 4, 1, NULL);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		goto out_map;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		goto out_map;
+	}
+
+	/* Sign the instructions alone; the sparse map is not folded. */
+	if (!ASSERT_OK(sign_buf(dir, insns, sizeof(insns), sig, &sig_sz),
+		       "sign-file"))
+		goto cleanup;
+
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+	attr.insns = ptr_to_u64(insns);
+	attr.insn_cnt = ARRAY_SIZE(insns);
+	attr.license = ptr_to_u64("Dual BSD/GPL");
+	attr.prog_flags = BPF_F_SLEEPABLE;
+	attr.fd_array = ptr_to_u64(&map_fd);
+	attr.fd_array_cnt = 0; /* sparse: force lazy map resolution */
+	attr.signature = ptr_to_u64(sig);
+	attr.signature_size = sig_sz;
+	attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+	memcpy(attr.prog_name, "signed_sparse", sizeof("signed_sparse"));
+
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	err = prog_fd < 0 ? -errno : prog_fd;
+	ASSERT_EQ(err, -EACCES, "signed program binding a sparse fd_array map rejected");
+	if (prog_fd >= 0)
+		close(prog_fd);
+cleanup:
+	run_setup("cleanup", dir);
+out_map:
+	close(map_fd);
+}
+
+static void signed_module_kfunc_rejected(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, BPF_PSEUDO_KFUNC_CALL, 1, 1),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	char dir_tmpl[] = "/tmp/signed_loader_kfnXXXXXX", *dir;
+	int prog_fd, err, fds[2];
+	struct btf *btf = NULL;
+	__u32 sig_sz = 8192;
+	union bpf_attr attr;
+	__u8 sig[8192];
+
+	syscall(__NR_request_key, "keyring", "_uid.0", NULL,
+		KEY_SPEC_SESSION_KEYRING);
+	dir = mkdtemp(dir_tmpl);
+	if (!ASSERT_OK_PTR(dir, "mkdtemp"))
+		return;
+	if (!ASSERT_OK(run_setup("setup", dir), "verify_sig_setup")) {
+		rmdir(dir);
+		return;
+	}
+	if (!ASSERT_OK(sign_buf(dir, insns, sizeof(insns), sig, &sig_sz),
+		       "sign-file"))
+		goto cleanup;
+	btf = btf__new_empty();
+	if (!ASSERT_OK_PTR(btf, "btf_new_empty"))
+		goto cleanup;
+	btf__add_int(btf, "int", 4, BTF_INT_SIGNED);
+	if (!ASSERT_OK(btf__load_into_kernel(btf), "btf_load"))
+		goto cleanup;
+	fds[0] = -1;
+	fds[1] = btf__fd(btf);
+
+	memset(&attr, 0, sizeof(attr));
+	attr.prog_type = BPF_PROG_TYPE_SYSCALL;
+	attr.insns = ptr_to_u64(insns);
+	attr.insn_cnt = ARRAY_SIZE(insns);
+	attr.license = ptr_to_u64("Dual BSD/GPL");
+	attr.prog_flags = BPF_F_SLEEPABLE;
+	attr.fd_array = ptr_to_u64(fds);
+	attr.fd_array_cnt = 0; /* sparse: force lazy kfunc BTF resolution */
+	attr.signature = ptr_to_u64(sig);
+	attr.signature_size = sig_sz;
+	attr.keyring_id = KEY_SPEC_SESSION_KEYRING;
+	memcpy(attr.prog_name, "signed_kfunc", sizeof("signed_kfunc"));
+
+	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr,
+			  offsetofend(union bpf_attr, keyring_id));
+	err = prog_fd < 0 ? -errno : prog_fd;
+	if (prog_fd >= 0)
+		close(prog_fd);
+
+	ASSERT_EQ(err, -EACCES, "module kfunc BTF in signed program rejected");
+cleanup:
+	if (btf)
+		btf__free(btf);
+	run_setup("cleanup", dir);
+}
+
 void test_signed_loader(void)
 {
-	if (test__start_subtest("metadata_check_shape"))
-		metadata_check_shape();
+	if (test__start_subtest("loadtime_no_map"))
+		loadtime_no_map();
+	if (test__start_subtest("loadtime_with_map"))
+		loadtime_with_map();
 	if (test__start_subtest("metadata_match"))
 		metadata_match();
-	if (test__start_subtest("metadata_sha_mismatch"))
-		metadata_sha_mismatch();
-	if (test__start_subtest("metadata_not_exclusive"))
-		metadata_not_exclusive();
-	if (test__start_subtest("metadata_hash_not_computed"))
-		metadata_hash_not_computed();
 	if (test__start_subtest("signature_enforced"))
 		signature_enforced();
+	if (test__start_subtest("signed_nonexcl_fd_array_rejected"))
+		signed_nonexcl_fd_array_rejected();
+	if (test__start_subtest("signed_unfrozen_fd_array_rejected"))
+		signed_unfrozen_fd_array_rejected();
+	if (test__start_subtest("signed_nonarray_fd_array_rejected"))
+		signed_nonarray_fd_array_rejected();
+	if (test__start_subtest("signed_btf_fd_array_rejected"))
+		signed_btf_fd_array_rejected();
+	if (test__start_subtest("signed_module_kfunc_rejected"))
+		signed_module_kfunc_rejected();
+	if (test__start_subtest("signature_failure_logs"))
+		signature_failure_logs();
 	if (test__start_subtest("signature_too_large"))
 		signature_too_large();
+	if (test__start_subtest("signature_zero_size"))
+		signature_zero_size();
 	if (test__start_subtest("signature_bad_keyring"))
 		signature_bad_keyring();
 	if (test__start_subtest("metadata_ctx_max_entries_ignored"))
@@ -1114,6 +1803,8 @@ void test_signed_loader(void)
 		metadata_ctx_initial_value_ignored();
 	if (test__start_subtest("signature_authenticates_insns"))
 		signature_authenticates_insns();
+	if (test__start_subtest("signature_authenticates_metadata"))
+		signature_authenticates_metadata();
 	if (test__start_subtest("hash_requires_frozen"))
 		hash_requires_frozen();
 	if (test__start_subtest("no_update_after_freeze"))
@@ -1132,4 +1823,10 @@ void test_signed_loader(void)
 		map_hash_unsupported_type();
 	if (test__start_subtest("lsm_signature_verdict"))
 		lsm_signature_verdict();
+	if (test__start_subtest("signed_no_fd_array"))
+		signed_no_fd_array();
+	if (test__start_subtest("signed_map_by_fd_rejected"))
+		signed_map_by_fd_rejected();
+	if (test__start_subtest("signed_sparse_fd_array_rejected"))
+		signed_sparse_fd_array_rejected();
 }
tools/testing/selftests/bpf/progs/test_signed_loader.c +5 -4
index d9a4b85f9391..50451a69b99a 100644
@@ -4,10 +4,11 @@
 
 /*
  * Minimal, map-less program. Driven through libbpf's gen_loader (gen_hash)
- * by prog_tests/signed_loader.c so the generated light-skeleton loader (with
- * the emit_signature_match metadata check) can be exercised against good
- * and tampered metadata. A socket filter needs no load-time attach resolution,
- * and having no maps keeps the generated loader's ctx trivial (0 maps, 1 prog).
+ * by prog_tests/signed_loader.c so the generated light-skeleton loader can be
+ * exercised against good and tampered metadata, which the kernel now verifies
+ * at load time via the insns||metadata signature. A socket filter needs no
+ * load-time attach resolution, and having no maps keeps the generated loader's
+ * ctx trivial (0 maps, 1 prog).
  */
 SEC("socket")
 int probe(void *ctx)
Signature · 1 line
2.43.0
#14 lore raw

Re: [PATCH bpf-next v6 7/8] selftests/bpf: Verify load-time signed loader metadata

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Missing file descriptor cleanup on unexpected test failure. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Missing file descriptor cleanup on unexpected test failure.
--

--- Patch [7]: [PATCH bpf-next v6 7/8] selftests/bpf: Verify load-time signed loader metadata --- commit 64830bb6cea6aee71f09d788c841cd423f6308e6
Author: Daniel Borkmann <[email protected]>

selftests/bpf: Verify load-time signed loader metadata

This commit updates the signed loader tests to verify load-time signed loader metadata end to end. It extends the tests with more cases, such as map-less programs and asserting the LSM admission hook, while retiring the older subtests that asserted the removed in-loader check.

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +0 -0
index 5fc417e31fc61..0019492cf07a8 100644

[ ... ]

Quoted 25 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +10 -9
-static void metadata_sha_mismatch(void)
+static void signature_enforced(void)
 {
+	static const __u8 junk[64] = { 0x30, 0x42, 0x13, 0x37, };
 	struct gen_loader_fixture f;
-	bool ran;
-	int r;
+	int fd;
 
 	if (gen_loader_fixture_init(&f) == 0) {
 		/*
-		 * blob[0] lives in the loader's fd_array scratch (first add_data in
-		 * bpf_gen__init); a 0-map program never reads it, so flipping it
-		 * changes only map->sha. The metadata check is the only thing that
-		 * can notice -> isolates emit_signature_match.
+		 * A present-but-invalid signature (the cert bytes are not a
+		 * PKCS#7 signature) must be rejected at load: the signature
+		 * path is honored, not ignored. (The valid path is covered by
+		 * the signed lskels.) Pin -EBADMSG, the PKCS#7 parse failure:
+		 * a looser fd < 0 check could also be satisfied by the sparse
+		 * fd_array rejection (-EACCES) that the loader's map reference
+		 * would trip even if the signature were silently ignored.
 		 */
-		f.blob[0] ^= 0xff;
-		r = run_gen_loader(f.gopts.insns, f.gopts.insns_sz, f.blob,

tools/testing/selftests/bpf/prog_tests/signed_loader.c static void metadata_match(void) · line 331

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +3 -4
-				   f.data_sz, f.excl, sizeof(f.excl), NULL, 0,
-				   true, f.ctx, f.ctx_sz, &ran);
-		ASSERT_TRUE(ran, "loader ran");
-		ASSERT_EQ(r, -EINVAL, "tampered blob rejected by emit_signature_match");
+		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
+				 sizeof(junk), KEY_SPEC_SESSION_KEYRING, 0);
+		ASSERT_EQ(fd, -EBADMSG, "invalid signature rejected at load");
 	}
 	gen_loader_fixture_fini(&f);
 }

[Severity: Medium]
If the kernel unexpectedly accepts the load during signature_enforced, load_loader will return a valid file descriptor. Does this file descriptor leak since the ASSERT_EQ macro allows execution to continue?

Other tests introduced in this patch, such as signature_failure_logs, use the following pattern to ensure the file descriptor is closed on test failure:

    if (fd >= 0)
        close(fd);

Would it make sense to include this cleanup here to prevent file descriptor exhaustion during a cascading test suite failure?

[ ... ]

Quoted 34 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +20 -1
@@ -495,12 +573,31 @@ static void signature_too_large(void)
 		 * is rejected before the buffer is read.
 		 */
 		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
-				 64 << 20, KEY_SPEC_SESSION_KEYRING);
+				 64 << 20, KEY_SPEC_SESSION_KEYRING, 0);
 		ASSERT_EQ(fd, -EINVAL, "oversized signature rejected");
 	}
 	gen_loader_fixture_fini(&f);
 }
 
+static void signature_zero_size(void)
+{
+	static const __u8 junk[64] = {};
+	struct gen_loader_fixture f;
+	int fd;
+
+	if (gen_loader_fixture_init(&f) == 0) {
+		/*
+		 * A present signature with signature_size == 0 is rejected
+		 * up front, before the keyring is resolved or the signature
+		 * buffer is read.
+		 */
+		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
+				 0, KEY_SPEC_SESSION_KEYRING, 0);
+		ASSERT_EQ(fd, -EINVAL, "zero-size signature rejected");
+	}
+	gen_loader_fixture_fini(&f);
+}
+
 static void signature_bad_keyring(void)
 {
 	static const __u8 junk[64] = {};

tools/testing/selftests/bpf/prog_tests/signed_loader.c static void signature_bad_keyring(void) · line 618

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +1 -1
@@ -515,7 +612,7 @@ static void signature_bad_keyring(void)
 		 * large positive serial takes the user-keyring path and won't exist.
 		 */
 		fd = load_loader(f.gopts.insns, f.gopts.insns_sz, -1, junk,
-				 sizeof(junk), INT_MAX);
+				 sizeof(junk), INT_MAX, 0);
 		ASSERT_EQ(fd, -EINVAL, "signature with bad keyring_id rejected");
 	}
 	gen_loader_fixture_fini(&f);

[Severity: Medium]
Similar to signature_enforced, if load_loader unexpectedly succeeds in the newly added signature_zero_size test, or in the updated signature_too_large and signature_bad_keyring tests, could this result in leaked file descriptors?

Adding the same close cleanup check here might help prevent test environment instability if these assertions ever fail.

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

Re: [PATCH bpf-next v6 7/8] selftests/bpf: Verify load-time signed loader metadata

Quoted 2 lines · On 7/8/26 10:07 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Missing file descriptor cleanup on unexpected test failure.

That one makes sense, if there's nothing else, I'll send this as a small follow-up.

author maintainer
#16 lore raw

PATCH v6 8/8 Documentation/bpf: Add BPF signing and enforcement doc

In reply to Daniel Borkmann

Describe the BPF signing design end to end: why a trusted loader is needed, the signature(insns || metadata) contract, load-time verification via fd_array (exclusive + frozen maps), the binary BPF_SIG_{UNSIGNED,VERIFIED} verdict, and how [BPF] LSMs can enforce policy on it.

This writes down the contract on the discussion points with the LSM / integrity folks [0][1]: by the time security_bpf_prog_load() is called, signature verification has fully completed and covers the instructions plus the frozen contents of every bound exclusive map; there is no intermediate "loader verified, payload pending" state to reason about; and what BPF_SIG_VERIFIED means at each hook is spelled out explicitly.

---
 Documentation/bpf/index.rst   |   1 +
 Documentation/bpf/signing.rst | 497 ++++++++++++++++++++++++++++++++++
 2 files changed, 498 insertions(+)
 create mode 100644 Documentation/bpf/signing.rst
Documentation/bpf/index.rst +1 -0
index 0d5c6f659266..638a00d42bc2 100644
@@ -28,6 +28,7 @@ that goes into great technical depth about the BPF Architecture.
    classic_vs_extended.rst
    bpf_iterators
    bpf_licensing
+   signing
    test_debug
    clang-notes
    linux-notes
Documentation/bpf/signing.rst new file +497 -0

497 lines not on this page · raw message

Signature · 1 line
2.43.0
#17 lore raw
In reply to Daniel Borkmann
This series was applied to bpf/bpf-next.git (master) by Kumar Kartikeya Dwivedi <[email protected]>:

Hello:

This series was applied to bpf/bpf-next.git (master) by Kumar Kartikeya Dwivedi <[email protected]>:

Quoted 10 lines · On Wed, 8 Jul 2026 09:53:35 +0200 you wrote:

The BPF signing scheme signs a light skeleton's loader program and lets the loader vouch for everything else: bpftool bakes the SHA256 of the metadata map into the loader's instructions, signs the instructions, and the loader compares the (frozen, exclusive) map against that hash from within BPF once it runs. The construction is sound as a trusted hash chain, but the kernel itself never attests the metadata, and that split has been the recurring objection from the LSM / integrity side since the scheme was proposed.

[...]

Here is the summary with links:
- [bpf-next,v6,1/8] bpf: Resolve and cache fd_array objects at load time

    https://git.kernel.org/bpf/bpf-next/c/d5a85392392c
  - [bpf-next,v6,2/8] bpf: Verify signed loader metadata at load time
    https://git.kernel.org/bpf/bpf-next/c/b707068e0ed9
  - [bpf-next,v6,3/8] libbpf: Drop in-loader metadata check for load-time verification
    https://git.kernel.org/bpf/bpf-next/c/a2d784869a0f
  - [bpf-next,v6,4/8] bpftool: Check EVP_Digest when computing excl_prog_hash
    https://git.kernel.org/bpf/bpf-next/c/576bcaa1f5c2
  - [bpf-next,v6,5/8] bpftool: Cover loader metadata with the program signature
    https://git.kernel.org/bpf/bpf-next/c/92c7717981bb
  - [bpf-next,v6,6/8] selftests/bpf: Adjust bpf_map layout in verifier_map_ptr
    https://git.kernel.org/bpf/bpf-next/c/77e5f3c91453
  - [bpf-next,v6,7/8] selftests/bpf: Verify load-time signed loader metadata
    https://git.kernel.org/bpf/bpf-next/c/99b321dde704
  - [bpf-next,v6,8/8] Documentation/bpf: Add BPF signing and enforcement doc
    https://git.kernel.org/bpf/bpf-next/c/84c42f515f18

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html