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