Skip to contentSkip to conversation

binfmt_misc: transparent interpreters and PT_INTERP loader substitution

PATCH In review Christian Brauner 3 participants 41 messages Jul 21 – Jul 23

Subsystems (6)
lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

v2 cover binfmt_misc: transparent interpreters and PT_INTERP loader substitution

binfmt_misc has exactly one execution model where the registered interpreter becomes the executed program and the matched binary is handed to it as an argument. For wine or qemu-user that is the point. For a per-binary loader it is backwards. The interpreter is an implementation detail of running the binary, yet it owns the entire process identity:

- argv[0] and /proc/pid/cmdline show the interpreter invocation, not what the caller executed.

- /proc/self/exe names the interpreter. Relocatable programs commonly locate themselves through it and find the dynamic linker instead.

- A binary passed to execveat() as an inaccessible O_CLOEXEC fd cannot run at all as the interpreter has no path to open it by.

- gdb cross-validates AT_ENTRY/AT_PHDR against the exe file and discards the load displacement on mismatch leaving PIE symbols unrelocated.

This series adds two dispatch modes that close the gap from opposite ends:

(1) transparent dispatch

Registered with the 'T' flag or chosen per exec with BPF_BINPRM_TRANSPARENT. The binary is sent to the interpreter through AT_EXECFD, the argument vector stays exactly as the caller built it, and the kernel labels mm->exe_file and comm with the binary. A new AT_FLAGS_TRANSPARENT_INTERP aux vector bit is raised indicating that nothing was spliced, argv belongs to the program, and to load it from the descriptor.

The interpreter keeps control of mapping the binary, so the mode covers foreign architectures and non-ELF payloads.

The exe label is not a new privilege. It names precisely the file the caller passed to execve(), not a file of the process's choosing. That file is permission-checked, write-denied while the process runs and recorded by audit. Credential derivation does not change exactly as today.

(2) loader substitution

The kernel executes the matched binary natively as the main image and substitutes the registered interpreter for the binary's PT_INTERP. binfmt_misc functions as a PT_INTERP override. There is no contract and no identity to reconstruct. So a stock dynamic loader works unchanged. Hence, 'L' is for native-arch ELF with PT_INTERP.

The two modes compose. A bpf handler reads the ELF header from bprm->buf and grades per binary, picking 'L' where it applies and 'T' or classic dispatch for the rest. If userspace control over relocation is wanted 'T' is the way to go.

---
Changes in v2:
- Move "exec: do not act on a stale execfd request without an executable" into vfs.fixes.

- support 'L' for binfmt_elf_fdpic
- Share the substitution between the two ELF loaders instead of
open-coding it twice.
- Reject a relative interpreter path when registering an 'L' or 'C'
entry without 'F'.
- Map -ENOEXEC from the loader-substitution interpreter open to -EACCES.
- Keep the write denial on bprm->executable unconditionally until
begin_new_exec() hands the file over.
- Reject a staged interpreter argument for a transparent dispatch
instead of silently discarding it.
- WARN_ON_ONCE() a loader staged by an earlier format in
load_misc_binary().
- Fix various selftests issues.
- Link to v1: https://patch.msgid.link/20260720-work-bpf-binfmt_misc-ptinterp-v1-0-ddb76c9a508e@kernel.org

---
Christian Brauner (21):
binfmt_misc: require an absolute interpreter path with 'C' docs, binfmt_misc: keep general usage out of the handler sections
binfmt_misc: table-drive the register string flags
binfmt_misc: normalize the per-exec invocation flags
binfmt_misc: split out entry_open_interpreter() and build_interp_argv()
exec: release the replaced file with do_close_execat() selftests/exec: convert the binfmt_misc bpf test to the kselftest harness
exec: add AT_FLAGS_TRANSPARENT_INTERP
exec: label mm->exe_file with the binary for a transparent dispatch
binfmt_misc: add transparent interpreter dispatch
binfmt_misc: add a static transparent flag 'T'
binfmt_misc: let a bpf handler run the interpreter transparently selftests/exec: test the transparent binfmt_misc mode
binfmt_misc: document the transparent identity contract
exec: carry a PT_INTERP substitute in struct linux_binprm
binfmt_elf: consume a stashed PT_INTERP substitute
binfmt_elf_fdpic: consume a stashed PT_INTERP substitute
binfmt_misc: add the 'L' loader substitution flag
binfmt_misc: let a bpf handler request loader substitution selftests/exec: test binfmt_misc loader substitution
binfmt_misc: document loader substitution

 Documentation/admin-guide/binfmt-misc.rst          | 177 ++++++++--
 fs/binfmt_elf.c                                    |  10 +-
 fs/binfmt_elf_fdpic.c                              |  11 +-
 fs/binfmt_misc.c                                   | 314 +++++++++++------
 fs/binfmt_misc_bpf.c                               |  22 +-
 fs/exec.c                                          |  84 ++++-
 include/linux/binfmt_misc.h                        |   8 +
 include/linux/binfmts.h                            |  25 ++
 include/uapi/linux/binfmts.h                       |   7 +
 tools/testing/selftests/exec/.gitignore            |   5 +
 tools/testing/selftests/exec/Makefile              |  27 +-
 .../testing/selftests/exec/binfmt_loader_payload.c | 167 ++++++++++
 tools/testing/selftests/exec/binfmt_misc_bpf.c     | 342 ++++++++++---------
 tools/testing/selftests/exec/binfmt_misc_common.h  | 205 ++++++++++++
 tools/testing/selftests/exec/binfmt_misc_loader.c  | 371 +++++++++++++++++++++
 .../selftests/exec/binfmt_misc_transparent.c       | 108 ++++++
 .../selftests/exec/binfmt_transparent_interp.c     | 130 ++++++++
 tools/testing/selftests/exec/loader.bpf.c          |  56 ++++
 tools/testing/selftests/exec/transparent.bpf.c     |  57 ++++
 19 files changed, 1823 insertions(+), 303 deletions(-)

---
base-commit: 6cea93ff6fe97df34b63fe94487473e16c73b74b
change-id: 20260719-work-bpf-binfmt_misc-ptinterp-e6ee99ff6ba8

author maintainer
#1 lore raw

PATCH v2 1/21 binfmt_misc: require an absolute interpreter path with 'C'

A 'C' entry computes the credentials from the matched binary instead of from the interpreter. So a set*id binary hands its credentials to whatever the entry names as its interpreter.

Without 'F' that interpreter is not opened until the exec happens and open_exec() resolves the path relative to the current working directory.

The working directory at that point belongs to whoever runs the binary not to whoever registered the entry. So :x:M::\x7fELF::interp:C lets every user who execs a matching set*id binary from a directory they control run their own interp with that binary's credentials.

A relative interpreter has no sensible use here to begin with. The registering task cannot know what the working directory will be. Make the register string reject the combination at registration time.

This does refuse register strings that used to be accepted. The 'F' flag covers the case where the interpreter really is meant to be resolved in the registrant's context, and it resolves it once, at registration.

---
 Documentation/admin-guide/binfmt-misc.rst | 4 ++++
 fs/binfmt_misc.c                          | 6 ++++++
 2 files changed, 10 insertions(+)
Documentation/admin-guide/binfmt-misc.rst +4 -0
index 7f42abf9cfba..ce94c8c36534 100644
@@ -98,6 +98,10 @@ There are some restrictions:
  - the magic must reside in the first 128 bytes of the file, i.e.
    offset+size(magic) has to be less than 128
  - the interpreter string may not exceed 127 characters
+ - an interpreter used with ``C`` but without ``F`` has to be named by an
+   absolute path. It is opened when the binary is executed, so a relative
+   one would be resolved against the working directory of whoever runs
+   the binary
 
 
 bpf-backed handlers
fs/binfmt_misc.c +6 -0
index c06cea00a6d6..bfe30fe532ba 100644
@@ -683,6 +683,12 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 			 MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_FILE)))
 		return ERR_PTR(-EINVAL);
 
+	/* Non-F opens the interp at exec against the caller's cwd; require absolute. */
+	if ((e->flags & MISC_FMT_CREDENTIALS) &&
+	    !(e->flags & MISC_FMT_OPEN_FILE) &&
+	    e->interpreter[0] != '/')
+		return ERR_PTR(-EINVAL);
+
 	return no_free_ptr(e);
 }
 
Signature · 1 line
2.53.0
author maintainer
#3 lore raw

PATCH v2 2/21 docs, binfmt_misc: keep general usage out of the handler sections

In reply to Christian Brauner

The general usage trails the bpf-backed handlers section and therefore reads as part of it. It predates that section and applies to binfmt_misc as a whole.

Move it back up so the handler section ends where the file does. Upcoming sections describing the transparent and loader dispatch modes append after it without swallowing the general prose again.

Pure text move, no content changes.

---
 Documentation/admin-guide/binfmt-misc.rst | 79 ++++++++++++++++---------------
 1 file changed, 40 insertions(+), 39 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +40 -39
index ce94c8c36534..d689f21858b2 100644
@@ -104,6 +104,46 @@ There are some restrictions:
    the 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
+``/etc/fstab`` so it auto mounts on boot.
+
+You may want to add the binary formats in one of your ``/etc/rc`` scripts during
+boot-up. Read the manual of your init program to figure out how to do this
+right.
+
+Think about the order of adding entries! Later added entries are matched first!
+
+
+A few examples (assumed you are in ``/proc/sys/fs/binfmt_misc``):
+
+- enable support for em86 (like binfmt_em86, for Alpha AXP only)::
+
+    echo ':i386:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
+    echo ':i486:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x06:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
+
+- enable support for packed DOS applications (pre-configured dosemu hdimages)::
+
+    echo ':DEXE:M::\x0eDEX::/usr/bin/dosexec:' > register
+
+- enable support for Windows executables using wine::
+
+    echo ':DOSWin:M::MZ::/usr/local/bin/wine:' > register
+
+For java support see Documentation/admin-guide/java.rst
+
+
+You can enable/disable binfmt_misc or one binary type by echoing 0 (to disable)
+or 1 (to enable) to ``/proc/sys/fs/binfmt_misc/status`` or
+``/proc/.../the_name``.
+Catting the file tells you the current status of ``binfmt_misc/the_entry``.
+
+You can remove one entry or all entries by echoing -1 to ``/proc/.../the_name``
+or ``/proc/sys/fs/binfmt_misc/status``. A single entry can also be removed
+by simply unlinking (``rm``) ``/proc/.../the_name``.
+
+
 bpf-backed handlers
 -------------------
 
@@ -161,45 +201,6 @@ 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.
 
-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
-``/etc/fstab`` so it auto mounts on boot.
-
-You may want to add the binary formats in one of your ``/etc/rc`` scripts during
-boot-up. Read the manual of your init program to figure out how to do this
-right.
-
-Think about the order of adding entries! Later added entries are matched first!
-
-
-A few examples (assumed you are in ``/proc/sys/fs/binfmt_misc``):
-
-- enable support for em86 (like binfmt_em86, for Alpha AXP only)::
-
-    echo ':i386:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
-    echo ':i486:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x06:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
-
-- enable support for packed DOS applications (pre-configured dosemu hdimages)::
-
-    echo ':DEXE:M::\x0eDEX::/usr/bin/dosexec:' > register
-
-- enable support for Windows executables using wine::
-
-    echo ':DOSWin:M::MZ::/usr/local/bin/wine:' > register
-
-For java support see Documentation/admin-guide/java.rst
-
-
-You can enable/disable binfmt_misc or one binary type by echoing 0 (to disable)
-or 1 (to enable) to ``/proc/sys/fs/binfmt_misc/status`` or
-``/proc/.../the_name``.
-Catting the file tells you the current status of ``binfmt_misc/the_entry``.
-
-You can remove one entry or all entries by echoing -1 to ``/proc/.../the_name``
-or ``/proc/sys/fs/binfmt_misc/status``. A single entry can also be removed
-by simply unlinking (``rm``) ``/proc/.../the_name``.
-
 
 Hints
 -----
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

PATCH v2 3/21 binfmt_misc: table-drive the register string flags

In reply to Christian Brauner

Every flag character of the register string is spelled out three
times: in the parser, in the entry's /proc output and in the delimiter blacklist that keeps a flag character from sending the flag scan off the end of the buffer. The three lists have to agree, and each new flag has to be added to all of them.

Describe a flag once - character, entry flag, implied flags and a description for the registration debug output - and drive all three from the table.

While at it, express the "a 'B' entry carries no flags" check as what it is, an empty flags field, rather than as a fourth list of every flag character. Equivalent: the check runs right after check_special_flags(), which advances past exactly the flag characters it consumed and sets exactly their flags.

No functional change.

---
 fs/binfmt_misc.c | 92 ++++++++++++++++++++++++++++++++------------------------
 1 file changed, 52 insertions(+), 40 deletions(-)
fs/binfmt_misc.c +52 -40
index bfe30fe532ba..c0a3b42a38f7 100644
@@ -10,6 +10,7 @@
 
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 
+#include <linux/array_size.h>
 #include <linux/binfmt_misc.h>
 #include <linux/binfmts.h>
 #include <linux/bitops.h>
@@ -51,6 +52,36 @@ enum binfmt_misc_entry_flags {
 	MISC_FMT_OPEN_FILE	= (1U << 28),
 };
 
+/**
+ * struct binfmt_misc_flag - a flag character of the register string
+ * @c: the character userspace writes and reads back
+ * @flag: the entry flag it sets
+ * @implies: entry flags it turns on in addition
+ * @desc: what it does, for the registration debug output
+ */
+struct binfmt_misc_flag {
+	char		c;
+	unsigned long	flag;
+	unsigned long	implies;
+	const char	*desc;
+};
+
+static const struct binfmt_misc_flag misc_flags[] = {
+	{ 'P', MISC_FMT_PRESERVE_ARGV0,	0,			"preserve argv0"		},
+	{ 'O', MISC_FMT_OPEN_BINARY,	0,			"open binary"			},
+	{ 'C', MISC_FMT_CREDENTIALS,	MISC_FMT_OPEN_BINARY,	"credentials from the binary"	},
+	{ 'F', MISC_FMT_OPEN_FILE,	0,			"open interpreter file now"	},
+};
+
+/* Look up a flag character, NULL if @c is not one. */
+static const struct binfmt_misc_flag *misc_flag_by_char(const char c)
+{
+	for (int i = 0; i < ARRAY_SIZE(misc_flags); i++)
+		if (misc_flags[i].c == c)
+			return &misc_flags[i];
+	return NULL;
+}
+
 struct binfmt_misc_entry {
 	struct hlist_node node;
 	unsigned long flags;		/* type, status, etc. */
@@ -424,30 +455,16 @@ static char *scanarg(char *s, char del)
 	return s;
 }
 
+/* Parse the 'flags' field, stopping at the first character that is not one. */
 static char *check_special_flags(char *p, struct binfmt_misc_entry *e)
 {
 	for (;; p++) {
-		switch (*p) {
-		case 'P':
-			pr_debug("register: flag: P (preserve argv0)\n");
-			e->flags |= MISC_FMT_PRESERVE_ARGV0;
-			break;
-		case 'O':
-			pr_debug("register: flag: O (open binary)\n");
-			e->flags |= MISC_FMT_OPEN_BINARY;
-			break;
-		case 'C':
-			pr_debug("register: flag: C (preserve creds)\n");
-			/* C implies O */
-			e->flags |= MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY;
-			break;
-		case 'F':
-			pr_debug("register: flag: F: open interpreter file now\n");
-			e->flags |= MISC_FMT_OPEN_FILE;
-			break;
-		default:
+		const struct binfmt_misc_flag *f = misc_flag_by_char(*p);
+
+		if (!f)
 			return p;
-		}
+		pr_debug("register: flag: %c (%s)\n", f->c, f->desc);
+		e->flags |= f->flag | f->implies;
 	}
 }
 
@@ -570,7 +587,7 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 					      size_t count)
 {
 	struct binfmt_misc_entry *e __free(kfree) = NULL;
-	char *buf, *p;
+	char *buf, *p, *flags;
 	char del;
 
 	pr_debug("register: received %zu bytes\n", count);
@@ -595,7 +612,7 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 	pr_debug("register: delim: %#x {%c}\n", del, del);
 
 	/* A flag-char delimiter runs the flag scan off the buffer. */
-	if (del == 'P' || del == 'O' || del == 'C' || del == 'F')
+	if (misc_flag_by_char(del))
 		return ERR_PTR(-EINVAL);
 
 	/* Pad the buffer with the delim to simplify parsing below. */
@@ -666,21 +683,21 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 	}
 
 	/* Parse the 'flags' field. */
+	flags = p;
 	p = check_special_flags(p, e);
-	if (*p == '\n')
-		p++;
-	if (p != buf + count)
-		return ERR_PTR(-EINVAL);
 
 	/*
 	 * A bpf handler decides the invocation flags per exec with
-	 * bpf_binprm_set_flags() rather than fixing them at registration, so a
-	 * 'B' entry carries no flags: 'P', 'C' and 'O' become per-exec choices
-	 * and 'F' (pre-open a fixed interpreter) is meaningless for it.
+	 * bpf_binprm_set_flags() rather than fixing them at registration, and
+	 * 'F' (pre-open a fixed interpreter) is meaningless for it, so a 'B'
+	 * entry's flags field has to be empty.
 	 */
-	if (test_bit(MISC_FMT_BPF_BIT, &e->flags) &&
-	    (e->flags & (MISC_FMT_PRESERVE_ARGV0 | MISC_FMT_OPEN_BINARY |
-			 MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_FILE)))
+	if (test_bit(MISC_FMT_BPF_BIT, &e->flags) && p != flags)
+		return ERR_PTR(-EINVAL);
+
+	if (*p == '\n')
+		p++;
+	if (p != buf + count)
 		return ERR_PTR(-EINVAL);
 
 	/* Non-F opens the interp at exec against the caller's cwd; require absolute. */
@@ -749,14 +766,9 @@ static int bm_entry_show(struct seq_file *m, void *unused)
 
 	/* print the special flags */
 	seq_puts(m, "flags: ");
-	if (e->flags & MISC_FMT_PRESERVE_ARGV0)
-		seq_putc(m, 'P');
-	if (e->flags & MISC_FMT_OPEN_BINARY)
-		seq_putc(m, 'O');
-	if (e->flags & MISC_FMT_CREDENTIALS)
-		seq_putc(m, 'C');
-	if (e->flags & MISC_FMT_OPEN_FILE)
-		seq_putc(m, 'F');
+	for (int i = 0; i < ARRAY_SIZE(misc_flags); i++)
+		if (e->flags & misc_flags[i].flag)
+			seq_putc(m, misc_flags[i].c);
 	seq_putc(m, '\n');
 
 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
Signature · 1 line
2.53.0
author maintainer
#7 lore raw

PATCH v2 4/21 binfmt_misc: normalize the per-exec invocation flags

In reply to Christian Brauner

A static entry fixes its invocation flags at registration. A 'B' entry's load program picks them per exec. Since load_misc_binary() branches on which kind of entry matched and then applies the two flag sets side by side every flag is handled twice and each new one has to be added to both arms.

Translate the 'B' flags into the entry flags they mirror and let the dispatch act on a single set of flags. The boolean the two arms communicated 'P' can be removed.

No functional change.

---
 fs/binfmt_misc.c | 62 +++++++++++++++++++++++++++++++++++---------------------
 1 file changed, 39 insertions(+), 23 deletions(-)
fs/binfmt_misc.c +39 -23
index c0a3b42a38f7..dc2ee012da10 100644
@@ -319,6 +319,40 @@ static const char *entry_select_interpreter(const struct binfmt_misc_entry *e,
 	return ERR_PTR(retval);
 }
 
+/**
+ * entry_invocation_flags - the invocation flags in effect for this exec
+ * @e: matched binary type handler
+ * @bprm: binary that is being executed
+ *
+ * A static entry fixes its flags at registration, a 'B' entry's load program
+ * picks them per exec with bpf_binprm_set_flags(). Translate the latter into
+ * the former, implications included, so the dispatch has one set to act on.
+ *
+ * Return: the invocation flags for this exec
+ */
+static unsigned long entry_invocation_flags(const struct binfmt_misc_entry *e,
+					    struct linux_binprm *bprm)
+{
+	unsigned long flags = 0;
+	u64 bpf_flags;
+
+	if (!test_bit(MISC_FMT_BPF_BIT, &e->flags))
+		return e->flags;
+
+	bpf_flags = bprm->bpf_flags;
+	/* Clear so they can't accumulate into a nested interpreter level. */
+	bprm->bpf_flags = 0;
+
+	if (bpf_flags & BPF_BINPRM_PRESERVE_ARGV0)
+		flags |= MISC_FMT_PRESERVE_ARGV0;
+	if (bpf_flags & BPF_BINPRM_EXECFD)
+		flags |= MISC_FMT_OPEN_BINARY;
+	if (bpf_flags & BPF_BINPRM_CREDENTIALS)
+		flags |= MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY;
+
+	return flags;
+}
+
 /*
  * the loader itself
  */
@@ -328,7 +362,7 @@ static int load_misc_binary(struct linux_binprm *bprm)
 	const char *interpreter;
 	struct file *interp_file;
 	struct binfmt_misc *misc;
-	bool preserve_argv0, want_execfd, want_creds;
+	unsigned long flags;
 	int retval;
 
 	misc = current_binfmt_misc();
@@ -347,28 +381,10 @@ static int load_misc_binary(struct linux_binprm *bprm)
 	if (IS_ERR(interpreter))
 		return PTR_ERR(interpreter);
 
-	/*
-	 * The invocation flags are fixed at registration for a static handler
-	 * and chosen per exec by the load program, via bpf_binprm_set_flags(),
-	 * for a bpf one.
-	 */
-	if (test_bit(MISC_FMT_BPF_BIT, &fmt->flags)) {
-		u64 f = bprm->bpf_flags;
-
-		/* Clear so it can't accumulate into a nested interpreter level. */
-		bprm->bpf_flags = 0;
-
-		preserve_argv0 = f & BPF_BINPRM_PRESERVE_ARGV0;
-		want_creds = f & BPF_BINPRM_CREDENTIALS;
-		want_execfd = f & (BPF_BINPRM_CREDENTIALS | BPF_BINPRM_EXECFD);
-	} else {
-		preserve_argv0 = fmt->flags & MISC_FMT_PRESERVE_ARGV0;
-		want_creds = fmt->flags & MISC_FMT_CREDENTIALS;
-		want_execfd = fmt->flags & MISC_FMT_OPEN_BINARY;
-	}
+	flags = entry_invocation_flags(fmt, bprm);
 
 	/* The entry's own choice - not one accumulated from an earlier level. */
-	if (preserve_argv0) {
+	if (flags & MISC_FMT_PRESERVE_ARGV0) {
 		bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0;
 	} else {
 		retval = remove_arg_zero(bprm);
@@ -424,9 +440,9 @@ static int load_misc_binary(struct linux_binprm *bprm)
 		return PTR_ERR(interp_file);
 
 	bprm->interpreter = interp_file;
-	if (want_execfd)
+	if (flags & MISC_FMT_OPEN_BINARY)
 		bprm->have_execfd = 1;
-	if (want_creds)
+	if (flags & MISC_FMT_CREDENTIALS)
 		bprm->execfd_creds = 1;
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#9 lore raw

PATCH v2 5/21 binfmt_misc: split out entry_open_interpreter() and build_interp_argv()

In reply to Christian Brauner

Opening the interpreter is a property of the matched entry: an 'F' entry hands out a clone of the file it pre-opened at registration time, any other entry opens the selected path. Give that its own helper instead of an if/else in the middle of load_misc_binary(), and let it fail early rather than carrying an ERR_PTR through the successful branch.

Building the interpreter's argument vector is the bulk of what remains and the one part of load_misc_binary() that is specific to the classic dispatch. Move it into its own helper too, so the dispatch reads as what it is: pick a handler, pick an interpreter, build the invocation, open it.

No functional change.

---
 fs/binfmt_misc.c | 110 ++++++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 76 insertions(+), 34 deletions(-)
fs/binfmt_misc.c +76 -34
index dc2ee012da10..304109a5091f 100644
@@ -353,35 +353,52 @@ static unsigned long entry_invocation_flags(const struct binfmt_misc_entry *e,
 	return flags;
 }
 
-/*
- * the loader itself
+/**
+ * entry_open_interpreter - open the entry's interpreter for execution
+ * @e: matched binary type handler
+ * @interpreter: the interpreter selected for this exec
+ *
+ * An 'F' entry hands out a clone of the file it pre-opened at registration,
+ * any other entry opens the selected path.
+ *
+ * Return: the opened interpreter on success, an ERR_PTR on failure
  */
-static int load_misc_binary(struct linux_binprm *bprm)
+static struct file *entry_open_interpreter(const struct binfmt_misc_entry *e,
+					   const char *interpreter)
 {
-	struct binfmt_misc_entry *fmt __free(put_binfmt_handler) = NULL;
-	const char *interpreter;
-	struct file *interp_file;
-	struct binfmt_misc *misc;
-	unsigned long flags;
+	struct file *interp_file __free(fput) = NULL;
 	int retval;
 
-	misc = current_binfmt_misc();
-	if (!READ_ONCE(misc->enabled))
-		return -ENOEXEC;
+	if (!(e->flags & MISC_FMT_OPEN_FILE))
+		return open_exec(interpreter);
 
-	fmt = get_binfmt_handler(misc, bprm);
-	if (!fmt)
-		return -ENOEXEC;
+	interp_file = file_clone_open(e->interp_file);
+	if (IS_ERR(interp_file))
+		return interp_file;
 
-	/* Need to be able to load the file after exec */
-	if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
-		return -ENOENT;
+	retval = exe_file_deny_write_access(interp_file);
+	if (retval)
+		return ERR_PTR(retval);
 
-	interpreter = entry_select_interpreter(fmt, bprm);
-	if (IS_ERR(interpreter))
-		return PTR_ERR(interpreter);
+	return no_free_ptr(interp_file);
+}
 
-	flags = entry_invocation_flags(fmt, bprm);
+/**
+ * build_interp_argv - splice the interpreter invocation into the argv
+ * @bprm: binary that is being executed
+ * @interpreter: the interpreter selected for this exec
+ * @flags: invocation flags in effect for this exec
+ *
+ * The interpreter becomes argv[0] and the binary its last argument, with an
+ * optional staged argument in between. The caller's argv[0] is dropped
+ * unless 'P' keeps it.
+ *
+ * Return: 0 on success, a negative error code on failure
+ */
+static int build_interp_argv(struct linux_binprm *bprm, const char *interpreter,
+			     unsigned long flags)
+{
+	int retval;
 
 	/* The entry's own choice - not one accumulated from an earlier level. */
 	if (flags & MISC_FMT_PRESERVE_ARGV0) {
@@ -418,24 +435,49 @@ static int load_misc_binary(struct linux_binprm *bprm)
 		return retval;
 	bprm->argc++;
 
+	return 0;
+}
+
+/*
+ * the loader itself
+ */
+static int load_misc_binary(struct linux_binprm *bprm)
+{
+	struct binfmt_misc_entry *fmt __free(put_binfmt_handler) = NULL;
+	const char *interpreter;
+	struct file *interp_file;
+	struct binfmt_misc *misc;
+	unsigned long flags;
+	int retval;
+
+	misc = current_binfmt_misc();
+	if (!READ_ONCE(misc->enabled))
+		return -ENOEXEC;
+
+	fmt = get_binfmt_handler(misc, bprm);
+	if (!fmt)
+		return -ENOEXEC;
+
+	/* Need to be able to load the file after exec */
+	if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
+		return -ENOENT;
+
+	interpreter = entry_select_interpreter(fmt, bprm);
+	if (IS_ERR(interpreter))
+		return PTR_ERR(interpreter);
+
+	flags = entry_invocation_flags(fmt, bprm);
+
+	retval = build_interp_argv(bprm, interpreter, flags);
+	if (retval)
+		return retval;
+
 	/* Update interp in case binfmt_script needs it. */
 	retval = bprm_change_interp(interpreter, bprm);
 	if (retval < 0)
 		return retval;
 
-	if (fmt->flags & MISC_FMT_OPEN_FILE) {
-		interp_file = file_clone_open(fmt->interp_file);
-		if (!IS_ERR(interp_file)) {
-			int err = exe_file_deny_write_access(interp_file);
-
-			if (err) {
-				fput(interp_file);
-				interp_file = ERR_PTR(err);
-			}
-		}
-	} else {
-		interp_file = open_exec(interpreter);
-	}
+	interp_file = entry_open_interpreter(fmt, interpreter);
 	if (IS_ERR(interp_file))
 		return PTR_ERR(interp_file);
 
Signature · 1 line
2.53.0
author maintainer
#11 lore raw

PATCH v2 6/21 exec: release the replaced file with do_close_execat()

In reply to Christian Brauner

When the format search stages an interpreter exec_binprm() swaps it in and releases the file it replaces. Dropping the write denial the open took is done manually ahead of both release paths. The one path that keeps the file silently relies on it not being called.

Let's just use do_close_execat() on the two paths that release the file and drop the denial explicitly on the one that does not.

No functional change.

---
 fs/exec.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
fs/exec.c +6 -4
index 41e1684d999c..061e0f9fb4ef 100644
@@ -1735,15 +1735,17 @@ static int exec_binprm(struct linux_binprm *bprm)
 		bprm->file = bprm->interpreter;
 		bprm->interpreter = NULL;
 
-		exe_file_allow_write_access(exec);
 		if (unlikely(bprm->have_execfd)) {
 			if (bprm->executable) {
-				fput(exec);
+				do_close_execat(exec);
 				return -ENOEXEC;
 			}
+			/* Only the reference is kept, for AT_EXECFD. */
+			exe_file_allow_write_access(exec);
 			bprm->executable = exec;
-		} else
-			fput(exec);
+		} else {
+			do_close_execat(exec);
+		}
 	}
 
 	audit_bprm(bprm);
Signature · 1 line
2.53.0
author maintainer
#13 lore raw

PATCH v2 7/21 selftests/exec: convert the binfmt_misc bpf test to the kselftest harness

In reply to Christian Brauner

The test reports its own pass and fail lines, returns a bare 4 for KSFT_SKIP and runs both cases in one process, so a failure in the first takes the second with it. It also open-codes the register, unregister, file-copy and mount helpers that the tests for the upcoming transparent and loader dispatch modes need again.

Convert it to the kselftest harness: a fixture for the common setup and teardown, one TEST_F per case so each is reported and isolated separately, and SKIP() for the root, BTF and binfmt_misc preconditions. Move the helpers to a shared header on the way, with the register helper preserving the write's errno so a caller can tell a rejected flag combination (EINVAL) from a kernel that does not know the flag at all. The synthetic ELF header gains an e_machine argument and uses the elf.h constants instead of open-coded numbers.

No change in what is tested.

---
 tools/testing/selftests/exec/Makefile             |   6 +-
 tools/testing/selftests/exec/binfmt_misc_bpf.c    | 195 ++++++++--------------
 tools/testing/selftests/exec/binfmt_misc_common.h |  98 +++++++++++
 3 files changed, 168 insertions(+), 131 deletions(-)
tools/testing/selftests/exec/Makefile +4 -2
index ec66c1fecfc0..fb5ca59af51d 100644
@@ -44,6 +44,8 @@ endif
 EXTRA_CLEAN := $(OUTPUT)/subdir.moved $(OUTPUT)/execveat.moved $(OUTPUT)/xxxxx*	\
 	       $(OUTPUT)/S_I*.test
 
+LOCAL_HDRS += binfmt_misc_common.h
+
 include ../lib.mk
 
 CHECK_EXEC_SAMPLES := $(top_srcdir)/samples/check-exec
@@ -91,7 +93,7 @@ $(OUTPUT)/vmlinux.h:
 $(OUTPUT)/%.bpf.o: %.bpf.c $(OUTPUT)/vmlinux.h
 	$(CLANG) -g -O2 -target bpf -mcpu=v3 $(BPF_CFLAGS) $(LIBBPF_CFLAGS) -c $< -o $@
 
-$(OUTPUT)/binfmt_misc_bpf: binfmt_misc_bpf.c
+$(OUTPUT)/binfmt_misc_bpf: binfmt_misc_bpf.c binfmt_misc_common.h
 	$(CC) $(CFLAGS) $(LIBBPF_CFLAGS) $(LDFLAGS) $< $(LIBBPF_LDLIBS) -o $@
 
 $(OUTPUT)/binfmt_bpf_interp: binfmt_bpf_interp.c
@@ -102,4 +104,4 @@ $(OUTPUT)/binfmt_bpf_interp: binfmt_bpf_interp.c
 $(OUTPUT)/binfmt_bpf_app: binfmt_bpf_app.c
 	$(CC) $(CFLAGS) $(LDFLAGS) -Wl,--dynamic-linker,'$$ORIGIN/binfmt_bpf_interp' $< -o $@
 
-EXTRA_CLEAN += $(OUTPUT)/vmlinux.h $(OUTPUT)/bpf_interp.bpf.o $(OUTPUT)/nix_origin.bpf.o
+EXTRA_CLEAN += $(OUTPUT)/vmlinux.h $(OUTPUT)/*.bpf.o
tools/testing/selftests/exec/binfmt_misc_bpf.c +66 -129

262 lines not on this page · raw message

tools/testing/selftests/exec/binfmt_misc_common.h new file +98 -0

98 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#15 lore raw

PATCH v2 8/21 exec: add AT_FLAGS_TRANSPARENT_INTERP

In reply to Christian Brauner

A transparent binfmt_misc dispatch hands the binary to the interpreter through AT_EXECFD and leaves the argument vector exactly as the caller built it. The loader on the receiving end has to know which contract it got.

On the classic 'O'/'C' entries the binary's path is spliced into the argument vector and the loader consumes arguments. In transparent mode nothing was spliced and argv belongs entirely to the program. This cannot be inferred from AT_EXECFD alone. Raise a new AT_FLAGS bit following the AT_FLAGS_PRESERVE_ARGV0 precedent added for qemu-user in commit 2347961b11d4 ("binfmt_misc: pass binfmt_misc flags to the interpreter").

The bit also announces that mm->exe_file names the binary rather than the interpreter (added in the next commit). A loader that sees the bit may finish the identity polish by fixing up AT_PHDR/AT_ENTRY/AT_BASE in saved_auxv and fix the code/data markers via one uncapped PR_SET_MM_MAP once it has mapped the binary. I've got glibc patches for this as well but it's useful for any loader.

BINPRM_FLAGS_TRANSPARENT_INTERP carries the mode from binfmt_misc to the ELF loaders. Both had their own copy of the AT_FLAGS translation, so give them one bprm_at_flags() to share instead of a second copy that can drift. Nothing sets the bprm flag yet.

---
 fs/binfmt_elf.c              |  5 +----
 fs/binfmt_elf_fdpic.c        |  5 +----
 include/linux/binfmts.h      | 22 ++++++++++++++++++++++
 include/uapi/linux/binfmts.h |  7 +++++++
 4 files changed, 31 insertions(+), 8 deletions(-)
fs/binfmt_elf.c +1 -4
index 16a56b6b3f6c..be8fd437b5a3 100644
@@ -179,7 +179,6 @@ create_elf_tables(struct linux_binprm *bprm, const struct elfhdr *exec,
 	unsigned char k_rand_bytes[16];
 	int items;
 	elf_addr_t *elf_info;
-	elf_addr_t flags = 0;
 	int ei_index;
 	const struct cred *cred = current_cred();
 	struct vm_area_struct *vma;
@@ -254,9 +253,7 @@ create_elf_tables(struct linux_binprm *bprm, const struct elfhdr *exec,
 	NEW_AUX_ENT(AT_PHENT, sizeof(struct elf_phdr));
 	NEW_AUX_ENT(AT_PHNUM, exec->e_phnum);
 	NEW_AUX_ENT(AT_BASE, interp_load_addr);
-	if (bprm->interp_flags & BINPRM_FLAGS_PRESERVE_ARGV0)
-		flags |= AT_FLAGS_PRESERVE_ARGV0;
-	NEW_AUX_ENT(AT_FLAGS, flags);
+	NEW_AUX_ENT(AT_FLAGS, bprm_at_flags(bprm));
 	NEW_AUX_ENT(AT_ENTRY, e_entry);
 	NEW_AUX_ENT(AT_UID, from_kuid_munged(cred->user_ns, cred->uid));
 	NEW_AUX_ENT(AT_EUID, from_kuid_munged(cred->user_ns, cred->euid));
fs/binfmt_elf_fdpic.c +1 -4
index fe0b5c5ed2bc..0a3cdf280307 100644
@@ -509,7 +509,6 @@ static int create_elf_fdpic_tables(struct linux_binprm *bprm,
 	char *k_platform, *k_base_platform;
 	char __user *u_platform, *u_base_platform, *p;
 	int loop;
-	unsigned long flags = 0;
 	int ei_index;
 	elf_addr_t *elf_info;
 
@@ -649,9 +648,7 @@ static int create_elf_fdpic_tables(struct linux_binprm *bprm,
 	NEW_AUX_ENT(AT_PHENT,	sizeof(struct elf_phdr));
 	NEW_AUX_ENT(AT_PHNUM,	exec_params->hdr.e_phnum);
 	NEW_AUX_ENT(AT_BASE,	interp_params->elfhdr_addr);
-	if (bprm->interp_flags & BINPRM_FLAGS_PRESERVE_ARGV0)
-		flags |= AT_FLAGS_PRESERVE_ARGV0;
-	NEW_AUX_ENT(AT_FLAGS,	flags);
+	NEW_AUX_ENT(AT_FLAGS,	bprm_at_flags(bprm));
 	NEW_AUX_ENT(AT_ENTRY,	exec_params->entry_addr);
 	NEW_AUX_ENT(AT_UID,	(elf_addr_t) from_kuid_munged(cred->user_ns, cred->uid));
 	NEW_AUX_ENT(AT_EUID,	(elf_addr_t) from_kuid_munged(cred->user_ns, cred->euid));
include/linux/binfmts.h +22 -0
index 03e1794b5cbb..62465574e2a0 100644
@@ -93,6 +93,28 @@ struct linux_binprm {
 #define BINPRM_FLAGS_PRESERVE_ARGV0_BIT 3
 #define BINPRM_FLAGS_PRESERVE_ARGV0 (1 << BINPRM_FLAGS_PRESERVE_ARGV0_BIT)
 
+/* binfmt_misc dispatched to the interpreter transparently */
+#define BINPRM_FLAGS_TRANSPARENT_INTERP_BIT 4
+#define BINPRM_FLAGS_TRANSPARENT_INTERP (1 << BINPRM_FLAGS_TRANSPARENT_INTERP_BIT)
+
+/**
+ * bprm_at_flags - the AT_FLAGS this invocation implies
+ * @bprm: binary that is being executed
+ *
+ * Tell the program on the receiving end which dispatch contract it got.
+ *
+ * Return: the AT_FLAGS value for this exec
+ */
+static inline unsigned long bprm_at_flags(const struct linux_binprm *bprm)
+{
+	/* Transparency preserves the whole argv, argv[0] included. */
+	if (bprm->interp_flags & BINPRM_FLAGS_TRANSPARENT_INTERP)
+		return AT_FLAGS_TRANSPARENT_INTERP;
+	if (bprm->interp_flags & BINPRM_FLAGS_PRESERVE_ARGV0)
+		return AT_FLAGS_PRESERVE_ARGV0;
+	return 0;
+}
+
 /*
  * This structure defines the functions that are used to load the binary formats that
  * linux accepts.
include/uapi/linux/binfmts.h +7 -0
index c6f9450efc12..aafc07d78b80 100644
@@ -22,4 +22,11 @@ struct pt_regs;
 #define AT_FLAGS_PRESERVE_ARGV0_BIT 0
 #define AT_FLAGS_PRESERVE_ARGV0 (1 << AT_FLAGS_PRESERVE_ARGV0_BIT)
 
+/*
+ * The interpreter runs transparently: the argument vector and the exe
+ * link belong to the binary passed in AT_EXECFD.
+ */
+#define AT_FLAGS_TRANSPARENT_INTERP_BIT 1
+#define AT_FLAGS_TRANSPARENT_INTERP (1 << AT_FLAGS_TRANSPARENT_INTERP_BIT)
+
 #endif /* _UAPI_LINUX_BINFMTS_H */
Signature · 1 line
2.53.0
author maintainer
#16 lore raw

PATCH v2 9/21 exec: label mm->exe_file with the binary for a transparent dispatch

In reply to Christian Brauner

When binfmt_misc dispatches a binary to an interpreter, the interpreter becomes bprm->file and begin_new_exec() labels mm->exe_file with it. For wine or qemu-user that is the point. For the transparent mode it defeats the point. The interpreter is an implementation detail and the process's identity is the binary. Relocatable programs that locate themselves via /proc/self/exe find the dynamic linker instead [1].

Userspace cannot repair this after the fact. The exe link is the one capability-gated field of PR_SET_MM_MAP, deliberately, because an uncapped exe swap lets any ptrace-capable process masquerade as an arbitrary executable.

bprm->executable is the file execve() access-checked and kept open for AT_EXECFD. It is already the file would_dump() bases the dumpability decision on and the file bprm->execfd_creds derives credentials from. Label mm->exe_file with it when the dispatch is transparent and the identity is correct from the start. The label names precisely the file the caller passed to execve().

Write-denial moves along with the label. Rather than tracking per mode who still owes a release, the denial do_open_execat() took stays on bprm->executable until the file is handed over. begin_new_exec() drops it right before installing the descriptor - set_mm_exe_file() has taken its own denial on the identity file by then - and free_bprm() releases an unconsumed executable with do_close_execat() like the other exec files. For a transparent dispatch the result is exact parity with a direct execution: a concurrently written binary fails execve() with -ETXTBSY at open and a running one cannot be opened for writing. The interpreter consequently is not exe-pinned and matches the role it has in a native PT_INTERP exec. A classic execfd dispatch now keeps the binary write-denied until the exec completes rather than only until the interpreter swap; the difference is confined to the exec itself.

Nothing sets BINPRM_FLAGS_TRANSPARENT_INTERP yet; the transparent dispatch machinery in binfmt_misc follows and raises it from birth, so the label and the aux vector bit that announces it appear together.

---
 fs/exec.c | 36 +++++++++++++++++++++++++++---------
 1 file changed, 27 insertions(+), 9 deletions(-)
fs/exec.c +27 -9
index 061e0f9fb4ef..128964d1e9d6 100644
@@ -1101,6 +1101,17 @@ void __set_task_comm(struct task_struct *tsk, const char *buf, bool exec)
 	perf_event_comm(tsk, exec);
 }
 
+/*
+ * The file the process presents as: its exe link and comm. A transparent
+ * dispatch presents as the binary, which is bprm->executable.
+ */
+static struct file *bprm_identity_file(const struct linux_binprm *bprm)
+{
+	if (bprm->interp_flags & BINPRM_FLAGS_TRANSPARENT_INTERP)
+		return bprm->executable;
+	return bprm->file;
+}
+
 /*
  * Calling this is the point of no return. None of the failures will be
  * seen by userspace since either the process is already taking a fatal
@@ -1151,7 +1162,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 * not visible until then. Doing it here also ensures
 	 * we don't race against replace_mm_exe_file().
 	 */
-	retval = set_mm_exe_file(bprm->mm, bprm->file);
+	retval = set_mm_exe_file(bprm->mm, bprm_identity_file(bprm));
 	if (retval)
 		goto out;
 
@@ -1241,6 +1252,8 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 * Let's fix it up to be something reasonable.
 	 */
 	if (bprm->comm_from_dentry) {
+		struct file *comm_file = bprm_identity_file(bprm);
+
 		/*
 		 * Hold RCU lock to keep the name from being freed behind our back.
 		 * Use acquire semantics to make sure the terminating NUL from
@@ -1250,7 +1263,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 		 * detecting a concurrent rename and just want a terminated name.
 		 */
 		rcu_read_lock();
-		__set_task_comm(me, smp_load_acquire(&bprm->file->f_path.dentry->d_name.name),
+		__set_task_comm(me, smp_load_acquire(&comm_file->f_path.dentry->d_name.name),
 				true);
 		rcu_read_unlock();
 	} else {
@@ -1291,10 +1304,17 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	/* Pass the opened binary to the interpreter. */
 	if (bprm->have_execfd) {
-		retval = FD_ADD(0, bprm->executable);
-		if (retval < 0)
-			goto out_unlock;
+		struct file *executable = bprm->executable;
+
+		/* mm->exe_file carries its own write denial now so drop it. */
+		exe_file_allow_write_access(executable);
 		bprm->executable = NULL;
+		retval = FD_ADD(0, executable);
+		if (retval < 0) {
+			/* The reference was not consumed. */
+			fput(executable);
+			goto out_unlock;
+		}
 		bprm->execfd = retval;
 	}
 	return 0;
@@ -1413,8 +1433,7 @@ static void free_bprm(struct linux_binprm *bprm)
 	if (bprm->old_mm)
 		exec_mm_put_old(bprm->old_mm);
 	do_close_execat(bprm->file);
-	if (bprm->executable)
-		fput(bprm->executable);
+	do_close_execat(bprm->executable);
 	/* If a binfmt changed the interp, free it. */
 	if (bprm->interp != bprm->filename)
 		kfree(bprm->interp);
@@ -1740,8 +1759,7 @@ static int exec_binprm(struct linux_binprm *bprm)
 				do_close_execat(exec);
 				return -ENOEXEC;
 			}
-			/* Only the reference is kept, for AT_EXECFD. */
-			exe_file_allow_write_access(exec);
+			/* Kept for AT_EXECFD; the write denial rides along until hand-over. */
 			bprm->executable = exec;
 		} else {
 			do_close_execat(exec);
Signature · 1 line
2.53.0
author maintainer
#17 lore raw

PATCH v2 10/21 binfmt_misc: add transparent interpreter dispatch

In reply to Christian Brauner

A binfmt_misc interpreter is visible to the binary it runs. argv[0] becomes the interpreter path and the binary's path is appended as an argument and /proc/pid/cmdline shows both. For wine or qemu-user that is the point. 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.

Add the dispatch machinery for a transparent mode. The binary is handed to the interpreter through AT_EXECFD. The argument vector and bprm->interp are left exactly as the caller set them. argv[0] and /proc/pid/cmdline look like a direct execution of the binary.

The interpreter loads the binary from AT_EXECFD for this. A relocatable loader can and glibc's ld.so is gaining AT_EXECFD support [1]. A staged interpreter argument is rejected: no argv slot is built for it to land in.

The transparent branch raises BINPRM_FLAGS_TRANSPARENT_INTERP. A dispatch through it labels mm->exe_file with the binary and raises AT_FLAGS_TRANSPARENT_INTERP next to AT_EXECFD. The aux vector bit is the loader's hint to retarget saved_auxv and the statistics markers to the binary, which is only correct while the exe link names the binary too.

The inaccessible-path bail moves after handler selection and into the path-building branch. A transparent interpreter takes the binary from AT_EXECFD instead of a path, so the restriction does not apply to it and the O_CLOEXEC execveat() case above can work. Nothing can take the transparent branch yet.

---
 fs/binfmt_misc.c | 27 +++++++++++++++++++--------
 1 file changed, 19 insertions(+), 8 deletions(-)
fs/binfmt_misc.c +19 -8
index 304109a5091f..e5a17ca935ca 100644
@@ -50,6 +50,7 @@ enum binfmt_misc_entry_flags {
 	MISC_FMT_OPEN_BINARY	= (1U << 30),
 	MISC_FMT_CREDENTIALS	= (1U << 29),
 	MISC_FMT_OPEN_FILE	= (1U << 28),
+	MISC_FMT_TRANSPARENT	= (1U << 27),
 };
 
 /**
@@ -400,6 +401,10 @@ static int build_interp_argv(struct linux_binprm *bprm, const char *interpreter,
 {
 	int retval;
 
+	/* The interpreter has to be able to load the binary by path. */
+	if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
+		return -ENOENT;
+
 	/* The entry's own choice - not one accumulated from an earlier level. */
 	if (flags & MISC_FMT_PRESERVE_ARGV0) {
 		bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0;
@@ -458,21 +463,23 @@ static int load_misc_binary(struct linux_binprm *bprm)
 	if (!fmt)
 		return -ENOEXEC;
 
-	/* Need to be able to load the file after exec */
-	if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
-		return -ENOENT;
-
 	interpreter = entry_select_interpreter(fmt, bprm);
 	if (IS_ERR(interpreter))
 		return PTR_ERR(interpreter);
 
 	flags = entry_invocation_flags(fmt, bprm);
 
-	retval = build_interp_argv(bprm, interpreter, flags);
-	if (retval)
-		return retval;
+	/* No argv is built for a staged argument to land in. */
+	if ((flags & MISC_FMT_TRANSPARENT) && bprm->bpf_interp_arg)
+		return -EINVAL;
 
-	/* Update interp in case binfmt_script needs it. */
+	if (!(flags & MISC_FMT_TRANSPARENT)) {
+		retval = build_interp_argv(bprm, interpreter, flags);
+		if (retval)
+			return retval;
+	}
+
+	/* Update interp for the next round; sched_prepare_exec reports it. */
 	retval = bprm_change_interp(interpreter, bprm);
 	if (retval < 0)
 		return retval;
@@ -481,6 +488,10 @@ static int load_misc_binary(struct linux_binprm *bprm)
 	if (IS_ERR(interp_file))
 		return PTR_ERR(interp_file);
 
+	/* Raise only past the last failure, or an -ENOEXEC decline leaks it. */
+	if (flags & MISC_FMT_TRANSPARENT)
+		bprm->interp_flags |= BINPRM_FLAGS_TRANSPARENT_INTERP;
+
 	bprm->interpreter = interp_file;
 	if (flags & MISC_FMT_OPEN_BINARY)
 		bprm->have_execfd = 1;
Signature · 1 line
2.53.0
author maintainer
#20 lore raw

PATCH v2 11/21 binfmt_misc: add a static transparent flag 'T'

In reply to Christian Brauner

Let a registration opt into transparent dispatch. The 'T' flag lets a matched binary keep its argument vector and is sent to the interpreter through AT_EXECFD. The process's identity is the binary's.

'T' implies 'O' exactly like 'C' does. 'P' is rejected in combination with it. Transparency preserves the whole argument vector so there is nothing left for 'P' to say. 'C' remains an independent choice and 'F' keeps working. A pre-opened interpreter is orthogonal to how the binary is handed over.

Like the other flag characters 'T' cannot be used as the field delimiter. The flag scan would run off the registration buffer.

---
 Documentation/admin-guide/binfmt-misc.rst | 10 ++++++++++
 fs/binfmt_misc.c                          |  6 ++++++
 2 files changed, 16 insertions(+)
Documentation/admin-guide/binfmt-misc.rst +10 -0
index d689f21858b2..f0a0bdb681fe 100644
@@ -90,6 +90,16 @@ Here is what the fields mean:
 	    emulation is installed and uses the opened image to spawn the
 	    emulator, meaning it is always available once installed,
 	    regardless of how the environment changes.
+      ``T`` - transparent
+            Run the interpreter transparently. The binary is handed to
+            the interpreter through ``AT_EXECFD`` (``T`` implies ``O``),
+            the argument vector is left exactly as the caller built it
+            and the kernel labels ``/proc/pid/exe`` with the binary
+            instead of the interpreter. The interpreter has to load the
+            binary from ``AT_EXECFD`` and follow the
+            ``AT_FLAGS_TRANSPARENT_INTERP`` contract. Combining ``T``
+            with ``P`` is rejected: transparency preserves the whole
+            argument vector, argv[0] included.
 
 
 There are some restrictions:
fs/binfmt_misc.c +6 -0
index e5a17ca935ca..71833b976131 100644
@@ -72,6 +72,7 @@ static const struct binfmt_misc_flag misc_flags[] = {
 	{ 'O', MISC_FMT_OPEN_BINARY,	0,			"open binary"			},
 	{ 'C', MISC_FMT_CREDENTIALS,	MISC_FMT_OPEN_BINARY,	"credentials from the binary"	},
 	{ 'F', MISC_FMT_OPEN_FILE,	0,			"open interpreter file now"	},
+	{ 'T', MISC_FMT_TRANSPARENT,	MISC_FMT_OPEN_BINARY,	"transparent"			},
 };
 
 /* Look up a flag character, NULL if @c is not one. */
@@ -764,6 +765,11 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags) && p != flags)
 		return ERR_PTR(-EINVAL);
 
+	/* Transparency preserves the whole argv, argv[0] included. */
+	if ((e->flags & MISC_FMT_TRANSPARENT) &&
+	    (e->flags & MISC_FMT_PRESERVE_ARGV0))
+		return ERR_PTR(-EINVAL);
+
 	if (*p == '\n')
 		p++;
 	if (p != buf + count)
Signature · 1 line
2.53.0
author maintainer
#23 lore raw

PATCH v2 12/21 binfmt_misc: let a bpf handler run the interpreter transparently

In reply to Christian Brauner

Expose transparent mode 'T' to the bpf handler via a new BPF_BINPRM_TRANSPARENT flag. A bpf handler can decide per binary whether the dispatch is transparent. This way users may choose a native-looking loader for one binary and a visible wrapper invocation for the next.

---
 Documentation/admin-guide/binfmt-misc.rst | 15 +++++++++++++--
 fs/binfmt_misc.c                          |  2 ++
 fs/binfmt_misc_bpf.c                      | 17 ++++++++++++-----
 include/linux/binfmt_misc.h               |  4 ++++
 4 files changed, 31 insertions(+), 7 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +13 -2
index f0a0bdb681fe..81b78e315fad 100644
@@ -189,8 +189,8 @@ 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``
+The invocation flags a static entry fixes at registration - ``P``, ``C``,
+``O`` and ``T`` - 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:
 
@@ -202,6 +202,17 @@ 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 (the ``T``
+  flag): 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. ``BPF_BINPRM_PRESERVE_ARGV0`` and a staged
+  interpreter argument are rejected in combination with it, just as ``P``
+  is with ``T``. It also lets a handler
+  run a binary passed as an inaccessible ``O_CLOEXEC`` file descriptor to
+  ``execveat()``, which a path-splicing dispatch cannot: 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 +2 -0
index 71833b976131..622c62ee6683 100644
@@ -351,6 +351,8 @@ static unsigned long entry_invocation_flags(const struct binfmt_misc_entry *e,
 		flags |= MISC_FMT_OPEN_BINARY;
 	if (bpf_flags & BPF_BINPRM_CREDENTIALS)
 		flags |= MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY;
+	if (bpf_flags & BPF_BINPRM_TRANSPARENT)
+		flags |= MISC_FMT_TRANSPARENT | MISC_FMT_OPEN_BINARY;
 
 	return flags;
 }
fs/binfmt_misc_bpf.c +12 -5
index 65a3b8313fbe..c3d1b8c51f90 100644
@@ -174,19 +174,26 @@ __bpf_kfunc int bpf_binprm_set_interp_arg(struct linux_binprm *bprm,
  * @flags: an OR of enum bpf_binprm_flags values
  *
  * To be called from the load program of a struct binfmt_misc_ops handler. It
- * decides per exec what a static entry fixes at registration with the P, C and
- * O flags: BPF_BINPRM_PRESERVE_ARGV0 keeps the caller's argv[0],
+ * decides per exec what a static entry fixes at registration with the P, C, O
+ * and T 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
+ * Return: 0 on success, -EINVAL if @flags contains an unknown bit or an
+ * invalid combination
  */
 __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;
+
+	/* Transparency preserves the whole argv, argv[0] included. */
+	if ((flags & BPF_BINPRM_TRANSPARENT) && (flags & BPF_BINPRM_PRESERVE_ARGV0))
 		return -EINVAL;
 
 	bprm->bpf_flags = flags;
include/linux/binfmt_misc.h +4 -0
index d3112a00cc19..26da749391b4 100644
@@ -16,6 +16,9 @@ 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 (like the 'T' flag); implies
+ *                          execfd, excludes preserve-argv0
  *
  * 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 +27,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
author maintainer
#24 lore raw

PATCH v2 13/21 selftests/exec: test the transparent binfmt_misc mode

In reply to Christian Brauner

Verify the identity a transparent dispatch constructs, from both activation paths.

- binfmt_misc_transparent: registers a magic entry with the static 'T' flag and execs a matched binary with arguments.

- binfmt_misc_bpf: a handler whose load program sets BPF_BINPRM_TRANSPARENT.

Both dispatch to a shared asserting interpreter that runs in place of the binary and checks the contract from the inside:

- AT_FLAGS carries AT_FLAGS_TRANSPARENT_INTERP
- AT_EXECFD refers to the very inode of the binary
- /proc/self/exe resolves to the binary
- argv and /proc/self/cmdline are exactly what the caller passed with nothing spliced in
- comm is the binary's basename
- the binary is write-denied while it runs

The static test also validates the registration. 'T' combined with 'P' must be rejected. A kernel that does not know 'T' turns the test into a skip. The asserting interpreter and the static test build without the bpf toolchain so the core transparent semantics stay covered on systems where the bpf cases are skipped.

---
 tools/testing/selftests/exec/.gitignore            |   2 +
 tools/testing/selftests/exec/Makefile              |   7 +-
 tools/testing/selftests/exec/binfmt_misc_bpf.c     |  45 ++++++-
 .../selftests/exec/binfmt_misc_transparent.c       | 108 +++++++++++++++++
 .../selftests/exec/binfmt_transparent_interp.c     | 130 +++++++++++++++++++++
 tools/testing/selftests/exec/transparent.bpf.c     |  57 +++++++++
 6 files changed, 345 insertions(+), 4 deletions(-)
tools/testing/selftests/exec/.gitignore +2 -0
index 8b93b405c424..94b9ab4eb46c 100644
@@ -22,5 +22,7 @@ S_I*.test
 binfmt_misc_bpf
 binfmt_bpf_interp
 binfmt_bpf_app
+binfmt_misc_transparent
+binfmt_transparent_interp
 *.bpf.o
 vmlinux.h
tools/testing/selftests/exec/Makefile +6 -1
index fb5ca59af51d..b316ff46d03c 100644
@@ -21,6 +21,11 @@ TEST_GEN_PROGS += recursion-depth
 TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
 
+# Static ('T' flag) transparent binfmt_misc test; the asserting interpreter
+# is shared with the bpf harness's transparent case. No bpf toolchain needed.
+TEST_GEN_PROGS += binfmt_misc_transparent
+TEST_GEN_FILES += binfmt_transparent_interp
+
 # binfmt_misc bpf-backed ('B') handler test: a libbpf harness plus its
 # struct_ops objects and the test interpreter/app it routes between. Only
 # built when clang, bpftool, the vmlinux BTF and libbpf are all present
@@ -35,7 +40,7 @@ HAVE_BPF_TOOLCHAIN ?= $(shell command -v $(CLANG) >/dev/null 2>&1 && \
 			pkg-config --exists libbpf 2>/dev/null && echo y)
 ifeq ($(HAVE_BPF_TOOLCHAIN),y)
 TEST_GEN_PROGS += binfmt_misc_bpf
-TEST_GEN_FILES += bpf_interp.bpf.o nix_origin.bpf.o
+TEST_GEN_FILES += bpf_interp.bpf.o nix_origin.bpf.o transparent.bpf.o
 TEST_GEN_FILES += binfmt_bpf_interp binfmt_bpf_app
 else
 $(info exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, vmlinux BTF and libbpf)
tools/testing/selftests/exec/binfmt_misc_bpf.c +42 -3

75 lines not on this page · raw message

tools/testing/selftests/exec/binfmt_misc_transparent.c new file +108 -0

108 lines not on this page · raw message

tools/testing/selftests/exec/binfmt_transparent_interp.c new file +130 -0

130 lines not on this page · raw message

tools/testing/selftests/exec/transparent.bpf.c new file +57 -0

57 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#27 lore raw

PATCH v2 14/21 binfmt_misc: document the transparent identity contract

In reply to Christian Brauner

Describe what a transparent dispatch constructs and the loader contract behind AT_FLAGS_TRANSPARENT_INTERP. Also note what deliberately stays different (the address space layout) and what stays unchanged (credential derivation without 'C').

---
 Documentation/admin-guide/binfmt-misc.rst | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
Documentation/admin-guide/binfmt-misc.rst +30 -0
index 81b78e315fad..ea1c1c0676c8 100644
@@ -223,6 +223,36 @@ binfmt_misc instances themselves are looked up. The entry keeps the handler
 alive; deleting the struct_ops map only prevents new activations.
 
 
+Transparent interpreters
+------------------------
+
+With the ``T`` flag or ``BPF_BINPRM_TRANSPARENT`` the dispatch is invisible
+to the resulting process. The argument vector is left exactly as the caller
+built it. The binary is passed through ``AT_EXECFD``. The kernel also labels
+``/proc/pid/exe`` correctly. The binary's file is write-denied while the
+process runs and the interpreter's is not, exactly as if the binary had been
+executed directly. A transparent entry does not change how credentials are
+derived. As
+with any other entry, set*id bits of the binary are only honored with ``C`` (or
+``BPF_BINPRM_CREDENTIALS``).
+
+The interpreter has to be built for this contract. The kernel announces it
+with ``AT_FLAGS_TRANSPARENT_INTERP`` in the ``AT_FLAGS`` aux vector entry
+next to ``AT_EXECFD``. The argument vector belongs entirely to the program,
+nothing was spliced in, so the interpreter doesn't consume arguments and
+simply loads the program from the descriptor. The bit is also the loader's
+license to finish the identity. After mapping the program it may retarget the
+``AT_PHDR``/``AT_ENTRY``/``AT_BASE`` entries of ``/proc/pid/auxv`` and the
+code/data statistics markers via one ``PR_SET_MM_MAP`` which completes
+what attaching debuggers observe. The prctl is privileged - it takes
+``CONFIG_CHECKPOINT_RESTORE`` plus ``CAP_CHECKPOINT_RESTORE`` or
+``CAP_SYS_ADMIN`` in the caller's user namespace - so a loader running
+without these leaves the aux vector and the markers as the kernel set
+them. What remains visibly different from a direct
+execution is the address space layout. The interpreter occupies the main-image
+position and the program lives in the mmap region.
+
+
 Hints
 -----
 
Signature · 1 line
2.53.0
author maintainer
#30 lore raw

PATCH v2 15/21 exec: carry a PT_INTERP substitute in struct linux_binprm

In reply to Christian Brauner

binfmt_misc currently supports an execution model where the registered interpreter becomes the executed program and the matched binary is handed to it as payload. The upcoming binfmt_misc loader mode inverts this. The matched binary remains the executed program and the registered interpreter is substituted into the role the binary's PT_INTERP would have played.

Add the channel for that hand-over. bprm->loader carries an open_exec-style struct file reference from the binfmt_misc match to the binary format that consumes it. Unlike bprm->interpreter it does not request a restart of the format search. The stashing handler declines the exec with -ENOEXEC and the search continues to the real format in the same round.

Both ELF loaders consume it, so give them the two helpers to do it with rather than a copy each. bprm_open_interpreter() hands out the substitute in place of what PT_INTERP names and bprm_drop_loader() releases one that turned out not to apply.

Establish the complete lifecycle up front so a stashed loader can neither leak nor be silently ignored.

- Chain restart: if another format wins the round by staging bprm->interpreter (binfmt_script) the stashed loader belonged to the file being replaced. Drop it at the top of the swap block in exec_binprm().

- Unclaimed or error: free_bprm() releases a still-stashed loader next to the other bprm file references.

- Silent non-substitution: a final format that reaches begin_new_exec() with a pending loader would run the binary while ignoring the override. Refuse with -ENOEXEC before the point of no return. Formats that do not know about the override (binfmt_flat, out-of-tree) need no changes.

---
 fs/exec.c               | 42 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/binfmts.h |  3 +++
 2 files changed, 45 insertions(+)
fs/exec.c +42 -0
index 128964d1e9d6..856731f78d05 100644
@@ -1123,6 +1123,10 @@ int begin_new_exec(struct linux_binprm * bprm)
 	struct task_struct *me = current;
 	int retval;
 
+	/* A pending PT_INTERP substitution this format cannot consume. */
+	if (bprm->loader)
+		return -ENOEXEC;
+
 	/* Once we are committed compute the creds */
 	retval = bprm_creds_from_file(bprm);
 	if (retval)
@@ -1414,6 +1418,39 @@ static void do_close_execat(struct file *file)
 	fput(file);
 }
 
+/**
+ * bprm_open_interpreter - open the interpreter the binary asks for
+ * @bprm: binary that is being executed
+ * @path: the interpreter path named in the binary's PT_INTERP
+ *
+ * A binfmt_misc loader entry substitutes for the interpreter the binary
+ * names. Hand out the stashed substitute if there is one and open @path
+ * if there is not. The caller owns the reference either way and releases
+ * it like any other open_exec() one.
+ *
+ * Return: the interpreter on success, an ERR_PTR on failure
+ */
+struct file *bprm_open_interpreter(struct linux_binprm *bprm, const char *path)
+{
+	if (bprm->loader)
+		return no_free_ptr(bprm->loader);
+	return open_exec(path);
+}
+
+/**
+ * bprm_drop_loader - discard a PT_INTERP substitute that does not apply
+ * @bprm: binary that is being executed
+ *
+ * A binary without PT_INTERP has nothing to substitute for, so drop the
+ * override and let the binary load natively rather than have
+ * begin_new_exec() refuse it. A no-op once bprm_open_interpreter() took
+ * the substitute.
+ */
+void bprm_drop_loader(struct linux_binprm *bprm)
+{
+	do_close_execat(no_free_ptr(bprm->loader));
+}
+
 static void free_bprm(struct linux_binprm *bprm)
 {
 	if (bprm->mm) {
@@ -1433,6 +1470,8 @@ static void free_bprm(struct linux_binprm *bprm)
 	if (bprm->old_mm)
 		exec_mm_put_old(bprm->old_mm);
 	do_close_execat(bprm->file);
+	/* An unconsumed PT_INTERP substitute from a binfmt_misc loader entry. */
+	bprm_drop_loader(bprm);
 	do_close_execat(bprm->executable);
 	/* If a binfmt changed the interp, free it. */
 	if (bprm->interp != bprm->filename)
@@ -1750,6 +1789,9 @@ static int exec_binprm(struct linux_binprm *bprm)
 		if (!bprm->interpreter)
 			break;
 
+		/* A stashed PT_INTERP substitute belonged to the replaced file. */
+		bprm_drop_loader(bprm);
+
 		exec = bprm->file;
 		bprm->file = bprm->interpreter;
 		bprm->interpreter = NULL;
include/linux/binfmts.h +3 -0
index 62465574e2a0..a2daecbb01d6 100644
@@ -62,6 +62,7 @@ struct linux_binprm {
 		is_check:1;
 	struct file *executable; /* Executable to pass to the interpreter */
 	struct file *interpreter;
+	struct file *loader;
 	struct file *file;
 	struct cred *cred;	/* new credentials */
 	int unsafe;		/* how unsafe this exec is (mask of LSM_UNSAFE_*) */
@@ -159,6 +160,8 @@ extern int begin_new_exec(struct linux_binprm * bprm);
 extern void setup_new_exec(struct linux_binprm * bprm);
 extern void finalize_exec(struct linux_binprm *bprm);
 extern void would_dump(struct linux_binprm *, struct file *);
+struct file *bprm_open_interpreter(struct linux_binprm *bprm, const char *path);
+void bprm_drop_loader(struct linux_binprm *bprm);
 
 extern int suid_dumpable;
 
Signature · 1 line
2.53.0
author maintainer
#31 lore raw

PATCH v2 16/21 binfmt_elf: consume a stashed PT_INTERP substitute

In reply to Christian Brauner

When a binfmt_misc loader entry stashed bprm->loader use it instead of opening the path named in PT_INTERP. The substitution deliberately changes as little as possible. Ownership transfers into the local interpreter reference which the existing success and error paths already release.

A binary without PT_INTERP has nothing to substitute for. Drop the override at the end of the segment scan and load the binary natively.

Nothing sets bprm->loader yet.

---
 fs/binfmt_elf.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/binfmt_elf.c +4 -1
index be8fd437b5a3..00ff35cad441 100644
@@ -901,7 +901,7 @@ static int load_elf_binary(struct linux_binprm *bprm)
 		if (elf_interpreter[elf_ppnt->p_filesz - 1] != '\0')
 			goto out_free_interp;
 
-		interpreter = open_exec(elf_interpreter);
+		interpreter = bprm_open_interpreter(bprm, elf_interpreter);
 		kfree(elf_interpreter);
 		retval = PTR_ERR(interpreter);
 		if (IS_ERR(interpreter))
@@ -932,6 +932,9 @@ static int load_elf_binary(struct linux_binprm *bprm)
 		goto out_free_ph;
 	}
 
+	/* No PT_INTERP to substitute for: the override does not apply. */
+	bprm_drop_loader(bprm);
+
 	elf_ppnt = elf_phdata;
 	for (i = 0; i < elf_ex->e_phnum; i++, elf_ppnt++)
 		switch (elf_ppnt->p_type) {
Signature · 1 line
2.53.0
author maintainer
#34 lore raw

PATCH v2 17/21 binfmt_elf_fdpic: consume a stashed PT_INTERP substitute

In reply to Christian Brauner

Do what binfmt_elf does. When a binfmt_misc loader entry stashed bprm->loader use it in place of the path named in PT_INTERP, and drop the override when the binary names no interpreter at all.

Without this 'L' is unusable on nommu, where fdpic is the only ELF loader. On ARM with an MMU both loaders are registered but split the ELF space between them along elf_check_fdpic(), so an fdpic binary is never picked up by binfmt_elf either.

Declining is what fdpic did so far, but it declined late. The pending override was only caught in begin_new_exec(), by which point the segment scan had opened the interpreter the binary itself names and overwritten bprm->buf with its header, leaving the next format in the round to inspect a buffer that no longer describes the file it is offered. The scan consumes the override now, so of the in-tree formats only binfmt_flat still relies on the refusal, and it reads bprm->buf without writing it.

Transparent dispatch needs nothing on top of the AT_FLAGS translation both loaders already share. The binary travels in AT_EXECFD, which create_elf_fdpic_tables() emits, and the exe and comm labelling is done in exec.c for every format.

---
 fs/binfmt_elf_fdpic.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
fs/binfmt_elf_fdpic.c +5 -1
index 0a3cdf280307..068c46875c74 100644
@@ -263,7 +263,8 @@ static int load_elf_fdpic_binary(struct linux_binprm *bprm)
 			kdebug("Using ELF interpreter %s", interpreter_name);
 
 			/* replace the program with the interpreter */
-			interpreter = open_exec(interpreter_name);
+			interpreter = bprm_open_interpreter(bprm,
+							    interpreter_name);
 			retval = PTR_ERR(interpreter);
 			if (IS_ERR(interpreter)) {
 				interpreter = NULL;
@@ -299,6 +300,9 @@ static int load_elf_fdpic_binary(struct linux_binprm *bprm)
 
 	}
 
+	/* No PT_INTERP to substitute for: the override does not apply. */
+	bprm_drop_loader(bprm);
+
 	if (is_constdisp(&exec_params.hdr))
 		exec_params.flags |= ELF_FDPIC_FLAG_CONSTDISP;
 
Signature · 1 line
2.53.0
author maintainer
#35 lore raw

PATCH v2 18/21 binfmt_misc: add the 'L' loader substitution flag

In reply to Christian Brauner

Add the first activation of the PT_INTERP substitution machinery. A static entry registered with the new 'L' flag no longer runs the registered interpreter with the binary as payload. It stashes the interpreter as bprm->loader and declines the match with -ENOEXEC. The format search continues in the same round. binfmt_elf claims the binary as a fully native exec and substitutes the stashed file for the binary's PT_INTERP.

'L' rejects every classic-dispatch flag at registration. 'T', 'P' and 'O' have nothing to act on (no argv splice, no execfd) and 'C' is subsumed (credentials derive from the binary natively). 'F' composes and is valuable: with it the substitute is pre-opened at registration time and immune to mount namespace changes. Without it the substitute is opened at exec time in the exec'ing task's context, so 'L' joins 'C' in the requirement that the interpreter be named by an absolute path. As with 'C', only trusted interpreters should be registered. The substituted loader runs with credentials derived from the binary.

Like the other flag characters 'L' cannot be used as the field delimiter. The flag scan would run off the registration buffer.

The interpreter open is shared with the classic path via the entry_open_interpreter() helper. An open error fails the exec. Map -ENOEXEC to -EACCES to avoid letting the binary run with its own PT_INTERP.

---
 Documentation/admin-guide/binfmt-misc.rst | 15 ++++++++++----
 fs/binfmt_misc.c                          | 33 +++++++++++++++++++++++++++++--
 2 files changed, 42 insertions(+), 6 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +11 -4
index ea1c1c0676c8..a9f685077925 100644
@@ -100,6 +100,13 @@ Here is what the fields mean:
             ``AT_FLAGS_TRANSPARENT_INTERP`` contract. Combining ``T``
             with ``P`` is rejected: transparency preserves the whole
             argument vector, argv[0] included.
+      ``L`` - loader substitution
+            Do not run the interpreter on the binary at all: load the
+            binary itself as a fully native exec and substitute the
+            interpreter for the loader named in the binary's
+            ``PT_INTERP``. See the "Loader substitution" section
+            below. ``L`` rejects ``T``, ``P``, ``O`` and ``C``;
+            ``F`` composes.
 
 
 There are some restrictions:
@@ -108,10 +115,10 @@ There are some restrictions:
  - the magic must reside in the first 128 bytes of the file, i.e.
    offset+size(magic) has to be less than 128
  - the interpreter string may not exceed 127 characters
- - an interpreter used with ``C`` but without ``F`` has to be named by an
-   absolute path. It is opened when the binary is executed, so a relative
-   one would be resolved against the working directory of whoever runs
-   the binary
+ - an interpreter used with ``C`` or ``L`` but without ``F`` has to be
+   named by an absolute path. It is opened when the binary is executed, so
+   a relative one would be resolved against the working directory of
+   whoever runs the binary
 
 
 To use binfmt_misc you have to mount it first. You can mount it with
fs/binfmt_misc.c +31 -2
index 622c62ee6683..a60e69e4514f 100644
@@ -51,6 +51,7 @@ enum binfmt_misc_entry_flags {
 	MISC_FMT_CREDENTIALS	= (1U << 29),
 	MISC_FMT_OPEN_FILE	= (1U << 28),
 	MISC_FMT_TRANSPARENT	= (1U << 27),
+	MISC_FMT_LOADER		= (1U << 26),
 };
 
 /**
@@ -73,6 +74,7 @@ static const struct binfmt_misc_flag misc_flags[] = {
 	{ 'C', MISC_FMT_CREDENTIALS,	MISC_FMT_OPEN_BINARY,	"credentials from the binary"	},
 	{ 'F', MISC_FMT_OPEN_FILE,	0,			"open interpreter file now"	},
 	{ 'T', MISC_FMT_TRANSPARENT,	MISC_FMT_OPEN_BINARY,	"transparent"			},
+	{ 'L', MISC_FMT_LOADER,		0,			"loader substitution"		},
 };
 
 /* Look up a flag character, NULL if @c is not one. */
@@ -458,6 +460,9 @@ static int load_misc_binary(struct linux_binprm *bprm)
 	unsigned long flags;
 	int retval;
 
+	/* Only binfmt_misc stages one and exec_binprm() clears it per round. */
+	WARN_ON_ONCE(bprm->loader);
+
 	misc = current_binfmt_misc();
 	if (!READ_ONCE(misc->enabled))
 		return -ENOEXEC;
@@ -473,9 +478,27 @@ static int load_misc_binary(struct linux_binprm *bprm)
 	flags = entry_invocation_flags(fmt, bprm);
 
 	/* No argv is built for a staged argument to land in. */
-	if ((flags & MISC_FMT_TRANSPARENT) && bprm->bpf_interp_arg)
+	if ((flags & (MISC_FMT_LOADER | MISC_FMT_TRANSPARENT)) &&
+	    bprm->bpf_interp_arg)
 		return -EINVAL;
 
+	/*
+	 * Stash the interpreter for binfmt_elf to consume in place of the
+	 * binary's PT_INTERP and decline the match, so the search continues
+	 * to the real format in the same round.
+	 */
+	if (flags & MISC_FMT_LOADER) {
+		interp_file = entry_open_interpreter(fmt, interpreter);
+		if (IS_ERR(interp_file)) {
+			retval = PTR_ERR(interp_file);
+			/* Declining here would run the binary's own PT_INTERP. */
+			return retval == -ENOEXEC ? -EACCES : retval;
+		}
+
+		bprm->loader = interp_file;
+		return -ENOEXEC;
+	}
+
 	if (!(flags & MISC_FMT_TRANSPARENT)) {
 		retval = build_interp_argv(bprm, interpreter, flags);
 		if (retval)
@@ -772,13 +795,19 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 	    (e->flags & MISC_FMT_PRESERVE_ARGV0))
 		return ERR_PTR(-EINVAL);
 
+	/* A native exec splices no argv, passes no execfd and needs no creds. */
+	if ((e->flags & MISC_FMT_LOADER) &&
+	    (e->flags & (MISC_FMT_TRANSPARENT | MISC_FMT_PRESERVE_ARGV0 |
+			 MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY)))
+		return ERR_PTR(-EINVAL);
+
 	if (*p == '\n')
 		p++;
 	if (p != buf + count)
 		return ERR_PTR(-EINVAL);
 
 	/* Non-F opens the interp at exec against the caller's cwd; require absolute. */
-	if ((e->flags & MISC_FMT_CREDENTIALS) &&
+	if ((e->flags & (MISC_FMT_LOADER | MISC_FMT_CREDENTIALS)) &&
 	    !(e->flags & MISC_FMT_OPEN_FILE) &&
 	    e->interpreter[0] != '/')
 		return ERR_PTR(-EINVAL);
Signature · 1 line
2.53.0
author maintainer
#36 lore raw

PATCH v2 19/21 binfmt_misc: let a bpf handler request loader substitution

In reply to Christian Brauner

Give bpf handlers the per-exec equivalent of the static 'L' flag. A load program that sets BPF_BINPRM_LOADER has its selected interpreter substituted for the binary's PT_INTERP instead of run with the binary as payload. The binary otherwise executes as a fully native exec.

A single handler can now grade its dispatch per binary: native-arch ELF with PT_INTERP gets loader substitution for full native identity. Anything else, such as foreign arch, static, non-ELF can use transparent or classic dispatch. The load program can read the binary's ELF header from bprm->buf to make that call.

---
 Documentation/admin-guide/binfmt-misc.rst |  9 ++++++---
 fs/binfmt_misc.c                          |  2 ++
 fs/binfmt_misc_bpf.c                      | 17 ++++++++++++-----
 include/linux/binfmt_misc.h               |  4 ++++
 4 files changed, 24 insertions(+), 8 deletions(-)
Documentation/admin-guide/binfmt-misc.rst +6 -3
index a9f685077925..72b389d61f6f 100644
@@ -197,9 +197,9 @@ 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``,
-``O`` and ``T`` - 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:
+``O``, ``T`` and ``L`` - 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).
@@ -220,6 +220,9 @@ decide them differently for each binary it handles:
   run a binary passed as an inaccessible ``O_CLOEXEC`` file descriptor to
   ``execveat()``, which a path-splicing dispatch cannot: the interpreter
   has no path by which to open it.
+- ``BPF_BINPRM_LOADER`` substitutes the interpreter for the binary's
+  ``PT_INTERP`` and runs the binary as a fully native exec (the ``L``
+  flag). It excludes the other flags and a staged interpreter argument.
 
 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 +2 -0
index a60e69e4514f..a68f6c18c5cf 100644
@@ -355,6 +355,8 @@ static unsigned long entry_invocation_flags(const struct binfmt_misc_entry *e,
 		flags |= MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY;
 	if (bpf_flags & BPF_BINPRM_TRANSPARENT)
 		flags |= MISC_FMT_TRANSPARENT | MISC_FMT_OPEN_BINARY;
+	if (bpf_flags & BPF_BINPRM_LOADER)
+		flags |= MISC_FMT_LOADER;
 
 	return flags;
 }
fs/binfmt_misc_bpf.c +12 -5
index c3d1b8c51f90..92003ea640d3 100644
@@ -174,13 +174,15 @@ __bpf_kfunc int bpf_binprm_set_interp_arg(struct linux_binprm *bprm,
  * @flags: an OR of enum bpf_binprm_flags values
  *
  * To be called from the load program of a struct binfmt_misc_ops handler. It
- * decides per exec what a static entry fixes at registration with the P, C, O
- * and T flags: BPF_BINPRM_PRESERVE_ARGV0 keeps the caller's argv[0],
+ * decides per exec what a static entry fixes at registration with the P, C,
+ * O, T and L 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.
  * 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.
+ * making the exec look like a direct execution of the binary.
+ * BPF_BINPRM_LOADER substitutes the interpreter for the binary's PT_INTERP
+ * and runs the binary as a native exec; it excludes every other flag.
+ * Calling it again replaces the flags, passing zero clears them again.
  *
  * Return: 0 on success, -EINVAL if @flags contains an unknown bit or an
  * invalid combination
@@ -189,7 +191,12 @@ __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_TRANSPARENT))
+		      BPF_BINPRM_EXECFD | BPF_BINPRM_TRANSPARENT |
+		      BPF_BINPRM_LOADER))
+		return -EINVAL;
+
+	/* Loader substitution is a native exec: no splice, execfd or creds work. */
+	if ((flags & BPF_BINPRM_LOADER) && (flags & ~BPF_BINPRM_LOADER))
 		return -EINVAL;
 
 	/* Transparency preserves the whole argv, argv[0] included. */
include/linux/binfmt_misc.h +4 -0
index 26da749391b4..4abdfd36b3fa 100644
@@ -19,6 +19,9 @@ struct user_namespace;
  * @BPF_BINPRM_TRANSPARENT: leave argv untouched, the interpreter takes the
  *                          binary from AT_EXECFD (like the 'T' flag); implies
  *                          execfd, excludes preserve-argv0
+ * @BPF_BINPRM_LOADER: substitute the interpreter for the binary's PT_INTERP
+ *                     and run the binary as a native exec (like the 'L'
+ *                     flag); excludes every other flag
  *
  * 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.
@@ -28,6 +31,7 @@ enum bpf_binprm_flags {
 	BPF_BINPRM_CREDENTIALS		= (1ULL << 1),
 	BPF_BINPRM_EXECFD		= (1ULL << 2),
 	BPF_BINPRM_TRANSPARENT		= (1ULL << 3),
+	BPF_BINPRM_LOADER		= (1ULL << 4),
 };
 
 /**
Signature · 1 line
2.53.0
author maintainer
#37 lore raw

PATCH v2 20/21 selftests/exec: test binfmt_misc loader substitution

In reply to Christian Brauner

Exercise the 'L' flag end to end. The payload runs as the main image with a copy of the system loader substituted for its PT_INTERP, and asserts the native identity from inside:

- argv exactly as the caller built it
- no AT_EXECFD
- AT_FLAGS clear
- AT_BASE set but outside its own image
- AT_PHDR/AT_ENTRY inside it
- /proc/self/{exe,comm,stat} and AT_EXECFN all describing the binary
- ETXTBSY on the running binary
- the substituted loader visible in /proc/self/maps under its real path

Magic matching pokes a marker into the ELF header's e_ident padding (EI_PAD, offset 9), which sits inside the match window and is ignored by kernel and loader alike. the same binary is also matched by extension.

Two cases cover the paths where the substitution does not happen. A '#!' file that matched an 'L' entry is claimed by binfmt_script rather than by binfmt_elf, so the staged substitute has to be released when the interpreter replaces the file; the test opens the loader for writing afterwards, which fails with ETXTBSY if the write denial was leaked instead. A relative interpreter path is rejected at registration for both 'L' and 'C', neither of which may resolve one against the working directory of whoever runs the binary.

The bpf-side BPF_BINPRM_LOADER path shares all machinery past the flag mapping. A harness case for it can join the bpf runtime coverage of the transparent series.

---
 tools/testing/selftests/exec/.gitignore            |   3 +
 tools/testing/selftests/exec/Makefile              |  14 +
 .../testing/selftests/exec/binfmt_loader_payload.c | 167 ++++++++++
 tools/testing/selftests/exec/binfmt_misc_bpf.c     | 112 +++++--
 tools/testing/selftests/exec/binfmt_misc_common.h  | 107 ++++++
 tools/testing/selftests/exec/binfmt_misc_loader.c  | 371 +++++++++++++++++++++
 tools/testing/selftests/exec/loader.bpf.c          |  56 ++++
 7 files changed, 808 insertions(+), 22 deletions(-)
tools/testing/selftests/exec/.gitignore +3 -0
index 94b9ab4eb46c..fbbb1600ddb9 100644
@@ -24,5 +24,8 @@ binfmt_bpf_interp
 binfmt_bpf_app
 binfmt_misc_transparent
 binfmt_transparent_interp
+binfmt_misc_loader
+binfmt_loader_payload
+binfmt_loader_payload_static
 *.bpf.o
 vmlinux.h
tools/testing/selftests/exec/Makefile +14 -0
index b316ff46d03c..b05b82ceae42 100644
@@ -26,6 +26,13 @@ TEST_GEN_PROGS += check-exec
 TEST_GEN_PROGS += binfmt_misc_transparent
 TEST_GEN_FILES += binfmt_transparent_interp
 
+# 'L' (loader substitution) binfmt_misc test: the payload runs as the main
+# image with a copy of the system loader substituted for its PT_INTERP and
+# asserts the native identity from inside; the static build proves the
+# override is dropped for a binary without PT_INTERP.
+TEST_GEN_PROGS += binfmt_misc_loader
+TEST_GEN_FILES += binfmt_loader_payload binfmt_loader_payload_static
+
 # binfmt_misc bpf-backed ('B') handler test: a libbpf harness plus its
 # struct_ops objects and the test interpreter/app it routes between. Only
 # built when clang, bpftool, the vmlinux BTF and libbpf are all present
@@ -41,6 +48,7 @@ HAVE_BPF_TOOLCHAIN ?= $(shell command -v $(CLANG) >/dev/null 2>&1 && \
 ifeq ($(HAVE_BPF_TOOLCHAIN),y)
 TEST_GEN_PROGS += binfmt_misc_bpf
 TEST_GEN_FILES += bpf_interp.bpf.o nix_origin.bpf.o transparent.bpf.o
+TEST_GEN_FILES += loader.bpf.o
 TEST_GEN_FILES += binfmt_bpf_interp binfmt_bpf_app
 else
 $(info exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, vmlinux BTF and libbpf)
@@ -104,6 +112,12 @@ $(OUTPUT)/binfmt_misc_bpf: binfmt_misc_bpf.c binfmt_misc_common.h
 $(OUTPUT)/binfmt_bpf_interp: binfmt_bpf_interp.c
 	$(CC) $(CFLAGS) $(LDFLAGS) $< -o $@
 
+$(OUTPUT)/binfmt_loader_payload: binfmt_loader_payload.c binfmt_misc_common.h
+	$(CC) $(CFLAGS) $(LDFLAGS) -fPIE -pie $< -o $@
+
+$(OUTPUT)/binfmt_loader_payload_static: binfmt_loader_payload.c binfmt_misc_common.h
+	$(CC) $(CFLAGS) $(LDFLAGS) -static $< -o $@
+
 # PT_INTERP is set to the literal "$ORIGIN/binfmt_bpf_interp"; the nix_origin
 # handler resolves it relative to the binary at run time.
 $(OUTPUT)/binfmt_bpf_app: binfmt_bpf_app.c
tools/testing/selftests/exec/binfmt_loader_payload.c new file +167 -0

167 lines not on this page · raw message

tools/testing/selftests/exec/binfmt_misc_bpf.c +90 -22

155 lines not on this page · raw message

tools/testing/selftests/exec/binfmt_misc_common.h +107 -0

130 lines not on this page · raw message

tools/testing/selftests/exec/binfmt_misc_loader.c new file +371 -0

371 lines not on this page · raw message

tools/testing/selftests/exec/loader.bpf.c new file +56 -0

56 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#38 lore raw

PATCH v2 21/21 binfmt_misc: document loader substitution

In reply to Christian Brauner

Describe the L mode next to the transparent one.

---
 Documentation/admin-guide/binfmt-misc.rst | 47 +++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
Documentation/admin-guide/binfmt-misc.rst +47 -0
index 72b389d61f6f..d49809e62a52 100644
@@ -263,6 +263,53 @@ execution is the address space layout. The interpreter occupies the main-image
 position and the program lives in the mmap region.
 
 
+Loader substitution
+-------------------
+
+The ``L`` flag turns the execution model around. Instead of running the
+registered interpreter with the binary as its payload the kernel loads
+the matched binary itself as the main image and substitutes the registered
+interpreter for the loader named in the binary's ``PT_INTERP``.
+
+Because the exec is native, there is no dispatch identity to
+reconstruct and no contract the substitute has to implement. A stock
+dynamic loader works unchanged. The argument vector is untouched,
+credentials and ``AT_SECURE`` derive from the binary, there is no
+``AT_EXECFD`` and no marker in the aux vector, the binary sits in the
+main-image slot with the native brk placement so ``/proc/pid/maps``,
+core dumps and perf mmap records have the native shape, and the
+identity is already complete when ``PTRACE_EVENT_EXEC`` stops the
+tracee. So launching under a debugger works, not just attaching. ``L``
+entries are for ELF binaries of a native architecture. Foreign-arch
+emulation and non-ELF payloads remain the domain of the classic and
+transparent modes.
+
+The override applies when the format that finally claims the file is
+ELF with a ``PT_INTERP``. A matched binary without one or an
+interpreter-less ``ET_DYN`` drops the override and runs natively. A file
+claimed by another format - a ``#!`` script, say - is handled by that
+format as if the entry had not matched. ``L`` is therefore not an
+enforcement mechanism: it decides how a binary that asks for a loader is
+run, it does not guarantee that everything matching the entry runs under
+the substitute. A format that cannot consume the override at all instead
+refuses the exec with ``ENOEXEC`` before the point of no return.
+
+A wrong-architecture ELF fails the whole exec with ``ENOEXEC`` exactly
+as if no entry had matched. A substitute that is not ELF of the right
+architecture fails with ``ELIBBAD``. The usual ``PT_INTERP`` sanity
+checks on the binary still apply. But the segment's content is otherwise
+irrelevant.
+
+``L`` rejects the classic-dispatch flags ``T``, ``P``, ``O`` and ``C``
+at registration. ``F`` composes and is valuable: with it the substitute
+is opened at registration time, so later mount namespace or path changes
+cannot redirect it. Without it the substitute is opened when the binary
+is executed, and the path is resolved in the mount namespace and root of
+whoever runs the binary, which is why it has to be absolute. As with
+``C``, register only trusted interpreters. The substituted loader runs
+with credentials derived from the binary.
+
+
 Hints
 -----
 
Signature · 1 line
2.53.0
#25 lore raw

Re: [PATCH v2 13/21] selftests/exec: test the transparent binfmt_misc mode

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Insecure usage of predictable `/tmp` files without `O_EXCL` enables Local Privilege Escalation via…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Insecure usage of predictable /tmp files without O_EXCL enables Local Privilege Escalation via arbitrary file truncation and TOCTOU race condition.
- [Medium] Continuing execution after stat/fstat failure leads to uninitialized memory read.
- [Medium] Stack-based buffer overflow in the test interpreter when copying environment variables.
--

--- Patch [13]: [PATCH v2 13/21] selftests/exec: test the transparent binfmt_misc mode --- commit f9d24508b6065861653a1b024a163b3671852433
Author: Christian Brauner <[email protected]>

selftests/exec: test the transparent binfmt_misc mode

This commit adds tests for the transparent binfmt_misc mode, verifying the identity a transparent dispatch constructs from both activation paths. It introduces a static transparent binfmt_misc test and a bpf-backed handler test.

Quoted 5 lines
tools/testing/selftests/exec/binfmt_misc_transparent.c new file +0 -0
new file mode 100644
index 0000000000000..de59dc8c5695e

[ ... ]

tools/testing/selftests/exec/binfmt_misc_transparent.c line 32

Quoted 7 lines
tools/testing/selftests/exec/binfmt_misc_transparent.c new file +7 -0
+/* The target only has to carry the magic; it is never actually loaded. */
+static int create_target(void)
+{
+	char buf[128] = MAGIC "\n";
+	int fd;
+
+	fd = open(TARGET_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0755);

[Severity: High]
Does creating predictable temporary files in /tmp without O_EXCL while requiring root execution introduce a TOCTOU race or arbitrary file truncation vulnerability?

If a local unprivileged attacker pre-creates TARGET_PATH (/tmp/binfmt_transparent_target) as a symlink before this test runs, could they truncate arbitrary system files?

Furthermore, since this file is later executed as root via execl() in TEST_F(transparent, dispatch):

    if (pid == 0) {
        execl(TARGET_PATH, TRANSPARENT_ARGV0, "argone", "argtwo", (char *)NULL);

could an attacker swap the contents of this predictable file just before execution to achieve local privilege escalation?

[ ... ]

Quoted 5 lines
tools/testing/selftests/exec/binfmt_transparent_interp.c new file +0 -0
new file mode 100644
index 0000000000000..2a71c47067582

[ ... ]

Quoted 2 lines
tools/testing/selftests/exec/binfmt_transparent_interp.c new file +2 -0
+int main(int argc, char **argv)
+{

[ ... ]

tools/testing/selftests/exec/binfmt_transparent_interp.c line 72

Quoted 7 lines
tools/testing/selftests/exec/binfmt_transparent_interp.c new file +7 -0
+	/* AT_EXECFD refers to the very file that was executed. */
+	execfd = getauxval(AT_EXECFD);
+	ok(execfd > 2, "no AT_EXECFD");
+	ok(!stat(binary, &stb), "cannot stat the binary");
+	ok(!fstat((int)execfd, &stfd), "cannot fstat AT_EXECFD");
+	ok(stb.st_dev == stfd.st_dev && stb.st_ino == stfd.st_ino,
+	   "AT_EXECFD is not the binary");

[Severity: Medium]
Since the ok() helper logs an error but does not abort execution, what happens if stat() or fstat() fail here?

Does this lead to reading uninitialized memory from the stb and stfd structs during the stb.st_dev == stfd.st_dev comparison?

[ ... ]

tools/testing/selftests/exec/binfmt_transparent_interp.c line 93

Quoted 7 lines
tools/testing/selftests/exec/binfmt_transparent_interp.c new file +7 -0
+	/* And so did the kernel's copy of it: the same strings, NUL separated. */
+	for (i = 0, expect_len = 0; i < ARRAY_SIZE(want); i++) {
+		size_t len = strlen(want[i]) + 1;
+
+		memcpy(expect + expect_len, want[i], len);
+		expect_len += len;
+	}

[Severity: Medium]
Is there a risk of a stack buffer overflow here if extremely long environment variables are passed to the test interpreter?

The want array is populated from BINFMT_TEST_BINARY and BINFMT_TEST_ARGV0. Since expect is a fixed-size stack buffer (PATH_MAX + 32) and there is no bounds checking before this memcpy() in main(), could an attacker overflow the buffer by invoking the interpreter directly with oversized environment variables?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260721-work-bpf-binfmt_misc-ptinterp-v2-0-e57866e4ae0f@kernel.org?part=13
#28 lore raw

Re: [PATCH v2 14/21] binfmt_misc: document the transparent identity contract

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Documentation incorrectly claims PR_SET_MM_MAP requires privileges to retarget auxv and memory…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Documentation incorrectly claims PR_SET_MM_MAP requires privileges to retarget auxv and memory markers. --

--- Patch [14]: [PATCH v2 14/21] binfmt_misc: document the transparent identity contract --- commit ca9e0f57f6063d4c7be0eda47389dcf9a21a1409
Author: Christian Brauner <[email protected]>

binfmt_misc: document the transparent identity contract

This commit documents the transparent interpreter contract for binfmt_misc, describing how arguments are preserved, how the binary is passed via AT_EXECFD, and the roles of the interpreter and program during loading.

Quoted 4 lines
Documentation/admin-guide/binfmt-misc.rst +0 -0
index 81b78e315fad8..ea1c1c0676c88 100644

[ ... ]

Documentation/admin-guide/binfmt-misc.rst binfmt_misc instances themselves are looked up. The entry keeps the handler · line 228

Quoted 7 lines
Documentation/admin-guide/binfmt-misc.rst +6 -0
@@ -223,6 +223,36 @@ binfmt_misc instances themselves are looked up. The entry keeps the handler
+code/data statistics markers via one ``PR_SET_MM_MAP`` which completes
+what attaching debuggers observe. The prctl is privileged - it takes
+``CONFIG_CHECKPOINT_RESTORE`` plus ``CAP_CHECKPOINT_RESTORE`` or
+``CAP_SYS_ADMIN`` in the caller's user namespace - so a loader running
+without these leaves the aux vector and the markers as the kernel set
+them. What remains visibly different from a direct

[Severity: Medium]
Is this documentation accurate regarding the privilege requirements for PR_SET_MM_MAP?

Looking at prctl_set_mm_map(), the checkpoint_restore_ns_capable() check is explicitly skipped if the provided prctl_map.exe_fd is -1.

Because a transparent interpreter already has /proc/pid/exe correctly labeled by the kernel, the loader shouldn't need to change the exe_fd.

Doesn't this mean a loader can successfully retarget the auxv and memory markers completely unprivileged by simply passing exe_fd = -1?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260721-work-bpf-binfmt_misc-ptinterp-v2-0-e57866e4ae0f@kernel.org?part=14
#14 lore raw

Re: [PATCH v2 07/21] selftests/exec: convert the binfmt_misc bpf test to the kselftest harness

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

New issues:
- [Medium] FIXTURE_SETUP unconditionally mounts the bpf filesystem, leaking stacked mounts in the host mount namespace for every executed test case.

Pre-existing issues:
- [High] The selftest runs as root, uses predictable temporary paths without O_EXCL, and ignores the return value of mkdir, allowing a local unprivileged attacker to mount a symlink attack to overwrite arbitrary files. --

--- Patch [7]: [PATCH v2 07/21] selftests/exec: convert the binfmt_misc bpf test to the kselftest harness --- commit d2f3d4f22570fe58bd70c6c3a7484277cc3de4f4
Author: Christian Brauner <[email protected]>

selftests/exec: convert the binfmt_misc bpf test to the kselftest harness

This commit converts the binfmt_misc bpf test to the kselftest harness. It introduces a fixture for common setup and teardown, replacing the open-coded main function and moving helpers to a shared header. The test cases are split into individual TEST_F blocks.

Quoted 4 lines
tools/testing/selftests/exec/binfmt_misc_bpf.c +0 -0
index cb89d2766fe2a..dd541c0a464da 100644

[ ... ]

Quoted 11 lines
tools/testing/selftests/exec/binfmt_misc_bpf.c +5 -1
@@ -186,92 +139,76 @@ static int run_case(const char *objfile, const char *handler,
 	return ret;
 }
 
-int main(void)
+FIXTURE(bpf_handler) {
+	char obj[PATH_MAX];	/* struct_ops object of the case under test */
+};
+
+FIXTURE_SETUP(bpf_handler)
 {

[ ... ]

tools/testing/selftests/exec/binfmt_misc_bpf.c static int run_case(const char *objfile, const char *handler, · line 167

Quoted 3 lines
tools/testing/selftests/exec/binfmt_misc_bpf.c +0 -0
 	if (stat("/sys/fs/bpf", &st) < 0)
 		mkdir("/sys/fs/bpf", 0755);
 	mount("bpf", "/sys/fs/bpf", "bpf", 0, NULL);

[Severity: Medium]
Since FIXTURE_SETUP is executed prior to every test case, doesn't this unconditionally mount the bpf filesystem without unsharing the mount namespace?

Since there is no corresponding umount in FIXTURE_TEARDOWN, this seems to leak a stacked mount on the host's /sys/fs/bpf directory for every test case executed.

Quoted 4 lines
tools/testing/selftests/exec/binfmt_misc_bpf.c +2 -2
-	if (access(BINFMT_REG, F_OK) < 0)
-		mount("binfmt_misc", "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, NULL);
+	if (!binfmt_misc_available())
+		SKIP(return, "no binfmt_misc");

[ ... ]

tools/testing/selftests/exec/binfmt_misc_bpf.c static int run_case(const char *objfile, const char *handler, · line 197

Quoted 8 lines
tools/testing/selftests/exec/binfmt_misc_bpf.c +4 -2
+/* A "$ORIGIN/..." PT_INTERP resolved to an interpreter next to the binary. */
+TEST_F(bpf_handler, origin_relative_interpreter)
+{
+	char src[PATH_MAX], app[PATH_MAX], interp[PATH_MAX];
 
-	/* Case 2: $ORIGIN-relative PT_INTERP -> co-located interpreter. */
-	printf("[*] case 2: $ORIGIN interpreter resolved relative to the binary\n");
 	mkdir(RELOC_DIR, 0755);

[Severity: High]
This is a pre-existing issue, but does ignoring the return value of mkdir() here allow a local symlink attack?

Because the test requires root privileges and uses predictable paths in /tmp/ (like RELOC_DIR), an unprivileged attacker could pre-create /tmp/binfmt_reloc/ and place a symlink inside it (e.g., app -> /etc/shadow).

Since the attacker owns the pre-created directory, it bypasses the fs.protected_symlinks and fs.protected_regular sysctl mitigations.

Quoted 5 lines
tools/testing/selftests/exec/binfmt_misc_bpf.c +5 -0
+	snprintf(app, sizeof(app), "%s/app", RELOC_DIR);
+	snprintf(interp, sizeof(interp), "%s/binfmt_bpf_interp", RELOC_DIR);
+	ASSERT_EQ(artifact_path(src, sizeof(src), "binfmt_bpf_app"), 0);
+	ASSERT_EQ(copy_file(src, app), 0);
+	ASSERT_EQ(copy_file(INTERP_PATH, interp), 0);

[ ... ]

Quoted 6 lines
tools/testing/selftests/exec/binfmt_misc_common.h new file +0 -0
new file mode 100644
index 0000000000000..854c7a6d34e17
@@ -0,0 +1,98 @@

[ ... ]

tools/testing/selftests/exec/binfmt_misc_common.h line 28

Quoted 10 lines
tools/testing/selftests/exec/binfmt_misc_common.h new file +10 -0
+static inline int copy_file(const char *src, const char *dst)
+{
+	char buf[4096];
+	int in, out;
+	ssize_t n;
+
+	in = open(src, O_RDONLY);
+	if (in < 0)
+		return -1;
+	out = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0755);

[Severity: High]
This is a pre-existing issue, but does opening the file without O_EXCL allow the symlink to be followed and the target file truncated?

If an attacker pre-creates the symlink in RELOC_DIR, when the root-executed test opens the predictable path without O_EXCL, it will follow the symlink and truncate the target file, leading to local privilege escalation or denial of service.

Quoted 4 lines
tools/testing/selftests/exec/binfmt_misc_common.h new file +4 -0
+	if (out < 0) {
+		close(in);
+		return -1;
+	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260721-work-bpf-binfmt_misc-ptinterp-v2-0-e57866e4ae0f@kernel.org?part=7
#18 lore raw

Re: [PATCH v2 10/21] binfmt_misc: add transparent interpreter dispatch

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Contradiction between commit message and code regarding `bprm->interp` modification in…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Contradiction between commit message and code regarding bprm->interp modification in transparent execution mode. --

--- Patch [10]: [PATCH v2 10/21] binfmt_misc: add transparent interpreter dispatch --- commit 6ffbfe6dc985c69faed5889214a86663cd8cbca7
Author: Christian Brauner <[email protected]>

binfmt_misc: add transparent interpreter dispatch

This commit adds a transparent mode to binfmt_misc, where the binary is passed to the interpreter via AT_EXECFD without modifying the argument vector or bprm->interp. This aims to make the execution look like a direct execution of the binary to the application.

Quoted 4 lines
fs/binfmt_misc.c +0 -0
index 304109a5091f0..e5a17ca935cad 100644

[ ... ]

Quoted 1 line
fs/binfmt_misc.c +0 -0
@@ -458,21 +463,23 @@ static int load_misc_binary(struct linux_binprm *bprm)

[ ... ]

Quoted 8 lines
fs/binfmt_misc.c +3 -3
 	flags = entry_invocation_flags(fmt, bprm);
 
-	retval = build_interp_argv(bprm, interpreter, flags);
-	if (retval)
-		return retval;
+	/* No argv is built for a staged argument to land in. */
+	if ((flags & MISC_FMT_TRANSPARENT) && bprm->bpf_interp_arg)
+		return -EINVAL;

fs/binfmt_misc.c static int load_misc_binary(struct linux_binprm *bprm) · line 483

Quoted 10 lines
fs/binfmt_misc.c +7 -1
 
-	/* Update interp in case binfmt_script needs it. */
+	if (!(flags & MISC_FMT_TRANSPARENT)) {
+		retval = build_interp_argv(bprm, interpreter, flags);
+		if (retval)
+			return retval;
+	}
+
+	/* Update interp for the next round; sched_prepare_exec reports it. */
 	retval = bprm_change_interp(interpreter, bprm);

[Severity: Medium]
The commit message explicitly states: "The argument vector and bprm->interp are left exactly as the caller set them." Is this description accurate for transparent mode?

Looking at load_misc_binary(), bprm_change_interp() is called unconditionally, which updates bprm->interp to the transparent loader's path.

If the transparent loader happens to be a script, won't binfmt_script consume this updated bprm->interp and modify argv by replacing the original argv[0] with the loader script's path? Does this break the untouched argv promise for script loaders during transparent execution?

Quoted 3 lines
fs/binfmt_misc.c +0 -0
 	if (retval < 0)
 		return retval;
@@ -481,6 +488,10 @@ static int load_misc_binary(struct linux_binprm *bprm)
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260721-work-bpf-binfmt_misc-ptinterp-v2-0-e57866e4ae0f@kernel.org?part=10
#32 lore raw

Re: [PATCH v2 16/21] binfmt_elf: consume a stashed PT_INTERP substitute

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] `load_elf_binary` consumes `bprm->loader` but can later return `-ENOEXEC`, defeating the…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] load_elf_binary consumes bprm->loader but can later return -ENOEXEC, defeating the begin_new_exec safety net for fallback formats. --

--- Patch [16]: [PATCH v2 16/21] binfmt_elf: consume a stashed PT_INTERP substitute --- commit 1d03dfaf1de4f305ec2f86af4a17c4c21f4a7858
Author: Christian Brauner <[email protected]>

binfmt_elf: consume a stashed PT_INTERP substitute

When a binfmt_misc loader entry stashes bprm->loader, use it instead of opening the path named in PT_INTERP. A binary without PT_INTERP drops the override and is loaded natively.

Quoted 3 lines
fs/binfmt_elf.c +0 -0

[ ... ]

fs/binfmt_elf.c static int load_elf_binary(struct linux_binprm *bprm) · line 938

Quoted 8 lines
fs/binfmt_elf.c +3 -0
@@ -932,6 +932,9 @@ static int load_elf_binary(struct linux_binprm *bprm)
 		goto out_free_ph;
 	}
 
+	/* No PT_INTERP to substitute for: the override does not apply. */
+	bprm_drop_loader(bprm);
+
 	elf_ppnt = elf_phdata;

[Severity: Medium]
If load_elf_binary() consumes bprm->loader here (or earlier in bprm_open_interpreter()) but later returns -ENOEXEC, does this defeat the safety net for fallback formats?

For example, if parse_elf_properties() fails later in the function:

	retval = parse_elf_properties(interpreter ?: bprm->file,
				      elf_property_phdata, &arch_state);
	if (retval)
		goto out_free_dentry;

If this returns -ENOEXEC, load_elf_binary() will exit after the loader has been consumed (bprm->loader is now NULL).

Would this allow search_binary_handler() to fall back to the next format (like binfmt_elf_fdpic) which could then successfully execute the file natively, bypassing the intended loader override?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260721-work-bpf-binfmt_misc-ptinterp-v2-0-e57866e4ae0f@kernel.org?part=16
#21 lore raw

Re: [PATCH v2 11/21] binfmt_misc: add a static transparent flag 'T'

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] Unprivileged users can spoof `/proc/pid/exe` of arbitrary system binaries to bypass path-based…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Unprivileged users can spoof /proc/pid/exe of arbitrary system binaries to bypass path-based security mechanisms (like Polkit) using the new T (transparent) flag in a user namespace binfmt_misc mount. --

--- Patch [11]: [PATCH v2 11/21] binfmt_misc: add a static transparent flag 'T' --- commit b5f0e2f272e45d606e37bd2e4e198bd848f87a56
Author: Christian Brauner <[email protected]>
Subject: binfmt_misc: add a static transparent flag 'T'

This commit adds a 'T' flag to binfmt_misc registrations to allow transparent dispatch. The matched binary keeps its argument vector and is sent to the interpreter through AT_EXECFD, with the process identity set to the binary's identity rather than the interpreter's.

Quoted 4 lines
fs/binfmt_misc.c +0 -0
index e5a17ca935cad..71833b976131b 100644

[ ... ]

fs/binfmt_misc.c static struct binfmt_misc_entry *create_entry(const char __user *buffer, · line 772

Quoted 9 lines
fs/binfmt_misc.c +5 -0
@@ -764,6 +765,11 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags) && p != flags)
 		return ERR_PTR(-EINVAL);
 
+	/* Transparency preserves the whole argv, argv[0] included. */
+	if ((e->flags & MISC_FMT_TRANSPARENT) &&
+	    (e->flags & MISC_FMT_PRESERVE_ARGV0))
+		return ERR_PTR(-EINVAL);
+

[Severity: Critical]
Does this code allow an unprivileged user to spoof /proc/pid/exe for arbitrary system binaries?

Since binfmt_misc supports unprivileged user namespace mounts, could a local user mount it and register a handler using the new 'T' flag to match a privileged system binary?

If the 'C' flag is omitted, the execution wouldn't fail suid checks and the interpreter would run with unprivileged credentials. However, the transparent flag unconditionally sets BINPRM_FLAGS_TRANSPARENT_INTERP in load_misc_binary(), which later triggers execution paths where the privileged system binary becomes the identity file:

fs/exec.c:bprm_identity_file() {
    ...
    if (bprm->interp_flags & BINPRM_FLAGS_TRANSPARENT_INTERP)
        return bprm->executable;
    ...
}
fs/exec.c:begin_new_exec() {
    ...
    retval = set_mm_exe_file(bprm->mm, bprm_identity_file(bprm));
    ...
}

Could this bypass path-based authorization checks in system services like Polkit by masquerading the unprivileged interpreter as a trusted system binary, essentially circumventing the capable(CAP_SYS_RESOURCE) check normally required to change mm->exe_file?

Quoted 3 lines
fs/binfmt_misc.c +0 -0
 	if (*p == '\n')
 		p++;
 	if (p != buf + count)
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260721-work-bpf-binfmt_misc-ptinterp-v2-0-e57866e4ae0f@kernel.org?part=11
author maintainer
#22 lore raw

Re: [PATCH v2 11/21] binfmt_misc: add a static transparent flag 'T'

Quoted 56 lines · On Tue, Jul 21, 2026 at 02:39:34PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Unprivileged users can spoof /proc/pid/exe of arbitrary system binaries to bypass path-based security mechanisms (like Polkit) using the new T (transparent) flag in a user namespace binfmt_misc mount. --

--- Patch [11]: [PATCH v2 11/21] binfmt_misc: add a static transparent flag 'T' --- commit b5f0e2f272e45d606e37bd2e4e198bd848f87a56
Author: Christian Brauner <[email protected]>
Subject: binfmt_misc: add a static transparent flag 'T'

This commit adds a 'T' flag to binfmt_misc registrations to allow transparent dispatch. The matched binary keeps its argument vector and is sent to the interpreter through AT_EXECFD, with the process identity set to the binary's identity rather than the interpreter's.

Quoted 4 lines
fs/binfmt_misc.c +0 -0
index e5a17ca935cad..71833b976131b 100644

[ ... ]

fs/binfmt_misc.c static struct binfmt_misc_entry *create_entry(const char __user *buffer, · line 772

Quoted 9 lines
fs/binfmt_misc.c +5 -0
@@ -764,6 +765,11 @@ static struct binfmt_misc_entry *create_entry(const char __user *buffer,
 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags) && p != flags)
 		return ERR_PTR(-EINVAL);
 
+	/* Transparency preserves the whole argv, argv[0] included. */
+	if ((e->flags & MISC_FMT_TRANSPARENT) &&
+	    (e->flags & MISC_FMT_PRESERVE_ARGV0))
+		return ERR_PTR(-EINVAL);
+

[Severity: Critical]
Does this code allow an unprivileged user to spoof /proc/pid/exe for arbitrary system binaries?

Since binfmt_misc supports unprivileged user namespace mounts, could a local user mount it and register a handler using the new 'T' flag to match a privileged system binary?

If the 'C' flag is omitted, the execution wouldn't fail suid checks and the interpreter would run with unprivileged credentials. However, the transparent flag unconditionally sets BINPRM_FLAGS_TRANSPARENT_INTERP in load_misc_binary(), which later triggers execution paths where the privileged system binary becomes the identity file:

fs/exec.c:bprm_identity_file() {
    ...
    if (bprm->interp_flags & BINPRM_FLAGS_TRANSPARENT_INTERP)
        return bprm->executable;
    ...
}
fs/exec.c:begin_new_exec() {
    ...
    retval = set_mm_exe_file(bprm->mm, bprm_identity_file(bprm));
    ...
}
Quoted 4 lines

Could this bypass path-based authorization checks in system services like Polkit by masquerading the unprivileged interpreter as a trusted system binary, essentially circumventing the capable(CAP_SYS_RESOURCE) check normally required to change mm->exe_file?

/proc/self/exe is trivially fakeable by using PR_SET_MM_MAP which is available in user namespaces. CRIU is building on that.

author maintainer
#26 lore raw

Re: [PATCH v2 13/21] selftests/exec: test the transparent binfmt_misc mode

In reply to [email protected]
Quoted 4 lines · On Tue, Jul 21, 2026 at 02:25:16PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Insecure usage of predictable /tmp files without O_EXCL enables Local Privilege Escalation via arbitrary file truncation and TOCTOU race condition.
- [Medium] Continuing execution after stat/fstat failure leads to uninitialized memory read.
- [Medium] Stack-based buffer overflow in the test interpreter when copying environment variables.

This is a selftest, not the actual code. It doesn't have to defend against obvious abuse.

author maintainer
#29 lore raw

Re: [PATCH v2 14/21] binfmt_misc: document the transparent identity contract

In reply to [email protected]
Quoted 33 lines · On Tue, Jul 21, 2026 at 02:26:20PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Documentation incorrectly claims PR_SET_MM_MAP requires privileges to retarget auxv and memory markers. --

--- Patch [14]: [PATCH v2 14/21] binfmt_misc: document the transparent identity contract --- commit ca9e0f57f6063d4c7be0eda47389dcf9a21a1409
Author: Christian Brauner <[email protected]>

binfmt_misc: document the transparent identity contract

This commit documents the transparent interpreter contract for binfmt_misc, describing how arguments are preserved, how the binary is passed via AT_EXECFD, and the roles of the interpreter and program during loading.

Quoted 4 lines
Documentation/admin-guide/binfmt-misc.rst +0 -0
index 81b78e315fad8..ea1c1c0676c88 100644

[ ... ]

Documentation/admin-guide/binfmt-misc.rst binfmt_misc instances themselves are looked up. The entry keeps the handler · line 228

Quoted 7 lines
Documentation/admin-guide/binfmt-misc.rst +6 -0
@@ -223,6 +223,36 @@ binfmt_misc instances themselves are looked up. The entry keeps the handler
+code/data statistics markers via one ``PR_SET_MM_MAP`` which completes
+what attaching debuggers observe. The prctl is privileged - it takes
+``CONFIG_CHECKPOINT_RESTORE`` plus ``CAP_CHECKPOINT_RESTORE`` or
+``CAP_SYS_ADMIN`` in the caller's user namespace - so a loader running
+without these leaves the aux vector and the markers as the kernel set
+them. What remains visibly different from a direct

[Severity: Medium]
Is this documentation accurate regarding the privilege requirements for PR_SET_MM_MAP?

Quoted 8 lines

Looking at prctl_set_mm_map(), the checkpoint_restore_ns_capable() check is explicitly skipped if the provided prctl_map.exe_fd is -1.

Because a transparent interpreter already has /proc/pid/exe correctly labeled by the kernel, the loader shouldn't need to change the exe_fd.

Doesn't this mean a loader can successfully retarget the auxv and memory markers completely unprivileged by simply passing exe_fd = -1?

This is correct. Not sure how this escaped me and my automated review. Thanks. I'll fold that fix in.

author maintainer
#19 lore raw

Re: [PATCH v2 10/21] binfmt_misc: add transparent interpreter dispatch

In reply to [email protected]
Quoted 4 lines

If the transparent loader happens to be a script, won't binfmt_script consume this updated bprm->interp and modify argv by replacing the original argv[0] with the loader script's path? Does this break the untouched argv promise for script loaders during transparent execution?

Yeah, but that's binfmt_script's whole job. The point is that binfmt_misc doesn't touch argv, not that binfmt_script doesn't.

author maintainer
#33 lore raw

Re: [PATCH v2 16/21] binfmt_elf: consume a stashed PT_INTERP substitute

In reply to [email protected]
Quoted 39 lines · On Tue, Jul 21, 2026 at 02:38:58PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] load_elf_binary consumes bprm->loader but can later return -ENOEXEC, defeating the begin_new_exec safety net for fallback formats. --

--- Patch [16]: [PATCH v2 16/21] binfmt_elf: consume a stashed PT_INTERP substitute --- commit 1d03dfaf1de4f305ec2f86af4a17c4c21f4a7858
Author: Christian Brauner <[email protected]>

binfmt_elf: consume a stashed PT_INTERP substitute

When a binfmt_misc loader entry stashes bprm->loader, use it instead of opening the path named in PT_INTERP. A binary without PT_INTERP drops the override and is loaded natively.

Quoted 3 lines
fs/binfmt_elf.c +0 -0

[ ... ]

fs/binfmt_elf.c static int load_elf_binary(struct linux_binprm *bprm) · line 938

Quoted 8 lines
fs/binfmt_elf.c +3 -0
@@ -932,6 +932,9 @@ static int load_elf_binary(struct linux_binprm *bprm)
 		goto out_free_ph;
 	}
 
+	/* No PT_INTERP to substitute for: the override does not apply. */
+	bprm_drop_loader(bprm);
+
 	elf_ppnt = elf_phdata;

[Severity: Medium]
If load_elf_binary() consumes bprm->loader here (or earlier in bprm_open_interpreter()) but later returns -ENOEXEC, does this defeat the safety net for fallback formats?

For example, if parse_elf_properties() fails later in the function:

	retval = parse_elf_properties(interpreter ?: bprm->file,
				      elf_property_phdata, &arch_state);
	if (retval)
		goto out_free_dentry;
Quoted 6 lines

If this returns -ENOEXEC, load_elf_binary() will exit after the loader has been consumed (bprm->loader is now NULL).

Would this allow search_binary_handler() to fall back to the next format (like binfmt_elf_fdpic) which could then successfully execute the file natively, bypassing the intended loader override?

If there's no PT_INTERP for the binary we have no business with it and hence elf fdpic doesn't.

#39 lore raw
In reply to Christian Brauner
Quoted 7 lines · Christian Brauner

[...]

 tools/testing/selftests/exec/loader.bpf.c          |  56 ++++
 tools/testing/selftests/exec/transparent.bpf.c     |  57 ++++
 19 files changed, 1823 insertions(+), 303 deletions(-)

---
base-commit: 6cea93ff6fe97df34b63fe94487473e16c73b74b
change-id: 20260719-work-bpf-binfmt_misc-ptinterp-e6ee99ff6ba8

Started to review (slowly); looks like the first ~10 are mostly NFC / refactor / documentation.

This b4 thing is so slick; I want something like this for GitHub now.

Signature · 1 line
Farid Zakaria <[email protected]>
Reviewed-by on v2 1/21
#2 lore raw

Re: [PATCH v2 01/21] binfmt_misc: require an absolute interpreter path with 'C'

In reply to Christian Brauner
Quoted 8 lines · Christian Brauner

A 'C' entry computes the credentials from the matched binary instead of from the interpreter. So a set*id binary hands its credentials to whatever the entry names as its interpreter.

Without 'F' that interpreter is not opened until the exec happens and open_exec() resolves the path relative to the current working directory.

[...]

Signature · 1 line
Farid Zakaria <[email protected]>
Reviewed-by on v2 2/21
#4 lore raw

Re: [PATCH v2 02/21] docs, binfmt_misc: keep general usage out of the handler sections

In reply to Christian Brauner
Quoted 9 lines · Christian Brauner

The general usage trails the bpf-backed handlers section and therefore reads as part of it. It predates that section and applies to binfmt_misc as a whole.

Move it back up so the handler section ends where the file does. Upcoming sections describing the transparent and loader dispatch modes append after it without swallowing the general prose again.

[...]

Signature · 1 line
Farid Zakaria <[email protected]>
Reviewed-by on v2 3/21
#6 lore raw

Re: [PATCH v2 03/21] binfmt_misc: table-drive the register string flags

In reply to Christian Brauner

On Tue, 21 Jul 2026 16:13:45 +0200, Christian Brauner <[email protected]> wrote:

Nice sensible refactor.

fs/binfmt_misc.c enum binfmt_misc_entry_flags { · line 68

Quoted 13 lines
fs/binfmt_misc.c +0 -0
index bfe30fe53..c0a3b42a3 100644
@@ -51,6 +52,36 @@ enum binfmt_misc_entry_flags {

[ ... skip 11 lines ... ]

fs/binfmt_misc.c +6 -0
+	char		c;
+	unsigned long	flag;
+	unsigned long	implies;
+	const char	*desc;
+};
+

I know this is a direct 1:1 of the doc but implies seems unecessary rather than on a single flags field.

Quoted 5 lines
fs/binfmt_misc.c +0 -1
@@ -749,14 +766,9 @@ static int bm_entry_show(struct seq_file *m, void *unused)
 
 	/* print the special flags */
 	seq_puts(m, "flags: ");
-	if (e->flags & MISC_FMT_PRESERVE_ARGV0)

fs/binfmt_misc.c static int bm_entry_show(struct seq_file *m, void *unused) · line 771

Quoted 10 lines
fs/binfmt_misc.c +3 -7
-		seq_putc(m, 'P');
-	if (e->flags & MISC_FMT_OPEN_BINARY)
-		seq_putc(m, 'O');
-	if (e->flags & MISC_FMT_CREDENTIALS)
-		seq_putc(m, 'C');
-	if (e->flags & MISC_FMT_OPEN_FILE)
-		seq_putc(m, 'F');
+	for (int i = 0; i < ARRAY_SIZE(misc_flags); i++)
+		if (e->flags & misc_flags[i].flag)
+			seq_putc(m, misc_flags[i].c);

Should this check for implies?

Signature · 1 line
Farid Zakaria <[email protected]>
Reviewed-by on v2 4/21
#8 lore raw

Re: [PATCH v2 04/21] binfmt_misc: normalize the per-exec invocation flags

In reply to Christian Brauner
Quoted 11 lines · Christian Brauner

A static entry fixes its invocation flags at registration. A 'B' entry's load program picks them per exec. Since load_misc_binary() branches on which kind of entry matched and then applies the two flag sets side by side every flag is handled twice and each new one has to be added to both arms.

Translate the 'B' flags into the entry flags they mirror and let the dispatch act on a single set of flags. The boolean the two arms communicated 'P' can be removed.

[...]

Signature · 1 line
Farid Zakaria <[email protected]>
Reviewed-by on v2 5/21
#10 lore raw

Re: [PATCH v2 05/21] binfmt_misc: split out entry_open_interpreter() and build_interp_argv()

In reply to Christian Brauner
Quoted 6 lines · Christian Brauner

Opening the interpreter is a property of the matched entry: an 'F' entry hands out a clone of the file it pre-opened at registration time, any other entry opens the selected path. Give that its own helper instead of an if/else in the middle of load_misc_binary(), and let it fail early rather than carrying an ERR_PTR through the successful branch.

Quoted 7 lines

Building the interpreter's argument vector is the bulk of what remains and the one part of load_misc_binary() that is specific to the classic dispatch. Move it into its own helper too, so the dispatch reads as what it is: pick a handler, pick an interpreter, build the invocation, open it.

[...]

Signature · 1 line
Farid Zakaria <[email protected]>
Reviewed-by on v2 6/21
#12 lore raw

Re: [PATCH v2 06/21] exec: release the replaced file with do_close_execat()

In reply to Christian Brauner

# Add your code comments below. There is no need to trim or delete

# any existing content -- just insert your comments under the relevant
# lines of code. Lines starting with "> " are quoted diff context and
# lines starting with "| " are comments from other reviewers.
# The final email will be reformatted automatically to include only
# the sections that have your comments.
#
Quoted 28 lines

When the format search stages an interpreter exec_binprm() swaps it in and releases the file it replaces. Dropping the write denial the open took is done manually ahead of both release paths. The one path that keeps the file silently relies on it not being called.

Let's just use do_close_execat() on the two paths that release the file and drop the denial explicitly on the one that does not.

No functional change.

fs/exec.c +2 -2
index 41e1684d9..061e0f9fb 100644
@@ -1735,15 +1735,17 @@ static int exec_binprm(struct linux_binprm *bprm)
 		bprm->file = bprm->interpreter;
 		bprm->interpreter = NULL;
 
-		exe_file_allow_write_access(exec);
 		if (unlikely(bprm->have_execfd)) {
 			if (bprm->executable) {
-				fput(exec);
+				do_close_execat(exec);
 				return -ENOEXEC;
 			}
+			/* Only the reference is kept, for AT_EXECFD. */

fs/exec.c static int exec_binprm(struct linux_binprm *bprm) · line 1751

Quoted 10 lines
fs/exec.c +4 -2
+			exe_file_allow_write_access(exec);
 			bprm->executable = exec;
-		} else
-			fput(exec);
+		} else {
+			do_close_execat(exec);
+		}
 	}
 
 	audit_bprm(bprm);
Signature · 1 line
Farid Zakaria <[email protected]>
author maintainer
#40 lore raw
In reply to Farid Zakaria
Quoted 9 lines · Farid Zakaria
Quoted 7 lines · Christian Brauner

[...]

 tools/testing/selftests/exec/loader.bpf.c          |  56 ++++
 tools/testing/selftests/exec/transparent.bpf.c     |  57 ++++
 19 files changed, 1823 insertions(+), 303 deletions(-)

---
base-commit: 6cea93ff6fe97df34b63fe94487473e16c73b74b
change-id: 20260719-work-bpf-binfmt_misc-ptinterp-e6ee99ff6ba8

Quoted 4 lines

Started to review (slowly); looks like the first ~10 are mostly NFC / refactor / documentation.

This b4 thing is so slick; I want something like this for GitHub now.

You're not the only one. :)