* [PATCH v2 1/5] exec: stash a bpf-selected interpreter in struct linux_binprm
2026-07-12 4:08 [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Farid Zakaria
@ 2026-07-12 4:08 ` Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 2/5] binfmt_misc: add binfmt_misc_ops bpf struct_ops Farid Zakaria
` (4 subsequent siblings)
5 siblings, 0 replies; 8+ messages in thread
From: Farid Zakaria @ 2026-07-12 4:08 UTC (permalink / raw)
To: Christian Brauner, Alexei Starovoitov, Daniel Borkmann,
Martin KaFai Lau, Shuah Khan
Cc: Andrii Nakryiko, Kees Cook, Alexander Viro, Jan Kara,
Jonathan Corbet, Jann Horn, John Ericson, linux-fsdevel, linux-mm,
linux-kernel, bpf, linux-doc, linux-kselftest, Farid Zakaria
From: Christian Brauner <brauner@kernel.org>
The upcoming bpf-backed binfmt_misc handlers select the interpreter for
a binary programmatically at exec time. The selection runs before
load_misc_binary() has copied the binary path from bprm->interp into
the argument vector, so the selecting program cannot go through
bprm_change_interp() directly without clobbering argv[1].
Stage the selected path in the bprm instead. The bprm is exclusively
owned by the task doing the exec so no synchronization is needed. The
consumer frees and clears the field once the exec attempt that set it
is finished; free_bprm() covers all error paths.
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
fs/exec.c | 1 +
include/linux/binfmts.h | 1 +
2 files changed, 2 insertions(+)
diff --git a/fs/exec.c b/fs/exec.c
index b92fe7db1..7c9e28f54 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -1418,6 +1418,7 @@ static void free_bprm(struct linux_binprm *bprm)
/* If a binfmt changed the interp, free it. */
if (bprm->interp != bprm->filename)
kfree(bprm->interp);
+ kfree(bprm->bpf_interp);
kfree(bprm->fdpath);
kfree(bprm);
}
diff --git a/include/linux/binfmts.h b/include/linux/binfmts.h
index 7e7333b7b..1dbec6905 100644
--- a/include/linux/binfmts.h
+++ b/include/linux/binfmts.h
@@ -65,6 +65,7 @@ struct linux_binprm {
of the time same as filename, but could be
different for binfmt_{misc,script} */
const char *fdpath; /* generated filename for execveat */
+ const char *bpf_interp; /* interpreter selected by a bpf handler */
unsigned interp_flags;
int execfd; /* File descriptor of the executable */
unsigned long exec;
--
2.51.2
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH v2 2/5] binfmt_misc: add binfmt_misc_ops bpf struct_ops
2026-07-12 4:08 [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 1/5] exec: stash a bpf-selected interpreter in struct linux_binprm Farid Zakaria
@ 2026-07-12 4:08 ` Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 3/5] binfmt_misc: wire up bpf-backed 'B' entries Farid Zakaria
` (3 subsequent siblings)
5 siblings, 0 replies; 8+ messages in thread
From: Farid Zakaria @ 2026-07-12 4:08 UTC (permalink / raw)
To: Christian Brauner, Alexei Starovoitov, Daniel Borkmann,
Martin KaFai Lau, Shuah Khan
Cc: Andrii Nakryiko, Kees Cook, Alexander Viro, Jan Kara,
Jonathan Corbet, Jann Horn, John Ericson, linux-fsdevel, linux-mm,
linux-kernel, bpf, linux-doc, linux-kselftest, Farid Zakaria
From: Christian Brauner <brauner@kernel.org>
Add the bpf plumbing for binary type handlers whose matching and
interpreter selection are implemented by a bpf program instead of a
fixed magic/extension and a fixed interpreter string recorded at
registration time. This serves relocatable binary formats where the
interpreter must be computed per binary, e.g. relative to the location
of the binary itself, as discussed for hermetic Nix-style executables.
A handler is an instance of the new binfmt_misc_ops struct_ops with a
single op:
int (*load)(struct linux_binprm *bprm);
and a name that binfmt_misc entries reference it by. struct_ops is the
sanctioned mechanism for this kind of user-supplied policy callback:
program types, attach types, and the uapi helper list are frozen, and
every recently added subsystem hook (bpf qdisc, SMC handshake control,
io_uring loop ops, sched_ext) is a struct_ops user. The op receives the
bprm as a trusted BTF pointer, so a program can match on the header in
bprm->buf, read arbitrary file content via bpf_dynptr_from_file() to
parse e.g. ELF program headers, and inspect the binary's location. No
dedicated program type, ctx blob, or uapi helper is needed.
The load program is required to be sleepable. Reliable file reads at
exec time fault in the file's pages; a non-sleepable program would be
limited to whatever happens to be resident in the page cache and would
fail sporadically on cold caches. This also constrains the caller:
binfmt_misc must invoke the op from sleepable context, which a later
patch takes care of.
The interpreter is selected through the new kfunc:
int bpf_binprm_set_interp(struct linux_binprm *bprm,
const char *path, size_t path__sz);
which enforces an absolute path shorter than PATH_MAX and stages a copy
in the bprm. The bprm is exclusively owned by the task doing the exec,
so no shared or per-CPU state is involved and nothing here can race.
The kfunc is registered for struct_ops programs with a filter limiting
it to binfmt_misc_ops programs.
Registering an ops instance (updating the struct_ops map or attaching
its link) publishes the handler under its name in a registry keyed by
the registering task's user namespace. Lookups walk the user namespace
hierarchy upwards, mirroring how binfmt_misc instances themselves are
resolved in load_binfmt_misc(). Consumers take a reference on the ops
via bpf_struct_ops_get() which pins the underlying map and programs, so
an activated handler keeps working even if the map is deleted or the
registering container goes away; deregistration only prevents new
activations, exactly like unregistering a tcp congestion ops with live
users.
Link: https://lore.kernel.org/20260704211409.1978485-1-farid.m.zakaria@gmail.com
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
fs/Kconfig.binfmt | 14 +++
fs/Makefile | 1 +
fs/binfmt_misc_bpf.c | 275 ++++++++++++++++++++++++++++++++++++++++++++
include/linux/binfmt_misc.h | 49 ++++++++
4 files changed, 339 insertions(+)
diff --git a/fs/Kconfig.binfmt b/fs/Kconfig.binfmt
index 1949e25c7..daeac4889 100644
--- a/fs/Kconfig.binfmt
+++ b/fs/Kconfig.binfmt
@@ -168,6 +168,20 @@ config BINFMT_MISC
you have use for it; the module is called binfmt_misc. If you
don't know what to answer at this point, say Y.
+config BINFMT_MISC_BPF
+ bool "BPF-selected interpreters for misc binaries"
+ depends on BINFMT_MISC=y
+ depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+ help
+ Allow binfmt_misc binary type handlers to be implemented as bpf
+ struct_ops programs. Instead of matching a fixed magic and
+ redirecting to a fixed interpreter recorded at registration time
+ such handlers match binaries programmatically and compute the
+ interpreter to use per binary, e.g. relative to the location of
+ the binary itself.
+
+ If you don't know what to answer at this point, say N.
+
config COREDUMP
bool "Enable core dump support" if EXPERT
default y
diff --git a/fs/Makefile b/fs/Makefile
index 89a8a9d20..499c6670f 100644
--- a/fs/Makefile
+++ b/fs/Makefile
@@ -33,6 +33,7 @@ obj-$(CONFIG_FS_ENCRYPTION) += crypto/
obj-$(CONFIG_FS_VERITY) += verity/
obj-$(CONFIG_FILE_LOCKING) += locks.o
obj-$(CONFIG_BINFMT_MISC) += binfmt_misc.o
+obj-$(CONFIG_BINFMT_MISC_BPF) += binfmt_misc_bpf.o
obj-$(CONFIG_BINFMT_SCRIPT) += binfmt_script.o
obj-$(CONFIG_BINFMT_ELF) += binfmt_elf.o
obj-$(CONFIG_COMPAT_BINFMT_ELF) += compat_binfmt_elf.o
diff --git a/fs/binfmt_misc_bpf.c b/fs/binfmt_misc_bpf.c
new file mode 100644
index 000000000..72da0964d
--- /dev/null
+++ b/fs/binfmt_misc_bpf.c
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * BPF-backed binary type handlers for binfmt_misc.
+ *
+ * A handler is a struct binfmt_misc_ops struct_ops map. Loading and
+ * registering it makes the handler available under its name in the user
+ * namespace it was registered in. A binfmt_misc 'B' entry activates it:
+ *
+ * echo ':entry:B:<handler-name>::::' > <binfmt_misc>/register
+ */
+
+#include <linux/binfmt_misc.h>
+#include <linux/binfmts.h>
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+#include <linux/cred.h>
+#include <linux/init.h>
+#include <linux/limits.h>
+#include <linux/mutex.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/user_namespace.h>
+
+struct bm_bpf_ops_reg {
+ struct list_head list;
+ const struct binfmt_misc_ops *ops;
+ struct bpf_link *link;
+ struct user_namespace *user_ns;
+};
+
+static DEFINE_MUTEX(bm_bpf_ops_lock);
+static LIST_HEAD(bm_bpf_ops_list);
+
+static struct bpf_struct_ops bpf_binfmt_misc_ops;
+
+static struct bm_bpf_ops_reg *bm_bpf_ops_find(const struct user_namespace *user_ns,
+ const char *name)
+{
+ struct bm_bpf_ops_reg *reg;
+
+ lockdep_assert_held(&bm_bpf_ops_lock);
+
+ list_for_each_entry(reg, &bm_bpf_ops_list, list) {
+ if (reg->user_ns == user_ns && !strcmp(reg->ops->name, name))
+ return reg;
+ }
+ return NULL;
+}
+
+/**
+ * binfmt_misc_get_ops - look up a bpf binary type handler by name
+ * @user_ns: user namespace of the binfmt_misc instance
+ * @name: name the handler was registered under
+ *
+ * Search @user_ns and its ancestors for a handler named @name, mirroring
+ * the instance lookup in load_binfmt_misc(). The returned handler stays
+ * callable until binfmt_misc_put_ops() even if the backing struct_ops map
+ * is detached or deleted in the meantime.
+ *
+ * Return: the handler on success, NULL on failure
+ */
+const struct binfmt_misc_ops *binfmt_misc_get_ops(struct user_namespace *user_ns,
+ const char *name)
+{
+ const struct user_namespace *ns;
+ struct bm_bpf_ops_reg *reg;
+
+ guard(mutex)(&bm_bpf_ops_lock);
+
+ for (ns = user_ns; ns; ns = ns->parent) {
+ reg = bm_bpf_ops_find(ns, name);
+ if (!reg)
+ continue;
+ if (!bpf_struct_ops_get(reg->ops))
+ return NULL;
+ return reg->ops;
+ }
+ return NULL;
+}
+
+void binfmt_misc_put_ops(const struct binfmt_misc_ops *ops)
+{
+ bpf_struct_ops_put(ops);
+}
+
+bool bpf_prog_is_binfmt_misc_ops(const struct bpf_prog *prog)
+{
+ return prog->type == BPF_PROG_TYPE_STRUCT_OPS &&
+ prog->aux->st_ops == &bpf_binfmt_misc_ops;
+}
+
+__bpf_kfunc_start_defs();
+
+/**
+ * bpf_binprm_set_interp - select the interpreter for the current exec
+ * @bprm: binary that is being executed
+ * @path: absolute path to the interpreter
+ * @path__sz: size of the @path buffer, including the terminating NUL
+ *
+ * To be called from the load program of a struct binfmt_misc_ops handler
+ * before returning a positive value. The path is opened with the
+ * credentials of the task doing the exec after the program returns.
+ *
+ * Return: 0 on success, a negative errno on failure
+ */
+__bpf_kfunc int bpf_binprm_set_interp(struct linux_binprm *bprm,
+ const char *path, size_t path__sz)
+{
+ size_t len;
+ char *interp;
+
+ if (!path__sz)
+ return -EINVAL;
+ len = strnlen(path, path__sz);
+ if (len == path__sz)
+ return -EINVAL;
+ if (path[0] != '/')
+ return -EINVAL;
+ if (len >= PATH_MAX)
+ return -ENAMETOOLONG;
+
+ interp = kmemdup_nul(path, len, GFP_KERNEL);
+ if (!interp)
+ return -ENOMEM;
+
+ kfree(bprm->bpf_interp);
+ bprm->bpf_interp = interp;
+ return 0;
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(bm_bpf_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_binprm_set_interp, KF_SLEEPABLE)
+BTF_KFUNCS_END(bm_bpf_kfunc_ids)
+
+static int bm_bpf_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id)
+{
+ if (!btf_id_set8_contains(&bm_bpf_kfunc_ids, kfunc_id))
+ return 0;
+ if (bpf_prog_is_binfmt_misc_ops(prog))
+ return 0;
+ return -EACCES;
+}
+
+static const struct btf_kfunc_id_set bm_bpf_kfunc_set = {
+ .owner = THIS_MODULE,
+ .set = &bm_bpf_kfunc_ids,
+ .filter = bm_bpf_kfunc_filter,
+};
+
+static int bm_bpf_ops__load(struct linux_binprm *bprm)
+{
+ return 0;
+}
+
+static struct binfmt_misc_ops bm_bpf_ops_stubs = {
+ .load = bm_bpf_ops__load,
+};
+
+static int bm_bpf_init(struct btf *btf)
+{
+ return register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
+ &bm_bpf_kfunc_set);
+}
+
+static int bm_bpf_check_member(const struct btf_type *t,
+ const struct btf_member *member,
+ const struct bpf_prog *prog)
+{
+ u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+ switch (moff) {
+ case offsetof(struct binfmt_misc_ops, load):
+ /* Reliable file reads at exec time require sleeping. */
+ if (!prog->sleepable)
+ return -EINVAL;
+ break;
+ }
+ return 0;
+}
+
+static int bm_bpf_init_member(const struct btf_type *t,
+ const struct btf_member *member,
+ void *kdata, const void *udata)
+{
+ const struct binfmt_misc_ops *uops = udata;
+ struct binfmt_misc_ops *ops = kdata;
+ u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+ switch (moff) {
+ case offsetof(struct binfmt_misc_ops, name):
+ if (bpf_obj_name_cpy(ops->name, uops->name,
+ sizeof(ops->name)) <= 0)
+ return -EINVAL;
+ return 1;
+ }
+ return 0;
+}
+
+static int bm_bpf_validate(void *kdata)
+{
+ struct binfmt_misc_ops *ops = kdata;
+
+ if (!ops->load)
+ return -EINVAL;
+ return 0;
+}
+
+static int bm_bpf_reg(void *kdata, struct bpf_link *link)
+{
+ struct binfmt_misc_ops *ops = kdata;
+ struct bm_bpf_ops_reg *reg;
+
+ reg = kzalloc_obj(*reg, GFP_KERNEL_ACCOUNT);
+ if (!reg)
+ return -ENOMEM;
+
+ reg->ops = ops;
+ reg->link = link;
+ reg->user_ns = get_user_ns(current_user_ns());
+
+ guard(mutex)(&bm_bpf_ops_lock);
+
+ if (bm_bpf_ops_find(reg->user_ns, ops->name)) {
+ put_user_ns(reg->user_ns);
+ kfree(reg);
+ return -EEXIST;
+ }
+
+ list_add(®->list, &bm_bpf_ops_list);
+ return 0;
+}
+
+static void bm_bpf_unreg(void *kdata, struct bpf_link *link)
+{
+ struct bm_bpf_ops_reg *reg;
+
+ guard(mutex)(&bm_bpf_ops_lock);
+
+ list_for_each_entry(reg, &bm_bpf_ops_list, list) {
+ if (reg->ops == kdata && reg->link == link) {
+ list_del(®->list);
+ put_user_ns(reg->user_ns);
+ kfree(reg);
+ return;
+ }
+ }
+}
+
+static const struct bpf_verifier_ops bm_bpf_verifier_ops = {
+ .get_func_proto = bpf_base_func_proto,
+ .is_valid_access = bpf_tracing_btf_ctx_access,
+};
+
+static struct bpf_struct_ops bpf_binfmt_misc_ops = {
+ .verifier_ops = &bm_bpf_verifier_ops,
+ .init = bm_bpf_init,
+ .check_member = bm_bpf_check_member,
+ .init_member = bm_bpf_init_member,
+ .validate = bm_bpf_validate,
+ .reg = bm_bpf_reg,
+ .unreg = bm_bpf_unreg,
+ .cfi_stubs = &bm_bpf_ops_stubs,
+ .name = "binfmt_misc_ops",
+ .owner = THIS_MODULE,
+};
+
+static int __init bm_bpf_struct_ops_init(void)
+{
+ return register_bpf_struct_ops(&bpf_binfmt_misc_ops, binfmt_misc_ops);
+}
+late_initcall(bm_bpf_struct_ops_init);
diff --git a/include/linux/binfmt_misc.h b/include/linux/binfmt_misc.h
new file mode 100644
index 000000000..e1d26c430
--- /dev/null
+++ b/include/linux/binfmt_misc.h
@@ -0,0 +1,49 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_BINFMT_MISC_H
+#define _LINUX_BINFMT_MISC_H
+
+#include <linux/types.h>
+
+struct bpf_prog;
+struct linux_binprm;
+struct user_namespace;
+
+#define BINFMT_MISC_OPS_NAME_MAX 16
+
+/**
+ * struct binfmt_misc_ops - bpf-backed binary type handler
+ * @load: match @bprm and select an interpreter via bpf_binprm_set_interp();
+ * returns > 0 if the binary was handled, 0 to fall through to the
+ * handlers registered after this one, a negative errno to fail the
+ * exec; -ENOEXEC does not fail the exec but moves on to the
+ * remaining binary formats
+ * @name: name that 'B' entries reference the handler by
+ */
+struct binfmt_misc_ops {
+ int (*load)(struct linux_binprm *bprm);
+ char name[BINFMT_MISC_OPS_NAME_MAX];
+};
+
+#ifdef CONFIG_BINFMT_MISC_BPF
+const struct binfmt_misc_ops *binfmt_misc_get_ops(struct user_namespace *user_ns,
+ const char *name);
+void binfmt_misc_put_ops(const struct binfmt_misc_ops *ops);
+bool bpf_prog_is_binfmt_misc_ops(const struct bpf_prog *prog);
+#else
+static inline const struct binfmt_misc_ops *
+binfmt_misc_get_ops(struct user_namespace *user_ns, const char *name)
+{
+ return NULL;
+}
+
+static inline void binfmt_misc_put_ops(const struct binfmt_misc_ops *ops)
+{
+}
+
+static inline bool bpf_prog_is_binfmt_misc_ops(const struct bpf_prog *prog)
+{
+ return false;
+}
+#endif /* CONFIG_BINFMT_MISC_BPF */
+
+#endif /* _LINUX_BINFMT_MISC_H */
--
2.51.2
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH v2 3/5] binfmt_misc: wire up bpf-backed 'B' entries
2026-07-12 4:08 [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 1/5] exec: stash a bpf-selected interpreter in struct linux_binprm Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 2/5] binfmt_misc: add binfmt_misc_ops bpf struct_ops Farid Zakaria
@ 2026-07-12 4:08 ` Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 4/5] bpf: allow fs kfuncs for binfmt_misc_ops programs Farid Zakaria
` (2 subsequent siblings)
5 siblings, 0 replies; 8+ messages in thread
From: Farid Zakaria @ 2026-07-12 4:08 UTC (permalink / raw)
To: Christian Brauner, Alexei Starovoitov, Daniel Borkmann,
Martin KaFai Lau, Shuah Khan
Cc: Andrii Nakryiko, Kees Cook, Alexander Viro, Jan Kara,
Jonathan Corbet, Jann Horn, John Ericson, linux-fsdevel, linux-mm,
linux-kernel, bpf, linux-doc, linux-kselftest, Farid Zakaria
From: Christian Brauner <brauner@kernel.org>
Activate a registered binfmt_misc_ops handler through the existing text
interface with the new 'B' entry type:
echo ':name:B:<handler-name>::::' > <binfmt_misc>/register
The offset field carries the handler name; magic, mask, and interpreter
must be empty since the program supplies both the matching and the
interpreter. Reusing the register file keeps the existing permission
model intact: activating a handler requires the same write access to a
binfmt_misc instance as any other registration, and the per user
namespace instance semantics apply unchanged. A 'B' entry in a
container's own instance shadows the host's handlers just like any
other entry, and the privilege needed to shadow e.g. all ELF binaries
is the same as for a static 'M' entry matching \x7fELF today; the only
novelty is that matching becomes programmable.
The entry takes its own reference on the ops for its whole lifetime.
It is dropped in put_binfmt_handler() next to the MISC_FMT_OPEN_FILE
interp_file cleanup, which the existing users refcount already defers
past any concurrent load_misc_binary(), and explicitly on the
registration failure path where the users refcount is not live yet.
The program runs from load_misc_binary(), never from the matching walk
under entries_lock: the read_lock disables preemption while the load
program must be able to sleep to read file content. search_binfmt_handler()
therefore only nominates the next enabled 'B' entry and the program
decides outside the lock. A declining program (returning 0) falls
through to handlers registered after it via a skip cursor and a rescan;
entries registered or removed between rescans can shift the cursor, so
a program may be consulted twice in that window, which is harmless
since matching must be free of side effects. Returning a positive value
without having selected an interpreter terminates the binfmt_misc scan
with -ENOEXEC so the remaining binary formats still get a shot.
The 'C' and 'F' flags are rejected for 'B' entries. 'F' exists to
pre-open a fixed interpreter at registration time in the registrar's
context which is meaningless for a per-exec computed path. 'C' honors
the suid bits of the matched binary while executing the interpreter;
combined with a program-chosen interpreter that would let a user
namespace root pick what runs with a setuid binary's credentials. The
computed path itself cannot widen access: it is opened with open_exec()
under the caller's credentials with the usual LSM and noexec checks,
identical to a statically registered interpreter.
Link: https://lore.kernel.org/20260704211409.1978485-1-farid.m.zakaria@gmail.com
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
Co-developed-by: Farid Zakaria <farid.m.zakaria@gmail.com>
Signed-off-by: Farid Zakaria <farid.m.zakaria@gmail.com>
Assisted-by: Claude:Opus-4.8
---
Documentation/admin-guide/binfmt-misc.rst | 40 +++++++-
fs/binfmt_misc.c | 149 +++++++++++++++++++++++++++---
2 files changed, 175 insertions(+), 14 deletions(-)
diff --git a/Documentation/admin-guide/binfmt-misc.rst b/Documentation/admin-guide/binfmt-misc.rst
index 306ef48f5..de948dae7 100644
--- a/Documentation/admin-guide/binfmt-misc.rst
+++ b/Documentation/admin-guide/binfmt-misc.rst
@@ -26,11 +26,13 @@ Here is what the fields mean:
name below ``/proc/sys/fs/binfmt_misc``; cannot contain slashes ``/`` for
obvious reasons.
- ``type``
- is the type of recognition. Give ``M`` for magic and ``E`` for extension.
+ is the type of recognition. Give ``M`` for magic, ``E`` for extension and
+ ``B`` for a bpf-backed handler (see below).
- ``offset``
is the offset of the magic/mask in the file, counted in bytes. This
defaults to 0 if you omit it (i.e. you write ``:name:type::magic...``).
- Ignored when using filename extension matching.
+ Ignored when using filename extension matching. For ``B`` entries this
+ field carries the name of the bpf handler instead.
- ``magic``
is the byte sequence binfmt_misc is matching for. The magic string
may contain hex-encoded characters like ``\x0a`` or ``\xA4``. Note that you
@@ -97,6 +99,40 @@ There are some restrictions:
offset+size(magic) has to be less than 128
- the interpreter string may not exceed 127 characters
+
+bpf-backed handlers
+-------------------
+
+With ``CONFIG_BINFMT_MISC_BPF`` both the matching and the interpreter
+selection can be delegated to a bpf program. A handler is an instance of the
+``binfmt_misc_ops`` struct_ops with a sleepable ``load`` program and a
+``name``. Once the struct_ops map is registered the handler can be activated
+with a ``B`` entry that references it by name and carries neither magic,
+mask, nor interpreter::
+
+ echo ':qemu:B:my_handler::::' > register
+
+At exec time the ``load`` program receives the ``linux_binprm`` of the
+binary. It can match on the header in ``bprm->buf``, read the file itself,
+e.g. to parse ELF program headers, and derive the interpreter from the
+binary's location. It selects the interpreter by calling the
+``bpf_binprm_set_interp()`` kfunc with an absolute path and returning a
+positive value. Returning ``0`` falls through to the handlers registered
+after this one, a negative errno fails the exec with that error;
+``-ENOEXEC`` ends the binfmt_misc search but lets the remaining binary
+formats have a go. The interpreter is opened with the credentials of the
+task doing the exec, exactly as a statically registered interpreter would
+be.
+
+Handlers are looked up in the user namespace the struct_ops map was
+registered in, falling back to ancestor namespaces, mirroring how
+binfmt_misc instances themselves are looked up. The entry keeps the handler
+alive; deleting the struct_ops map only prevents new registrations.
+
+The ``C`` and ``F`` flags cannot be combined with ``B`` entries: there is no
+fixed interpreter to pre-open and a program-selected interpreter must never
+inherit the credentials of a setuid binary.
+
To use binfmt_misc you have to mount it first. You can mount it with
``mount -t binfmt_misc none /proc/sys/fs/binfmt_misc`` command, or you can add
a line ``none /proc/sys/fs/binfmt_misc binfmt_misc defaults 0 0`` to your
diff --git a/fs/binfmt_misc.c b/fs/binfmt_misc.c
index fcaad14f8..4ece75f95 100644
--- a/fs/binfmt_misc.c
+++ b/fs/binfmt_misc.c
@@ -11,6 +11,7 @@
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/binfmts.h>
+#include <linux/binfmt_misc.h>
#include <linux/bitops.h>
#include <linux/bits.h>
#include <linux/bug.h>
@@ -38,6 +39,7 @@
enum binfmt_misc_entry_bits {
MISC_FMT_ENABLED_BIT = 0,
MISC_FMT_MAGIC_BIT = 1,
+ MISC_FMT_BPF_BIT = 2,
};
/* Entry behavior flags, fixed at registration time. */
@@ -59,6 +61,8 @@ struct binfmt_misc_entry {
char *name;
struct dentry *dentry;
struct file *interp_file;
+ const struct binfmt_misc_ops *bpf_ops; /* bpf-backed handler ('B') */
+ const char *bpf_ops_name;
refcount_t users; /* sync removal with load_misc_binary() */
struct rcu_head rcu;
char buf[]; /* register string, fields point in here */
@@ -109,16 +113,21 @@ static bool entry_matches_extension(const struct binfmt_misc_entry *e,
* search_binfmt_handler - search for a binary handler for @bprm
* @misc: handle to binfmt_misc instance
* @bprm: binary for which we are looking for a handler
+ * @bpf_skip: number of bpf-backed handlers to skip over
*
* Search for a binary type handler for @bprm in the list of registered binary
- * type handlers.
+ * type handlers. A bpf-backed handler cannot be matched here as its program
+ * must run in sleepable context; it is returned as a candidate and the
+ * program decides in load_misc_binary(). @bpf_skip resumes the search after
+ * the first @bpf_skip candidates declined.
*
* The caller must hold the RCU read lock.
*
* Return: binary type list entry on success, NULL on failure
*/
static struct binfmt_misc_entry *
-search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)
+search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm,
+ unsigned int bpf_skip)
{
char *dot = strrchr(bprm->interp, '.');
const char *ext = dot ? dot + 1 : NULL;
@@ -130,6 +139,15 @@ search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)
if (!test_bit(MISC_FMT_ENABLED_BIT, &e->flags))
continue;
+ /* A bpf handler is decided in load_misc_binary(). */
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
+ if (bpf_skip) {
+ bpf_skip--;
+ continue;
+ }
+ return e;
+ }
+
if (test_bit(MISC_FMT_MAGIC_BIT, &e->flags)) {
if (entry_matches_magic(e, bprm))
return e;
@@ -146,6 +164,7 @@ search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)
* get_binfmt_handler - try to find a binary type handler
* @misc: handle to binfmt_misc instance
* @bprm: binary for which we are looking for a handler
+ * @bpf_skip: number of bpf-backed handlers to skip over
*
* Try to find a binfmt handler for the binary type. If one is found take a
* reference to protect against removal via bm_{entry,status}_write(). The
@@ -156,13 +175,14 @@ search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)
* Return: binary type list entry on success, NULL on failure
*/
static struct binfmt_misc_entry *get_binfmt_handler(struct binfmt_misc *misc,
- struct linux_binprm *bprm)
+ struct linux_binprm *bprm,
+ unsigned int bpf_skip)
{
struct binfmt_misc_entry *e;
guard(rcu)();
do {
- e = search_binfmt_handler(misc, bprm);
+ e = search_binfmt_handler(misc, bprm, bpf_skip);
} while (e && !refcount_inc_not_zero(&e->users));
return e;
}
@@ -182,6 +202,8 @@ static void put_binfmt_handler(struct binfmt_misc_entry *e)
exe_file_allow_write_access(e->interp_file);
filp_close(e->interp_file, NULL);
}
+ if (e->bpf_ops)
+ binfmt_misc_put_ops(e->bpf_ops);
/* Lockless walkers may still dereference this entry. */
kfree_rcu(e, rcu);
}
@@ -224,13 +246,16 @@ static int load_misc_binary(struct linux_binprm *bprm)
struct binfmt_misc_entry *fmt __free(put_binfmt_handler) = NULL;
struct file *interp_file;
struct binfmt_misc *misc;
+ const char *interpreter;
+ unsigned int bpf_skip = 0;
int retval;
misc = current_binfmt_misc();
if (!READ_ONCE(misc->enabled))
return -ENOEXEC;
- fmt = get_binfmt_handler(misc, bprm);
+retry:
+ fmt = get_binfmt_handler(misc, bprm, bpf_skip);
if (!fmt)
return -ENOEXEC;
@@ -238,6 +263,37 @@ static int load_misc_binary(struct linux_binprm *bprm)
if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
return -ENOENT;
+ if (test_bit(MISC_FMT_BPF_BIT, &fmt->flags)) {
+ /*
+ * A bpf-backed handler matches and picks the interpreter in
+ * sleepable context: > 0 means it handled the binary, 0 falls
+ * through to the handlers after this one and a negative errno
+ * fails the exec.
+ */
+ retval = fmt->bpf_ops->load(bprm);
+ if (retval < 0) {
+ /* Keep a program-supplied error within errno range. */
+ if (retval < -MAX_ERRNO)
+ retval = -ENOEXEC;
+ return retval;
+ }
+ if (!retval) {
+ /* Declined: move on to the handlers after this one. */
+ kfree(bprm->bpf_interp);
+ bprm->bpf_interp = NULL;
+ put_binfmt_handler(fmt);
+ fmt = NULL;
+ bpf_skip++;
+ goto retry;
+ }
+ /* Selecting an interpreter is part of the contract. */
+ if (!bprm->bpf_interp)
+ return -ENOEXEC;
+ interpreter = bprm->bpf_interp;
+ } else {
+ interpreter = fmt->interpreter;
+ }
+
if (fmt->flags & MISC_FMT_PRESERVE_ARGV0) {
bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0;
} else {
@@ -256,13 +312,13 @@ static int load_misc_binary(struct linux_binprm *bprm)
bprm->argc++;
/* add the interp as argv[0] */
- retval = copy_string_kernel(fmt->interpreter, bprm);
+ retval = copy_string_kernel(interpreter, bprm);
if (retval < 0)
return retval;
bprm->argc++;
/* Update interp in case binfmt_script needs it. */
- retval = bprm_change_interp(fmt->interpreter, bprm);
+ retval = bprm_change_interp(interpreter, bprm);
if (retval < 0)
return retval;
@@ -277,7 +333,7 @@ static int load_misc_binary(struct linux_binprm *bprm)
}
}
} else {
- interp_file = open_exec(fmt->interpreter);
+ interp_file = open_exec(interpreter);
}
if (IS_ERR(interp_file))
return PTR_ERR(interp_file);
@@ -428,6 +484,38 @@ static char *parse_extension_fields(struct binfmt_misc_entry *e, char *p,
return p;
}
+/* Parse the 'offset' field of a 'B' entry: the bpf handler name. */
+static char *parse_bpf_fields(struct binfmt_misc_entry *e, char *p, char del)
+{
+ char *s;
+
+ /* The 'offset' field carries the bpf handler name. */
+ s = strchr(p, del);
+ if (!s)
+ return NULL;
+ *s++ = '\0';
+ e->bpf_ops_name = p;
+ if (!e->bpf_ops_name[0] ||
+ strlen(e->bpf_ops_name) >= BINFMT_MISC_OPS_NAME_MAX)
+ return NULL;
+ p = s;
+ pr_debug("register: bpf handler: {%s}\n", e->bpf_ops_name);
+
+ /* The 'magic' field must be empty. */
+ s = strchr(p, del);
+ if (!s || s != p)
+ return NULL;
+ *s++ = '\0';
+ p = s;
+
+ /* The 'mask' field must be empty. */
+ s = strchr(p, del);
+ if (!s || s != p)
+ return NULL;
+ *s++ = '\0';
+ return s;
+}
+
/*
* This registers a new binary format, it recognises the syntax
* ':name:type:offset:magic:mask:interpreter:flags'
@@ -492,13 +580,21 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
pr_debug("register: type: M (magic)\n");
e->flags = BIT(MISC_FMT_ENABLED_BIT) | BIT(MISC_FMT_MAGIC_BIT);
break;
+ case 'B':
+ if (!IS_ENABLED(CONFIG_BINFMT_MISC_BPF))
+ return ERR_PTR(-EINVAL);
+ pr_debug("register: type: B (bpf)\n");
+ e->flags = BIT(MISC_FMT_ENABLED_BIT) | BIT(MISC_FMT_BPF_BIT);
+ break;
default:
return ERR_PTR(-EINVAL);
}
if (*p++ != del)
return ERR_PTR(-EINVAL);
- if (test_bit(MISC_FMT_MAGIC_BIT, &e->flags))
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags))
+ p = parse_bpf_fields(e, p, del);
+ else if (test_bit(MISC_FMT_MAGIC_BIT, &e->flags))
p = parse_magic_fields(e, p, del);
else
p = parse_extension_fields(e, p, del);
@@ -511,8 +607,13 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
if (!p)
return ERR_PTR(-EINVAL);
*p++ = '\0';
- if (!e->interpreter[0])
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
+ /* The program selects the interpreter at exec time. */
+ if (e->interpreter[0])
+ return ERR_PTR(-EINVAL);
+ } else if (!e->interpreter[0]) {
return ERR_PTR(-EINVAL);
+ }
pr_debug("register: interpreter: {%s}\n", e->interpreter);
/* Parse the 'flags' field. */
@@ -522,6 +623,14 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
if (p != buf + count)
return ERR_PTR(-EINVAL);
+ /*
+ * A program-selected interpreter cannot be pre-opened and must not
+ * inherit the credentials of a setuid binary it was chosen for.
+ */
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags) &&
+ (e->flags & (MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_FILE)))
+ return ERR_PTR(-EINVAL);
+
return no_free_ptr(e);
}
@@ -575,7 +684,10 @@ static int bm_entry_show(struct seq_file *m, void *unused)
else
seq_puts(m, "disabled\n");
- seq_printf(m, "interpreter %s\n", e->interpreter);
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags))
+ seq_printf(m, "bpf %s\n", e->bpf_ops_name);
+ else
+ seq_printf(m, "interpreter %s\n", e->interpreter);
/* print the special flags */
seq_puts(m, "flags: ");
@@ -589,7 +701,9 @@ static int bm_entry_show(struct seq_file *m, void *unused)
seq_putc(m, 'F');
seq_putc(m, '\n');
- if (!test_bit(MISC_FMT_MAGIC_BIT, &e->flags)) {
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
+ /* No magic or extension to print for a bpf handler. */
+ } else if (!test_bit(MISC_FMT_MAGIC_BIT, &e->flags)) {
seq_printf(m, "extension .%s\n", e->magic);
} else {
seq_printf(m, "offset %i\nmagic ", e->offset);
@@ -840,6 +954,15 @@ static ssize_t bm_register_write(struct file *file, const char __user *buffer,
if (IS_ERR(e))
return PTR_ERR(e);
+ if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
+ e->bpf_ops = binfmt_misc_get_ops(sb->s_user_ns, e->bpf_ops_name);
+ if (!e->bpf_ops) {
+ pr_notice("register: no bpf handler named %s\n",
+ e->bpf_ops_name);
+ return -ENOENT;
+ }
+ }
+
if (e->flags & MISC_FMT_OPEN_FILE) {
/*
* Now that we support unprivileged binfmt_misc mounts make
@@ -864,6 +987,8 @@ static ssize_t bm_register_write(struct file *file, const char __user *buffer,
exe_file_allow_write_access(f);
filp_close(f, NULL);
}
+ if (e->bpf_ops)
+ binfmt_misc_put_ops(e->bpf_ops);
return err;
}
--
2.51.2
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH v2 4/5] bpf: allow fs kfuncs for binfmt_misc_ops programs
2026-07-12 4:08 [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Farid Zakaria
` (2 preceding siblings ...)
2026-07-12 4:08 ` [PATCH v2 3/5] binfmt_misc: wire up bpf-backed 'B' entries Farid Zakaria
@ 2026-07-12 4:08 ` Farid Zakaria
2026-07-12 4:08 ` [PATCH v2 5/5] selftests/exec: add binfmt_misc bpf-backed handler test Farid Zakaria
2026-07-12 12:32 ` [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Christian Brauner
5 siblings, 0 replies; 8+ messages in thread
From: Farid Zakaria @ 2026-07-12 4:08 UTC (permalink / raw)
To: Christian Brauner, Alexei Starovoitov, Daniel Borkmann,
Martin KaFai Lau, Shuah Khan
Cc: Andrii Nakryiko, Kees Cook, Alexander Viro, Jan Kara,
Jonathan Corbet, Jann Horn, John Ericson, linux-fsdevel, linux-mm,
linux-kernel, bpf, linux-doc, linux-kselftest, Farid Zakaria
From: Christian Brauner <brauner@kernel.org>
The fs kfuncs are currently exclusive to LSM programs. A binfmt_misc
load program needs a subset of them to do anything interesting: to
compute an interpreter relative to the binary's location it wants
bpf_path_d_path() on bprm->file->f_path, and matching on per-binary
metadata wants bpf_get_file_xattr() and friends.
Register the fs kfunc set for struct_ops programs as well and extend
the filter to admit binfmt_misc_ops programs. The xattr setters stay
exclusive to LSM programs: a binary type handler decides how to run a
binary, it has no business modifying filesystem state.
This only takes effect in builds that have the fs kfunc set at all,
i.e. CONFIG_BPF_LSM. Without it a binfmt_misc handler is limited to
bprm fields and the file-backed dynptr, which are provided by the
common kfunc set.
Link: https://lore.kernel.org/20260704211409.1978485-1-farid.m.zakaria@gmail.com
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
fs/bpf_fs_kfuncs.c | 23 ++++++++++++++++++++---
1 file changed, 20 insertions(+), 3 deletions(-)
diff --git a/fs/bpf_fs_kfuncs.c b/fs/bpf_fs_kfuncs.c
index 768aca2dc..aa1fe988b 100644
--- a/fs/bpf_fs_kfuncs.c
+++ b/fs/bpf_fs_kfuncs.c
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2024 Google LLC. */
+#include <linux/binfmt_misc.h>
#include <linux/bpf.h>
#include <linux/bpf_lsm.h>
#include <linux/btf.h>
@@ -387,10 +388,20 @@ BTF_ID_FLAGS(func, bpf_remove_dentry_xattr, KF_SLEEPABLE)
BTF_ID_FLAGS(func, bpf_real_inode, KF_SLEEPABLE | KF_RET_NULL)
BTF_KFUNCS_END(bpf_fs_kfunc_set_ids)
+/* Side-effecting kfuncs that stay exclusive to LSM programs. */
+BTF_SET_START(bpf_fs_kfunc_lsm_only_ids)
+BTF_ID(func, bpf_set_dentry_xattr)
+BTF_ID(func, bpf_remove_dentry_xattr)
+BTF_SET_END(bpf_fs_kfunc_lsm_only_ids)
+
static int bpf_fs_kfuncs_filter(const struct bpf_prog *prog, u32 kfunc_id)
{
- if (!btf_id_set8_contains(&bpf_fs_kfunc_set_ids, kfunc_id) ||
- prog->type == BPF_PROG_TYPE_LSM)
+ if (!btf_id_set8_contains(&bpf_fs_kfunc_set_ids, kfunc_id))
+ return 0;
+ if (prog->type == BPF_PROG_TYPE_LSM)
+ return 0;
+ if (bpf_prog_is_binfmt_misc_ops(prog) &&
+ !btf_id_set_contains(&bpf_fs_kfunc_lsm_only_ids, kfunc_id))
return 0;
return -EACCES;
}
@@ -433,7 +444,13 @@ static const struct btf_kfunc_id_set bpf_fs_kfunc_set = {
static int __init bpf_fs_kfuncs_init(void)
{
- return register_btf_kfunc_id_set(BPF_PROG_TYPE_LSM, &bpf_fs_kfunc_set);
+ int ret;
+
+ ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_LSM, &bpf_fs_kfunc_set);
+ if (ret || !IS_ENABLED(CONFIG_BINFMT_MISC_BPF))
+ return ret;
+ return register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
+ &bpf_fs_kfunc_set);
}
late_initcall(bpf_fs_kfuncs_init);
--
2.51.2
^ permalink raw reply related [flat|nested] 8+ messages in thread* [PATCH v2 5/5] selftests/exec: add binfmt_misc bpf-backed handler test
2026-07-12 4:08 [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Farid Zakaria
` (3 preceding siblings ...)
2026-07-12 4:08 ` [PATCH v2 4/5] bpf: allow fs kfuncs for binfmt_misc_ops programs Farid Zakaria
@ 2026-07-12 4:08 ` Farid Zakaria
2026-07-12 12:32 ` [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Christian Brauner
5 siblings, 0 replies; 8+ messages in thread
From: Farid Zakaria @ 2026-07-12 4:08 UTC (permalink / raw)
To: Christian Brauner, Alexei Starovoitov, Daniel Borkmann,
Martin KaFai Lau, Shuah Khan
Cc: Andrii Nakryiko, Kees Cook, Alexander Viro, Jan Kara,
Jonathan Corbet, Jann Horn, John Ericson, linux-fsdevel, linux-mm,
linux-kernel, bpf, linux-doc, linux-kselftest, Farid Zakaria
Exercise the bpf-backed ('B') binfmt_misc handlers end to end. A handler
is a struct binfmt_misc_ops struct_ops map; the test loads and attaches
it (which publishes it by name), activates it with a 'B' entry, and
checks that a matched binary is routed to the interpreter the program
selected via bpf_binprm_set_interp().
Two self-contained cases are covered:
- bpf_interp: match a synthetic aarch64 ELF header from bprm->buf and
route it to a fixed interpreter chosen by the program.
- nix_origin: resolve a "$ORIGIN/..."-relative PT_INTERP to an
interpreter co-located with the binary -- the relocatable-loader
case the kernel ELF loader cannot express. The relocatable binary is
linked with PT_INTERP set to the literal "$ORIGIN/binfmt_bpf_interp"
(-Wl,--dynamic-linker), which the kernel cannot resolve on its own.
Both route to a small test interpreter that prints a marker, proving the
program-selected interpreter actually ran.
The bpf objects are compiled against the running kernel's BTF: the
Makefile generates vmlinux.h with bpftool and the harness links libbpf.
Override CLANG/BPFTOOL/VMLINUX_BTF/LIBBPF_CFLAGS/LIBBPF_LDLIBS as needed.
Signed-off-by: Farid Zakaria <farid.m.zakaria@gmail.com>
Assisted-by: Claude:Opus-4.8
---
tools/testing/selftests/exec/Makefile | 37 ++++
tools/testing/selftests/exec/binfmt_bpf_app.c | 12 ++
tools/testing/selftests/exec/binfmt_bpf_interp.c | 15 ++
tools/testing/selftests/exec/binfmt_misc_bpf.c | 260 +++++++++++++++++++++++
tools/testing/selftests/exec/bpf_interp.bpf.c | 52 +++++
tools/testing/selftests/exec/nix_origin.bpf.c | 179 ++++++++++++++++
6 files changed, 555 insertions(+)
diff --git a/tools/testing/selftests/exec/Makefile b/tools/testing/selftests/exec/Makefile
index 45a3cfc43..5423e3f7f 100644
--- a/tools/testing/selftests/exec/Makefile
+++ b/tools/testing/selftests/exec/Makefile
@@ -21,6 +21,12 @@ TEST_GEN_PROGS += recursion-depth
TEST_GEN_PROGS += null-argv
TEST_GEN_PROGS += check-exec
+# binfmt_misc bpf-backed ('B') handler test: a libbpf harness plus its
+# struct_ops objects and the test interpreter/app it routes between.
+TEST_GEN_PROGS += binfmt_misc_bpf
+TEST_GEN_FILES += bpf_interp.bpf.o nix_origin.bpf.o
+TEST_GEN_FILES += binfmt_bpf_interp binfmt_bpf_app
+
EXTRA_CLEAN := $(OUTPUT)/subdir.moved $(OUTPUT)/execveat.moved $(OUTPUT)/xxxxx* \
$(OUTPUT)/S_I*.test
@@ -55,3 +61,34 @@ $(OUTPUT)/script-exec.inc: $(CHECK_EXEC_SAMPLES)/script-exec.inc
cp $< $@
$(OUTPUT)/script-noexec.inc: $(CHECK_EXEC_SAMPLES)/script-noexec.inc
cp $< $@
+
+# --- binfmt_misc bpf ('B') handler test ---------------------------------
+# The struct_ops bpf objects are compiled against the running kernel's BTF.
+# Override CLANG/BPFTOOL/VMLINUX_BTF if they aren't on PATH or the vmlinux
+# BTF lives elsewhere, and LIBBPF_CFLAGS/LDLIBS to point at a libbpf install.
+CLANG ?= clang
+BPFTOOL ?= bpftool
+VMLINUX_BTF ?= /sys/kernel/btf/vmlinux
+BPF_CFLAGS ?= -I$(OUTPUT)
+LIBBPF_CFLAGS ?=
+LIBBPF_LDLIBS ?= -lbpf -lelf -lz
+
+$(OUTPUT)/vmlinux.h:
+ $(BPFTOOL) btf dump file $(VMLINUX_BTF) format c > $@
+ sed -i '/__ksym;$$/d' $@
+
+$(OUTPUT)/%.bpf.o: %.bpf.c $(OUTPUT)/vmlinux.h
+ $(CLANG) -g -O2 -target bpf -mcpu=v3 $(BPF_CFLAGS) -c $< -o $@
+
+$(OUTPUT)/binfmt_misc_bpf: binfmt_misc_bpf.c
+ $(CC) $(CFLAGS) $(LIBBPF_CFLAGS) $(LDFLAGS) $< $(LIBBPF_LDLIBS) -o $@
+
+$(OUTPUT)/binfmt_bpf_interp: binfmt_bpf_interp.c
+ $(CC) $(CFLAGS) $(LDFLAGS) $< -o $@
+
+# PT_INTERP is set to the literal "$ORIGIN/binfmt_bpf_interp"; the nix_origin
+# handler resolves it relative to the binary at run time.
+$(OUTPUT)/binfmt_bpf_app: binfmt_bpf_app.c
+ $(CC) $(CFLAGS) $(LDFLAGS) -Wl,--dynamic-linker,'$$ORIGIN/binfmt_bpf_interp' $< -o $@
+
+EXTRA_CLEAN += $(OUTPUT)/vmlinux.h $(OUTPUT)/bpf_interp.bpf.o $(OUTPUT)/nix_origin.bpf.o
diff --git a/tools/testing/selftests/exec/binfmt_bpf_app.c b/tools/testing/selftests/exec/binfmt_bpf_app.c
new file mode 100644
index 000000000..472270f14
--- /dev/null
+++ b/tools/testing/selftests/exec/binfmt_bpf_app.c
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A relocatable binary for the binfmt_misc_bpf $ORIGIN case. The Makefile
+ * links it with PT_INTERP set to the literal "$ORIGIN/binfmt_bpf_interp"
+ * (-Wl,--dynamic-linker), which the kernel ELF loader cannot resolve. The
+ * nix_origin bpf handler resolves it relative to this binary's directory and
+ * routes execution to the co-located interpreter.
+ */
+int main(void)
+{
+ return 0;
+}
diff --git a/tools/testing/selftests/exec/binfmt_bpf_interp.c b/tools/testing/selftests/exec/binfmt_bpf_interp.c
new file mode 100644
index 000000000..2db205f09
--- /dev/null
+++ b/tools/testing/selftests/exec/binfmt_bpf_interp.c
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test interpreter for the binfmt_misc_bpf selftest. A bpf-backed 'B' handler
+ * routes a matched binary here; printing this marker proves the program's
+ * chosen interpreter actually ran.
+ */
+#include <unistd.h>
+
+int main(int argc, char **argv)
+{
+ (void)argc;
+ (void)argv;
+ write(1, "BPF_INTERP_RAN\n", 15);
+ return 0;
+}
diff --git a/tools/testing/selftests/exec/binfmt_misc_bpf.c b/tools/testing/selftests/exec/binfmt_misc_bpf.c
new file mode 100644
index 000000000..b3e017ade
--- /dev/null
+++ b/tools/testing/selftests/exec/binfmt_misc_bpf.c
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Selftest for binfmt_misc bpf-backed ('B') handlers.
+ *
+ * A handler is a struct binfmt_misc_ops struct_ops map. Attaching it publishes
+ * it by name in the caller's user namespace; a 'B' entry activates it:
+ *
+ * echo ':name:B:<handler>::::' > /proc/sys/fs/binfmt_misc/register
+ *
+ * Two self-contained cases are exercised:
+ *
+ * 1. bpf_interp: the handler matches a synthetic aarch64 ELF header and
+ * routes it to a fixed interpreter chosen by the program.
+ * 2. nix_origin: the handler resolves a "$ORIGIN/..."-relative PT_INTERP to
+ * an interpreter co-located with the binary (the relocatable-loader case
+ * the kernel ELF loader cannot express).
+ *
+ * Both route to a test interpreter that prints BPF_INTERP_RAN, proving the
+ * program's chosen interpreter actually ran.
+ */
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <libgen.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+
+#include <bpf/libbpf.h>
+
+#define INTERP_PATH "/tmp/binfmt_bpf_interp"
+#define AARCH64_PATH "/tmp/binfmt_bpf_aarch64"
+#define RELOC_DIR "/tmp/binfmt_reloc"
+#define BINFMT_REG "/proc/sys/fs/binfmt_misc/register"
+#define EXPECT "BPF_INTERP_RAN"
+
+static char testdir[512]; /* directory holding this test's built artifacts */
+
+static int copy_file(const char *src, const char *dst)
+{
+ char buf[4096];
+ int in, out;
+ ssize_t n;
+
+ in = open(src, O_RDONLY);
+ if (in < 0)
+ return -1;
+ out = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0755);
+ if (out < 0) {
+ close(in);
+ return -1;
+ }
+ while ((n = read(in, buf, sizeof(buf))) > 0) {
+ if (write(out, buf, n) != n) {
+ close(in);
+ close(out);
+ return -1;
+ }
+ }
+ close(in);
+ close(out);
+ return n < 0 ? -1 : 0;
+}
+
+/* A minimal 64-bit little-endian aarch64 ELF header, padded to the read size. */
+static int create_fake_aarch64(const char *path)
+{
+ unsigned char hdr[256] = {0};
+ int fd;
+
+ hdr[0] = 0x7f; hdr[1] = 'E'; hdr[2] = 'L'; hdr[3] = 'F';
+ hdr[4] = 2; /* ELFCLASS64 */
+ hdr[5] = 1; /* ELFDATA2LSB */
+ hdr[6] = 1; /* EV_CURRENT */
+ hdr[16] = 2; /* e_type = ET_EXEC */
+ hdr[18] = 183 & 0xff; /* e_machine = EM_AARCH64 */
+ hdr[19] = (183 >> 8) & 0xff;
+ hdr[20] = 1; /* e_version */
+
+ fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
+ if (fd < 0)
+ return -1;
+ if (write(fd, hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
+ close(fd);
+ return -1;
+ }
+ close(fd);
+ return 0;
+}
+
+static int register_entry(const char *name, const char *handler)
+{
+ char rule[128];
+ int fd;
+ ssize_t n;
+
+ snprintf(rule, sizeof(rule), ":%s:B:%s::::", name, handler);
+ fd = open(BINFMT_REG, O_WRONLY);
+ if (fd < 0)
+ return -1;
+ n = write(fd, rule, strlen(rule));
+ close(fd);
+ return n < 0 ? -1 : 0;
+}
+
+static void unregister_entry(const char *name)
+{
+ char path[128];
+ int fd;
+
+ snprintf(path, sizeof(path), "/proc/sys/fs/binfmt_misc/%s", name);
+ fd = open(path, O_WRONLY);
+ if (fd >= 0) {
+ if (write(fd, "-1", 2) < 0)
+ ; /* best effort */
+ close(fd);
+ }
+}
+
+static int check_output(const char *cmd, const char *expected)
+{
+ char buf[128];
+ FILE *fp;
+
+ fp = popen(cmd, "r");
+ if (!fp)
+ return -1;
+ if (!fgets(buf, sizeof(buf), fp)) {
+ pclose(fp);
+ return -1;
+ }
+ pclose(fp);
+ return strncmp(buf, expected, strlen(expected)) ? -1 : 0;
+}
+
+/*
+ * Load @objfile, attach its struct_ops map @handler (which publishes the
+ * handler), activate a 'B' entry named @entry that references it, run @target
+ * and check it produced @expect.
+ */
+static int run_case(const char *objfile, const char *handler,
+ const char *entry, const char *target, const char *expect)
+{
+ struct bpf_object *obj;
+ struct bpf_map *map;
+ struct bpf_link *link;
+ int ret = -1;
+
+ obj = bpf_object__open_file(objfile, NULL);
+ if (!obj || libbpf_get_error(obj)) {
+ fprintf(stderr, "open %s failed\n", objfile);
+ return -1;
+ }
+ if (bpf_object__load(obj)) {
+ fprintf(stderr, "load %s failed (check dmesg for the verifier log)\n",
+ objfile);
+ goto close;
+ }
+ map = bpf_object__find_map_by_name(obj, handler);
+ if (!map) {
+ fprintf(stderr, "no struct_ops map '%s' in %s\n", handler, objfile);
+ goto close;
+ }
+ link = bpf_map__attach_struct_ops(map);
+ if (!link || libbpf_get_error(link)) {
+ fprintf(stderr, "attach struct_ops '%s' failed\n", handler);
+ goto close;
+ }
+ if (register_entry(entry, handler)) {
+ fprintf(stderr, "register 'B' entry '%s' failed\n", entry);
+ goto detach;
+ }
+ ret = check_output(target, expect);
+ unregister_entry(entry);
+detach:
+ bpf_link__destroy(link);
+close:
+ bpf_object__close(obj);
+ return ret;
+}
+
+int main(void)
+{
+ char src[600], obj[600], appdst[600], interpdst[600];
+ char exe[512];
+ ssize_t n;
+ int fail = 0;
+ struct stat st;
+
+ if (getuid() != 0) {
+ fprintf(stderr, "Skipping: test must be run as root\n");
+ return 4; /* KSFT_SKIP */
+ }
+
+ n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
+ if (n < 0) {
+ perror("readlink");
+ return 1;
+ }
+ exe[n] = '\0';
+ snprintf(testdir, sizeof(testdir), "%s", dirname(exe));
+
+ if (stat("/sys/fs/bpf", &st) < 0)
+ mkdir("/sys/fs/bpf", 0755);
+ mount("bpf", "/sys/fs/bpf", "bpf", 0, NULL);
+ if (access(BINFMT_REG, F_OK) < 0)
+ mount("binfmt_misc", "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, NULL);
+
+ /* Shared test interpreter. */
+ snprintf(src, sizeof(src), "%s/binfmt_bpf_interp", testdir);
+ if (copy_file(src, INTERP_PATH)) {
+ fprintf(stderr, "cannot install %s\n", INTERP_PATH);
+ return 1;
+ }
+
+ /* Case 1: match a synthetic aarch64 header -> fixed interpreter. */
+ printf("[*] case 1: match aarch64 header -> program-chosen interpreter\n");
+ if (create_fake_aarch64(AARCH64_PATH)) {
+ fprintf(stderr, "cannot create %s\n", AARCH64_PATH);
+ return 1;
+ }
+ snprintf(obj, sizeof(obj), "%s/bpf_interp.bpf.o", testdir);
+ if (run_case(obj, "bpf_interp", "test_bpf_interp", AARCH64_PATH, EXPECT) == 0)
+ printf("[+] case 1 passed\n");
+ else {
+ printf("[-] case 1 FAILED\n");
+ fail = 1;
+ }
+ unlink(AARCH64_PATH);
+
+ /* Case 2: $ORIGIN-relative PT_INTERP -> co-located interpreter. */
+ printf("[*] case 2: $ORIGIN interpreter resolved relative to the binary\n");
+ mkdir(RELOC_DIR, 0755);
+ snprintf(appdst, sizeof(appdst), "%s/app", RELOC_DIR);
+ snprintf(interpdst, sizeof(interpdst), "%s/binfmt_bpf_interp", RELOC_DIR);
+ snprintf(src, sizeof(src), "%s/binfmt_bpf_app", testdir);
+ if (copy_file(src, appdst) ||
+ copy_file(INTERP_PATH, interpdst)) {
+ fprintf(stderr, "cannot set up %s\n", RELOC_DIR);
+ fail = 1;
+ } else {
+ snprintf(obj, sizeof(obj), "%s/nix_origin.bpf.o", testdir);
+ if (run_case(obj, "nix_origin", "test_bpf_origin", appdst, EXPECT) == 0)
+ printf("[+] case 2 passed\n");
+ else {
+ printf("[-] case 2 FAILED\n");
+ fail = 1;
+ }
+ }
+ unlink(appdst);
+ unlink(interpdst);
+ rmdir(RELOC_DIR);
+ unlink(INTERP_PATH);
+
+ if (!fail)
+ printf("[*] all binfmt_misc bpf cases passed\n");
+ return fail;
+}
diff --git a/tools/testing/selftests/exec/bpf_interp.bpf.c b/tools/testing/selftests/exec/bpf_interp.bpf.c
new file mode 100644
index 000000000..ca98c3716
--- /dev/null
+++ b/tools/testing/selftests/exec/bpf_interp.bpf.c
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * binfmt_misc_ops handler for the selftest's fixed-interpreter case: match a
+ * 64-bit aarch64 ELF header from the prefetched buffer and route it to a fixed
+ * interpreter chosen by the program. This is the portable, self-contained
+ * equivalent of routing a foreign binary to an emulator: it matches
+ * programmatically and computes the interpreter, but points at a test binary
+ * the harness installs rather than a system emulator.
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+char _license[] SEC("license") = "GPL";
+
+#define EI_CLASS 4
+#define ELFCLASS64 2
+#define EM_AARCH64 183
+
+extern int bpf_binprm_set_interp(struct linux_binprm *bprm, const char *path,
+ size_t path__sz) __ksym;
+
+SEC("struct_ops.s/load")
+int BPF_PROG(bpf_interp_load, struct linux_binprm *bprm)
+{
+ /*
+ * Keep the path on the (writable) stack: bpf_binprm_set_interp() takes
+ * a sized memory arg and the verifier rejects a read-only .rodata
+ * buffer for it. The harness installs the interpreter at this path.
+ */
+ char interp[] = "/tmp/binfmt_bpf_interp";
+ __u16 machine;
+
+ if (bprm->buf[0] != 0x7f || bprm->buf[1] != 'E' ||
+ bprm->buf[2] != 'L' || bprm->buf[3] != 'F' ||
+ bprm->buf[EI_CLASS] != ELFCLASS64)
+ return 0;
+
+ /* e_machine is a 16-bit little-endian field at offset 18. */
+ machine = (__u8)bprm->buf[18] | ((__u16)(__u8)bprm->buf[19] << 8);
+ if (machine != EM_AARCH64)
+ return 0;
+
+ /* @path__sz includes the terminating NUL. */
+ return bpf_binprm_set_interp(bprm, interp, sizeof(interp)) ?: 1;
+}
+
+SEC(".struct_ops.link")
+struct binfmt_misc_ops bpf_interp = {
+ .load = (void *)bpf_interp_load,
+ .name = "bpf_interp",
+};
diff --git a/tools/testing/selftests/exec/nix_origin.bpf.c b/tools/testing/selftests/exec/nix_origin.bpf.c
new file mode 100644
index 000000000..a853d64f4
--- /dev/null
+++ b/tools/testing/selftests/exec/nix_origin.bpf.c
@@ -0,0 +1,179 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * nix_origin.bpf.c - $ORIGIN-relative PT_INTERP resolution
+ *
+ * A binfmt_misc_ops handler that makes relocatable (Nix-style) ELF
+ * binaries work: if PT_INTERP starts with "$ORIGIN/", the loader is
+ * resolved relative to the directory of the binary being executed and
+ * selected via bpf_binprm_set_interp(). Anything else is declined so
+ * regular binaries pass through untouched.
+ *
+ * Activate with:
+ * bpftool struct_ops register nix_origin.bpf.o /sys/fs/bpf
+ * echo ':nix-origin:B:nix_origin::::' > /proc/sys/fs/binfmt_misc/register
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+char _license[] SEC("license") = "GPL";
+
+#define PATH_MAX 4096
+#define EI_CLASS 4
+#define ELFCLASSXX 2 /* ELFCLASS64; flip to 1 for 32-bit */
+#define PT_INTERP 3
+#define MAX_PHDRS 64
+
+#define ORIGIN "$ORIGIN"
+#define ORIGIN_LEN (sizeof(ORIGIN) - 1)
+
+#define ENOENT 2
+#define ENAMETOOLONG 36
+
+extern int bpf_dynptr_from_file(struct file *file, __u32 flags,
+ struct bpf_dynptr *ptr__uninit) __ksym;
+extern int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr) __ksym;
+extern int bpf_path_d_path(const struct path *path, char *buf,
+ size_t buf__sz) __ksym;
+extern int bpf_binprm_set_interp(struct linux_binprm *bprm, const char *path,
+ size_t path__sz) __ksym;
+
+struct scratch {
+ char interp[PATH_MAX]; /* PT_INTERP as embedded in the binary */
+ char path[PATH_MAX]; /* d_path of the binary, becomes the result */
+};
+
+/* Keyed by pid: execs run concurrently and the program can sleep. */
+struct {
+ __uint(type, BPF_MAP_TYPE_HASH);
+ __uint(max_entries, 512);
+ __type(key, __u64);
+ __type(value, struct scratch);
+} scratch_map SEC(".maps");
+
+static const struct scratch zero_scratch;
+
+SEC("struct_ops.s/load")
+int BPF_PROG(nix_origin_load, struct linux_binprm *bprm)
+{
+ __u32 isz, sfx, rsz, slash;
+ struct elf64_phdr phdr;
+ struct elf64_hdr ehdr;
+ struct bpf_dynptr dp;
+ struct scratch *sc;
+ bool found = false;
+ __u64 id;
+ int ret = 0, len, i;
+
+ /* Cheap reject from the prefetched header. */
+ if (bprm->buf[0] != 0x7f || bprm->buf[1] != 'E' ||
+ bprm->buf[2] != 'L' || bprm->buf[3] != 'F' ||
+ bprm->buf[EI_CLASS] != ELFCLASSXX)
+ return 0;
+
+ if (bpf_dynptr_from_file(bprm->file, 0, &dp))
+ goto out;
+
+ if (bpf_dynptr_read(&ehdr, sizeof(ehdr), &dp, 0, 0))
+ goto out;
+ if (ehdr.e_phentsize != sizeof(struct elf64_phdr))
+ goto out;
+
+ bpf_for(i, 0, ehdr.e_phnum) {
+ if (i >= MAX_PHDRS)
+ break;
+ if (bpf_dynptr_read(&phdr, sizeof(phdr), &dp,
+ ehdr.e_phoff + i * sizeof(phdr), 0))
+ goto out;
+ if (phdr.p_type == PT_INTERP) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ goto out;
+
+ isz = phdr.p_filesz;
+ if (isz <= ORIGIN_LEN + 1 || isz >= sizeof(sc->interp))
+ goto out;
+ /*
+ * The range check above compiles to a test on a zero-extended copy of
+ * the u64 p_filesz, so the verifier does not carry the bound to the
+ * dynptr_read() length below ("unbounded memory access"). Mask isz to
+ * the buffer size (a power of two) and force the masked value to be
+ * materialized with a barrier so the read uses the bounded register.
+ */
+ isz &= sizeof(sc->interp) - 1;
+ barrier_var(isz);
+
+ id = bpf_get_current_pid_tgid();
+ if (bpf_map_update_elem(&scratch_map, &id, &zero_scratch, BPF_ANY))
+ goto out;
+ sc = bpf_map_lookup_elem(&scratch_map, &id);
+ if (!sc)
+ goto out_del;
+
+ if (bpf_dynptr_read(sc->interp, isz, &dp, phdr.p_offset, 0))
+ goto out_del;
+ if (sc->interp[isz - 1] != '\0')
+ goto out_del;
+
+ /* Not "$ORIGIN/..."? Decline, the elf loader owns it. */
+ if (sc->interp[0] != '$' || sc->interp[1] != 'O' ||
+ sc->interp[2] != 'R' || sc->interp[3] != 'I' ||
+ sc->interp[4] != 'G' || sc->interp[5] != 'I' ||
+ sc->interp[6] != 'N' || sc->interp[7] != '/')
+ goto out_del;
+
+ /*
+ * From here on the binary is ours: resolution failures fail the
+ * exec instead of falling back to binfmt_elf, which would resolve
+ * the literal "$ORIGIN/..." relative to the caller's cwd.
+ */
+ ret = -ENOENT;
+ len = bpf_path_d_path(&bprm->file->f_path, sc->path, sizeof(sc->path));
+ if (len <= 0 || len > sizeof(sc->path))
+ goto out_del;
+ /* Unreachable or unlinked ("... (deleted)") binaries can't resolve. */
+ if (sc->path[0] != '/')
+ goto out_del;
+
+ /* $ORIGIN = dirname of the binary. */
+ slash = 0;
+ bpf_for(i, 1, len - 1) {
+ if (i >= sizeof(sc->path))
+ break;
+ if (sc->path[i] == '/')
+ slash = i;
+ }
+
+ /* Splice the suffix (leading '/' and NUL included) onto the dir. */
+ sfx = isz - ORIGIN_LEN;
+ rsz = slash + sfx;
+ if (rsz > sizeof(sc->path)) {
+ ret = -ENAMETOOLONG;
+ goto out_del;
+ }
+ bpf_for(i, 0, sfx) {
+ __u32 s = ORIGIN_LEN + i, d = slash + i;
+
+ if (s >= sizeof(sc->interp) || d >= sizeof(sc->path))
+ break;
+ sc->path[d] = sc->interp[s];
+ }
+
+ ret = bpf_binprm_set_interp(bprm, sc->path, rsz);
+ if (!ret)
+ ret = 1;
+out_del:
+ bpf_map_delete_elem(&scratch_map, &id);
+out:
+ bpf_dynptr_file_discard(&dp);
+ return ret;
+}
+
+SEC(".struct_ops.link")
+struct binfmt_misc_ops nix_origin = {
+ .load = (void *)nix_origin_load,
+ .name = "nix_origin",
+};
--
2.51.2
^ permalink raw reply related [flat|nested] 8+ messages in thread* Re: [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers
2026-07-12 4:08 [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Farid Zakaria
` (4 preceding siblings ...)
2026-07-12 4:08 ` [PATCH v2 5/5] selftests/exec: add binfmt_misc bpf-backed handler test Farid Zakaria
@ 2026-07-12 12:32 ` Christian Brauner
2026-07-13 3:29 ` Farid Zakaria
5 siblings, 1 reply; 8+ messages in thread
From: Christian Brauner @ 2026-07-12 12:32 UTC (permalink / raw)
To: Farid Zakaria
Cc: Christian Brauner, Alexei Starovoitov, Daniel Borkmann,
Martin KaFai Lau, Shuah Khan, Andrii Nakryiko, Kees Cook,
Alexander Viro, Jan Kara, Jonathan Corbet, Jann Horn,
John Ericson, linux-fsdevel, linux-mm, linux-kernel, bpf,
linux-doc, linux-kselftest
> This is a continuation of Christian's bpf-backed binfmt_misc POC [1], which he offered
> to hand off to me. I am carrying it forward. The kernel design is his and is
> unchanged. This series rebases it onto his binfmt_misc locking/cleanup series [2]
> and adds selftests (+ fixed from the one's shared), and therefore does
> not apply to mainline alone.
>
> As for motivation for this whole change, Christian did a great VL;MR;
> write-up [1].
>
> TL;DR: binfmt_misc can match a binary and hand it to a fixed interpreter,
> but it can't match programmatically or compute the interpreter per binary.
> The Nix community would love to support relocatable binaries, where the
> correct loader can only be found relative to the binary itself.
> This adds a 'B' handler type: a binfmt_misc_ops struct_ops program that
> inspects the binary and picks the interpreter with one new kfunc,
> bpf_binprm_set_interp().
>
> bpftool struct_ops register nix_origin.bpf.o /sys/fs/bpf
> echo ':nix-origin:B:nix_origin::::' > /proc/sys/fs/binfmt_misc/register
Thanks! So I've spent some more time working on this because I had some
future ideas that I needed to make sure could be accomodated by this
(currently on vacation but hey...). So the version I have givex this a
better design and has future extensibility in mind:
- The single sleepable load op is split into two ops:
struct binfmt_misc_ops {
bool (*match)(struct linux_binprm *bprm);
int (*load)(struct linux_binprm *bprm);
char name[BINFMT_MISC_OPS_NAME_MAX];
};
The non-sleepable match program runs from the RCU entry lookup
walk itself, exactly like magic and extension matching: same
registration order, same first-match-wins semantics, and it can
only rely on the prefetched bprm->buf. It must be free of side
effects since the walk may be restarted.
The sleepable load program runs once the walk has committed to the
entry and does the file reading and the interpreter selection. Both
ops are mandatory, the struct_ops plumbing enforces the sleepability
of each, and since bpf_binprm_set_interp() is KF_SLEEPABLE a match
program cannot select an interpreter by construction.
- A match is a commitment. A failing load program fails the exec instead
of falling through to later entries. -ENOEXEC keeps its usual meaning
and hands the binary to the remaining binary formats, for a handler
that discovers it cannot serve the binary after all.
This kills the part of v1 I disliked the most: the skip cursor and the
leave-and-rescan loop in load_misc_binary() are gone. The walk is
never left and re-entered, and 'B' entries need no special semantics
against concurrent (un)registration anymore.
Your v2 changelog note about keeping the bpf retry loop in the
__free() style is moot as a consequence. The loop no longer exists.
- The load return convention flipped: 0 now means success after the
program called bpf_binprm_set_interp(). Returning 0 without having
selected an interpreter or returning a positive value is treated as
-ENOEXEC, other negative errnos fail the exec.
So the "return bpf_binprm_set_interp(...) ?: 1" idiom from the v1-era
programs becomes plain "return bpf_binprm_set_interp(...)".
- The handler name moved from the offset field to the interpreter field
that field consistently names whoever supplies the interpreter, a path
for static entries, a handler for 'B' entries. Offset, magic, and mask
must be empty:
echo ':nix-origin:B::::nix_origin:' > register
- 'C' is allowed now, v1 rejected it. It behaves exactly as for a static
entry. The setuid transition stays gated by vfsuid_has_mapping() in
the caller's user namespace. Which makes 'B' handlers usable for a
per-binary loader over setuid binaries. 'F' stays rejected as there
is no fixed interpreter to pre-open (I have other ideas how we'll do
something like it later.).
Nothing changed in the exec patch, the fs kfuncs patch, the kfunc
itself, or the registry/namespacing model.
I can send v3 in a bit if that's ok.
--
Christian Brauner <brauner@kernel.org>
^ permalink raw reply [flat|nested] 8+ messages in thread* Re: [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers
2026-07-12 12:32 ` [PATCH v2 0/5] binfmt_misc: bpf-backed binary type handlers Christian Brauner
@ 2026-07-13 3:29 ` Farid Zakaria
0 siblings, 0 replies; 8+ messages in thread
From: Farid Zakaria @ 2026-07-13 3:29 UTC (permalink / raw)
To: Christian Brauner, Farid Zakaria
Cc: Alexei Starovoitov, Daniel Borkmann, Martin KaFai Lau, Shuah Khan,
Andrii Nakryiko, Kees Cook, Alexander Viro, Jan Kara,
Jonathan Corbet, Jann Horn, John Ericson, linux-fsdevel, linux-mm,
linux-kernel, bpf, linux-doc, linux-kselftest
On Sun Jul 12, 2026 at 5:32 AM PDT, Christian Brauner wrote:
>> This is a continuation of Christian's bpf-backed binfmt_misc POC [1], which he offered
>> to hand off to me. I am carrying it forward. The kernel design is his and is
>> unchanged. This series rebases it onto his binfmt_misc locking/cleanup series [2]
>> and adds selftests (+ fixed from the one's shared), and therefore does
>> not apply to mainline alone.
>>
>> As for motivation for this whole change, Christian did a great VL;MR;
>> write-up [1].
>>
>> TL;DR: binfmt_misc can match a binary and hand it to a fixed interpreter,
>> but it can't match programmatically or compute the interpreter per binary.
>> The Nix community would love to support relocatable binaries, where the
>> correct loader can only be found relative to the binary itself.
>> This adds a 'B' handler type: a binfmt_misc_ops struct_ops program that
>> inspects the binary and picks the interpreter with one new kfunc,
>> bpf_binprm_set_interp().
>>
>> bpftool struct_ops register nix_origin.bpf.o /sys/fs/bpf
>> echo ':nix-origin:B:nix_origin::::' > /proc/sys/fs/binfmt_misc/register
>
> Thanks! So I've spent some more time working on this because I had some
> future ideas that I needed to make sure could be accomodated by this
> (currently on vacation but hey...). So the version I have givex this a
> better design and has future extensibility in mind:
>
I also enjoy hacking over my vacation. I'm often told to take break but
some of the best ideas come when on vacation :)
> - The single sleepable load op is split into two ops:
>
> struct binfmt_misc_ops {
> bool (*match)(struct linux_binprm *bprm);
> int (*load)(struct linux_binprm *bprm);
> char name[BINFMT_MISC_OPS_NAME_MAX];
> };
>
> The non-sleepable match program runs from the RCU entry lookup
> walk itself, exactly like magic and extension matching: same
> registration order, same first-match-wins semantics, and it can
> only rely on the prefetched bprm->buf. It must be free of side
> effects since the walk may be restarted.
>
Is relying on brpm->buf enough?
Right now that's only 256 bytes I think, which is not enough to read
segments we might care about. That worked fine when it was just a magic
number but the idea with the eBPF program is to make decisions based on
more data.
In the selftest I provided, the `PT_INTERP` segment is already at file
offset 0x318 (792). I was imaginging NixOS having to support
`PT_INTERP_NIX` in order for the produced binaries to be backwards
compatible with older kernels.
The other idea would be to make the `match()` broad and select
everything but then nearly all ELF64 binaries would match and then pay
the price to `load()` and ultimately `-ENOEXEC`. Seems like it would
make multiple BPF binfmt programs less useful.
> The sleepable load program runs once the walk has committed to the
> entry and does the file reading and the interpreter selection. Both
> ops are mandatory, the struct_ops plumbing enforces the sleepability
> of each, and since bpf_binprm_set_interp() is KF_SLEEPABLE a match
> program cannot select an interpreter by construction.
>
> - A match is a commitment. A failing load program fails the exec instead
> of falling through to later entries. -ENOEXEC keeps its usual meaning
> and hands the binary to the remaining binary formats, for a handler
> that discovers it cannot serve the binary after all.
>
> This kills the part of v1 I disliked the most: the skip cursor and the
> leave-and-rescan loop in load_misc_binary() are gone. The walk is
> never left and re-entered, and 'B' entries need no special semantics
> against concurrent (un)registration anymore.
>
> Your v2 changelog note about keeping the bpf retry loop in the
> __free() style is moot as a consequence. The loop no longer exists.
>
> - The load return convention flipped: 0 now means success after the
> program called bpf_binprm_set_interp(). Returning 0 without having
> selected an interpreter or returning a positive value is treated as
> -ENOEXEC, other negative errnos fail the exec.
>
> So the "return bpf_binprm_set_interp(...) ?: 1" idiom from the v1-era
> programs becomes plain "return bpf_binprm_set_interp(...)".
>
> - The handler name moved from the offset field to the interpreter field
> that field consistently names whoever supplies the interpreter, a path
> for static entries, a handler for 'B' entries. Offset, magic, and mask
> must be empty:
>
> echo ':nix-origin:B::::nix_origin:' > register
>
> - 'C' is allowed now, v1 rejected it. It behaves exactly as for a static
> entry. The setuid transition stays gated by vfsuid_has_mapping() in
> the caller's user namespace. Which makes 'B' handlers usable for a
> per-binary loader over setuid binaries. 'F' stays rejected as there
> is no fixed interpreter to pre-open (I have other ideas how we'll do
> something like it later.).
>
> Nothing changed in the exec patch, the fs kfuncs patch, the kfunc
> itself, or the registry/namespacing model.
>
> I can send v3 in a bit if that's ok.
I don't mind at all you sending v3 and in fact I've been enjoying your
involvement. I didn't know what to expect when I offered this idea up to
the community.
I'm happy to keep co-developing this with you within a design you feel
acceptable with. Please let me know how I can remain engaged and
helpful.
One last thing I was thinking about is that we will also need to support
$ORIGIN in the shebang path, however I just tested it and this current broad
BPF solution can largely handle it [1], with a small wrinkle.
$ printf '#!$ORIGIN/interp\n' > /opt/app/greet
$ cp ./interp /opt/app/interp # any interpreter/loader
$ chmod +x /opt/app/greet /opt/app/interp
# stock kernel: binfmt_script opens the literal "$ORIGIN/interp"
$ /opt/app/greet
bash: /opt/app/greet: $ORIGIN/interp: bad interpreter: No such file or directory
# with the handler registered, $ORIGIN resolves to the script's dir
$ bpftool struct_ops register shebang_origin.bpf.o /sys/fs/bpf
$ echo ':shebang-origin:B:shebang_origin::::' > /proc/sys/fs/binfmt_misc/register
$ /opt/app/greet
<runs /opt/app/interp, the loader found next to the script>
The wrinkle is that it can't express today is the single optional argument.
(i.e. `#!interp arg" -> argv[1]=arg`). We might ned a way to express
that in the load.
Anywyas, thanks again. All your ideas made sense modulo I'm unsure if
`bprm->buf` is enough to make a decision...
[1] https://gist.github.com/fzakaria/2e1e1c44fa488a951674f8761c672366
^ permalink raw reply [flat|nested] 8+ messages in thread