binfmt_misc: bpf-backed binary type handlers
Subsystems (6)
Christian Brauner
maintainerv2 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 selftests pass, and the design is what I want to discuss. The selftests are Farid's from his v2 posting, adapted to the contract below.
A handler is an instance of the new binfmt_misc_ops struct_ops with a name and 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];
};Both programs receive the bprm as a trusted BTF pointer and both are sleepable. The match program decides from the entry lookup walk whether the handler applies, under the same rules as magic matching:
registration order, first match wins. It is not limited to the prefetched 256 bytes in bprm->buf: it can read arbitrary file content through bpf_dynptr_from_file(), e.g. to find an ELF interpreter segment at whatever offset it sits. That is what makes multiple independent handlers workable at all - a handler that cannot read the file would have to match broadly and reject from its load program, stealing the binaries of every handler registered after it. To make this safe the entry walk becomes an SRCU read-side section. The load program of the matched handler then selects the interpreter, reading the file the same way and resolving 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. Selecting is the load program's privilege: the verifier rejects the selection kfuncs in match, keyed off the struct_ops member a program attaches to. A match commits the exec to the handler: a failing load fails the exec instead of falling through to later entries, with -ENOEXEC handing over to the remaining binary formats, so the walk is never left and re-entered.
The genuinely new piece of bpf surface is a small family of kfuncs:
int bpf_binprm_set_interp(struct linux_binprm *bprm, const char *path, size_t path__sz); int bpf_binprm_set_interp_arg(struct linux_binprm *bprm, const char *arg, size_t arg__sz); int bpf_binprm_set_flags(struct linux_binprm *bprm, enum bpf_binprm_flags flags);
staging the selected interpreter, an optional single argument for it (the slot the optional argument of a #! interpreter line has), and the per-exec invocation flags - 'P', 'C' and 'O' equivalents plus a transparent invocation mode as BPF_BINPRM_* bits - in the bprm. Selection cannot go through bprm_change_interp() directly because load_misc_binary() copies bprm->interp into argv[1] after the program ran, hence the staging fields 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 interpreter field carries the handler name - it consistently names whoever supplies the interpreter - and offset, magic, and mask 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.
A 'B' entry carries no flags in the register string: the load program chooses the invocation flags per exec through bpf_binprm_set_flags() instead. BPF_BINPRM_PRESERVE_ARGV0, BPF_BINPRM_CREDENTIALS and BPF_BINPRM_EXECFD keep the static 'P', 'C' and 'O' semantics - BPF_BINPRM_CREDENTIALS honors the matched binary's suid bits exactly as a static 'C' entry does, with the setuid transition gated by vfsuid_has_mapping() in the caller's user namespace either way, which makes 'B' handlers usable for a per-binary loader over setuid binaries. BPF_BINPRM_TRANSPARENT has no static counterpart: the binary is handed to the interpreter through AT_EXECFD with the argument vector left untouched, so the exec looks like a direct execution of the binary and a binary passed as an inaccessible O_CLOEXEC fd to execveat() can be run at all. 'F' (pre-open a fixed interpreter) is
rejected: a 'B' entry has no fixed interpreter. 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/match")
bool BPF_PROG(nix_match, struct linux_binprm *bprm)
{
return !bpf_strncmp(bprm->buf, 4, "\x7f" "ELF");
}
SEC("struct_ops.s/load")
int BPF_PROG(nix_load, struct linux_binprm *bprm)
{
char path[256];
long n;
n = bpf_path_d_path(&bprm->file->f_path, path, sizeof(path));
if (n < 0)
return n;
/* derive the loader location from the binary's path */
return bpf_binprm_set_interp(bprm, path, sizeof(path));
}
SEC(".struct_ops.link")
struct binfmt_misc_ops nix = {
.match = (void *)nix_match,
.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]
---
Changes in v2:
- Rebase onto vfs-7.3.binfmt (write access fixes, RCU handler lookup and cleanups): the entry walk is lockless now.
- Split the handler into a match program consulted from the lookup walk itself - exactly like magic/extension matching - and the load program invoked once the walk has committed to the entry. Both are sleepable and can read the file: a match limited to the prefetched bprm->buf cannot recognise formats whose distinguishing data sits past 256 bytes, and with several handlers registered match-broadly-and-reject-in-load would break first-match-wins. The entry walk becomes an SRCU read-side section (srcu-fast) to allow that. The selection kfuncs are restricted to the load program by the verifier via the struct_ops member offset. A failing load fails the exec instead of falling through to later entries, so the walk is never left and re-entered: the v1 skip cursor and its rescan loop are gone and 'B' entries need no special semantics against concurrent (un)registration.
- Move the handler name from the offset field to the interpreter
field: it consistently names whoever supplies the interpreter, a path for static entries and a handler for 'B' entries.
- Let the load program pass a single optional argument to the interpreter via the new bpf_binprm_set_interp_arg() kfunc, mirroring the optional argument of a #! interpreter line.
- Let the load program choose the invocation flags per exec via the new bpf_binprm_set_flags() kfunc - BPF_BINPRM_PRESERVE_ARGV0, BPF_BINPRM_CREDENTIALS and BPF_BINPRM_EXECFD mirroring 'P', 'C' and 'O' - instead of fixing them at registration; the register string rejects 'P', 'C' and 'O' for 'B' entries. BPF_BINPRM_CREDENTIALS keeps the static 'C' semantics: the setuid transition stays gated by vfsuid_has_mapping() in the caller's user namespace.
- Add BPF_BINPRM_TRANSPARENT on top of the static flags: the binary is handed to the interpreter through AT_EXECFD with the argument vector left untouched, so the exec looks like a direct execution of the binary and a binary passed as an inaccessible O_CLOEXEC fd to execveat() can be run at all.
- Picked up Farid's selftests from his v2 posting and adapted them to the contract above: the register grammar, both programs sleepable with nix_origin's match reading PT_INTERP itself, the load return convention, and a skip on kernels without CONFIG_BINFMT_MISC_BPF.
---
Christian Brauner (8):
exec: stash bpf-selected interpreter state in struct linux_binprm
binfmt_misc: add binfmt_misc_ops bpf struct_ops
binfmt_misc: let the entry lookup walk sleep
binfmt_misc: wire up bpf-backed 'B' entries
bpf: allow fs kfuncs for binfmt_misc_ops programs
binfmt_misc: let bpf handlers pass an argument to the interpreter
binfmt_misc: let a bpf handler choose the invocation flags per exec
binfmt_misc: let a bpf handler run the interpreter transparently
Farid Zakaria (1):
selftests/exec: add binfmt_misc bpf-backed handler test
Documentation/admin-guide/binfmt-misc.rst | 73 ++++- fs/Kconfig.binfmt | 14 + fs/Makefile | 1 + fs/binfmt_misc.c | 306 ++++++++++++++++---- fs/binfmt_misc_bpf.c | 351 +++++++++++++++++++++++ fs/bpf_fs_kfuncs.c | 23 +- fs/exec.c | 2 + include/linux/binfmt_misc.h | 74 +++++ include/linux/binfmts.h | 8 + tools/testing/selftests/exec/.gitignore | 5 + tools/testing/selftests/exec/Makefile | 48 ++++ 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 | 277 ++++++++++++++++++ tools/testing/selftests/exec/bpf_interp.bpf.c | 61 ++++ tools/testing/selftests/exec/nix_origin.bpf.c | 224 +++++++++++++++ 16 files changed, 1434 insertions(+), 60 deletions(-)
---
base-commit: 79dec1889331ba2d4898886779f4d0a063f6a1ef
change-id: 20260707-work-bpf-binfmt_misc-e0b75341733e
Christian Brauner
maintainerPATCH v2 1/9 exec: stash bpf-selected interpreter state in struct linux_binprm
The upcoming bpf-backed binfmt_misc handlers decide how a binary is run programmatically at exec time: the interpreter itself, an optional single argument to pass to it, and the invocation flags that a static binfmt_misc entry fixes at registration 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 state in the bprm instead, grouped in struct binfmt_misc_bpf and embedded anonymously in struct linux_binprm so the bprm->bpf_* accesses stay direct. The bprm is exclusively owned by the task doing the exec so no synchronization is needed. The consumers free and clear the fields once the exec attempt that set them is finished; free_bprm() covers all error paths.
--- fs/exec.c | 2 ++ include/linux/binfmts.h | 8 ++++++++ 2 files changed, 10 insertions(+)
fs/exec.c +2 -0
@@ -1418,6 +1418,8 @@ 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->bpf_interp_arg);kfree (bprm->fdpath);kfree (bprm); }
include/linux/binfmts.h +8 -0
@@ -12,6 +12,13 @@ struct coredump_params;#define CORENAME_MAX_SIZE 128 +/* Interpreter selection staged by a bpf binfmt_misc handler. */ +struct binfmt_misc_bpf { +const char *bpf_interp;/* interpreter selected by a bpf handler */ +const char *bpf_interp_arg;/* interpreter argument from a bpf handler */ +u64 bpf_flags;/* enum bpf_binprm_flags from a bpf handler */ +}; +/* * This structure is used to hold the arguments that are used when loading binaries. */
@@ -65,6 +72,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 */ +struct binfmt_misc_bpf ;/* bpf handler interpreter selection */ unsigned interp_flags;int execfd;/* File descriptor of the executable */ unsigned long exec;
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 2/9 binfmt_misc: add binfmt_misc_ops bpf struct_ops
In reply to Christian BraunerAdd the bpf plumbing for binary type handlers whose matching and interpreter selection are implemented by bpf programs 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 name that binfmt_misc entries reference it by and two ops:
bool (*match)(struct linux_binprm *bprm);
int (*load)(struct linux_binprm *bprm);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 ops receive 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 two ops split along what they decide, not what they may do: the match program decides whether the handler applies to a binary, the load program decides how a matched binary is run. Both are required to be sleepable. Matching cannot be limited to the prefetched 256 bytes in bprm->buf: deciding whether a handler applies takes e.g. parsing the ELF program headers to find an interpreter segment, which sits at an arbitrary file offset, and non-sleepable file reads are limited to whatever happens to be resident in the page cache. A match program that cannot read the file reliably would have to match broadly and leave the rejection to its load program, which breaks first-match-wins entry semantics the moment more than one handler is registered. Reliable file reads at exec time fault in the file's pages, so both ops must be able to sleep. This also constrains the
caller: binfmt_misc must invoke both from sleepable context, which a later patch takes care of. Both ops are required; a handler that wants to decide everything from the load program supplies a match program that just returns true.
The load program communicates its decisions through three new kfuncs:
int bpf_binprm_set_interp(struct linux_binprm *bprm,
const char *path, size_t path__sz);
selects the interpreter and enforces an absolute path shorter than PATH_MAX.
int bpf_binprm_set_interp_arg(struct linux_binprm *bprm,
const char *arg, size_t arg__sz);
passes a single optional argument to the interpreter, mirroring the optional argument of a #! interpreter line - something a static entry cannot express at all.
int bpf_binprm_set_flags(struct linux_binprm *bprm,
enum bpf_binprm_flags flags);
chooses the invocation flags for this exec, with BPF_BINPRM_PRESERVE_ARGV0, BPF_BINPRM_CREDENTIALS and BPF_BINPRM_EXECFD mapping to 'P', 'C' and 'O'. Unknown bits are rejected so a program built against a newer kernel fails loudly on an older one rather than silently losing a flag. Repeated calls replace the staged flags and a zero argument clears them again - the set-or-clear semantics of bpf_bprm_opts_set() on the same struct. A flags word carries this better than a kfunc per flag: it is one call, it is set atomically, and new behaviour is a new bit rather than new surface - the same shape the register string's flags field already has.
All three stage their result in the bprm; consuming it from load_misc_binary() is wired up by the following patches. 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 kfuncs are registered for struct_ops programs with a filter that limits them to the load program of a binfmt_misc_ops instance, keyed off the struct_ops member offset the program attaches to: match decides whether a handler applies, load decides how the binary is run, and the verifier enforces that split at program load time.
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 current_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 | 349 ++++++++++++++++++++++++++++++++++++++++++++ include/linux/binfmt_misc.h | 71 +++++++++ 4 files changed, 435 insertions(+)
fs/Kconfig.binfmt +14 -0
@@ -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
@@ -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 +349 -0
349 lines not on this page · raw message
include/linux/binfmt_misc.h new file +71 -0
71 lines not on this page · raw message
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 3/9 binfmt_misc: let the entry lookup walk sleep
In reply to Christian BraunerThe upcoming bpf-backed binary type handlers run a match program from the entry lookup walk in load_misc_binary(). Deciding whether a handler applies means reading the binary - parsing ELF program headers sitting at arbitrary file offsets, say - and reliable file reads at exec time fault in the file's pages, so the walk must tolerate an entry's evaluation sleeping.
Switch the walk from RCU to SRCU in its fast flavor: srcu-fast read sections may block while the read side stays practically as cheap as the RCU read lock it replaces, so the common static-entry lookup does not pay for the new capability. Entry freeing moves from kfree_rcu() to call_srcu(). Removal still unlinks the entry immediately and never
blocks: a walker sleeping inside an entry's evaluation just keeps the entry alive until it leaves the read section. The module exit path flushes pending callbacks with srcu_barrier().
Take the reference on a matched entry at the match point inside the walk instead of retrying the whole search when the refcount raise fails. A restarted search was harmless when an entry's evaluation was a memcmp() on bprm->buf, but re-running match programs that may sleep on entries that were already consulted is not. An entry whose refcount hit zero is unlinked and dying, so treating it as absent and walking on is exactly what the bounded retry loop converged to, without ever evaluating an entry twice.
--- fs/binfmt_misc.c | 56 ++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 22 deletions(-)
fs/binfmt_misc.c +34 -22
@@ -29,6 +29,7 @@#include <linux/refcount.h> #include <linux/seq_file.h> #include <linux/slab.h> +#include <linux/srcu.h> #include <linux/string.h> #include <linux/string_helpers.h> #include <linux/uaccess.h>
@@ -82,6 +83,9 @@ struct binfmt_misc_entry {/* Trailing delimiter pad so field parsing always terminates at a delimiter. */ #define MISC_DELIM_PAD 8 +/* Protects the entry walk in load_misc_binary(), which may sleep in it. */ +DEFINE_STATIC_SRCU_FAST (bm_entries_srcu); +/* Check if @e's magic matches @bprm's buffer, applying the mask if set. */ static bool entry_matches_magic (const struct binfmt_misc_entry *e,const struct linux_binprm *bprm)
@@ -111,11 +115,14 @@ static bool entry_matches_extension(const struct binfmt_misc_entry *e,* @bprm: binary for which we are looking for a handler * * Search for a binary type handler for @bprm in the list of registered binary -* type handlers. +* type handlers. The matched entry is returned with a reference taken while +* the walk still held it; a dying entry - unlinked with its last reference +* gone - cannot be matched and the walk moves on. * -* The caller must hold the RCU read lock. +* The caller must hold the bm_entries_srcu read lock, which allows an +* entry's evaluation to sleep. * -* Return: binary type list entry on success, NULL on failure +* Return: referenced 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)
@@ -125,18 +132,23 @@ search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)struct binfmt_misc_entry *e;/* Walk all the registered handlers. */ -hlist_for_each_entry_rcu (e, &misc->entries, node) { +hlist_for_each_entry_rcu (e, &misc->entries, node, +srcu_read_lock_held (&bm_entries_srcu)) {/* Make sure this one is currently enabled. */ if (!test_bit (MISC_FMT_ENABLED_BIT , &e->flags))continue ;if (test_bit (MISC_FMT_MAGIC_BIT , &e->flags)) { -if (entry_matches_magic (e, bprm)) -return e; +if (!entry_matches_magic (e, bprm)) +continue ; }else { -if (entry_matches_extension (e, ext)) -return e; +if (!entry_matches_extension (e, ext)) +continue ; } + +/* A dying entry cannot be matched, walk on. */ +if (refcount_inc_not_zero (&e->users)) +return e; }return NULL ;
@@ -147,24 +159,22 @@ search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)* @misc: handle to binfmt_misc instance * @bprm: binary for which we are looking for a handler * -* 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 -* refcount of an entry can only drop to zero once it has been unlinked and -* a restarted search cannot find an unlinked entry again so the retry loop -* is bounded. +* Try to find a binfmt handler for the binary type. If one is found it is +* returned with a reference protecting it against removal via +* bm_{entry,status}_write(). * * 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 binfmt_misc_entry *e; +guard (srcu_fast)(&bm_entries_srcu); +return search_binfmt_handler (misc, bprm); +} -guard (rcu)(); -do { - e =search_binfmt_handler (misc, bprm); - }while (e && !refcount_inc_not_zero (&e->users)); -return e; +static void bm_entry_free_rcu (struct rcu_head *rcu) +{ +kfree (container_of(rcu ,struct binfmt_misc_entry ,rcu )); }/**
@@ -182,8 +192,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 ); } -/* Lockless walkers may still dereference this entry. */ -kfree_rcu (e, rcu); +/* Walkers may still dereference this entry, even sleeping. */ +call_srcu (&bm_entries_srcu, &e->rcu, bm_entry_free_rcu); } }
@@ -670,7 +680,7 @@ static void bm_evict_inode(struct inode *inode)* Adding and removing entries via bm_{entry,register,status}_write() and * unlink(2) happens under the exclusively held inode lock of the root * dentry keeping the list stable for writers. load_misc_binary() walks it -* concurrently under RCU. The entries_lock is only held around the actual +* concurrently under SRCU. The entries_lock is only held around the actual * unlink to serialize against bm_evict_inode() which unlinks entries * during umount without holding the root inode lock. */
@@ -1054,6 +1064,8 @@ static void __exit exit_misc_binfmt(void) {unregister_binfmt (&misc_format);unregister_filesystem (&bm_fs_type); +/* Flush pending bm_entry_free_rcu() callbacks before the text goes. */ +srcu_barrier (&bm_entries_srcu); }core_initcall (init_misc_binfmt);
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 4/9 binfmt_misc: wire up bpf-backed 'B' entries
In reply to Christian BraunerActivate 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, magic, and mask fields must be empty since the program does the matching; the interpreter field carries the handler name since the program supplies 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 from the SRCU callback that frees the entry rather than synchronously on the final put: a walker may be asleep inside the handler's match program while the entry's last reference goes away, so the ops must stay callable until every walker has left the read section - the same deferral the entry's own memory already gets. The registration failure path, where the users refcount is not live yet, drops it explicitly.
The match program runs from the lookup walk like magic and extension matching and under the same rules: strict registration order, first match wins. The walk became an SRCU read-side section in the previous patch, so the program can sleep: it decides on the actual file content - program headers beyond the prefetched bprm->buf, say - not just on whatever happens to be resident in the page cache. A match commits the exec to the handler. The sleepable load program then selects the interpreter from load_misc_binary() by calling bpf_binprm_set_interp() and returning zero; a failure fails the exec instead of falling through to later entries. The walk is never left and re-entered, so 'B' entries need no special semantics against concurrent registration and removal whatsoever. -ENOEXEC keeps its usual meaning and moves on to the remaining binary formats - a handler whose load program discovers that it cannot serve the binary after all hands it back to them - and so does returning zero without having selected an interpreter; other program-supplied errors are clamped to the errno range.
The 'F' flag is rejected for 'B' entries: it exists to pre-open a fixed interpreter at registration time in the registrar's context, and a 'B' entry has no fixed interpreter to pre-open.
'C' is accepted and behaves exactly as it does for a static entry. It honors the suid bits of the matched binary while executing the interpreter, which makes 'B' handlers usable for the setuid case, e.g. a per-binary loader. This does not let the program's registrant widen
access: bprm_fill_uid() gates the credential transition on vfsuid_has_mapping() in the caller's user namespace, so the interpreter can only ever run as a uid that is mapped there, identical to a static 'C' entry. The computed path is opened with open_exec() under the caller's credentials with the usual LSM and noexec checks, and the programs run before the transition with the caller's credentials, never elevated.
--- Documentation/admin-guide/binfmt-misc.rst | 47 +++++++++- fs/binfmt_misc.c | 148 +++++++++++++++++++++++++++--- 2 files changed, 180 insertions(+), 15 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +45 -2
@@ -26,7 +26,8 @@ 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...``).
@@ -48,7 +49,8 @@ Here is what the fields mean: filename extension matching. - ``interpreter`` is the program that should be invoked with the binary as first - argument (specify the full path) + argument (specify the full path). For ``B`` entries this field + carries the name of the bpf handler instead (see below). - ``flags`` is an optional field that controls several aspects of the invocation of the interpreter. It is a string of capital letters, each controls a
@@ -97,6 +99,47 @@ 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 bpf programs. A handler is an instance of the +``binfmt_misc_ops`` struct_ops with a ``match`` and a ``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 in the ``interpreter`` field +and carries neither offset, magic, nor mask:: + + echo ':qemu:B::::my_handler:' > register + +Both programs receive the ``linux_binprm`` of the binary and both can +sleep. The ``match`` program decides whether the handler applies: it is +consulted during the entry walk exactly like magic and extension matching, +in the same registration order with the same first-match-wins semantics. +Unlike static matching it is not limited to the prefetched first bytes of +the file in ``bprm->buf``: it can read the file, e.g. to parse ELF program +headers whose data sits at arbitrary offsets. It only decides, though: the +selection kfuncs below are rejected in it. The ``load`` program of the +matched handler then selects the interpreter: it can equally read the file +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 ``0``. A match is committed: a failing +``load`` fails the exec with its error instead of falling through to later +entries; ``-ENOEXEC`` 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 activations. + +The ``F`` flag cannot be combined with ``B`` entries: it pre-opens a fixed +interpreter at registration time and a ``B`` entry has none. The ``C`` flag +works as it does for a static entry: the interpreter runs with the matched +binary's credentials, bounded to user namespaces that map the binary's owner +just like any other setuid exec. + 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 +135 -13
274 lines not on this page · raw message
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 5/9 bpf: allow fs kfuncs for binfmt_misc_ops programs
In reply to Christian BraunerThe fs kfuncs are currently exclusive to LSM programs. A binfmt_misc handler needs a subset of them to do anything interesting: computing an interpreter relative to the binary's location wants bpf_path_d_path() on bprm->file->f_path from the load program, and matching on per-binary metadata wants bpf_get_file_xattr() and friends right from the match program.
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
@@ -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
Christian Brauner
maintainerPATCH v2 6/9 binfmt_misc: let bpf handlers pass an argument to the interpreter
In reply to Christian BraunerA bpf binfmt_misc handler selects an interpreter but, unlike binfmt_script, load_misc_binary() builds the argument vector as just [interpreter, binary, ...] with no slot for an argument to the interpreter. A handler that wants to reproduce a #! line therefore cannot express its single optional argument, e.g. a handler that resolves $ORIGIN in a script's #! path loses the argument that followed the interpreter.
Have load_misc_binary() consume the argument staged through the bpf_binprm_set_interp_arg() kfunc and insert it between the interpreter and the binary - the same position and single-argument semantics binfmt_script gives the argument of a #! line. The argument is cleared once spliced into the argument vector, and a load program that fails after staging one has it dropped on the way out: whether the exec fails or -ENOEXEC hands the binary back to the remaining formats, a stale argument cannot leak into a nested interpreter's argv. This also lets static-style handlers pass a fixed interpreter argument, which plain binfmt_misc has never been able to express.
--- Documentation/admin-guide/binfmt-misc.rst | 6 ++++++ fs/binfmt_misc.c | 30 ++++++++++++++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +6 -0
@@ -129,6 +129,12 @@ entries; ``-ENOEXEC`` 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. +The ``load`` program can also pass a single argument to the interpreter with +the ``bpf_binprm_set_interp_arg()`` kfunc. It is inserted between the +interpreter and the binary, exactly like the optional argument of a ``#!`` +interpreter line, e.g. for a handler that resolves ``$ORIGIN`` in a script's +``#!`` path and needs to preserve the argument that followed it. + 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
fs/binfmt_misc.c +26 -4
@@ -268,14 +268,22 @@ static const char *entry_select_interpreter(const struct binfmt_misc_entry *e,/* Keep a program-supplied error within errno range. */ if (retval >0 || retval < -MAX_ERRNO ) retval = -ENOEXEC ; -return ERR_PTR (retval); + goto drop_staged; }/* Selecting an interpreter is part of the contract. */ -if (!bprm->bpf_interp) -return ERR_PTR (-ENOEXEC ); +if (!bprm->bpf_interp) { + retval = -ENOEXEC ; + goto drop_staged; + }return bprm->bpf_interp; + +drop_staged: +/* A failing load leaves nothing behind for later entries. */ +kfree (bprm->bpf_interp_arg); + bprm->bpf_interp_arg =NULL ; +return ERR_PTR (retval); }/*
@@ -316,12 +324,26 @@ static int load_misc_binary(struct linux_binprm *bprm)if (fmt->flags &MISC_FMT_OPEN_BINARY ) bprm->have_execfd =1 ; -/* make argv[1] be the path to the binary */ +/* make the binary the last argument to the interpreter */ retval =copy_string_kernel (bprm->interp, bprm);if (retval <0 )return retval; bprm->argc++; +/* +* A single optional argument to the interpreter, inserted between it +* and the binary just like the argument of a #! interpreter line. +*/ +if (bprm->bpf_interp_arg) { + retval =copy_string_kernel (bprm->bpf_interp_arg, bprm); +if (retval <0 ) +return retval; + bprm->argc++; +/* Consumed - don't let it leak into a nested interpreter's argv. */ +kfree (bprm->bpf_interp_arg); + bprm->bpf_interp_arg =NULL ; + } +/* add the interp as argv[0] */ retval =copy_string_kernel (interpreter, bprm);if (retval <0 )
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 7/9 binfmt_misc: let a bpf handler choose the invocation flags per exec
In reply to Christian BraunerThe 'P', 'C' and 'O' flags of a binfmt_misc entry - preserve argv[0], compute credentials from the binary, and pass the binary as an open file descriptor - are fixed at registration and apply to every binary the entry matches. A bpf handler matches, selects the interpreter and reads the binary per exec, so the flags should be its per-exec decision too: one handler may match both setuid and non-setuid binaries, argv[0]-sensitive ones and not.
Honor the flags the load program stages in bprm->bpf_flags through the bpf_binprm_set_flags() kfunc: BPF_BINPRM_PRESERVE_ARGV0, BPF_BINPRM_CREDENTIALS and BPF_BINPRM_EXECFD map to 'P', 'C' and 'O' and keep the semantics of their static counterparts, credentials implying the open file descriptor included.
Flags staged by a load program that then fails are dropped on the way out so they cannot leak into a later handler's exec, and the argv[0] decision acts on the entry's own choice instead of testing the accumulated bprm->interp_flags bit, which an earlier chain level may have left set and binfmt_misc never clears.
Since a 'B' entry's flags come from the program, it carries none in the register string: 'P', 'C' and 'O' are rejected there alongside 'F', which was already meaningless for it. load_misc_binary() takes the flags from the entry for a static handler and from bprm->bpf_flags for a bpf one.
--- Documentation/admin-guide/binfmt-misc.rst | 23 ++++++++++++---- fs/binfmt_misc.c | 46 +++++++++++++++++++++++-------- 2 files changed, 51 insertions(+), 18 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +17 -6
@@ -135,17 +135,28 @@ interpreter and the binary, exactly like the optional argument of a ``#!`` interpreter line, e.g. for a handler that resolves ``$ORIGIN`` in a script's ``#!`` path and needs to preserve the argument that followed it. +The invocation flags a static entry fixes at registration - ``P``, ``C`` +and ``O`` - are per-exec choices for a bpf handler, made by the ``load`` +program with the ``bpf_binprm_set_flags()`` kfunc, so a single handler can +decide them differently for each binary it handles: + +- ``BPF_BINPRM_PRESERVE_ARGV0`` keeps the caller's ``argv[0]`` (the ``P`` + flag). +- ``BPF_BINPRM_CREDENTIALS`` computes credentials from the binary (the ``C`` + flag), bounded to user namespaces that map the binary's owner just like + any other setuid exec. +- ``BPF_BINPRM_EXECFD`` opens the binary on the interpreter's behalf and + passes it through the ``AT_EXECFD`` aux vector entry (the ``O`` flag), so + the interpreter can run binaries it could not open by path. + +Because these are program choices, a ``B`` entry carries no flags in the +register string; ``F`` (pre-open a fixed interpreter) has no meaning for it. + 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 activations. -The ``F`` flag cannot be combined with ``B`` entries: it pre-opens a fixed -interpreter at registration time and a ``B`` entry has none. The ``C`` flag -works as it does for a static entry: the interpreter runs with the matched -binary's credentials, bounded to user namespaces that map the binary's owner -just like any other setuid exec. - 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 +34 -12
84 lines not on this page · raw message
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 8/9 binfmt_misc: let a bpf handler run the interpreter transparently
In reply to Christian BraunerA binfmt_misc interpreter is visible to the binary it runs: argv[0] becomes the interpreter path, the binary's path is appended as an argument and /proc/pid/cmdline shows both. For wine or qemu-user that is the point, but for a per-binary loader the interpreter is an implementation detail of running the binary that has no business in the argument vector. And a binary handed to execveat() as an O_CLOEXEC fd without a usable path cannot be run through binfmt_misc at all: the interpreter would have no path to open the binary by, so load_misc_binary() refuses upfront with -ENOENT.
Add BPF_BINPRM_TRANSPARENT. It goes beyond the static flags: the binary is handed to the interpreter through AT_EXECFD as with BPF_BINPRM_EXECFD, but the argument vector and bprm->interp are also left exactly as the caller set them, so argv[0] and /proc/pid/cmdline look like a direct execution of the binary. The interpreter has to load the binary from AT_EXECFD for this; a relocatable loader can, glibc's ld.so does not.
The inaccessible-path bail moves after the load program has run and into the path-building branch: a transparent interpreter takes the binary from AT_EXECFD instead of a path, so the restriction no longer applies and the O_CLOEXEC execveat() case above just works. BPF_BINPRM_PRESERVE_ARGV0 is subsumed - transparency preserves the whole argument vector, argv[0] included - and a staged interpreter argument is dropped: no argv slot is built for it to land in.
--- Documentation/admin-guide/binfmt-misc.rst | 9 +++ fs/binfmt_misc.c | 92 ++++++++++++++++++------------- fs/binfmt_misc_bpf.c | 6 +- include/linux/binfmt_misc.h | 3 + 4 files changed, 71 insertions(+), 39 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +9 -0
@@ -148,6 +148,15 @@ decide them differently for each binary it handles: - ``BPF_BINPRM_EXECFD`` opens the binary on the interpreter's behalf and passes it through the ``AT_EXECFD`` aux vector entry (the ``O`` flag), so the interpreter can run binaries it could not open by path. +- ``BPF_BINPRM_TRANSPARENT`` runs the interpreter transparently. It has no + static counterpart: the binary is handed over through ``AT_EXECFD`` as + with ``BPF_BINPRM_EXECFD``, but the argument vector is also left as the + caller passed it. An interpreter that loads the binary from ``AT_EXECFD`` + then appears in ``argv[0]`` and ``/proc/pid/cmdline`` as a direct + execution of the binary. This is also the only way a binfmt_misc handler + can run a binary passed as an inaccessible ``O_CLOEXEC`` file descriptor + to ``execveat()``, which otherwise fails because the interpreter has no + path by which to open it. Because these are program choices, a ``B`` entry carries no flags in the register string; ``F`` (pre-open a fixed interpreter) has no meaning for it.
fs/binfmt_misc.c +55 -37
126 lines not on this page · raw message
fs/binfmt_misc_bpf.c +4 -2
@@ -178,7 +178,9 @@ __bpf_kfunc int bpf_binprm_set_interp_arg(struct linux_binprm *bprm,* O flags: BPF_BINPRM_PRESERVE_ARGV0 keeps the caller's argv[0], * BPF_BINPRM_CREDENTIALS computes credentials from the binary, and * BPF_BINPRM_EXECFD hands the binary to the interpreter through AT_EXECFD. -* Calling it again replaces the flags, passing zero clears them again. +* BPF_BINPRM_TRANSPARENT additionally leaves the argument vector untouched, +* making the exec look like a direct execution of the binary. Calling it +* again replaces the flags, passing zero clears them again. * * Return: 0 on success, -EINVAL if @flags contains an unknown bit */
@@ -186,7 +188,7 @@ __bpf_kfunc int bpf_binprm_set_flags(struct linux_binprm *bprm, enum bpf_binprm_flags flags) {if (flags & ~(BPF_BINPRM_PRESERVE_ARGV0 |BPF_BINPRM_CREDENTIALS | -BPF_BINPRM_EXECFD )) +BPF_BINPRM_EXECFD |BPF_BINPRM_TRANSPARENT ))return -EINVAL ; bprm->bpf_flags = flags;
include/linux/binfmt_misc.h +3 -0
@@ -16,6 +16,8 @@ struct user_namespace;* @BPF_BINPRM_CREDENTIALS: compute credentials from the binary; implies execfd * (like the 'C' flag) * @BPF_BINPRM_EXECFD: pass the binary via AT_EXECFD (like the 'O' flag) +* @BPF_BINPRM_TRANSPARENT: leave argv untouched, the interpreter takes the +* binary from AT_EXECFD; implies execfd * * Set from a load program with bpf_binprm_set_flags(). Unlike a static entry, * a bpf handler chooses these per exec rather than once at registration.
@@ -24,6 +26,7 @@ enum bpf_binprm_flags {BPF_BINPRM_PRESERVE_ARGV0 = (1ULL <<0 ),BPF_BINPRM_CREDENTIALS = (1ULL <<1 ),BPF_BINPRM_EXECFD = (1ULL <<2 ), + BPF_BINPRM_TRANSPARENT = (1ULL << 3), };/**
Signature · 1 line
2.53.0
Christian Brauner
maintainerPATCH v2 9/9 selftests/exec: add binfmt_misc bpf-backed handler test
In reply to Christian BraunerFrom: Farid Zakaria <[email protected]>
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: the match program matches a synthetic aarch64 ELF header from the prefetched bprm->buf and the load program routes it to a fixed interpreter of its choosing.
- nix_origin: the match program parses the program headers to commit only to a "$ORIGIN/..."-relative PT_INTERP and the load program resolves it 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. The bpf pieces are only built when clang, bpftool, the vmlinux BTF and libbpf are all present (HAVE_BPF_TOOLCHAIN=y forces them) so the other exec selftests keep building without a bpf toolchain.
Christian Brauner (Amutable) <[email protected]> says:
Adapted to the two-op contract: 'B' entries carry the handler name in the interpreter field, both programs are sleepable, the match programs decide. nix_origin reads PT_INTERP from the match program and load returns zero on success. Skip on kernels without binfmt_misc_ops in BTF. Build the bpf pieces only when the toolchain is present and gitignore the generated artifacts.
--- tools/testing/selftests/exec/.gitignore | 5 + tools/testing/selftests/exec/Makefile | 48 ++++ 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 | 277 +++++++++++++++++++++++ tools/testing/selftests/exec/bpf_interp.bpf.c | 61 +++++ tools/testing/selftests/exec/nix_origin.bpf.c | 224 ++++++++++++++++++ 7 files changed, 642 insertions(+)
tools/testing/selftests/exec/.gitignore +5 -0
@@ -19,3 +19,8 @@ null-argv xxxxxxxx* pipe S_I*.test +binfmt_misc_bpf +binfmt_bpf_interp +binfmt_bpf_app +*.bpf.o +vmlinux.h
tools/testing/selftests/exec/Makefile +48 -0
57 lines not on this page · raw message
tools/testing/selftests/exec/binfmt_bpf_app.c new file +12 -0
@@ -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 ; +}
tools/testing/selftests/exec/binfmt_bpf_interp.c new file +15 -0
@@ -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 ; +}
tools/testing/selftests/exec/binfmt_misc_bpf.c new file +277 -0
277 lines not on this page · raw message
tools/testing/selftests/exec/bpf_interp.bpf.c new file +61 -0
61 lines not on this page · raw message
tools/testing/selftests/exec/nix_origin.bpf.c new file +224 -0
224 lines not on this page · raw message
Signature · 1 line
2.53.0
Quoted 7 lines · Christian Brauner
[...]
.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.
Thanks for the recent update.
Is it still "take it from here" or was this left-over from the previous series.
I think you've done the majority of the work here with the validation of the few selftests and mentioning the gap for shebangs.
Please let me know what you would like me to do next. I just tested reviewing the series with b4 + AI -- pretty cool. Was a little clunky to get it to work but overall a good experience. (I need to tinker with it a little for NixOS vim setup etc..)
I shared this patch series at my workplace as well.
I think there is some interest in the work.
(If you are curious as to why, I can elaborate on that as well).
I hope you are enjoying your vacation.
Signature · 1 line
Farid Zakaria <[email protected]>
Re: [PATCH v2 1/9] exec: stash bpf-selected interpreter state in struct linux_binprm
In reply to Christian BraunerQuoted 9 lines · Christian Brauner
The upcoming bpf-backed
binfmt_mischandlers decide how a binary is run programmatically at exec time: the interpreter itself, an optional single argument to pass to it, and the invocation flags that a staticbinfmt_miscentry fixes at registration time. The selection runs beforeload_misc_binary()has copied the binary path frombprm->interpinto the argument vector, so the selecting program cannot go throughbprm_change_interp()directly without clobbering argv[1].[...]
Signature · 1 line
Farid Zakaria <[email protected]>
Re: [PATCH v2 4/9] binfmt_misc: wire up bpf-backed 'B' entries
In reply to Christian Braunerfs/binfmt_misc.c static struct binfmt_misc *current_binfmt_misc(void) · line 279
Quoted 12 lines · Christian Brauner
fs/binfmt_misc.c +0
-0@@ -226,12 +240,51 @@ static struct binfmt_misc *current_binfmt_misc(void)[ ... skip 34 lines ... ]
fs/binfmt_misc.c +6
-0+/* Selecting an interpreter is part of the contract. */ +if (!bprm->bpf_interp) +return ERR_PTR (-ENOEXEC ); + +return bprm->bpf_interp; +}
The "contract" says that if the BPF program returns 0, it must take ownership of selecting the interpreter. However the bpf_interp can be NULL here and therefore is indistinguishable from the refuse to handle case.
We might want to treat 0-without-interp as a hard -ENOEXEC-to-caller.
Signature · 1 line
Farid Zakaria <[email protected]>
Re: [PATCH v2 5/9] bpf: allow fs kfuncs for binfmt_misc_ops programs
In reply to Christian BraunerQuoted 8 lines · Christian Brauner
The fs kfuncs are currently exclusive to LSM programs. A
binfmt_mischandler needs a subset of them to do anything interesting: computing an interpreter relative to the binary's location wantsbpf_path_d_path()onbprm->file->f_pathfrom the load program, and matching on per-binary metadata wantsbpf_get_file_xattr()and friends right from the match program.[...]
Signature · 1 line
Farid Zakaria <[email protected]>
Re: [PATCH v2 6/9] binfmt_misc: let bpf handlers pass an argument to the interpreter
In reply to Christian BraunerQuoted 8 lines · Christian Brauner
A bpf
binfmt_mischandler selects an interpreter but, unlikebinfmt_script,load_misc_binary()builds the argument vector as just [interpreter, binary, ...] with no slot for an argument to the interpreter. A handler that wants to reproduce a #! line therefore cannot express its single optional argument, e.g. a handler that resolves $ORIGIN in a script's #! path loses the argument that followed the interpreter.[...]
Signature · 1 line
Farid Zakaria <[email protected]>
Christian Brauner
maintainerQuoted 6 lines · Farid Zakaria
Quoted 5 lines · Christian Brauner
[...]
.load = (void *)nix_load, .name = "nix", };
Quoted 6 lines
Quoted 2 lines
Farid, this should slot underneath your qemu demo from [4] with the program ported to
struct_ops. Feel free to take it from here.Thanks for the recent update.
Is it still "take it from here" or was this left-over from the previous series.
Leftover from the previous series. :) Sorry.
Quoted 2 lines
I think you've done the majority of the work here with the validation of the few selftests and mentioning the gap for shebangs.
It was a nice joint effort imo. I think this is in general an interesting idea. I'm also working on some glibc loader patches. One of the patches in this series allows for "transparent binary execution" if the loader supports it.
In this mode you can pass AT_EXECFD to an interpreter and don't change the command line. An exec like this is indistinguishable from a "native" exec.
Quoted 8 lines
Please let me know what you would like me to do next. I just tested reviewing the series with b4 + AI -- pretty cool. Was a little clunky to get it to work but overall a good experience. (I need to tinker with it a little for NixOS vim setup etc..)
I shared this patch series at my workplace as well.
I think there is some interest in the work.
(If you are curious as to why, I can elaborate on that as well).
Sure, happy to hear other use-cases. I have a plan to make it possible to pre-open a set of interpreters (pin them essentially) when registering the handler in binfmt_misc and then bpf would be able to select from a set of pre-opened interpreters but that's for the future.
Quoted 1 line
I hope you are enjoying your vacation.
Thanks!
Quoted 7 lines · Christian Brauner
Quoted 6 lines · Farid Zakaria
Quoted 5 lines · Christian Brauner
[...]
.load = (void *)nix_load, .name = "nix", };
Quoted 9 lines
Quoted 6 lines
Quoted 2 lines
Farid, this should slot underneath your qemu demo from [4] with the program ported to
struct_ops. Feel free to take it from here.Thanks for the recent update.
Is it still "take it from here" or was this left-over from the previous series.Leftover from the previous series. :) Sorry.
No problem -- just checking.
Quoted 12 lines
Quoted 2 lines
I think you've done the majority of the work here with the validation of the few selftests and mentioning the gap for shebangs.
It was a nice joint effort imo. I think this is in general an interesting idea. I'm also working on some glibc loader patches. One of the patches in this series allows for "transparent binary execution" if the loader supports it.
In this mode you can pass
AT_EXECFDto an interpreter and don't change the command line. An exec like this is indistinguishable from a "native" exec.
This sounds super interesting (orthogonal to binfmt_misc and BPF work right?) but a neat feature nonetheless. I wonder if this makes it easier for tools like perf to attribute the correct binary or they have already handled interpreters in the cmdline well enough.
Quoted 5 lines
Quoted 5 lines
Please let me know what you would like me to do next. I just tested reviewing the series with b4 + AI -- pretty cool. Was a little clunky to get it to work but overall a good experience. (I need to tinker with it a little for NixOS vim setup etc..)
Quoted 9 lines
Quoted 3 lines
I shared this patch series at my workplace as well.
I think there is some interest in the work.
(If you are curious as to why, I can elaborate on that as well).Sure, happy to hear other use-cases. I have a plan to make it possible to pre-open a set of interpreters (pin them essentially) when registering the handler in
binfmt_miscand then bpf would be able to select from a set of pre-opened interpreters but that's for the future.
This is assuming that in prior calls to the BPF it returned the path string to be pinned?
As for the use case, we use buck2 --
a build system similar to Google's Bazel and does many things in spirit to Nix by leveraging RUN_PATH to create links to the shared-libraries.
We have customized our interpreter however the lack of $ORIGIN means that we've had to maintain a single glibc versioning across our machines as a platform since glibc has tight coupling between the loader and the libc.
This has been a pain point for upgrading. I think the ability for the loader to now be relative to $ORIGIN meanst hat each binary could diverge glibc/ld.so and not affect the rest of the machines.
tl;dr; ld.so from $ORIGIN itself is not only useful but since it's intimately tied to glibc, it allows for more flexibililty across our builds (very similar to NixOS in spirit).
Quoted 3 lines
Quoted 1 line
I hope you are enjoying your vacation.
Thanks!
Quoted 65 lines · Farid Zakaria
Quoted 7 lines · Christian Brauner
Quoted 6 lines · Farid Zakaria
Quoted 5 lines · Christian Brauner
[...]
.load = (void *)nix_load, .name = "nix", };Quoted 9 lines
Quoted 6 lines
Quoted 2 lines
Farid, this should slot underneath your qemu demo from [4] with the program ported to
struct_ops. Feel free to take it from here.Thanks for the recent update.
Is it still "take it from here" or was this left-over from the previous series.Leftover from the previous series. :) Sorry.
No problem -- just checking.
Quoted 12 lines
Quoted 2 lines
I think you've done the majority of the work here with the validation of the few selftests and mentioning the gap for shebangs.
It was a nice joint effort imo. I think this is in general an interesting idea. I'm also working on some glibc loader patches. One of the patches in this series allows for "transparent binary execution" if the loader supports it.
In this mode you can pass
AT_EXECFDto an interpreter and don't change the command line. An exec like this is indistinguishable from a "native" exec.This sounds super interesting (orthogonal to
binfmt_miscand BPF work right?) but a neat feature nonetheless. I wonder if this makes it easier for tools like perf to attribute the correct binary or they have already handled interpreters in the cmdline well enough.Quoted 5 lines
Quoted 5 lines
Please let me know what you would like me to do next. I just tested reviewing the series with b4 + AI -- pretty cool. Was a little clunky to get it to work but overall a good experience. (I need to tinker with it a little for NixOS vim setup etc..)
Quoted 9 lines
Quoted 3 lines
I shared this patch series at my workplace as well.
I think there is some interest in the work.
(If you are curious as to why, I can elaborate on that as well).Sure, happy to hear other use-cases. I have a plan to make it possible to pre-open a set of interpreters (pin them essentially) when registering the handler in
binfmt_miscand then bpf would be able to select from a set of pre-opened interpreters but that's for the future.This is assuming that in prior calls to the BPF it returned the path string to be pinned?
As for the use case, we use buck2 --
a build system similar to Google's Bazel and does many things in spirit to Nix by leveragingRUN_PATHto create links to the shared-libraries.We have customized our interpreter however the lack of $ORIGIN means that we've had to maintain a single glibc versioning across our machines as a platform since glibc has tight coupling between the loader and the libc.
Quoted 11 lines
This has been a pain point for upgrading. I think the ability for the loader to now be relative to $ORIGIN meanst hat each binary could diverge glibc/ld.so and not affect the rest of the machines.
tl;dr; ld.so from $ORIGIN itself is not only useful but since it's intimately tied to glibc, it allows for more flexibililty across our builds (very similar to NixOS in spirit).
Quoted 3 lines
Quoted 1 line
I hope you are enjoying your vacation.
Thanks!
Ah one more thing!
What's next for this patch? Do we wait for BPF maintainers to comment? Should I continue to add Reviewed-By trailers to the other patches? (I have limited knowledge on some of the mutex stuff but the agent review in b4 was helpful in understanding it enough to give a review.)
Sorry if it's obvious. I've never contributed to a patch this far along or substantial to the point of having to understand the merging/acceptance process in Linux.
Christian Brauner
maintainerQuoted 1 line
Should I continue to add Reviewed-By trailers to the other patches?
Review them, please where you can.
Quoted 6 lines
(I have limited knowledge on some of the mutex stuff but the agent review in b4 was helpful in understanding it enough to give a review.)
Sorry if it's obvious. I've never contributed to a patch this far along or substantial to the point of having to understand the merging/acceptance process in Linux.
I plan on getting this into -next in the near future.
Christian Brauner
maintainerQuoted 9 lines
Quoted 4 lines
In this mode you can pass
AT_EXECFDto an interpreter and don't change the command line. An exec like this is indistinguishable from a "native" exec.This sounds super interesting (orthogonal to
binfmt_miscand BPF work right?) but a neat feature nonetheless. I wonder if this makes it easier for tools like perf to attribute the correct binary or they have already handled interpreters in the cmdline well enough.
If you do gdb -p on a process that went through binfmt_misc it will load libc symbols by default. With transparent mode it will look exactly like a native exeuction and gdb will just work. IOW, if you have a loader that knows to consume a binary just from AT_EXECFD and honors AT_FLAG_PRESERVE_ARGV (the extension I have patches for) everything looks exactly like a native execution (ceteris paribus).
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Please let me know what you would like me to do next. I just tested reviewing the series with b4 + AI -- pretty cool. Was a little clunky to get it to work but overall a good experience. (I need to tinker with it a little for NixOS vim setup etc..)
I shared this patch series at my workplace as well.
I think there is some interest in the work.
(If you are curious as to why, I can elaborate on that as well).
Quoted 8 lines
Quoted 5 lines
Sure, happy to hear other use-cases. I have a plan to make it possible to pre-open a set of interpreters (pin them essentially) when registering the handler in
binfmt_miscand then bpf would be able to select from a set of pre-opened interpreters but that's for the future.This is assuming that in prior calls to the BPF it returned the path string to be pinned?
It's easier. We just need to extend "register" to add interpreters to an entry.
Quoted 4 lines · Christian Brauner
Quoted 1 line
Should I continue to add Reviewed-By trailers to the other patches?
Review them, please where you can.
Quoted 8 lines
Quoted 6 lines
(I have limited knowledge on some of the mutex stuff but the agent review in b4 was helpful in understanding it enough to give a review.)
Sorry if it's obvious. I've never contributed to a patch this far along or substantial to the point of having to understand the merging/acceptance process in Linux.
I plan on getting this into -next in the near future.
Sorry I have not reviewed them yet.
I got a little distracted preparing myself for some talks at DEFCON34 for the Nix village [1]
I plan to take a look at the remaining patches and add my Reviewed-By trailers to them in the next few days.
I also just saw the transparent execution patch and will review it as well (as much as I can).
One of the talks I plan on giving at DEFCON34 is about the idea to support relocatable binaries in Nix. I did a short self-summary of it if you are interested in reading it [2].
[1] https://nix.vegas
[2] https://fzakaria.com/2026/07/20/linux-kernel-will-support-origin-sort-of