Verify BPF signed loader at load time
Subsystems (8)
Daniel Borkmann
maintainerv3 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]/
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 (6):
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: Cover loader metadata with the program signature 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 | 490 ++++++++++ include/linux/bpf_verifier.h | 23 +- kernel/bpf/syscall.c | 81 +- kernel/bpf/verifier.c | 384 ++++++-- tools/bpf/bpftool/gen.c | 2 + tools/bpf/bpftool/sign.c | 17 +- 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 | 27 +- .../selftests/bpf/prog_tests/signed_loader.c | 859 ++++++++++++++---- 12 files changed, 1569 insertions(+), 393 deletions(-) create mode 100644 Documentation/bpf/signing.rst
Signature · 1 line
2.43.0
Daniel Borkmann
maintainerPATCH v3 1/6 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 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.
UAPI-wise nothing changes, its just the internals on how BPF processes and caches the fd_array favors. Split these into separate helpers for continuous versus sparse to make it easier to follow.
--- include/linux/bpf_verifier.h | 22 +++- kernel/bpf/verifier.c | 209 ++++++++++++++++++++++++++--------- 2 files changed, 179 insertions(+), 52 deletions(-)
include/linux/bpf_verifier.h +21 -1
@@ -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 +* lazily on first 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 +158 -51
291 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH bpf-next v3 1/6] bpf: Resolve and cache fd_array objects at load time
Quoted 16 lines · Daniel Borkmann
The
fd_arraypassed toBPF_PROG_LOADcarries 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, andcheck_and_resolve_insns()and the kfunc BTF resolver later read it again to resolve the program'sBPF_PSEUDO_MAP_IDXand 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_arrayindex, then bind that cached object for the rest of the load.env->fd_arraybecomes a small per-slot {map, btf} cache rather than abpfptr_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_cntgiven): the caller declares the length and every entry is resolved and bound up front (used also by signed loader)
Quoted 8 lines
- sparse (no
fd_array_cnt): left as the legacy path with nofd_arraycache; each reference reads its fd from the caller'sfd_arrayand resolves it on the spot. Deduplication inused_mapsand the kfunc BTF table keeps this correct, and only unsigned programs use this shape.UAPI-wise nothing changes, its just the internals on how BPF processes and caches the
fd_arrayfavors. Split these into separate helpers for continuous versus sparse to make it easier to follow.
Overall looks ok. A few comments below.
Quoted 290 lines
Signed-off-by Daniel Borkmann <[email protected]>Cc Anton Protopopov <[email protected]>--- include/linux/bpf_verifier.h | 22 +++- kernel/bpf/verifier.c | 209 ++++++++++++++++++++++++++--------- 2 files changed, 179 insertions(+), 52 deletions(-)include/linux/bpf_verifier.h +21
-1@@ -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 +* lazily on first 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 +127
-38@@ -2490,6 +2490,79 @@ int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,return 0 ; } +#define BPF_FD_SLOT_BTF 1UL + +static void fd_slot_set_map (struct bpf_fd_array *slot,struct bpf_map *map) +{ + slot->val = (unsigned long )map; +} + +static void fd_slot_set_btf (struct bpf_fd_array *slot,struct btf *btf) +{ + slot->val = (unsigned long )btf |BPF_FD_SLOT_BTF ; +} + +static struct bpf_map *fd_slot_map (struct bpf_fd_array slot) +{ +if (slot.val &BPF_FD_SLOT_BTF ) +return NULL ; +return (struct bpf_map *)slot.val; +} + +static struct btf *fd_slot_btf (struct bpf_fd_array slot) +{ +if (!(slot.val &BPF_FD_SLOT_BTF )) +return NULL ; +return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF ); +} + +static struct btf * +fd_array_get_btf_continuous (struct bpf_verifier_env *env,u32 idx) +{ +struct btf *btf; + +if (idx >= env->fd_array_cnt) { +verbose (env,"kfunc fd_idx %u out of bounds, fd_array_cnt %u\n" , + idx, env->fd_array_cnt); +return ERR_PTR (-EINVAL ); + } + btf =fd_slot_btf (env->fd_array[idx]); +if (!btf) { +verbose (env,"kfunc fd_idx %u is not a module BTF\n" , idx); +return ERR_PTR (-EINVAL ); + } +btf_get (btf); +return btf; +} + +static struct btf * +fd_array_get_btf_sparse (struct bpf_verifier_env *env,u32 idx) +{ +struct btf *btf; +int btf_fd; + +if (copy_from_bpfptr_offset (&btf_fd, env->fd_array_raw, + (size_t )idx *sizeof (btf_fd),sizeof (btf_fd))) +return ERR_PTR (-EFAULT ); + btf =btf_get_by_fd (btf_fd); +if (IS_ERR (btf)) { +verbose (env,"invalid module BTF fd specified\n" ); +return btf; + } +return btf; +} + +static struct btf *fd_array_get_btf (struct bpf_verifier_env *env,u32 idx) +{ +if (env->fd_array) +return fd_array_get_btf_continuous (env, idx); +if (!bpfptr_is_null (env->fd_array_raw)) +return fd_array_get_btf_sparse (env, idx); + +verbose (env,"kfunc offset > 0 without fd_array is invalid\n" ); +return ERR_PTR (-EPROTO ); +} +static struct btf *__find_kfunc_desc_btf (struct bpf_verifier_env *env,s16 offset) {@@ -2498,7 +2571,6 @@ static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,struct bpf_kfunc_btf *b;struct module *mod;struct btf *btf; -int btf_fd; tab = env->prog->aux->kfunc_btf_tab; b = bsearch(&kf_btf, tab->descs, tab->nr_descs,@@ -2509,22 +2581,9 @@ static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,return ERR_PTR (-E2BIG ); } -if (bpfptr_is_null (env->fd_array)) { -verbose (env,"kfunc offset > 0 without fd_array is invalid\n" ); -return ERR_PTR (-EPROTO ); - } - -if (copy_from_bpfptr_offset (&btf_fd, env->fd_array, - offset *sizeof (btf_fd), -sizeof (btf_fd))) -return ERR_PTR (-EFAULT ); - - btf =btf_get_by_fd (btf_fd); -if (IS_ERR (btf)) { -verbose (env,"invalid module BTF fd specified\n" ); + btf =fd_array_get_btf (env, offset); +if (IS_ERR (btf))return btf; - } -if (!btf_is_module (btf)) {verbose (env,"BTF fd for kfunc is not a module BTF\n" );btf_put (btf);@@ -17911,6 +17970,44 @@ static int add_used_map(struct bpf_verifier_env *env, int fd)return __add_used_map (env, map); } +static int fd_array_get_map_idx_continuous (struct bpf_verifier_env *env,u32 idx) +{ +struct bpf_map *map; + +if (idx >= env->fd_array_cnt) { +verbose (env,"fd_idx %u out of bounds, fd_array_cnt %u\n" , + idx, env->fd_array_cnt); +return -EINVAL ; + } + map =fd_slot_map (env->fd_array[idx]); +if (!map) { +verbose (env,"fd_idx %u is not a map\n" , idx); +return -EINVAL ; + } +return __add_used_map (env, map); +} + +static int fd_array_get_map_idx_sparse (struct bpf_verifier_env *env,u32 idx) +{ +int fd; + +if (copy_from_bpfptr_offset (&fd, env->fd_array_raw, + (size_t )idx *sizeof (fd),sizeof (fd))) +return -EFAULT ; +return add_used_map (env, fd); +} + +static int fd_array_get_map_idx (struct bpf_verifier_env *env,u32 idx) +{ +if (env->fd_array) +return fd_array_get_map_idx_continuous (env, idx); +if (!bpfptr_is_null (env->fd_array_raw)) +return fd_array_get_map_idx_sparse (env, idx); + +verbose (env,"fd_idx without fd_array is invalid\n" ); +return -EPROTO ; +} +static int check_alu_fields (struct bpf_verifier_env *env,struct bpf_insn *insn) {u8 class =BPF_CLASS (insn->code);@@ -18128,7 +18225,6 @@ static int check_and_resolve_insns(struct bpf_verifier_env *env)struct bpf_map *map;int map_idx;u64 addr; -u32 fd; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||@@ -18180,21 +18276,13 @@ static int check_and_resolve_insns(struct bpf_verifier_env *env)switch (insn[0 ].src_reg) {case BPF_PSEUDO_MAP_IDX_VALUE :case BPF_PSEUDO_MAP_IDX : -if (bpfptr_is_null (env->fd_array)) { -verbose (env,"fd_idx without fd_array is invalid\n" ); -return -EPROTO ; - } -if (copy_from_bpfptr_offset (&fd, env->fd_array, - insn[0 ].imm *sizeof (fd), -sizeof (fd))) -return -EFAULT ; + map_idx =fd_array_get_map_idx (env, insn[0 ].imm);break ;default : - fd = insn[0 ].imm; + map_idx =add_used_map (env, insn[0 ].imm);break ; } - map_idx =add_used_map (env, fd);if (map_idx <0 )return map_idx; map = env->used_maps[map_idx];@@ -19469,7 +19557,7 @@ struct btf *bpf_get_btf_vmlinux(void)* this case expect that every file descriptor in the array is either a map or * a BTF. Everything else is considered to be trash. */ -static int add_fd_from_fd_array (struct bpf_verifier_env *env,int fd) +static int add_fd_from_fd_array (struct bpf_verifier_env *env,u32 idx,int fd) {struct bpf_map *map;struct btf *btf;@@ -19481,51 +19569,69 @@ static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) err =__add_used_map (env, map);if (err <0 )return err; +fd_slot_set_map (&env->fd_array[idx], map);return 0 ; } btf =__btf_get_by_fd (f);if (!IS_ERR (btf)) {btf_get (btf); -return __add_used_btf (env, btf); + err =__add_used_btf (env, btf); +if (err <0 ) +return err; +fd_slot_set_btf (&env->fd_array[idx], btf); +return 0 ; }verbose (env,"fd %d is not pointing to valid bpf_map or btf\n" , fd);return PTR_ERR (map); } -static int process_fd_array (struct bpf_verifier_env *env,union bpf_attr *attr,bpfptr_t uattr) +#define MAX_FD_ARRAY_CNT (MAX_USED_MAPS + MAX_KFUNC_BTFS) + +static int process_fd_array_continuous (struct bpf_verifier_env *env, +bpfptr_t fd_array,u32 cnt) { -size_t size =sizeof (int ); -int ret; -int fd; +int fd, ret;u32 i; - env->fd_array =make_bpfptr (attr->fd_array, uattr.is_kernel); - -/* -* The only difference between old (no fd_array_cnt is given) and new -* APIs is that in the latter case the fd_array is expected to be
kernel/bpf/verifier.c static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) · line 19598
Quoted 10 lines
kernel/bpf/verifier.c +1
-9-* continuous and is scanned for map fds right away -*/ -if (!attr->fd_array_cnt) -return 0 ; - -/* Check for integer overflow */ -if (attr->fd_array_cnt >= (U32_MAX / size)) { -verbose (env,"fd_array_cnt is too big (%u)\n" , attr->fd_array_cnt); -return -EINVAL ; +if (cnt >MAX_FD_ARRAY_CNT ) {
So, I _think_ I've done the "unlimited" thing because there can be duplicates in fd_array. The limit is actually tracked by __add_{map_btf} So here we hard limit on the size of the fd_array itself. (Even without duplicates, this fd_array can contain, say, MAX_KFUNC_BTFS different maps, which will be in any case rejected by __add_used_map.)
Quoted 29 lines
kernel/bpf/verifier.c +18
-4+verbose (env,"fd_array has too many entries (%u, max %u)\n" , + cnt,MAX_FD_ARRAY_CNT ); +return -E2BIG ; } -for (i =0 ; i < attr->fd_array_cnt; i++) { -if (copy_from_bpfptr_offset (&fd, env->fd_array, i * size, size)) + env->fd_array =kvcalloc (cnt,sizeof (*env->fd_array),GFP_KERNEL ); +if (!env->fd_array) +return -ENOMEM ; + env->fd_array_cnt = cnt; +for (i =0 ; i < cnt; i++) { +if (copy_from_bpfptr_offset (&fd, fd_array, + (size_t )i *sizeof (fd),sizeof (fd)))return -EFAULT ; - - ret =add_fd_from_fd_array (env, fd); + ret =add_fd_from_fd_array (env, i, fd);if (ret)return ret; } +return 0 ; +} +static int process_fd_array (struct bpf_verifier_env *env, +union bpf_attr *attr,bpfptr_t uattr) +{ +bpfptr_t fd_array =make_bpfptr (attr->fd_array, uattr.is_kernel); +
kernel/bpf/verifier.c static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) · line 19633
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+if (bpfptr_is_null (fd_array)) +return 0 ; +/* +* New API: the caller passes fd_array_cnt and a continuous array that +* is resolved and bound up front. Legacy API (no fd_array_cnt): keep +* the caller's array and resolve entries lazily, on first reference. +*/ +if (attr->fd_array_cnt) +return process_fd_array_continuous (env, fd_array, + attr->fd_array_cnt);
Looks like this returns success in case (!fd_array && attr->fd_array_cnt), which is a misconfiguration and should be rejected.
Quoted 15 lines
kernel/bpf/verifier.c +2
-0+ env->fd_array_raw = fd_array;return 0 ; }@@ -20027,6 +20133,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,bpf_clear_insn_aux_data (env,0 , env->prog->len);vfree (env->insn_aux_data); err_free_env: +kvfree (env->fd_array);bpf_stack_liveness_free (env);kvfree (env->cfg.insn_postorder);kvfree (env->scc_info);Signature · 1 line
2.43.0
Daniel Borkmann
maintainerRe: [PATCH bpf-next v3 1/6] bpf: Resolve and cache fd_array objects at load time
Quoted 28 lines · Anton Protopopov
Quoted 16 lines · Daniel Borkmann
The
fd_arraypassed toBPF_PROG_LOADcarries 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, andcheck_and_resolve_insns()and the kfunc BTF resolver later read it again to resolve the program'sBPF_PSEUDO_MAP_IDXand 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_arrayindex, then bind that cached object for the rest of the load.env->fd_arraybecomes a small per-slot {map, btf} cache rather than abpfptr_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_cntgiven): the caller declares the length and every entry is resolved and bound up front (used also by signed loader)Quoted 8 lines
- sparse (no
fd_array_cnt): left as the legacy path with nofd_arraycache; each reference reads its fd from the caller'sfd_arrayand resolves it on the spot. Deduplication inused_mapsand the kfunc BTF table keeps this correct, and only unsigned programs use this shape.UAPI-wise nothing changes, its just the internals on how BPF processes and caches the
fd_arrayfavors. Split these into separate helpers for continuous versus sparse to make it easier to follow.Overall looks ok. A few comments below.
[...]
Quoted 17 lines
kernel/bpf/verifier.c static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) · line 19598
Quoted 5 lines
kernel/bpf/verifier.c +1
-4-/* Check for integer overflow */ -if (attr->fd_array_cnt >= (U32_MAX / size)) { -verbose (env,"fd_array_cnt is too big (%u)\n" , attr->fd_array_cnt); -return -EINVAL ; +if (cnt >MAX_FD_ARRAY_CNT ) {So, I _think_ I've done the "unlimited" thing because there can be duplicates in
fd_array. The limit is actually tracked by __add_{map_btf} So here we hard limit on the size of thefd_arrayitself. (Even without duplicates, thisfd_arraycan contain, say,MAX_KFUNC_BTFSdifferent maps, which will be in any case rejected by__add_used_map.)Quoted 5 lines
kernel/bpf/verifier.c +3
-0+verbose (env,"fd_array has too many entries (%u, max %u)\n" , + cnt,MAX_FD_ARRAY_CNT ); +return -E2BIG ; }
[...]
Quoted 11 lines
Quoted 11 lines
kernel/bpf/verifier.c +10
-0+static int process_fd_array (struct bpf_verifier_env *env, +union bpf_attr *attr,bpfptr_t uattr) +{ +bpfptr_t fd_array =make_bpfptr (attr->fd_array, uattr.is_kernel); + +if (bpfptr_is_null (fd_array)) +return 0 ; +/* +* New API: the caller passes fd_array_cnt and a continuous array that +* is resolved and bound up front. Legacy API (no fd_array_cnt): keep
Quoted 8 lines
kernel/bpf/verifier.c static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) · line 19633
Quoted 5 lines
kernel/bpf/verifier.c +5
-0+* the caller's array and resolve entries lazily, on first reference. +*/ +if (attr->fd_array_cnt) +return process_fd_array_continuous (env, fd_array, + attr->fd_array_cnt);Looks like this returns success in case (!fd_array &&
attr->fd_array_cnt), which is a misconfiguration and should be rejected.
Thanks for the review, addressing both in v4!
Daniel Borkmann
maintainerPATCH v3 2/6 bpf: Verify signed loader metadata at load time
In reply to Daniel BorkmannA 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 [0]. 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 [1][2]. 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 [3]. Let's implement the former, without growing the UAPI.
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. 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.
--- include/linux/bpf_verifier.h | 1 + kernel/bpf/syscall.c | 76 +-------------- kernel/bpf/verifier.c | 175 +++++++++++++++++++++++++++++++++++ 3 files changed, 178 insertions(+), 74 deletions(-)
include/linux/bpf_verifier.h +1 -0
@@ -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 +175 -0
234 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH bpf-next v3 2/6] bpf: Verify signed loader metadata at load time
Quoted 9 lines · Daniel Borkmann
A signed
gen_loaderprogram 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.
Quoted 12 lines
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 [0]. 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 [1][2]. 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 [3]. Let's implement the former, without growing the UAPI.
While you've documented some of the objections from the LSM side, you've missed the largest objection to the existing BPF signing
scheme: KP's scheme runs the PKCS7 signature over the lskel loader, while the scheme that Blaise proposed (in multiple forms, not just Hornet), runs the PKCS7 signature over both the lskel loader and the associated maps, just as you are doing in this patchset. Moving towards a scheme where the PKCS7 signature encompasses both the lskel loader and the maps is a good thing, I'm happy to see that. However, I do have other issues with this patch that I've mentioned previously (more below).
Quoted 39 lines
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 fromfd_arrayand append their frozen contents to the instructions before verification:
the signature now covers insns ||metadata_0||metadata_1|| [...] in thefd_arrayorder, and verification completes inbpf_check(), once thefd_arraymaps are resolved intoused_maps, before the LSM admission hook and the rest of verification.A program is either
BPF_SIG_UNSIGNEDorBPF_SIG_VERIFIED, with nothing in between. While folding thefd_arraymaps, 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, andBPF_SIG_VERIFIEDalways 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_cntmakes the verifier resolve and excl-check them (excl_prog_shavsprog->digest) before it would otherwise compute the digest, so computeprog->digestup front inbpf_check(), over the unmodified instructions the signature covers, for a load that folds metadata.Unsigned programs are not affected. 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.
Signed-off-by Daniel Borkmann <[email protected]>Link https://lore.kernel.org/bpf/CAHC9VhSDkwGgPfrBUh7EgBKEJj_JjnY68c0YAmuuLT_i--GskQ@mail.gmail.com [0] open hereLink https://lore.kernel.org/bpf/2f71d6c03698eb17d51f7247efde777627ee578a.camel@HansenPartnership.com [1] open here--- include/linux/bpf_verifier.h | 1 + kernel/bpf/syscall.c | 76 +-------------- kernel/bpf/verifier.c | 175 +++++++++++++++++++++++++++++++++++ 3 files changed, 178 insertions(+), 74 deletions(-)
...
Quoted 5 lines
kernel/bpf/syscall.c +0
-0
kernel/bpf/syscall.c static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at · line 3126
Quoted 10 lines
kernel/bpf/syscall.c +0
-4@@ -3189,10 +3121,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_atif (err <0 ) goto free_prog; - err =security_bpf_prog_load (prog, attr, token, uattr.is_kernel); -if (err) - goto free_prog; -/* run eBPF verifier */ err =bpf_check (&prog, attr, uattr, attr_log);if (err <0 )
As I mentioned previously, the security_bpf_prog_load() hook should not be moved. Its placement was deliberate, and moving it as you've done in this patch creates a security regression. Without this patch, for processes where SELinux is preventing BPF programs from being loaded, it is able to do so before the process allocates a potentially very large chunk of kernel memory, up to one million BPF instructions. With this patch, even in cases where SELinux will prevent the BPF program load operation, it is not able to do so before the process triggers a potential sizable memory allocation, opening the door for a local DoS attack.
In an effort to work with you on this, I did bring up two alternative
solutions: a new LSM hook for the signature verification, or the use of the existing security_bpf_prog() hook. The latter option is conceptually less clean than the former, but it should still work to control access to the BPF program based on the signature results. You've mentioned that you are not in favor of adding a new hook, but you have ignored the other potential solution of using the security_bpf_prog() hook.
You can (re)read my earlier comments at the lore link below:
https://lore.kernel.org/linux-security-module/CAHC9VhTtaT_8AXSfNKiq4cGq7T=6Dh=huM8niBCwOP8kj+ugjQ@mail.gmail.com/
While I don't like to do this, you haven't given me much of a choice; the security regression can not be ignored:
Quoted 34 lines
kernel/bpf/verifier.c +16
-1@@ -19901,11 +20060,27 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, ret =bpf_vlog_init (&env->log, attr_log->level, attr_log->ubuf, attr_log->size);if (ret) goto err_unlock; +if (env->signature) { + ret =bpf_prog_calc_tag (env->prog); +if (ret <0 ) + goto skip_full_check; + } ret =process_fd_array (env, attr, uattr);if (ret) goto skip_full_check; +if (env->signature) { + ret =bpf_prog_verify_signature (env, attr, uattr.is_kernel); +if (ret) + goto skip_full_check; + } + + ret =security_bpf_prog_load (env->prog, attr, env->prog->aux->token, + uattr.is_kernel); +if (ret) + goto skip_full_check; +mark_verifier_state_clean (env);if (IS_ERR (btf_vmlinux)) { --2.43.0
Signature · 1 line
paul-moore.com
Re: [PATCH bpf-next v3 2/6] bpf: Verify signed loader metadata at load time
Quoted 4 lines · Paul Moore
As I mentioned previously, the
security_bpf_prog_load()hook should not be moved. Its placement was deliberate, and moving it as you've done in this patch creates a security regression.
not true.
Quoted 4 lines
Without this patch,
for processes where SELinux is preventing BPF programs from being loaded, it is able to do so before the process allocates a potentially very large chunk of kernel memory, up to one million BPF instructions.
only when signature verification is requested and the hash over insns is what your hornet thingy did too.
So no regression whatsoever. Exact same behavior.
Quoted 4 lines
With this patch, even in cases where SELinux will prevent the BPF program load operation, it is not able to do so before the process triggers a potential sizable memory allocation, opening the door for a local DoS attack.
Not true either. Worst case is 1M which is 8Mbyte. Not even close to anything DoS worthy.
Quoted 3 lines
In an effort to work with you on this, I did bring up two alternative
solutions: a new LSM hook for the signature verification, or the use of the existingsecurity_bpf_prog()hook.
Sorry we're not going to add new hook because Paul has non-technical grudge against bpf.
Quoted 4 lines
While I don't like to do this, you haven't given me much of a choice; the security regression can not be ignored:
of course. will keep it and let Linus decide during the merge window.
Paul Moore
maintainerRe: [PATCH bpf-next v3 2/6] bpf: Verify signed loader metadata at load time
Quoted 1 line · Alexei Starovoitov
On Thu Jul 2, 2026 at 3:05 PM PDT, Paul Moore wrote:
...
Quoted 7 lines
Quoted 4 lines
With this patch, even in cases where SELinux will prevent the BPF program load operation, it is not able to do so before the process triggers a potential sizable memory allocation, opening the door for a local DoS attack.
Not true either. Worst case is 1M which is 8Mbyte. Not even close to anything DoS worthy.
That's 8MB in a single allocation that can be triggered directly by userspace. I suspect most systems allow a fair number of processes per user; that 8MB allocation can quickly multiply into a big number, especially for more modest, non-server systems/VMs.
Signature · 1 line
paul-moore.com
Daniel Borkmann
maintainerPATCH v3 3/6 libbpf: Drop in-loader metadata check for load-time verification
In reply to Daniel BorkmannThe 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. 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.
--- kernel/bpf/syscall.c | 5 --- 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 | 27 +----------- 5 files changed, 9 insertions(+), 101 deletions(-)
kernel/bpf/syscall.c +0 -5
@@ -1599,11 +1599,6 @@ static int map_create_alloc(union bpf_attr *attr, bpfptr_t uattr, struct bpf_ver 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" );
tools/lib/bpf/bpf_gen_internal.h +0 -1
@@ -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
@@ -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 -25
@@ -320,25 +320,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 +365,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 +375,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
Daniel Borkmann
maintainerPATCH v3 4/6 bpftool: Cover loader metadata with the program signature
In reply to Daniel Borkmannbpftool_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 [0].
--- 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
@@ -793,6 +793,8 @@ static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *hif (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
@@ -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;
@@ -178,7 +190,7 @@ int bpftool_prog_sign(struct bpf_load_and_run_opts *opts)EVP_Digest (opts->insns, opts->insns_sz, opts->excl_prog_hash, &opts->excl_prog_hash_sz,EVP_sha256 (),NULL ); - bd_out =BIO_new (BIO_s_mem ()); + bd_out =BIO_new (BIO_s_mem ());if (!bd_out) { err = -ENOMEM ; goto cleanup;
@@ -212,6 +224,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
[email protected]
AI reviewRe: [PATCH bpf-next v3 4/6] bpftool: Cover loader metadata with the program signature
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Pre-existing issues:
- [Medium] The return value of EVP_Digest() is ignored, meaning that if the digest computation fails, uninitialized stack memory is embedded as the excl_prog_hash in the generated C skeleton. --
commit e281b7d5ac70a49b622a3d4044b8e6f8e9dd90d4
Author: Daniel Borkmann <[email protected]>
bpftool: Cover loader metadata with the program signature
This commit updates bpftool's program signing logic to include loader metadata alongside instructions. The signed artifact now embeds both in the generated skeleton, allowing offline signature validation.
Quoted 4 lines
tools/bpf/bpftool/sign.c +0
-0
[ ... ]
tools/bpf/bpftool/sign.c int bpftool_prog_sign(struct bpf_load_and_run_opts *opts) · line 191
Quoted 3 lines
tools/bpf/bpftool/sign.c +0
-0@@ -178,7 +190,7 @@ int bpftool_prog_sign(struct bpf_load_and_run_opts *opts)EVP_Digest (opts->insns, opts->insns_sz, opts->excl_prog_hash, &opts->excl_prog_hash_sz,EVP_sha256 (),NULL );
[Severity: Medium]
This is a pre-existing issue, but should we check the return value of EVP_Digest() here?
If EVP_Digest() fails (for example, due to an OpenSSL internal error or memory allocation failure), it returns 0 and leaves the hash uncomputed.
When called from gen_trace() in tools/bpf/bpftool/gen.c, this would result in an uninitialized stack buffer (prog_sha) being written to the generated C skeleton file as excl_prog_hash. This could leak build-time tool stack memory into the generated code and cause the program signature validation to fail when loaded.
Quoted 6 lines
tools/bpf/bpftool/sign.c +1
-1- bd_out =BIO_new (BIO_s_mem ()); + bd_out =BIO_new (BIO_s_mem ());if (!bd_out) { err = -ENOMEM ; goto cleanup;
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Daniel Borkmann
maintainerRe: [PATCH bpf-next v3 4/6] bpftool: Cover loader metadata with the program signature
Quoted 4 lines · On 7/2/26 4:48 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Pre-existing issues:
- [Medium] The return value ofEVP_Digest()is ignored, meaning that if the digest computation fails, uninitialized stack memory is embedded as theexcl_prog_hashin the generated C skeleton.
Makes sense, I'll add a fix to address this pre-existing one, too.
Daniel Borkmann
maintainerPATCH v3 5/6 selftests/bpf: Verify load-time signed loader metadata
In reply to Daniel BorkmannThe 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 [...]
#410/1 signed_loader/loadtime_no_map:OK #410/2 signed_loader/loadtime_with_map:OK #410/3 signed_loader/metadata_match:OK #410/4 signed_loader/signature_enforced:OK #410/5 signed_loader/signed_nonexcl_fd_array_rejected:OK #410/6 signed_loader/signed_nonarray_fd_array_rejected:OK #410/7 signed_loader/signed_btf_fd_array_rejected:OK #410/8 signed_loader/signed_module_kfunc_rejected:OK #410/9 signed_loader/signature_failure_logs:OK #410/10 signed_loader/signature_too_large:OK #410/11 signed_loader/signature_bad_keyring:OK #410/12 signed_loader/metadata_ctx_max_entries_ignored:OK #410/13 signed_loader/metadata_ctx_initial_value_ignored:OK #410/14 signed_loader/signature_authenticates_insns:OK #410/15 signed_loader/hash_requires_frozen:OK #410/16 signed_loader/no_update_after_freeze:OK #410/17 signed_loader/freeze_writable_mmap:OK #410/18 signed_loader/no_writable_mmap_frozen:OK #410/19 signed_loader/map_hash_matches_libbpf:OK #410/20 signed_loader/map_hash_multi_element:OK #410/21 signed_loader/map_hash_bad_size:OK #410/22 signed_loader/map_hash_unsupported_type:OK #410/23 signed_loader/lsm_signature_verdict:OK #410/24 signed_loader/signed_no_fd_array:OK #410/25 signed_loader/signed_map_by_fd_rejected:OK #410/26 signed_loader/signed_sparse_fd_array_rejected:OK #410 signed_loader:OK
Summary: 1/26 PASSED, 0 SKIPPED, 0 FAILED
--- .../selftests/bpf/prog_tests/signed_loader.c | 859 ++++++++++++++---- 1 file changed, 695 insertions(+), 164 deletions(-)
tools/testing/selftests/bpf/prog_tests/signed_loader.c +695 -164
@@ -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,220 @@ 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.) */ - 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_LT (fd,0 ,"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" )) { + 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_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; -bool ran; -int r; +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. +* 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. */ - 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_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 void signature_enforced (void ) +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 ; + } +if (gen_loader_fixture_init (&f) !=0 ) + goto out; + have_fixture = true; + +/* +* 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 post-verifier" ); +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,7 +530,7 @@ 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);
@@ -515,7 +550,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 +610,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 +696,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 +749,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 +796,46 @@ 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);
@@ -1007,10 +1060,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 +1083,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 +1116,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,20 +1173,462 @@ 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 ) +return -errno; +if (bpf_map_update_elem (map_fd, &key, data,0 ) ||bpf_map_freeze (map_fd)) { + ret = -errno; + goto out_map; + } + +/* Sign insns || metadata, the same bytes the kernel reconstructs. */ + buf =malloc ((size_t )insns_sz + data_sz); +if (!buf) { + ret = -ENOMEM ; + goto out_map; + } +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_map; + +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 ) { + *load_ret = -errno; + ret = -errno; + goto out_map; + } + +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); +out_map: +free (buf); +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 map_fd =-1 , 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); +if (map_fd >=0 ) +close (map_fd); +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_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_bad_keyring" ))
@@ -1132,4 +1657,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 (); }
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH bpf-next v3 5/6] selftests/bpf: Verify load-time signed loader metadata
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] In `signed_btf_fd_array_rejected()`, if `gen_loader_fixture_init(&f)` fails partway (e.g.…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] In signed_btf_fd_array_rejected(), if gen_loader_fixture_init(&f) fails partway (e.g., bpf_object__gen_loader() fails), it returns non-zero and the code jumps to the out label. Because have_fixture is set to true only *after* the function call, the cleanup block if (have_fixture) gen_loader_fixture_fini(&f); is bypassed. This causes a memory leak of resources like f.skel which were partially allocated by gen_loader_fixture_init(). Setting have_fixture = true before the call (as correctly done in lsm_signature_verdict()) would prevent this leak, since gen_loader_fixture_init() zeroes the struct before allocation. --
commit 029153a8d1d1ffbf9c42e3430f45b09e6533827c
Author: Daniel Borkmann <[email protected]>
Subject: selftests/bpf: Verify load-time signed loader metadata
This commit updates the signed gen_loader selftests to verify load-time metadata enforcement. The kernel now folds the loader's frozen exclusive fd_array maps into the signature at load time instead of checking it from within BPF. The patch adds multiple test cases to ensure the signature logic and bounds are strictly enforced.
Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +0
-0
[ ... ]
Quoted 15 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +15
-0+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 );
tools/testing/selftests/bpf/prog_tests/signed_loader.c static void metadata_match(void) · line 421
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +10
-0+ 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 (gen_loader_fixture_init (&f) !=0 ) + goto out; + have_fixture = true;
[Severity: Low]
Does this leak partially allocated fixture resources on failure?
If gen_loader_fixture_init(&f) fails partway through its setup, it returns non-zero and the code jumps to the out label.
Because have_fixture is set to true only after the function call succeeds, the cleanup block at the out label:
if (have_fixture)
gen_loader_fixture_fini(&f);is bypassed. This skips the cleanup of resources like f.skel which may have been allocated prior to the failure.
Should have_fixture be set to true before calling gen_loader_fixture_init() so that any partially allocated resources are safely torn down?
[ ... ]
Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +11
-0+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); +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Daniel Borkmann
maintainerRe: [PATCH bpf-next v3 5/6] selftests/bpf: Verify load-time signed loader metadata
Quoted 2 lines · On 7/2/26 4:48 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Insigned_btf_fd_array_rejected(), ifgen_loader_fixture_init(&f)fails partway (e.g.,bpf_object__gen_loader()fails), it returns non-zero and the code jumps to theoutlabel. Becausehave_fixtureis set totrueonly *after* the function call, the cleanup blockif (have_fixture) gen_loader_fixture_fini(&f);is bypassed. This causes a memory leak of resources likef.skelwhich were partially allocated bygen_loader_fixture_init(). Settinghave_fixture = truebefore the call (as correctly done inlsm_signature_verdict()) would prevent this leak, sincegen_loader_fixture_init()zeroes the struct before allocation.
Ack, should have been set to true before gen_loader_fixture_init. Fixed locally for a v4.
[email protected]
AI reviewRe: [PATCH bpf-next v3 5/6] selftests/bpf: Verify load-time signed loader metadata
In reply to Daniel BorkmannThis isn't a bug, but was map_fd meant to be dropped from this test? It's initialized to -1 and never changed, so the cleanup branch is unreachable. The sibling tests signed_map_by_fd_rejected and…
Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +0
-0
[ ... ]
Quoted 14 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +10
-0@@ -1090,20 +1173,462 @@ static void lsm_signature_verdict(void)test_signed_loader_lsm__destroy (lsm); } +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 map_fd =-1 , prog_fd, err, fds[2 ]; +struct btf *btf =NULL ;
[ ... ]
tools/testing/selftests/bpf/prog_tests/signed_loader.c static void lsm_signature_verdict(void) · line 1608
Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +12
-0+ 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); +if (map_fd >=0 ) +close (map_fd);
This isn't a bug, but was map_fd meant to be dropped from this test? It's initialized to -1 and never changed, so the cleanup branch is unreachable. The sibling tests signed_map_by_fd_rejected and signed_sparse_fd_array_rejected create and close a map_fd, but signed_module_kfunc_rejected only uses BTF fds and never assigns map_fd.
tools/testing/selftests/bpf/prog_tests/signed_loader.c
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +2
-0+run_setup ("cleanup" , dir); +}
[ ... ]
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/28599478014
Daniel Borkmann
maintainerRe: [PATCH bpf-next v3 5/6] selftests/bpf: Verify load-time signed loader metadata
On 7/2/26 5:17 PM, [email protected] wrote:
[...]
Quoted 4 lines
Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/signed_loader.c +4
-0+cleanup: +if (btf) +btf__free (btf); +if (map_fd >=0 )
Quoted 8 lines
Review
Quoted 1 line
(quoted diff) +1
-0+ close(map_fd);This isn't a bug, but was
map_fdmeant to be dropped from this test? It's initialized to -1 and never changed, so the cleanup branch is unreachable. The sibling testssigned_map_by_fd_rejectedandsigned_sparse_fd_array_rejectedcreate and close amap_fd, butsigned_module_kfunc_rejectedonly uses BTF fds and never assignsmap_fd.
Ack, will clean up in a v4.
Daniel Borkmann
maintainerPATCH v3 6/6 Documentation/bpf: Add BPF signing and enforcement doc
In reply to Daniel BorkmannDescribe 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 | 490 ++++++++++++++++++++++++++++++++++ 2 files changed, 491 insertions(+) create mode 100644 Documentation/bpf/signing.rst
Documentation/bpf/index.rst +1 -0
@@ -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 +490 -0
490 lines not on this page · raw message
Signature · 1 line
2.43.0