xref: /linux/fs/binfmt_misc.c (revision 550a7e28d801d35dd23aa2cdd30b7a59e193e080)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * binfmt_misc.c
4  *
5  * Copyright (C) 1997 Richard Günther
6  *
7  * binfmt_misc detects binaries via a magic or filename extension and invokes
8  * a specified wrapper. See Documentation/admin-guide/binfmt-misc.rst for more details.
9  */
10 
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/array_size.h>
14 #include <linux/binfmt_misc.h>
15 #include <linux/binfmts.h>
16 #include <linux/bitops.h>
17 #include <linux/bits.h>
18 #include <linux/bug.h>
19 #include <linux/cleanup.h>
20 #include <linux/cred.h>
21 #include <linux/ctype.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/fs_context.h>
25 #include <linux/init.h>
26 #include <linux/kstrtox.h>
27 #include <linux/limits.h>
28 #include <linux/list.h>
29 #include <linux/magic.h>
30 #include <linux/module.h>
31 #include <linux/printk.h>
32 #include <linux/rculist.h>
33 #include <linux/refcount.h>
34 #include <linux/seq_file.h>
35 #include <linux/slab.h>
36 #include <linux/srcu.h>
37 #include <linux/string.h>
38 #include <linux/string_helpers.h>
39 #include <linux/uaccess.h>
40 #include <linux/user_namespace.h>
41 
42 #include "internal.h"
43 
44 /* Entry status and match type bit numbers. */
45 enum binfmt_misc_entry_bits {
46 	MISC_FMT_ENABLED_BIT	= 0,
47 	MISC_FMT_MAGIC_BIT	= 1,
48 	MISC_FMT_BPF_BIT	= 2,
49 };
50 
51 /* Entry behavior flags, fixed at registration time. */
52 enum binfmt_misc_entry_flags {
53 	MISC_FMT_PRESERVE_ARGV0	= (1U << 31),
54 	MISC_FMT_OPEN_BINARY	= (1U << 30),
55 	MISC_FMT_CREDENTIALS	= (1U << 29),
56 	MISC_FMT_OPEN_FILE	= (1U << 28),
57 	MISC_FMT_TRANSPARENT	= (1U << 27),
58 	MISC_FMT_LOADER		= (1U << 26),
59 	MISC_FMT_DISABLED	= (1U << 25),
60 };
61 
62 /* The flags that shape the invocation; a 'B' handler picks those per exec. */
63 #define MISC_FMT_INVOCATION_FLAGS (MISC_FMT_PRESERVE_ARGV0 |	\
64 				   MISC_FMT_OPEN_BINARY |	\
65 				   MISC_FMT_CREDENTIALS |	\
66 				   MISC_FMT_OPEN_FILE |		\
67 				   MISC_FMT_TRANSPARENT |	\
68 				   MISC_FMT_LOADER)
69 
70 /**
71  * struct binfmt_misc_flag - a flag character of the register string
72  * @c: the character userspace writes and reads back
73  * @flag: the entry flag it sets
74  * @implies: entry flags it turns on in addition
75  * @desc: what it does, for the registration debug output
76  */
77 struct binfmt_misc_flag {
78 	char		c;
79 	unsigned long	flag;
80 	unsigned long	implies;
81 	const char	*desc;
82 };
83 
84 static const struct binfmt_misc_flag misc_flags[] = {
85 	{ 'P', MISC_FMT_PRESERVE_ARGV0,	0,			"preserve argv0"		},
86 	{ 'O', MISC_FMT_OPEN_BINARY,	0,			"open binary"			},
87 	{ 'C', MISC_FMT_CREDENTIALS,	MISC_FMT_OPEN_BINARY,	"credentials from the binary"	},
88 	{ 'F', MISC_FMT_OPEN_FILE,	0,			"open interpreter file now"	},
89 	{ 'T', MISC_FMT_TRANSPARENT,	MISC_FMT_OPEN_BINARY,	"transparent"			},
90 	{ 'L', MISC_FMT_LOADER,		0,			"loader substitution"		},
91 	{ 'D', MISC_FMT_DISABLED,	0,			"register disabled"		},
92 };
93 
94 /* Look up a flag character, NULL if @c is not one. */
misc_flag_by_char(const char c)95 static const struct binfmt_misc_flag *misc_flag_by_char(const char c)
96 {
97 	for (int i = 0; i < ARRAY_SIZE(misc_flags); i++)
98 		if (misc_flags[i].c == c)
99 			return &misc_flags[i];
100 	return NULL;
101 }
102 
misc_valid_delim(const char c)103 static bool misc_valid_delim(const char c)
104 {
105 	if (!isascii(c) || !ispunct(c))
106 		return false;
107 	return c != '\\';
108 }
109 
110 struct binfmt_misc_entry {
111 	struct hlist_node node;
112 	unsigned long flags;		/* type, status, etc. */
113 	int offset;			/* offset of magic */
114 	int size;			/* size of magic/mask */
115 	char *magic;			/* magic or filename extension */
116 	char *mask;			/* mask, NULL for exact match */
117 	const char *interpreter;	/* filename of interpreter */
118 	char *name;
119 	struct dentry *dentry;
120 	const struct binfmt_misc_ops *bpf_ops;	/* bpf-backed handler ('B') */
121 	const char *bpf_ops_name;
122 	struct list_head interps;	/* the interpreters it bound */
123 	refcount_t users;		/* sync removal with load_misc_binary() */
124 	struct rcu_head rcu;
125 	char buf[];			/* register string, fields point in here */
126 };
127 
128 /*
129  * Max length of the register string.  Determined by:
130  *  - 7 delimiters
131  *  - name:   ~50 bytes
132  *  - type:   1 byte
133  *  - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE)
134  *  - magic:  128 bytes (512 in escaped form)
135  *  - mask:   128 bytes (512 in escaped form)
136  *  - interp: ~50 bytes
137  *  - flags:  5 bytes
138  * Round that up a bit, and then back off to hold the internal data
139  * (like struct binfmt_misc_entry).
140  */
141 #define MAX_REGISTER_LENGTH 1920
142 
143 /* Trailing delimiter pad so field parsing always terminates at a delimiter. */
144 #define MISC_DELIM_PAD 8
145 
146 /* Protects the entry walk in load_misc_binary(), which may sleep in it. */
147 DEFINE_STATIC_SRCU_FAST(bm_entries_srcu);
148 
149 /* Check if @e's magic matches @bprm's buffer, applying the mask if set. */
entry_matches_magic(const struct binfmt_misc_entry * e,const struct linux_binprm * bprm)150 static bool entry_matches_magic(const struct binfmt_misc_entry *e,
151 				const struct linux_binprm *bprm)
152 {
153 	const char *s = bprm->buf + e->offset;
154 	int i;
155 
156 	if (!e->mask)
157 		return !memcmp(s, e->magic, e->size);
158 
159 	for (i = 0; i < e->size; i++)
160 		if ((s[i] ^ e->magic[i]) & e->mask[i])
161 			return false;
162 	return true;
163 }
164 
165 /* Check if @e's registered extension matches @ext, NULL if there is none. */
entry_matches_extension(const struct binfmt_misc_entry * e,const char * ext)166 static bool entry_matches_extension(const struct binfmt_misc_entry *e,
167 				    const char *ext)
168 {
169 	return ext && !strcmp(e->magic, ext);
170 }
171 
172 /**
173  * search_binfmt_handler - search for a binary handler for @bprm
174  * @misc: handle to binfmt_misc instance
175  * @bprm: binary for which we are looking for a handler
176  *
177  * Search for a binary type handler for @bprm in the list of registered binary
178  * type handlers. A 'B' entry's match program decides whether the handler
179  * applies; it may sleep to read the binary. The matched entry is returned
180  * with a reference taken while the walk still held it; a dying entry -
181  * unlinked with its last reference gone - cannot be matched and the walk
182  * moves on.
183  *
184  * The caller must hold the bm_entries_srcu read lock, which allows an
185  * entry's evaluation to sleep.
186  *
187  * Return: referenced binary type list entry on success, NULL on failure
188  */
189 static struct binfmt_misc_entry *
search_binfmt_handler(struct binfmt_misc * misc,struct linux_binprm * bprm)190 search_binfmt_handler(struct binfmt_misc *misc, struct linux_binprm *bprm)
191 {
192 	char *dot = strrchr(bprm->interp, '.');
193 	const char *ext = dot ? dot + 1 : NULL;
194 	struct binfmt_misc_entry *e;
195 
196 	/* Walk all the registered handlers. */
197 	hlist_for_each_entry_rcu(e, &misc->entries, node,
198 				 srcu_read_lock_held(&bm_entries_srcu)) {
199 		/*
200 		 * Make sure this one is currently enabled. An entry enters
201 		 * the list at most once and only whole: its configuration is
202 		 * ordered before the rcu insertion that makes it visible
203 		 * here.
204 		 */
205 		if (!test_bit(MISC_FMT_ENABLED_BIT, &e->flags))
206 			continue;
207 
208 		if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
209 			if (!e->bpf_ops->match(bprm))
210 				continue;
211 		} else if (test_bit(MISC_FMT_MAGIC_BIT, &e->flags)) {
212 			if (!entry_matches_magic(e, bprm))
213 				continue;
214 		} else {
215 			if (!entry_matches_extension(e, ext))
216 				continue;
217 		}
218 
219 		/* A dying entry cannot be matched, walk on. */
220 		if (refcount_inc_not_zero(&e->users))
221 			return e;
222 	}
223 
224 	return NULL;
225 }
226 
227 /**
228  * get_binfmt_handler - try to find a binary type handler
229  * @misc: handle to binfmt_misc instance
230  * @bprm: binary for which we are looking for a handler
231  *
232  * Try to find a binfmt handler for the binary type. If one is found it is
233  * returned with a reference protecting it against removal via
234  * bm_{entry,status}_write().
235  *
236  * Return: binary type list entry on success, NULL on failure
237  */
get_binfmt_handler(struct binfmt_misc * misc,struct linux_binprm * bprm)238 static struct binfmt_misc_entry *get_binfmt_handler(struct binfmt_misc *misc,
239 						    struct linux_binprm *bprm)
240 {
241 	guard(srcu_fast)(&bm_entries_srcu);
242 	return search_binfmt_handler(misc, bprm);
243 }
244 
245 /**
246  * binfmt_misc_find_interp - find a bound interpreter by name
247  * @interps: the interpreters the matched entry was registered with
248  * @name: the name to look for
249  *
250  * Return: the interpreter on success, NULL if @interps has none by that name
251  */
252 const struct binfmt_misc_interp *
binfmt_misc_find_interp(const struct list_head * interps,const char * name)253 binfmt_misc_find_interp(const struct list_head *interps, const char *name)
254 {
255 	struct binfmt_misc_interp *interp;
256 
257 	list_for_each_entry(interp, interps, list)
258 		if (!strcmp(interp->name, name))
259 			return interp;
260 	return NULL;
261 }
262 
263 /* Undo the open_exec() a pre-opened interpreter file came from. */
close_interp_file(struct file * f)264 static void close_interp_file(struct file *f)
265 {
266 	if (IS_ERR_OR_NULL(f))
267 		return;
268 	exe_file_allow_write_access(f);
269 	filp_close(f, NULL);
270 }
271 
DEFINE_FREE(close_interp_file,struct file *,close_interp_file (_T))272 DEFINE_FREE(close_interp_file, struct file *, close_interp_file(_T))
273 
274 /*
275  * Open an interpreter @path for execution: now, in the writer's context,
276  * and - since binfmt_misc mounts can be unprivileged - with @cred, the
277  * credentials the control file being written was opened with, not the
278  * writer's own.
279  */
280 static struct file *open_interp_file(const struct cred *cred, const char *path)
281 {
282 	struct file *f;
283 
284 	scoped_with_creds(cred)
285 		f = open_exec(path);
286 	if (IS_ERR(f))
287 		pr_notice("register: failed to install interpreter %s\n", path);
288 	return f;
289 }
290 
291 /* Release the interpreters an entry was registered with. */
entry_put_interpreters(struct binfmt_misc_entry * e)292 static void entry_put_interpreters(struct binfmt_misc_entry *e)
293 {
294 	struct binfmt_misc_interp *interp, *tmp;
295 
296 	list_for_each_entry_safe(interp, tmp, &e->interps, list) {
297 		list_del(&interp->list);
298 		close_interp_file(interp->file);
299 		dec_ucount(interp->ucounts, UCOUNT_BINFMT_MISC_INTERPRETERS);
300 		kfree(interp);
301 	}
302 }
303 
304 /**
305  * entry_attach_interpreter - bind an opened interpreter to @e
306  * @e: entry being configured
307  * @name: name the load program will select it by; empty for the fixed
308  *        interpreter of a static entry
309  * @path: the path @f was opened from
310  * @f: the interpreter, opened for execution
311  *
312  * Every exec runs a clone of @f, so the path decided which file is bound
313  * and nothing else: it is not resolved again, in any namespace.
314  *
315  * The caller has to have validated @name and @path, established that @e
316  * cannot be matched yet, and owns @f until this succeeds.
317  *
318  * Return: 0 on success, -ENOSPC if the entry is full or the binder is out of
319  *         UCOUNT_BINFMT_MISC_INTERPRETERS budget, a negative errno on failure
320  */
entry_attach_interpreter(struct binfmt_misc_entry * e,const char * name,const char * path,struct file * f)321 static int entry_attach_interpreter(struct binfmt_misc_entry *e,
322 				    const char *name, const char *path,
323 				    struct file *f)
324 {
325 	size_t nlen = strlen(name), plen = strlen(path);
326 	struct binfmt_misc_interp *interp;
327 	struct ucounts *ucounts;
328 
329 	if (binfmt_misc_find_interp(&e->interps, name))
330 		return -EEXIST;
331 	if (list_count_nodes(&e->interps) >= BINFMT_MISC_INTERP_MAX)
332 		return -ENOSPC;
333 
334 	/* The binding keeps a file open, so charge it to whoever binds it. */
335 	ucounts = inc_ucount(current_user_ns(), current_euid(),
336 			     UCOUNT_BINFMT_MISC_INTERPRETERS);
337 	if (!ucounts)
338 		return -ENOSPC;
339 
340 	/* One allocation, both strings in it, like the entry's own buffer. */
341 	interp = kmalloc_flex(*interp, name, nlen + plen + 2,
342 			      GFP_KERNEL_ACCOUNT);
343 	if (!interp) {
344 		dec_ucount(ucounts, UCOUNT_BINFMT_MISC_INTERPRETERS);
345 		return -ENOMEM;
346 	}
347 
348 	interp->path = interp->name + nlen + 1;
349 	strscpy(interp->name, name, nlen + 1);
350 	strscpy(interp->name + nlen + 1, path, plen + 1);
351 	interp->file = f;
352 	interp->ucounts = ucounts;
353 	/* Publish the node: a lockless cat may be walking the list. */
354 	list_add_tail_rcu(&interp->list, &e->interps);
355 	pr_debug("register: interpreter: %s {%s}\n", name, path);
356 	return 0;
357 }
358 
bm_entry_free_rcu(struct rcu_head * rcu)359 static void bm_entry_free_rcu(struct rcu_head *rcu)
360 {
361 	struct binfmt_misc_entry *e = container_of(rcu, struct binfmt_misc_entry, rcu);
362 
363 	/* No walker that could sleep in the handler's programs is left. */
364 	if (e->bpf_ops)
365 		binfmt_misc_put_ops(e->bpf_ops);
366 	kfree(e);
367 }
368 
369 /**
370  * put_binfmt_handler - put binary handler entry
371  * @e: entry to put
372  *
373  * Free entry syncing with load_misc_binary() and defer final free to
374  * load_misc_binary() in case it is using the binary type handler we were
375  * requested to remove. Also the teardown for a registration that fails
376  * before add_entry() publishes the entry.
377  */
put_binfmt_handler(struct binfmt_misc_entry * e)378 static void put_binfmt_handler(struct binfmt_misc_entry *e)
379 {
380 	if (IS_ERR_OR_NULL(e))
381 		return;
382 
383 	if (refcount_dec_and_test(&e->users)) {
384 		entry_put_interpreters(e);
385 		/* Walkers may still dereference this entry, even sleeping. */
386 		call_srcu(&bm_entries_srcu, &e->rcu, bm_entry_free_rcu);
387 	}
388 }
389 
DEFINE_FREE(put_binfmt_handler,struct binfmt_misc_entry *,put_binfmt_handler (_T))390 DEFINE_FREE(put_binfmt_handler, struct binfmt_misc_entry *, put_binfmt_handler(_T))
391 
392 /* Drop everything a load program staged for this exec. */
393 static void drop_staged_selection(struct linux_binprm *bprm)
394 {
395 	kfree(bprm->bpf_interp);
396 	bprm->bpf_interp = NULL;
397 	kfree(bprm->bpf_interp_arg);
398 	bprm->bpf_interp_arg = NULL;
399 	if (bprm->bpf_interp_file) {
400 		fput(bprm->bpf_interp_file);
401 		bprm->bpf_interp_file = NULL;
402 	}
403 	bprm->bpf_flags = 0;
404 }
405 
406 /**
407  * current_binfmt_misc - get the binfmt_misc instance of the caller's user namespace
408  *
409  * If a user namespace doesn't have its own binfmt_misc mount it uses the
410  * handlers of its closest ancestor with one. This mimics the behavior of
411  * pre-namespaced binfmt_misc where all registered handlers were available
412  * to all users and user namespaces on the system. The init user namespace
413  * instance is statically set up so the fallback is never reached in
414  * practice.
415  *
416  * Return: the binfmt_misc instance of the caller's user namespace
417  */
current_binfmt_misc(void)418 static struct binfmt_misc *current_binfmt_misc(void)
419 {
420 	const struct user_namespace *user_ns;
421 	struct binfmt_misc *misc;
422 
423 	for (user_ns = current_user_ns(); user_ns; user_ns = user_ns->parent) {
424 		/* Pairs with smp_store_release() in bm_fill_super(). */
425 		misc = smp_load_acquire(&user_ns->binfmt_misc);
426 		if (misc)
427 			return misc;
428 	}
429 
430 	return &init_binfmt_misc;
431 }
432 
433 /**
434  * entry_select_interpreter - get the interpreter for the matched @e
435  * @e: matched binary type handler
436  * @bprm: binary that is being executed
437  *
438  * A static entry carries its interpreter path, for a 'B' entry the
439  * handler's load program selects it, either by path or by the name of one
440  * of the interpreters the entry bound. The match is committed, so a failing
441  * program fails the exec.
442  *
443  * Return: the interpreter on success, an ERR_PTR on failure
444  */
entry_select_interpreter(const struct binfmt_misc_entry * e,struct linux_binprm * bprm)445 static const char *entry_select_interpreter(const struct binfmt_misc_entry *e,
446 					    struct linux_binprm *bprm)
447 {
448 	int retval;
449 
450 	/*
451 	 * Drop what a previous chain level staged before anything can pick it
452 	 * up. A static entry stages nothing but consumes a staged file just
453 	 * like a 'B' entry does.
454 	 */
455 	drop_staged_selection(bprm);
456 
457 	if (!test_bit(MISC_FMT_BPF_BIT, &e->flags))
458 		return e->interpreter;
459 
460 	/* The interpreters this entry lets the program choose from. */
461 	bprm->bpf_interps = &e->interps;
462 	retval = e->bpf_ops->load(bprm);
463 	bprm->bpf_interps = NULL;
464 	if (retval) {
465 		/* Keep a program-supplied error within errno range. */
466 		if (retval > 0 || retval < -MAX_ERRNO)
467 			retval = -ENOEXEC;
468 		goto drop_staged;
469 	}
470 
471 	/* Selecting an interpreter is part of the contract. */
472 	if (!bprm->bpf_interp) {
473 		retval = -ENOEXEC;
474 		goto drop_staged;
475 	}
476 
477 	return bprm->bpf_interp;
478 
479 drop_staged:
480 	/* A failing load leaves nothing behind for later entries. */
481 	drop_staged_selection(bprm);
482 	return ERR_PTR(retval);
483 }
484 
485 /**
486  * entry_invocation_flags - the invocation flags in effect for this exec
487  * @e: matched binary type handler
488  * @bprm: binary that is being executed
489  *
490  * A static entry fixes its flags at registration, a 'B' entry's load program
491  * picks them per exec with bpf_binprm_set_flags(). Translate the latter into
492  * the former, implications included, so the dispatch has one set to act on.
493  *
494  * Return: the invocation flags for this exec
495  */
entry_invocation_flags(const struct binfmt_misc_entry * e,struct linux_binprm * bprm)496 static unsigned long entry_invocation_flags(const struct binfmt_misc_entry *e,
497 					    struct linux_binprm *bprm)
498 {
499 	unsigned long flags = 0;
500 	u64 bpf_flags;
501 
502 	if (!test_bit(MISC_FMT_BPF_BIT, &e->flags))
503 		return e->flags;
504 
505 	bpf_flags = bprm->bpf_flags;
506 	/* Clear so they can't accumulate into a nested interpreter level. */
507 	bprm->bpf_flags = 0;
508 
509 	if (bpf_flags & BPF_BINPRM_PRESERVE_ARGV0)
510 		flags |= MISC_FMT_PRESERVE_ARGV0;
511 	if (bpf_flags & BPF_BINPRM_EXECFD)
512 		flags |= MISC_FMT_OPEN_BINARY;
513 	if (bpf_flags & BPF_BINPRM_CREDENTIALS)
514 		flags |= MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY;
515 	if (bpf_flags & BPF_BINPRM_TRANSPARENT)
516 		flags |= MISC_FMT_TRANSPARENT | MISC_FMT_OPEN_BINARY;
517 	if (bpf_flags & BPF_BINPRM_LOADER)
518 		flags |= MISC_FMT_LOADER;
519 
520 	return flags;
521 }
522 
523 /**
524  * entry_open_interpreter - open the entry's interpreter for execution
525  * @e: matched binary type handler
526  * @bprm: binary that is being executed
527  * @interpreter: the interpreter selected for this exec
528  *
529  * An 'F' entry hands out a clone of the file it pre-opened at registration,
530  * and so does a 'B' entry whose load program selected one of the
531  * interpreters it bound. Any other entry opens the selected path.
532  *
533  * Return: the opened interpreter on success, an ERR_PTR on failure
534  */
entry_open_interpreter(const struct binfmt_misc_entry * e,struct linux_binprm * bprm,const char * interpreter)535 static struct file *entry_open_interpreter(const struct binfmt_misc_entry *e,
536 					   struct linux_binprm *bprm,
537 					   const char *interpreter)
538 {
539 	struct file *interp_file __free(fput) = NULL;
540 	struct binfmt_misc_interp *interp;
541 	struct file *bound;
542 	int retval;
543 
544 	if (bprm->bpf_interp_file) {
545 		bound = bprm->bpf_interp_file;
546 	} else if (e->flags & MISC_FMT_OPEN_FILE) {
547 		/* An 'F' entry pre-opened exactly one interpreter. */
548 		interp = list_first_entry(&e->interps,
549 					  struct binfmt_misc_interp, list);
550 		bound = interp->file;
551 	} else {
552 		return open_exec(interpreter);
553 	}
554 
555 	interp_file = file_clone_open(bound);
556 	if (IS_ERR(interp_file))
557 		return interp_file;
558 
559 	retval = exe_file_deny_write_access(interp_file);
560 	if (retval)
561 		return ERR_PTR(retval);
562 
563 	return no_free_ptr(interp_file);
564 }
565 
566 /**
567  * build_interp_argv - splice the interpreter invocation into the argv
568  * @bprm: binary that is being executed
569  * @interpreter: the interpreter selected for this exec
570  * @flags: invocation flags in effect for this exec
571  *
572  * The interpreter becomes argv[0] and the binary its last argument, with an
573  * optional staged argument in between. The caller's argv[0] is dropped
574  * unless 'P' keeps it.
575  *
576  * Return: 0 on success, a negative error code on failure
577  */
build_interp_argv(struct linux_binprm * bprm,const char * interpreter,unsigned long flags)578 static int build_interp_argv(struct linux_binprm *bprm, const char *interpreter,
579 			     unsigned long flags)
580 {
581 	int retval;
582 
583 	/* The interpreter has to be able to load the binary by path. */
584 	if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
585 		return -ENOENT;
586 
587 	/* The entry's own choice - not one accumulated from an earlier level. */
588 	if (flags & MISC_FMT_PRESERVE_ARGV0) {
589 		bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0;
590 	} else {
591 		retval = remove_arg_zero(bprm);
592 		if (retval)
593 			return retval;
594 	}
595 
596 	/* make the binary the last argument to the interpreter */
597 	retval = copy_string_kernel(bprm->interp, bprm);
598 	if (retval < 0)
599 		return retval;
600 	bprm->argc++;
601 
602 	/*
603 	 * A single optional argument to the interpreter, inserted between it
604 	 * and the binary just like the argument of a #! interpreter line.
605 	 */
606 	if (bprm->bpf_interp_arg) {
607 		retval = copy_string_kernel(bprm->bpf_interp_arg, bprm);
608 		if (retval < 0)
609 			return retval;
610 		bprm->argc++;
611 		/* Consumed - don't let it leak into a nested interpreter's argv. */
612 		kfree(bprm->bpf_interp_arg);
613 		bprm->bpf_interp_arg = NULL;
614 	}
615 
616 	/* add the interp as argv[0] */
617 	retval = copy_string_kernel(interpreter, bprm);
618 	if (retval < 0)
619 		return retval;
620 	bprm->argc++;
621 
622 	return 0;
623 }
624 
625 /*
626  * the loader itself
627  */
load_misc_binary(struct linux_binprm * bprm)628 static int load_misc_binary(struct linux_binprm *bprm)
629 {
630 	struct binfmt_misc_entry *fmt __free(put_binfmt_handler) = NULL;
631 	const char *interpreter;
632 	struct file *interp_file;
633 	struct binfmt_misc *misc;
634 	unsigned long flags;
635 	int retval;
636 
637 	/* Only binfmt_misc stages one and exec_binprm() clears it per round. */
638 	WARN_ON_ONCE(bprm->loader);
639 
640 	misc = current_binfmt_misc();
641 	if (!READ_ONCE(misc->enabled))
642 		return -ENOEXEC;
643 
644 	fmt = get_binfmt_handler(misc, bprm);
645 	if (!fmt)
646 		return -ENOEXEC;
647 
648 	interpreter = entry_select_interpreter(fmt, bprm);
649 	if (IS_ERR(interpreter))
650 		return PTR_ERR(interpreter);
651 
652 	flags = entry_invocation_flags(fmt, bprm);
653 
654 	/* No argv is built for a staged argument to land in. */
655 	if ((flags & (MISC_FMT_LOADER | MISC_FMT_TRANSPARENT)) &&
656 	    bprm->bpf_interp_arg)
657 		return -EINVAL;
658 
659 	/*
660 	 * Stash the interpreter for binfmt_elf to consume in place of the
661 	 * binary's PT_INTERP and decline the match, so the search continues
662 	 * to the real format in the same round.
663 	 */
664 	if (flags & MISC_FMT_LOADER) {
665 		interp_file = entry_open_interpreter(fmt, bprm, interpreter);
666 		if (IS_ERR(interp_file)) {
667 			retval = PTR_ERR(interp_file);
668 			/* Declining here would run the binary's own PT_INTERP. */
669 			return retval == -ENOEXEC ? -EACCES : retval;
670 		}
671 
672 		bprm->loader = interp_file;
673 		return -ENOEXEC;
674 	}
675 
676 	if (!(flags & MISC_FMT_TRANSPARENT)) {
677 		retval = build_interp_argv(bprm, interpreter, flags);
678 		if (retval)
679 			return retval;
680 	}
681 
682 	/* Update interp for the next round; sched_prepare_exec reports it. */
683 	retval = bprm_change_interp(interpreter, bprm);
684 	if (retval < 0)
685 		return retval;
686 
687 	interp_file = entry_open_interpreter(fmt, bprm, interpreter);
688 	if (IS_ERR(interp_file))
689 		return PTR_ERR(interp_file);
690 
691 	/* Raise only past the last failure, or an -ENOEXEC decline leaks it. */
692 	if (flags & MISC_FMT_TRANSPARENT)
693 		bprm->interp_flags |= BINPRM_FLAGS_TRANSPARENT_INTERP;
694 
695 	bprm->interpreter = interp_file;
696 	if (flags & MISC_FMT_OPEN_BINARY)
697 		bprm->have_execfd = 1;
698 	if (flags & MISC_FMT_CREDENTIALS)
699 		bprm->execfd_creds = 1;
700 	return 0;
701 }
702 
703 /* Command parsers */
704 
705 /*
706  * Scan the argument starting at @s up to the delimiter @del, recognising
707  * the \x escape. Terminates the argument with a NUL and returns a pointer
708  * past it or NULL on a malformed escape.
709  */
scanarg(char * s,char del)710 static char *scanarg(char *s, char del)
711 {
712 	char c;
713 
714 	while ((c = *s++) != del) {
715 		if (c == '\\' && *s == 'x') {
716 			s++;
717 			if (!isxdigit(*s++))
718 				return NULL;
719 			if (!isxdigit(*s++))
720 				return NULL;
721 		}
722 	}
723 	s[-1] = '\0';
724 	return s;
725 }
726 
727 /* Parse the 'flags' field, stopping at the first character that is not one. */
check_special_flags(char * p,struct binfmt_misc_entry * e)728 static char *check_special_flags(char *p, struct binfmt_misc_entry *e)
729 {
730 	for (;; p++) {
731 		const struct binfmt_misc_flag *f = misc_flag_by_char(*p);
732 
733 		if (!f)
734 			return p;
735 		pr_debug("register: flag: %c (%s)\n", f->c, f->desc);
736 		e->flags |= f->flag | f->implies;
737 	}
738 }
739 
740 /* Parse the 'offset', 'magic' and 'mask' fields of an 'M' entry. */
parse_magic_fields(struct binfmt_misc_entry * e,char * p,char del)741 static char *parse_magic_fields(struct binfmt_misc_entry *e, char *p, char del)
742 {
743 	char *s;
744 
745 	/* Parse the 'offset' field. */
746 	s = strchr(p, del);
747 	if (!s)
748 		return NULL;
749 	*s = '\0';
750 	if (p != s) {
751 		if (kstrtoint(p, 10, &e->offset) || e->offset < 0)
752 			return NULL;
753 	}
754 	p = s + 1;
755 	pr_debug("register: offset: %#x\n", e->offset);
756 
757 	/* Parse the 'magic' field. */
758 	e->magic = p;
759 	p = scanarg(p, del);
760 	if (!p || !e->magic[0])
761 		return NULL;
762 	print_hex_dump_debug(
763 		KBUILD_MODNAME ": register: magic[raw]: ",
764 		DUMP_PREFIX_NONE, 16, 1, e->magic, p - e->magic, true);
765 
766 	/* Parse the 'mask' field. */
767 	e->mask = p;
768 	p = scanarg(p, del);
769 	if (!p)
770 		return NULL;
771 	if (!e->mask[0]) {
772 		e->mask = NULL;
773 		pr_debug("register:  mask[raw]: none\n");
774 	} else {
775 		print_hex_dump_debug(
776 			KBUILD_MODNAME ": register:  mask[raw]: ",
777 			DUMP_PREFIX_NONE, 16, 1, e->mask, p - e->mask, true);
778 	}
779 
780 	/*
781 	 * Decode the magic & mask fields. Note: while we might have accepted
782 	 * embedded NUL bytes from above, the unescape helpers will stop at
783 	 * the first one they encounter.
784 	 */
785 	e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX);
786 	if (e->mask && string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size)
787 		return NULL;
788 	if (e->size > BINPRM_BUF_SIZE || BINPRM_BUF_SIZE - e->size < e->offset)
789 		return NULL;
790 	pr_debug("register: magic/mask length: %i\n", e->size);
791 	print_hex_dump_debug(
792 		KBUILD_MODNAME ": register: magic[decoded]: ",
793 		DUMP_PREFIX_NONE, 16, 1, e->magic, e->size, true);
794 	if (e->mask)
795 		print_hex_dump_debug(
796 			KBUILD_MODNAME ": register:  mask[decoded]: ",
797 			DUMP_PREFIX_NONE, 16, 1, e->mask, e->size, true);
798 	return p;
799 }
800 
801 /* Parse the 'magic' field of an 'E' entry: the filename extension. */
parse_extension_fields(struct binfmt_misc_entry * e,char * p,char del)802 static char *parse_extension_fields(struct binfmt_misc_entry *e, char *p,
803 				    char del)
804 {
805 	/* Skip the 'offset' field. */
806 	p = strchr(p, del);
807 	if (!p)
808 		return NULL;
809 	*p++ = '\0';
810 
811 	/* Parse the 'magic' field. */
812 	e->magic = p;
813 	p = strchr(p, del);
814 	if (!p)
815 		return NULL;
816 	*p++ = '\0';
817 	if (!e->magic[0] || strchr(e->magic, '/'))
818 		return NULL;
819 	pr_debug("register: extension: {%s}\n", e->magic);
820 
821 	/* Skip the 'mask' field. */
822 	p = strchr(p, del);
823 	if (!p)
824 		return NULL;
825 	*p++ = '\0';
826 	return p;
827 }
828 
829 /*
830  * Parse the fields of a 'B' entry: the 'offset', 'magic' and 'mask' fields
831  * must be empty. The handler name is carried in the 'interpreter' field.
832  */
parse_bpf_fields(struct binfmt_misc_entry * e,char * p,char del)833 static char *parse_bpf_fields(struct binfmt_misc_entry *e, char *p, char del)
834 {
835 	/* The 'offset' field must be empty. */
836 	if (*p++ != del)
837 		return NULL;
838 
839 	/* The 'magic' field must be empty. */
840 	if (*p++ != del)
841 		return NULL;
842 
843 	/* The 'mask' field must be empty. */
844 	if (*p++ != del)
845 		return NULL;
846 
847 	return p;
848 }
849 
850 /*
851  * This registers a new binary format, it recognises the syntax
852  * ':name:type:offset:magic:mask:interpreter:flags'
853  * where the ':' is the IFS, that can be chosen with the first char
854  */
create_entry(const char __user * buffer,size_t count)855 static struct binfmt_misc_entry *create_entry(const char __user *buffer,
856 					      size_t count)
857 {
858 	struct binfmt_misc_entry *e __free(kfree) = NULL;
859 	char *buf, *p;
860 	char del;
861 
862 	pr_debug("register: received %zu bytes\n", count);
863 
864 	/* some sanity checks */
865 	if ((count < 11) || (count > MAX_REGISTER_LENGTH))
866 		return ERR_PTR(-EINVAL);
867 
868 	e = kmalloc_flex(*e, buf, count + MISC_DELIM_PAD, GFP_KERNEL_ACCOUNT);
869 	if (!e)
870 		return ERR_PTR(-ENOMEM);
871 
872 	p = buf = e->buf;
873 
874 	memset(e, 0, sizeof(*e));
875 	INIT_LIST_HEAD(&e->interps);
876 	if (copy_from_user(buf, buffer, count))
877 		return ERR_PTR(-EFAULT);
878 
879 	del = *p++;	/* delimiter */
880 
881 	pr_debug("register: delim: %#x\n", del);
882 
883 	if (!misc_valid_delim(del))
884 		return ERR_PTR(-EINVAL);
885 
886 	/* Pad the buffer with the delim to simplify parsing below. */
887 	memset(buf + count, del, MISC_DELIM_PAD);
888 
889 	/* Parse the 'name' field. */
890 	e->name = p;
891 	p = strchr(p, del);
892 	if (!p)
893 		return ERR_PTR(-EINVAL);
894 	*p++ = '\0';
895 	if (!e->name[0] ||
896 	    !strcmp(e->name, ".") ||
897 	    !strcmp(e->name, "..") ||
898 	    strchr(e->name, '/'))
899 		return ERR_PTR(-EINVAL);
900 
901 	pr_debug("register: name: {%s}\n", e->name);
902 
903 	/* Parse the 'type' field. */
904 	switch (*p++) {
905 	case 'E':
906 		pr_debug("register: type: E (extension)\n");
907 		e->flags = BIT(MISC_FMT_ENABLED_BIT);
908 		break;
909 	case 'M':
910 		pr_debug("register: type: M (magic)\n");
911 		e->flags = BIT(MISC_FMT_ENABLED_BIT) | BIT(MISC_FMT_MAGIC_BIT);
912 		break;
913 	case 'B':
914 		pr_debug("register: type: B (bpf)\n");
915 		if (!IS_ENABLED(CONFIG_BINFMT_MISC_BPF))
916 			return ERR_PTR(-EINVAL);
917 		e->flags = BIT(MISC_FMT_ENABLED_BIT) | BIT(MISC_FMT_BPF_BIT);
918 		break;
919 	default:
920 		return ERR_PTR(-EINVAL);
921 	}
922 	if (*p++ != del)
923 		return ERR_PTR(-EINVAL);
924 
925 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags))
926 		p = parse_bpf_fields(e, p, del);
927 	else if (test_bit(MISC_FMT_MAGIC_BIT, &e->flags))
928 		p = parse_magic_fields(e, p, del);
929 	else
930 		p = parse_extension_fields(e, p, del);
931 	if (!p)
932 		return ERR_PTR(-EINVAL);
933 
934 	/* Parse the 'interpreter' field. */
935 	e->interpreter = p;
936 	p = strchr(p, del);
937 	if (!p)
938 		return ERR_PTR(-EINVAL);
939 	*p++ = '\0';
940 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
941 		/* The 'interpreter' field carries the handler name. */
942 		e->bpf_ops_name = e->interpreter;
943 		e->interpreter = NULL;
944 		if (!e->bpf_ops_name[0])
945 			return ERR_PTR(-EINVAL);
946 		pr_debug("register: bpf handler: {%s}\n", e->bpf_ops_name);
947 	} else if (!e->interpreter[0]) {
948 		return ERR_PTR(-EINVAL);
949 	} else {
950 		pr_debug("register: interpreter: {%s}\n", e->interpreter);
951 	}
952 
953 	/* Parse the 'flags' field. */
954 	p = check_special_flags(p, e);
955 
956 	/*
957 	 * A bpf handler decides the invocation flags per exec with
958 	 * bpf_binprm_set_flags() rather than fixing them at registration, and
959 	 * the interpreters it binds pre-open what 'F' would have, so a 'B'
960 	 * entry carries no invocation flags.
961 	 */
962 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags) &&
963 	    (e->flags & MISC_FMT_INVOCATION_FLAGS))
964 		return ERR_PTR(-EINVAL);
965 
966 	/*
967 	 * 'D' is a directive for this registration rather than a lasting
968 	 * property, so consume it: the entry is created disabled and stays
969 	 * out of the search list until '1' is written to its entry file.
970 	 * Staying out is what leaves it open to being given interpreters;
971 	 * the first enable publishes it, for good.
972 	 */
973 	if (e->flags & MISC_FMT_DISABLED) {
974 		e->flags &= ~MISC_FMT_DISABLED;
975 		clear_bit(MISC_FMT_ENABLED_BIT, &e->flags);
976 	}
977 
978 	/* Transparency preserves the whole argv, argv[0] included. */
979 	if ((e->flags & MISC_FMT_TRANSPARENT) &&
980 	    (e->flags & MISC_FMT_PRESERVE_ARGV0))
981 		return ERR_PTR(-EINVAL);
982 
983 	/* A native exec splices no argv, passes no execfd and needs no creds. */
984 	if ((e->flags & MISC_FMT_LOADER) &&
985 	    (e->flags & (MISC_FMT_TRANSPARENT | MISC_FMT_PRESERVE_ARGV0 |
986 			 MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY)))
987 		return ERR_PTR(-EINVAL);
988 
989 	if (*p == '\n')
990 		p++;
991 	if (p != buf + count)
992 		return ERR_PTR(-EINVAL);
993 
994 	/* Non-F opens the interp at exec against the caller's cwd; require absolute. */
995 	if ((e->flags & (MISC_FMT_LOADER | MISC_FMT_CREDENTIALS)) &&
996 	    !(e->flags & MISC_FMT_OPEN_FILE) &&
997 	    e->interpreter[0] != '/')
998 		return ERR_PTR(-EINVAL);
999 
1000 	/* Born holding one reference; put_binfmt_handler() is the teardown. */
1001 	refcount_set(&e->users, 1);
1002 	return no_free_ptr(e);
1003 }
1004 
1005 /* Commands accepted by the /status and /<entry> files. */
1006 enum bm_command {
1007 	BM_CMD_IGNORE,	/* empty write */
1008 	BM_CMD_DISABLE,	/* "0" */
1009 	BM_CMD_ENABLE,	/* "1" */
1010 	BM_CMD_REMOVE,	/* "-1" */
1011 };
1012 
1013 /* Longest of the commands above, "-1\n". */
1014 #define MAX_COMMAND_LENGTH 3
1015 
1016 /*
1017  * Parse what userspace wrote to /status or an entry file: '1' enables,
1018  * '0' disables and '-1' removes the entry or all entries.
1019  */
parse_command(const char * s,size_t count)1020 static int parse_command(const char *s, size_t count)
1021 {
1022 	if (count > MAX_COMMAND_LENGTH)
1023 		return -EINVAL;
1024 	if (!count)
1025 		return BM_CMD_IGNORE;
1026 	if (s[count - 1] == '\n')
1027 		count--;
1028 	if (count == 1 && s[0] == '0')
1029 		return BM_CMD_DISABLE;
1030 	if (count == 1 && s[0] == '1')
1031 		return BM_CMD_ENABLE;
1032 	if (count == 2 && s[0] == '-' && s[1] == '1')
1033 		return BM_CMD_REMOVE;
1034 	return -EINVAL;
1035 }
1036 
1037 /* Copy in a command from a file that takes nothing else, and parse it. */
read_command(const char __user * buffer,size_t count)1038 static int read_command(const char __user *buffer, size_t count)
1039 {
1040 	char s[MAX_COMMAND_LENGTH + 1];
1041 
1042 	if (count > sizeof(s) - 1)
1043 		return -EINVAL;
1044 	if (copy_from_user(s, buffer, count))
1045 		return -EFAULT;
1046 	return parse_command(s, count);
1047 }
1048 
1049 /* generic stuff */
1050 
1051 /* The root directory's inode; its lock serializes configuring an instance. */
bm_root_inode(struct super_block * sb)1052 static struct inode *bm_root_inode(struct super_block *sb)
1053 {
1054 	return d_inode(sb->s_root);
1055 }
1056 
bm_seq_hex(struct seq_file * m,const u8 * data,int size)1057 static void bm_seq_hex(struct seq_file *m, const u8 *data, int size)
1058 {
1059 	for (int i = 0; i < size; i++)
1060 		seq_printf(m, "%02x", data[i]);
1061 }
1062 
bm_entry_show(struct seq_file * m,void * unused)1063 static int bm_entry_show(struct seq_file *m, void *unused)
1064 {
1065 	struct binfmt_misc_entry *e = m->private;
1066 
1067 	if (test_bit(MISC_FMT_ENABLED_BIT, &e->flags))
1068 		seq_puts(m, "enabled\n");
1069 	else
1070 		seq_puts(m, "disabled\n");
1071 
1072 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
1073 		struct binfmt_misc_interp *interp;
1074 
1075 		seq_printf(m, "bpf %s\n", e->bpf_ops->name);
1076 		/*
1077 		 * A staged entry's set can still grow, so every binding is
1078 		 * rcu-published. The open file pins the entry and with it
1079 		 * every node, so rcu is for the tearing, not the lifetime.
1080 		 */
1081 		rcu_read_lock();
1082 		list_for_each_entry_rcu(interp, &e->interps, list)
1083 			seq_printf(m, "bpf-interpreter %s %s\n",
1084 				   interp->name, interp->path);
1085 		rcu_read_unlock();
1086 	} else {
1087 		seq_printf(m, "interpreter %s\n", e->interpreter);
1088 	}
1089 
1090 	/* print the special flags */
1091 	seq_puts(m, "flags: ");
1092 	for (int i = 0; i < ARRAY_SIZE(misc_flags); i++)
1093 		if (e->flags & misc_flags[i].flag)
1094 			seq_putc(m, misc_flags[i].c);
1095 	seq_putc(m, '\n');
1096 
1097 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
1098 		/* The program does the matching. */
1099 	} else if (!test_bit(MISC_FMT_MAGIC_BIT, &e->flags)) {
1100 		seq_printf(m, "extension .%s\n", e->magic);
1101 	} else {
1102 		seq_printf(m, "offset %i\nmagic ", e->offset);
1103 		bm_seq_hex(m, e->magic, e->size);
1104 		if (e->mask) {
1105 			seq_puts(m, "\nmask ");
1106 			bm_seq_hex(m, e->mask, e->size);
1107 		}
1108 		seq_putc(m, '\n');
1109 	}
1110 	return 0;
1111 }
1112 
bm_get_inode(struct super_block * sb,umode_t mode)1113 static struct inode *bm_get_inode(struct super_block *sb, umode_t mode)
1114 {
1115 	struct inode *inode = new_inode(sb);
1116 
1117 	if (inode) {
1118 		inode->i_ino = get_next_ino();
1119 		inode->i_mode = mode;
1120 		simple_inode_init_ts(inode);
1121 	}
1122 	return inode;
1123 }
1124 
1125 /**
1126  * i_binfmt_misc - retrieve struct binfmt_misc from a binfmt_misc inode
1127  * @inode: inode of the relevant binfmt_misc instance
1128  *
1129  * This helper retrieves struct binfmt_misc from a binfmt_misc inode. This can
1130  * be done without any memory barriers because we are guaranteed that
1131  * user_ns->binfmt_misc is fully initialized. It was fully initialized when the
1132  * binfmt_misc mount was first created.
1133  *
1134  * Return: struct binfmt_misc of the relevant binfmt_misc instance
1135  */
i_binfmt_misc(struct inode * inode)1136 static struct binfmt_misc *i_binfmt_misc(struct inode *inode)
1137 {
1138 	return inode->i_sb->s_user_ns->binfmt_misc;
1139 }
1140 
1141 /**
1142  * bm_evict_inode - cleanup data associated with @inode
1143  * @inode: inode to which the data is attached
1144  *
1145  * Cleanup the binary type handler data associated with @inode if a binary type
1146  * entry is removed or the filesystem is unmounted and the super block is
1147  * shutdown.
1148  *
1149  * If the ->evict call was not caused by a super block shutdown but by
1150  * removing the entry via bm_{entry,status}_write() or unlink(2) the entry
1151  * will have already been removed from the list. We keep the hlist_unhashed()
1152  * check to make that explicit.
1153 */
bm_evict_inode(struct inode * inode)1154 static void bm_evict_inode(struct inode *inode)
1155 {
1156 	struct binfmt_misc_entry *e = inode->i_private;
1157 
1158 	clear_inode(inode);
1159 
1160 	if (e) {
1161 		struct binfmt_misc *misc;
1162 
1163 		misc = i_binfmt_misc(inode);
1164 		spin_lock(&misc->entries_lock);
1165 		if (!hlist_unhashed(&e->node))
1166 			hlist_del_init_rcu(&e->node);
1167 		spin_unlock(&misc->entries_lock);
1168 		put_binfmt_handler(e);
1169 	}
1170 }
1171 
1172 /**
1173  * unlink_binfmt_handler - unhash a binary type handler
1174  * @misc: handle to binfmt_misc instance
1175  * @e: binary type handler to unhash
1176  *
1177  * Adding and removing entries via bm_{entry,register,status}_write() and
1178  * unlink(2) happens under the exclusively held inode lock of the root
1179  * dentry keeping the list stable for writers. load_misc_binary() walks it
1180  * concurrently under SRCU. The entries_lock is only held around the actual
1181  * unlink to serialize against bm_evict_inode() which unlinks entries
1182  * during umount without holding the root inode lock.
1183  */
unlink_binfmt_handler(struct binfmt_misc * misc,struct binfmt_misc_entry * e)1184 static void unlink_binfmt_handler(struct binfmt_misc *misc,
1185 				  struct binfmt_misc_entry *e)
1186 {
1187 	spin_lock(&misc->entries_lock);
1188 	hlist_del_init_rcu(&e->node);
1189 	spin_unlock(&misc->entries_lock);
1190 }
1191 
1192 /**
1193  * remove_binfmt_handler - remove a binary type handler
1194  * @misc: handle to binfmt_misc instance
1195  * @e: binary type handler to remove
1196  *
1197  * Remove a binary type handler from the list of binary type handlers and
1198  * remove its associated dentry.
1199  */
remove_binfmt_handler(struct binfmt_misc * misc,struct binfmt_misc_entry * e)1200 static void remove_binfmt_handler(struct binfmt_misc *misc,
1201 				  struct binfmt_misc_entry *e)
1202 {
1203 	unlink_binfmt_handler(misc, e);
1204 	locked_recursive_removal(e->dentry, NULL);
1205 }
1206 
1207 /* Remove @e unless it was already removed. */
bm_remove_entry(struct binfmt_misc_entry * e,struct super_block * sb)1208 static void bm_remove_entry(struct binfmt_misc_entry *e, struct super_block *sb)
1209 {
1210 	struct inode *root = bm_root_inode(sb);
1211 
1212 	inode_lock_nested(root, I_MUTEX_PARENT);
1213 	/* A staged entry is not hashed; the dentry says if it was removed. */
1214 	if (!d_unhashed(e->dentry))
1215 		remove_binfmt_handler(i_binfmt_misc(root), e);
1216 	inode_unlock(root);
1217 }
1218 
1219 /* Remove all entries of the binfmt_misc instance @misc belonging to @sb. */
bm_remove_all_entries(struct binfmt_misc * misc,struct super_block * sb)1220 static void bm_remove_all_entries(struct binfmt_misc *misc,
1221 				  struct super_block *sb)
1222 {
1223 	struct inode *root = bm_root_inode(sb);
1224 	struct dentry *child = NULL;
1225 
1226 	inode_lock_nested(root, I_MUTEX_PARENT);
1227 	/*
1228 	 * Walk the directory rather than the search list: a staged entry
1229 	 * is in the former but not yet in the latter. The control files
1230 	 * carry no entry and stay.
1231 	 */
1232 	while ((child = find_next_child(sb->s_root, child))) {
1233 		struct binfmt_misc_entry *e = d_inode(child)->i_private;
1234 
1235 		if (e)
1236 			remove_binfmt_handler(misc, e);
1237 	}
1238 	inode_unlock(root);
1239 }
1240 
1241 /**
1242  * bm_unlink - remove a binary type handler via unlink(2)
1243  * @dir: inode of the root directory
1244  * @dentry: entry file to remove
1245  *
1246  * Removing the entry file removes its binary type handler, exactly like
1247  * writing -1 to it does. The status and register control files can't be
1248  * removed. The VFS calls this with the root inode lock held which
1249  * serializes against the write based add and remove paths.
1250  */
bm_unlink(struct inode * dir,struct dentry * dentry)1251 static int bm_unlink(struct inode *dir, struct dentry *dentry)
1252 {
1253 	struct binfmt_misc_entry *e = d_inode(dentry)->i_private;
1254 
1255 	if (!e)
1256 		return -EPERM;
1257 
1258 	unlink_binfmt_handler(i_binfmt_misc(dir), e);
1259 	return simple_unlink(dir, dentry);
1260 }
1261 
1262 static const struct inode_operations bm_dir_inode_operations = {
1263 	.lookup		= simple_lookup,
1264 	.unlink		= bm_unlink,
1265 };
1266 
1267 /* /<entry> */
1268 
bm_entry_open(struct inode * inode,struct file * file)1269 static int bm_entry_open(struct inode *inode, struct file *file)
1270 {
1271 	int ret;
1272 
1273 	ret = single_open(file, bm_entry_show, inode->i_private);
1274 	if (ret)
1275 		return ret;
1276 
1277 	/* seq_open() clears FMODE_PWRITE, bm_entry_write() takes any offset */
1278 	if (file->f_mode & FMODE_WRITE)
1279 		file->f_mode |= FMODE_PWRITE;
1280 	return 0;
1281 }
1282 
1283 /*
1284  * Longest '+<name> <path>' a write can spell, and with it the longest
1285  * command an entry file takes: the two delimiters and a newline on top of
1286  * the two names.
1287  */
1288 #define MAX_BINDING_LENGTH (BINFMT_MISC_INTERP_NAME_MAX + PATH_MAX + 3)
1289 
1290 /**
1291  * bm_entry_add_interp - bind another interpreter to a staged entry
1292  * @e: the entry
1293  * @file: the entry file being written to, for its credentials
1294  * @buf: the '+<name> <path>' command, parsed in place and owned by the caller
1295  * @count: its length
1296  *
1297  * A 'D' entry is registered outside the search list, which is what leaves
1298  * it open to being configured: it cannot be matched, so no exec can be
1299  * holding its interpreters and the set can still grow. Its first enable
1300  * publishes it and ends that. One interpreter per write, up to
1301  * BINFMT_MISC_INTERP_MAX of them, none of which has to fit in a register
1302  * string.
1303  *
1304  * Return: @count on success, a negative errno on failure
1305  */
bm_entry_add_interp(struct binfmt_misc_entry * e,struct file * file,char * buf,size_t count)1306 static ssize_t bm_entry_add_interp(struct binfmt_misc_entry *e,
1307 				   struct file *file, char *buf, size_t count)
1308 {
1309 	struct file *f __free(close_interp_file) = NULL;
1310 	struct inode *root = bm_root_inode(file_inode(file)->i_sb);
1311 	size_t nlen, plen;
1312 	char *name, *path;
1313 	int retval;
1314 
1315 	/* Settled before the open: type is fixed, publication is permanent. */
1316 	if (!test_bit(MISC_FMT_BPF_BIT, &e->flags))
1317 		return -EINVAL;
1318 	if (!hlist_unhashed_lockless(&e->node))
1319 		return -EBUSY;
1320 
1321 	/* '+<name> <path>': the path is everything past the first space. */
1322 	name = buf + 1;
1323 	path = strchr(name, ' ');
1324 	if (!path)
1325 		return -EINVAL;
1326 	*path++ = '\0';
1327 
1328 	plen = strlen(path);
1329 	/* The command has to end at the write, like a register string. */
1330 	if (path + plen != buf + count)
1331 		return -EINVAL;
1332 	if (plen && path[plen - 1] == '\n')
1333 		path[--plen] = '\0';
1334 	/* Resolved now, so a relative path would name the writer's cwd. */
1335 	if (path[0] != '/')
1336 		return -EINVAL;
1337 
1338 	nlen = path - name - 1;
1339 	if (!nlen || nlen > BINFMT_MISC_INTERP_NAME_MAX)
1340 		return -EINVAL;
1341 	/* The name prints between delimiters, so keep it a printable word. */
1342 	for (const char *p = name; *p; p++)
1343 		if (!isascii(*p) || !isgraph(*p))
1344 			return -EINVAL;
1345 
1346 	/* Opened before the lock: resolving it may walk this very filesystem. */
1347 	f = open_interp_file(file->f_cred, path);
1348 	if (IS_ERR(f))
1349 		return PTR_ERR(f);
1350 
1351 	inode_lock(root);
1352 	if (d_unhashed(e->dentry))
1353 		retval = -ENOENT;	/* removed while we were opening it */
1354 	else if (!hlist_unhashed(&e->node))
1355 		retval = -EBUSY;	/* published while we were opening it */
1356 	else
1357 		retval = entry_attach_interpreter(e, name, path, f);
1358 	inode_unlock(root);
1359 	if (retval)
1360 		return retval;
1361 
1362 	/* The file is owned by the entry now. */
1363 	retain_and_null_ptr(f);
1364 	return count;
1365 }
1366 
bm_entry_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)1367 static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
1368 				size_t count, loff_t *ppos)
1369 {
1370 	struct inode *inode = file_inode(file);
1371 	struct binfmt_misc_entry *e = inode->i_private;
1372 	char *buf __free(kfree) = NULL;
1373 	int res;
1374 
1375 	/* A binding is the longest command this file takes. */
1376 	if (count > MAX_BINDING_LENGTH)
1377 		return -E2BIG;
1378 
1379 	buf = memdup_user_nul(buffer, count);
1380 	if (IS_ERR(buf))
1381 		return PTR_ERR(buf);
1382 
1383 	/* '+<name> <path>' binds an interpreter, everything else toggles. */
1384 	if (buf[0] == '+')
1385 		return bm_entry_add_interp(e, file, buf, count);
1386 
1387 	res = parse_command(buf, count);
1388 
1389 	switch (res) {
1390 	case BM_CMD_DISABLE:
1391 		clear_bit(MISC_FMT_ENABLED_BIT, &e->flags);
1392 		break;
1393 	case BM_CMD_ENABLE: {
1394 		struct inode *root = bm_root_inode(inode->i_sb);
1395 
1396 		/*
1397 		 * The first enable publishes a 'D' entry into the search
1398 		 * list, whole. The lock keeps that ordered against a second
1399 		 * enable, against removal - a removed entry has nothing left
1400 		 * to publish - and against binding: what can be matched can
1401 		 * no longer be configured.
1402 		 */
1403 		inode_lock(root);
1404 		set_bit(MISC_FMT_ENABLED_BIT, &e->flags);
1405 		if (hlist_unhashed(&e->node) && !d_unhashed(e->dentry)) {
1406 			struct binfmt_misc *misc = i_binfmt_misc(inode);
1407 
1408 			spin_lock(&misc->entries_lock);
1409 			hlist_add_head_rcu(&e->node, &misc->entries);
1410 			spin_unlock(&misc->entries_lock);
1411 		}
1412 		inode_unlock(root);
1413 		break;
1414 	}
1415 	case BM_CMD_REMOVE:
1416 		bm_remove_entry(e, inode->i_sb);
1417 		break;
1418 	default:
1419 		return res;
1420 	}
1421 
1422 	return count;
1423 }
1424 
1425 static const struct file_operations bm_entry_operations = {
1426 	.open		= bm_entry_open,
1427 	.read		= seq_read,
1428 	.write		= bm_entry_write,
1429 	.llseek		= seq_lseek,
1430 	.release	= single_release,
1431 };
1432 
1433 /* /register */
1434 
1435 /* add to filesystem */
add_entry(struct binfmt_misc_entry * e,struct super_block * sb)1436 static int add_entry(struct binfmt_misc_entry *e, struct super_block *sb)
1437 {
1438 	struct dentry *dentry = simple_start_creating(sb->s_root, e->name);
1439 	struct inode *inode;
1440 	struct binfmt_misc *misc;
1441 
1442 	if (IS_ERR(dentry))
1443 		return PTR_ERR(dentry);
1444 
1445 	inode = bm_get_inode(sb, S_IFREG | 0644);
1446 	if (unlikely(!inode)) {
1447 		simple_done_creating(dentry);
1448 		return -ENOMEM;
1449 	}
1450 
1451 	e->dentry = dentry;
1452 	inode->i_private = e;
1453 	inode->i_fop = &bm_entry_operations;
1454 
1455 	d_make_persistent(dentry, inode);
1456 	/* A 'D' entry stays out of the search list until its first enable. */
1457 	if (test_bit(MISC_FMT_ENABLED_BIT, &e->flags)) {
1458 		misc = i_binfmt_misc(inode);
1459 		spin_lock(&misc->entries_lock);
1460 		hlist_add_head_rcu(&e->node, &misc->entries);
1461 		spin_unlock(&misc->entries_lock);
1462 	}
1463 	simple_done_creating(dentry);
1464 	return 0;
1465 }
1466 
bm_register_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)1467 static ssize_t bm_register_write(struct file *file, const char __user *buffer,
1468 			       size_t count, loff_t *ppos)
1469 {
1470 	struct binfmt_misc_entry *e __free(put_binfmt_handler) = NULL;
1471 	struct super_block *sb = file_inode(file)->i_sb;
1472 	int err;
1473 
1474 	e = create_entry(buffer, count);
1475 	if (IS_ERR(e))
1476 		return PTR_ERR(e);
1477 
1478 	if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
1479 		e->bpf_ops = binfmt_misc_get_ops(sb->s_user_ns, e->bpf_ops_name);
1480 		if (!e->bpf_ops) {
1481 			pr_notice("register: no bpf handler named %s\n",
1482 				  e->bpf_ops_name);
1483 			return -ENOENT;
1484 		}
1485 	}
1486 
1487 	if (e->flags & MISC_FMT_OPEN_FILE) {
1488 		struct file *f = open_interp_file(file->f_cred, e->interpreter);
1489 
1490 		if (IS_ERR(f))
1491 			return PTR_ERR(f);
1492 		err = entry_attach_interpreter(e, "", e->interpreter, f);
1493 		if (err) {
1494 			close_interp_file(f);
1495 			return err;
1496 		}
1497 	}
1498 
1499 	err = add_entry(e, sb);
1500 	if (err)
1501 		return err;
1502 
1503 	/* The entry is owned by its inode now. */
1504 	retain_and_null_ptr(e);
1505 	return count;
1506 }
1507 
1508 static const struct file_operations bm_register_operations = {
1509 	.write		= bm_register_write,
1510 	.llseek		= noop_llseek,
1511 };
1512 
1513 /* /status */
1514 
1515 static ssize_t
bm_status_read(struct file * file,char __user * buf,size_t nbytes,loff_t * ppos)1516 bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1517 {
1518 	struct binfmt_misc *misc;
1519 	const char *s;
1520 
1521 	misc = i_binfmt_misc(file_inode(file));
1522 	s = READ_ONCE(misc->enabled) ? "enabled\n" : "disabled\n";
1523 	return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
1524 }
1525 
bm_status_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)1526 static ssize_t bm_status_write(struct file *file, const char __user *buffer,
1527 		size_t count, loff_t *ppos)
1528 {
1529 	struct binfmt_misc *misc;
1530 	int res = read_command(buffer, count);
1531 
1532 	misc = i_binfmt_misc(file_inode(file));
1533 	switch (res) {
1534 	case BM_CMD_DISABLE:
1535 		WRITE_ONCE(misc->enabled, false);
1536 		break;
1537 	case BM_CMD_ENABLE:
1538 		WRITE_ONCE(misc->enabled, true);
1539 		break;
1540 	case BM_CMD_REMOVE:
1541 		bm_remove_all_entries(misc, file_inode(file)->i_sb);
1542 		break;
1543 	default:
1544 		return res;
1545 	}
1546 
1547 	return count;
1548 }
1549 
1550 static const struct file_operations bm_status_operations = {
1551 	.read		= bm_status_read,
1552 	.write		= bm_status_write,
1553 	.llseek		= default_llseek,
1554 };
1555 
1556 /* Superblock handling */
1557 
1558 static const struct super_operations bm_super_ops = {
1559 	.statfs		= simple_statfs,
1560 	.evict_inode	= bm_evict_inode,
1561 };
1562 
bm_fill_super(struct super_block * sb,struct fs_context * fc)1563 static int bm_fill_super(struct super_block *sb, struct fs_context *fc)
1564 {
1565 	int err;
1566 	struct user_namespace *user_ns = sb->s_user_ns;
1567 	struct binfmt_misc *misc;
1568 	static const struct tree_descr bm_files[] = {
1569 		[2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
1570 		[3] = {"register", &bm_register_operations, S_IWUSR},
1571 		/* last one */ {""}
1572 	};
1573 
1574 	/* The fscontext fd may have been passed to another user namespace. */
1575 	if (user_ns != current_user_ns())
1576 		return -EINVAL;
1577 
1578 	/* Never exec off this instance and never let anything stack on it. */
1579 	sb->s_iflags |= SB_I_NOEXEC | SB_I_NODEV;
1580 	sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH;
1581 
1582 	/*
1583 	 * Lazily allocate a new binfmt_misc instance for this namespace, i.e.
1584 	 * do it here during the first mount of binfmt_misc. We don't need to
1585 	 * waste memory for every user namespace allocation. It's likely much
1586 	 * more common to not mount a separate binfmt_misc instance than it is
1587 	 * to mount one.
1588 	 *
1589 	 * While multiple superblocks can exist they are keyed by userns in
1590 	 * s_fs_info for binfmt_misc. Hence, the vfs guarantees that
1591 	 * bm_fill_super() is called exactly once whenever a binfmt_misc
1592 	 * superblock for a userns is created. This in turn lets us conclude
1593 	 * that when a binfmt_misc superblock is created for the first time for
1594 	 * a userns there's no one racing us. Therefore we don't need any
1595 	 * barriers when we dereference binfmt_misc.
1596 	 */
1597 	misc = user_ns->binfmt_misc;
1598 	if (!misc) {
1599 		/*
1600 		 * If it turns out that most user namespaces actually want to
1601 		 * register their own binary type handler and therefore all
1602 		 * create their own separate binfmt_misc mounts we should
1603 		 * consider turning this into a kmem cache.
1604 		 */
1605 		misc = kzalloc_obj(struct binfmt_misc);
1606 		if (!misc)
1607 			return -ENOMEM;
1608 
1609 		INIT_HLIST_HEAD(&misc->entries);
1610 		spin_lock_init(&misc->entries_lock);
1611 
1612 		/* Pairs with smp_load_acquire() in current_binfmt_misc(). */
1613 		smp_store_release(&user_ns->binfmt_misc, misc);
1614 	}
1615 
1616 	/*
1617 	 * When the binfmt_misc superblock for this userns is shutdown
1618 	 * ->enabled might have been set to false and we don't reinitialize
1619 	 * ->enabled again during shutdown as someone might already be mounting
1620 	 * binfmt_misc again. It also would be pointless since by then we know
1621 	 * that the binary type list for this binfmt_misc mount is empty making
1622 	 * load_misc_binary() return -ENOEXEC independent of whether ->enabled
1623 	 * is true. Instead, if someone mounts binfmt_misc for the first time or
1624 	 * again we simply reset ->enabled to true.
1625 	 */
1626 	WRITE_ONCE(misc->enabled, true);
1627 
1628 	err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
1629 	if (err)
1630 		return err;
1631 
1632 	sb->s_op = &bm_super_ops;
1633 	d_inode(sb->s_root)->i_op = &bm_dir_inode_operations;
1634 	return 0;
1635 }
1636 
bm_free(struct fs_context * fc)1637 static void bm_free(struct fs_context *fc)
1638 {
1639 	if (fc->s_fs_info)
1640 		put_user_ns(fc->s_fs_info);
1641 }
1642 
bm_get_tree(struct fs_context * fc)1643 static int bm_get_tree(struct fs_context *fc)
1644 {
1645 	return get_tree_keyed(fc, bm_fill_super, get_user_ns(fc->user_ns));
1646 }
1647 
1648 static const struct fs_context_operations bm_context_ops = {
1649 	.free		= bm_free,
1650 	.get_tree	= bm_get_tree,
1651 };
1652 
bm_kill_sb(struct super_block * sb)1653 static void bm_kill_sb(struct super_block *sb)
1654 {
1655 	struct user_namespace *user_ns = sb->s_fs_info;
1656 
1657 	kill_anon_super(sb);
1658 	put_user_ns(user_ns);
1659 }
1660 
bm_init_fs_context(struct fs_context * fc)1661 static int bm_init_fs_context(struct fs_context *fc)
1662 {
1663 	fc->ops = &bm_context_ops;
1664 	return 0;
1665 }
1666 
1667 static struct linux_binfmt misc_format = {
1668 	.module = THIS_MODULE,
1669 	.load_binary = load_misc_binary,
1670 };
1671 
1672 static struct file_system_type bm_fs_type = {
1673 	.owner		= THIS_MODULE,
1674 	.name		= "binfmt_misc",
1675 	.init_fs_context = bm_init_fs_context,
1676 	.fs_flags	= FS_USERNS_MOUNT,
1677 	.kill_sb	= bm_kill_sb,
1678 };
1679 MODULE_ALIAS_FS("binfmt_misc");
1680 
init_misc_binfmt(void)1681 static int __init init_misc_binfmt(void)
1682 {
1683 	int err = register_filesystem(&bm_fs_type);
1684 	if (!err)
1685 		insert_binfmt(&misc_format);
1686 	return err;
1687 }
1688 
exit_misc_binfmt(void)1689 static void __exit exit_misc_binfmt(void)
1690 {
1691 	unregister_binfmt(&misc_format);
1692 	unregister_filesystem(&bm_fs_type);
1693 	/* Flush pending bm_entry_free_rcu() callbacks before the text goes. */
1694 	srcu_barrier(&bm_entries_srcu);
1695 }
1696 
1697 core_initcall(init_misc_binfmt);
1698 module_exit(exit_misc_binfmt);
1699 MODULE_DESCRIPTION("Kernel support for miscellaneous binaries");
1700 MODULE_LICENSE("GPL");
1701