Skip to contentSkip to conversation

binfmt_misc: bpf-backed binary type handlers

RFC PATCH Superseded Christian Brauner 2 participants 6 messages Jul 7

Subsystems (5)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

cover binfmt_misc: bpf-backed binary type handlers

This is a POC for the nix people and Farid and Eric in particular. I would take my hands off the wheel now that I POCed this and hand it to Farid if he likes to take it forward.

VL;MR (very long, must read):

For a while now Farid has been trying to make relocatable, hermetic binaries (think Nix-style store layouts) work without patchelf tricks or wrapper scripts. For such binaries the right dynamic loader can only be determined relative to the location of the binary itself, which neither PT_INTERP nor a fixed binfmt_misc interpreter string can express.

The first attempt was $ORIGIN expansion in PT_INTERP [1]. I pushed back on that. Userspace guards $ORIGIN behind AT_SECURE so the kernel would have to make the used loader depend on the type of binary, LSMs would need a say, it changes long-standing behavior in ways that are ripe for loader injection attacks, and bprm->file may not have a usable path at all (memfds, deleted files, unresolvable paths). Making the kernel splice bprm->file back together with PT_INTERP is terrible. The second attempt was a pluggable ELF interpreter loader registry [2] which would mean actual kernel modules for custom binary formats. Also no. binfmt_misc was invented to kill exactly this horrendous past.

What I suggested instead [3] was to put this where delegating binary formats to userspace already lives: binfmt_misc. The only things binfmt_misc cannot do today are matching programmatically and computing the interpreter per binary instead of using a fixed string recorded at registration time. Farid prototyped that with an eBPF program [4] and it turned out quite workable, but the prototype ran a SOCKET_FILTER program over bprm->buf, added a new helper to the frozen uapi helper list, and returned the computed path through per-CPU memory.

This series is the proposal turned into what I think the bpf side {c,sh}ould actually look like. It is a POC: it builds, the design is what I want to discuss, selftests and runtime testing are still missing.

A handler is an instance of the new binfmt_misc_ops struct_ops with a single sleepable op and a name:

	struct binfmt_misc_ops {
		int (*load)(struct linux_binprm *bprm);
		char name[BINFMT_MISC_OPS_NAME_MAX];
	};

The load program receives the bprm as a trusted BTF pointer, so it can match on the header in bprm->buf, read arbitrary file content through bpf_dynptr_from_file() (e.g. to parse ELF program headers), and resolve the binary's location via bpf_path_d_path() on &bprm->file->f_path. That also solves the prototype's limitation of only seeing the first 256 bytes of the file.

The one genuinely new piece of bpf surface is a single kfunc:

	int bpf_binprm_set_interp(struct linux_binprm *bprm,
				  const char *path, size_t path__sz);

which stages an absolute path in the bprm. It cannot go through bprm_change_interp() directly because load_misc_binary() copies bprm->interp into argv[1] after the program ran, hence the staging field added in patch 1.

Registering (attaching) the struct_ops map publishes the handler under its name in a registry keyed by the registering task's user namespace. Activation reuses the existing text interface with a new 'B' type where the offset field carries the handler name and magic, mask, and interpreter must be empty:

	echo ':origin:B:nix::::' > /proc/sys/fs/binfmt_misc/register

This keeps the existing permission and namespacing model completely intact. Activating a handler requires the same write access to a binfmt_misc instance as any other registration, a container mounting its own instance escapes the host's entries exactly as before, and shadowing e.g. all ELF binaries takes the same privilege as a static 'M' entry matching \x7fELF does today.

The only novelty is that matching becomes programmable. Handler lookup walks the user namespace hierarchy upwards, mirroring how binfmt_misc instances themselves are resolved, so a handler registered on the host can be activated from a container's own instance without being forced upon it.

The computed interpreter is opened with open_exec() under the caller's credentials and goes through the full LSM vetting as the next binprm level, exactly like a statically registered interpreter, so the program cannot widen access. It only ever redirects the caller to something the caller could exec anyway.

The 'C' and 'F' flags are rejected for 'B' entries. 'F' has no fixed interpreter to pre-open and 'C' would let a program-chosen interpreter run with a setuid binary's credentials. AT_EXECVE_CHECK never invokes programs and interpreter chains stay capped by the usual ELOOP depth.

A handler for the Nix case then looks roughly like:

	SEC("struct_ops.s/load")
	int BPF_PROG(nix_load, struct linux_binprm *bprm)
	{
		char path[256];
		long n;

		if (bpf_strncmp(bprm->buf, 4, "\x7f" "ELF"))
			return 0;

		n = bpf_path_d_path(&bprm->file->f_path, path, sizeof(path));
		if (n < 0)
			return 0;

		/* derive the loader location from the binary's path */

		return bpf_binprm_set_interp(bprm, path, sizeof(path)) ?: 1;
	}

	SEC(".struct_ops.link")
	struct binfmt_misc_ops nix = {
		.load = (void *)nix_load,
		.name = "nix",
	};

Farid, this should slot underneath your qemu demo from [4] with the program ported to struct_ops. Feel free to take it from here.

[1]: https://lore.kernel.org/[email protected]
[2]: https://lore.kernel.org/[email protected]
[3]: https://lore.kernel.org/20260703-meditation-ratsuchende-moratorium-9ecdf1f3f8bb@brauner
[4]: https://lore.kernel.org/[email protected]

---
Christian Brauner (4):
exec: stash a bpf-selected interpreter in struct linux_binprm
binfmt_misc: add binfmt_misc_ops bpf struct_ops
binfmt_misc: wire up bpf-backed 'B' entries
bpf: allow fs kfuncs for binfmt_misc_ops programs

 Documentation/admin-guide/binfmt-misc.rst |  40 ++++-
 fs/Kconfig.binfmt                         |  14 ++
 fs/Makefile                               |   1 +
 fs/binfmt_misc.c                          | 143 ++++++++++++++--
 fs/binfmt_misc_bpf.c                      | 275 ++++++++++++++++++++++++++++++
 fs/bpf_fs_kfuncs.c                        |  23 ++-
 fs/exec.c                                 |   1 +
 include/linux/binfmt_misc.h               |  49 ++++++
 include/linux/binfmts.h                   |   1 +
 9 files changed, 529 insertions(+), 18 deletions(-)

---
base-commit: dc59e4fea9d83f03bad6bddf3fa2e52491777482
change-id: 20260707-work-bpf-binfmt_misc-e0b75341733e

author maintainer
#1 lore raw

RFC PATCH 1/4 exec: stash a bpf-selected interpreter in struct linux_binprm

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.

---
 fs/exec.c               | 1 +
 include/linux/binfmts.h | 1 +
 2 files changed, 2 insertions(+)
fs/exec.c +1 -0
index b92fe7db176c..7c9e28f549a4 100644
@@ -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);
 }
include/linux/binfmts.h +1 -0
index 2c77e383e737..0070d207d54f 100644
@@ -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;
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

RFC PATCH 2/4 binfmt_misc: add binfmt_misc_ops bpf struct_ops

In reply to Christian Brauner

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.

---
 fs/Kconfig.binfmt           |  14 +++
 fs/Makefile                 |   1 +
 fs/binfmt_misc_bpf.c        | 275 ++++++++++++++++++++++++++++++++++++++++++++
 include/linux/binfmt_misc.h |  49 ++++++++
 4 files changed, 339 insertions(+)
fs/Kconfig.binfmt +14 -0
index 1949e25c7741..daeac4889d03 100644
@@ -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
fs/Makefile +1 -0
index 89a8a9d207d1..499c6670f0c1 100644
@@ -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
fs/binfmt_misc_bpf.c new file +275 -0

275 lines not on this page · raw message

include/linux/binfmt_misc.h new file +49 -0

49 lines not on this page · raw message

Signature · 1 line
2.53.0
#3 lore raw

Re: [PATCH RFC POC 2/4] binfmt_misc: add binfmt_misc_ops bpf struct_ops

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] TOCTOU race in bpf_binprm_set_interp allows bypassing the absolute path check. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] TOCTOU race in bpf_binprm_set_interp allows bypassing the absolute path check. --

--- Patch [2]: [PATCH RFC POC 2/4] binfmt_misc: add binfmt_misc_ops bpf struct_ops --- commit dcb835dea31af56f46fb0ad454883c437389225a
Author: Christian Brauner <[email protected]>

binfmt_misc: add binfmt_misc_ops bpf struct_ops

This commit adds a BPF struct_ops backend for binfmt_misc. It allows computing the interpreter programmatically for matching binaries instead of relying on fixed strings.

Quoted 5 lines
fs/binfmt_misc_bpf.c new file +0 -0
new file mode 100644
index 0000000000000..72da0964d9491

[ ... ]

fs/binfmt_misc_bpf.c line 119

Quoted 12 lines
fs/binfmt_misc_bpf.c new file +12 -0
+__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] != '/')

[Severity: Medium]
Does this create a Time-of-Check to Time-of-Use (TOCTOU) race if path points to a BPF map value?

If a BPF program passes a pointer to a map value as the path argument, userspace could concurrently modify that map value after this check for '/' but before the path is copied below. This would allow bypassing the absolute path validation.

Should the string be copied via kmemdup_nul() first, and then the absolute path check performed on the newly allocated interp buffer?

Quoted 12 lines
fs/binfmt_misc_bpf.c new file +12 -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;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#4 lore raw

RFC PATCH 3/4 binfmt_misc: wire up bpf-backed 'B' entries

In reply to Christian Brauner

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.

---
 Documentation/admin-guide/binfmt-misc.rst |  40 ++++++++-
 fs/binfmt_misc.c                          | 143 +++++++++++++++++++++++++++---
 2 files changed, 168 insertions(+), 15 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +38 -2
index c0a34fbf8022..c0efb0773628 100644
@@ -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
fs/binfmt_misc.c +130 -13

290 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#5 lore raw

RFC PATCH 4/4 bpf: allow fs kfuncs for binfmt_misc_ops programs

In reply to Christian Brauner

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.

---
 fs/bpf_fs_kfuncs.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)
fs/bpf_fs_kfuncs.c +20 -3
index 768aca2dc0f0..aa1fe988b6d2 100644
@@ -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);
Signature · 1 line
2.53.0