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
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. */
entry_matches_magic(const struct binfmt_misc_entry * e,const struct linux_binprm * bprm)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. */
entry_matches_extension(const struct binfmt_misc_entry * e,const char * ext)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 *
search_binfmt_handler(struct binfmt_misc * misc,struct linux_binprm * bprm)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 */
get_binfmt_handler(struct binfmt_misc * misc,struct linux_binprm * bprm)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 *
binfmt_misc_find_interp(const struct list_head * interps,const char * name)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. */
close_interp_file(struct file * f)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
DEFINE_FREE(close_interp_file,struct file *,close_interp_file (_T))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. */
entry_put_interpreters(struct binfmt_misc_entry * e)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 */
entry_attach_interpreter(struct binfmt_misc_entry * e,const char * name,const char * path,struct file * f)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_flex(*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
bm_entry_free_rcu(struct rcu_head * rcu)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 */
put_binfmt_handler(struct binfmt_misc_entry * e)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
DEFINE_FREE(put_binfmt_handler,struct binfmt_misc_entry *,put_binfmt_handler (_T))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 */
current_binfmt_misc(void)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 */
entry_select_interpreter(const struct binfmt_misc_entry * e,struct linux_binprm * bprm)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 */
entry_invocation_flags(const struct binfmt_misc_entry * e,struct linux_binprm * bprm)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 */
entry_open_interpreter(const struct binfmt_misc_entry * e,struct linux_binprm * bprm,const char * interpreter)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 */
build_interp_argv(struct linux_binprm * bprm,const char * interpreter,unsigned long flags)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 */
load_misc_binary(struct linux_binprm * bprm)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 */
scanarg(char * s,char del)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. */
check_special_flags(char * p,struct binfmt_misc_entry * e)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. */
parse_magic_fields(struct binfmt_misc_entry * e,char * p,char del)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. */
parse_extension_fields(struct binfmt_misc_entry * e,char * p,char del)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 */
parse_bpf_fields(struct binfmt_misc_entry * e,char * p,char del)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 */
create_entry(const char __user * buffer,size_t count)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_flex(*e, buf, count + MISC_DELIM_PAD, GFP_KERNEL_ACCOUNT);
862 if (!e)
863 return ERR_PTR(-ENOMEM);
864
865 p = buf = e->buf;
866
867 memset(e, 0, sizeof(*e));
868 INIT_LIST_HEAD(&e->interps);
869 if (copy_from_user(buf, buffer, count))
870 return ERR_PTR(-EFAULT);
871
872 del = *p++; /* delimiter */
873
874 pr_debug("register: delim: %#x {%c}\n", del, del);
875
876 /* A flag-char delimiter runs the flag scan off the buffer. */
877 if (misc_flag_by_char(del))
878 return ERR_PTR(-EINVAL);
879
880 /* Pad the buffer with the delim to simplify parsing below. */
881 memset(buf + count, del, MISC_DELIM_PAD);
882
883 /* Parse the 'name' field. */
884 e->name = p;
885 p = strchr(p, del);
886 if (!p)
887 return ERR_PTR(-EINVAL);
888 *p++ = '\0';
889 if (!e->name[0] ||
890 !strcmp(e->name, ".") ||
891 !strcmp(e->name, "..") ||
892 strchr(e->name, '/'))
893 return ERR_PTR(-EINVAL);
894
895 pr_debug("register: name: {%s}\n", e->name);
896
897 /* Parse the 'type' field. */
898 switch (*p++) {
899 case 'E':
900 pr_debug("register: type: E (extension)\n");
901 e->flags = BIT(MISC_FMT_ENABLED_BIT);
902 break;
903 case 'M':
904 pr_debug("register: type: M (magic)\n");
905 e->flags = BIT(MISC_FMT_ENABLED_BIT) | BIT(MISC_FMT_MAGIC_BIT);
906 break;
907 case 'B':
908 pr_debug("register: type: B (bpf)\n");
909 if (!IS_ENABLED(CONFIG_BINFMT_MISC_BPF))
910 return ERR_PTR(-EINVAL);
911 e->flags = BIT(MISC_FMT_ENABLED_BIT) | BIT(MISC_FMT_BPF_BIT);
912 break;
913 default:
914 return ERR_PTR(-EINVAL);
915 }
916 if (*p++ != del)
917 return ERR_PTR(-EINVAL);
918
919 if (test_bit(MISC_FMT_BPF_BIT, &e->flags))
920 p = parse_bpf_fields(e, p, del);
921 else if (test_bit(MISC_FMT_MAGIC_BIT, &e->flags))
922 p = parse_magic_fields(e, p, del);
923 else
924 p = parse_extension_fields(e, p, del);
925 if (!p)
926 return ERR_PTR(-EINVAL);
927
928 /* Parse the 'interpreter' field. */
929 e->interpreter = p;
930 p = strchr(p, del);
931 if (!p)
932 return ERR_PTR(-EINVAL);
933 *p++ = '\0';
934 if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
935 /* The 'interpreter' field carries the handler name. */
936 e->bpf_ops_name = e->interpreter;
937 e->interpreter = NULL;
938 if (!e->bpf_ops_name[0])
939 return ERR_PTR(-EINVAL);
940 pr_debug("register: bpf handler: {%s}\n", e->bpf_ops_name);
941 } else if (!e->interpreter[0]) {
942 return ERR_PTR(-EINVAL);
943 } else {
944 pr_debug("register: interpreter: {%s}\n", e->interpreter);
945 }
946
947 /* Parse the 'flags' field. */
948 p = check_special_flags(p, e);
949
950 /*
951 * A bpf handler decides the invocation flags per exec with
952 * bpf_binprm_set_flags() rather than fixing them at registration, and
953 * the interpreters it binds pre-open what 'F' would have, so a 'B'
954 * entry carries no invocation flags.
955 */
956 if (test_bit(MISC_FMT_BPF_BIT, &e->flags) &&
957 (e->flags & MISC_FMT_INVOCATION_FLAGS))
958 return ERR_PTR(-EINVAL);
959
960 /*
961 * 'D' is a directive for this registration rather than a lasting
962 * property, so consume it: the entry is created disabled and stays
963 * out of the search list until '1' is written to its entry file.
964 * Staying out is what leaves it open to being given interpreters;
965 * the first enable publishes it, for good.
966 */
967 if (e->flags & MISC_FMT_DISABLED) {
968 e->flags &= ~MISC_FMT_DISABLED;
969 clear_bit(MISC_FMT_ENABLED_BIT, &e->flags);
970 }
971
972 /* Transparency preserves the whole argv, argv[0] included. */
973 if ((e->flags & MISC_FMT_TRANSPARENT) &&
974 (e->flags & MISC_FMT_PRESERVE_ARGV0))
975 return ERR_PTR(-EINVAL);
976
977 /* A native exec splices no argv, passes no execfd and needs no creds. */
978 if ((e->flags & MISC_FMT_LOADER) &&
979 (e->flags & (MISC_FMT_TRANSPARENT | MISC_FMT_PRESERVE_ARGV0 |
980 MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY)))
981 return ERR_PTR(-EINVAL);
982
983 if (*p == '\n')
984 p++;
985 if (p != buf + count)
986 return ERR_PTR(-EINVAL);
987
988 /* Non-F opens the interp at exec against the caller's cwd; require absolute. */
989 if ((e->flags & (MISC_FMT_LOADER | MISC_FMT_CREDENTIALS)) &&
990 !(e->flags & MISC_FMT_OPEN_FILE) &&
991 e->interpreter[0] != '/')
992 return ERR_PTR(-EINVAL);
993
994 /* Born holding one reference; put_binfmt_handler() is the teardown. */
995 refcount_set(&e->users, 1);
996 return no_free_ptr(e);
997 }
998
999 /* Commands accepted by the /status and /<entry> files. */
1000 enum bm_command {
1001 BM_CMD_IGNORE, /* empty write */
1002 BM_CMD_DISABLE, /* "0" */
1003 BM_CMD_ENABLE, /* "1" */
1004 BM_CMD_REMOVE, /* "-1" */
1005 };
1006
1007 /* Longest of the commands above, "-1\n". */
1008 #define MAX_COMMAND_LENGTH 3
1009
1010 /*
1011 * Parse what userspace wrote to /status or an entry file: '1' enables,
1012 * '0' disables and '-1' removes the entry or all entries.
1013 */
parse_command(const char * s,size_t count)1014 static int parse_command(const char *s, size_t count)
1015 {
1016 if (count > MAX_COMMAND_LENGTH)
1017 return -EINVAL;
1018 if (!count)
1019 return BM_CMD_IGNORE;
1020 if (s[count - 1] == '\n')
1021 count--;
1022 if (count == 1 && s[0] == '0')
1023 return BM_CMD_DISABLE;
1024 if (count == 1 && s[0] == '1')
1025 return BM_CMD_ENABLE;
1026 if (count == 2 && s[0] == '-' && s[1] == '1')
1027 return BM_CMD_REMOVE;
1028 return -EINVAL;
1029 }
1030
1031 /* Copy in a command from a file that takes nothing else, and parse it. */
read_command(const char __user * buffer,size_t count)1032 static int read_command(const char __user *buffer, size_t count)
1033 {
1034 char s[MAX_COMMAND_LENGTH + 1];
1035
1036 if (count > sizeof(s) - 1)
1037 return -EINVAL;
1038 if (copy_from_user(s, buffer, count))
1039 return -EFAULT;
1040 return parse_command(s, count);
1041 }
1042
1043 /* generic stuff */
1044
1045 /* The root directory's inode; its lock serializes configuring an instance. */
bm_root_inode(struct super_block * sb)1046 static struct inode *bm_root_inode(struct super_block *sb)
1047 {
1048 return d_inode(sb->s_root);
1049 }
1050
bm_seq_hex(struct seq_file * m,const u8 * data,int size)1051 static void bm_seq_hex(struct seq_file *m, const u8 *data, int size)
1052 {
1053 for (int i = 0; i < size; i++)
1054 seq_printf(m, "%02x", data[i]);
1055 }
1056
bm_entry_show(struct seq_file * m,void * unused)1057 static int bm_entry_show(struct seq_file *m, void *unused)
1058 {
1059 struct binfmt_misc_entry *e = m->private;
1060
1061 if (test_bit(MISC_FMT_ENABLED_BIT, &e->flags))
1062 seq_puts(m, "enabled\n");
1063 else
1064 seq_puts(m, "disabled\n");
1065
1066 if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
1067 struct binfmt_misc_interp *interp;
1068
1069 seq_printf(m, "bpf %s\n", e->bpf_ops->name);
1070 /*
1071 * A staged entry's set can still grow, so every binding is
1072 * rcu-published. The open file pins the entry and with it
1073 * every node, so rcu is for the tearing, not the lifetime.
1074 */
1075 rcu_read_lock();
1076 list_for_each_entry_rcu(interp, &e->interps, list)
1077 seq_printf(m, "bpf-interpreter %s %s\n",
1078 interp->name, interp->path);
1079 rcu_read_unlock();
1080 } else {
1081 seq_printf(m, "interpreter %s\n", e->interpreter);
1082 }
1083
1084 /* print the special flags */
1085 seq_puts(m, "flags: ");
1086 for (int i = 0; i < ARRAY_SIZE(misc_flags); i++)
1087 if (e->flags & misc_flags[i].flag)
1088 seq_putc(m, misc_flags[i].c);
1089 seq_putc(m, '\n');
1090
1091 if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
1092 /* The program does the matching. */
1093 } else if (!test_bit(MISC_FMT_MAGIC_BIT, &e->flags)) {
1094 seq_printf(m, "extension .%s\n", e->magic);
1095 } else {
1096 seq_printf(m, "offset %i\nmagic ", e->offset);
1097 bm_seq_hex(m, e->magic, e->size);
1098 if (e->mask) {
1099 seq_puts(m, "\nmask ");
1100 bm_seq_hex(m, e->mask, e->size);
1101 }
1102 seq_putc(m, '\n');
1103 }
1104 return 0;
1105 }
1106
bm_get_inode(struct super_block * sb,umode_t mode)1107 static struct inode *bm_get_inode(struct super_block *sb, umode_t mode)
1108 {
1109 struct inode *inode = new_inode(sb);
1110
1111 if (inode) {
1112 inode->i_ino = get_next_ino();
1113 inode->i_mode = mode;
1114 simple_inode_init_ts(inode);
1115 }
1116 return inode;
1117 }
1118
1119 /**
1120 * i_binfmt_misc - retrieve struct binfmt_misc from a binfmt_misc inode
1121 * @inode: inode of the relevant binfmt_misc instance
1122 *
1123 * This helper retrieves struct binfmt_misc from a binfmt_misc inode. This can
1124 * be done without any memory barriers because we are guaranteed that
1125 * user_ns->binfmt_misc is fully initialized. It was fully initialized when the
1126 * binfmt_misc mount was first created.
1127 *
1128 * Return: struct binfmt_misc of the relevant binfmt_misc instance
1129 */
i_binfmt_misc(struct inode * inode)1130 static struct binfmt_misc *i_binfmt_misc(struct inode *inode)
1131 {
1132 return inode->i_sb->s_user_ns->binfmt_misc;
1133 }
1134
1135 /**
1136 * bm_evict_inode - cleanup data associated with @inode
1137 * @inode: inode to which the data is attached
1138 *
1139 * Cleanup the binary type handler data associated with @inode if a binary type
1140 * entry is removed or the filesystem is unmounted and the super block is
1141 * shutdown.
1142 *
1143 * If the ->evict call was not caused by a super block shutdown but by
1144 * removing the entry via bm_{entry,status}_write() or unlink(2) the entry
1145 * will have already been removed from the list. We keep the hlist_unhashed()
1146 * check to make that explicit.
1147 */
bm_evict_inode(struct inode * inode)1148 static void bm_evict_inode(struct inode *inode)
1149 {
1150 struct binfmt_misc_entry *e = inode->i_private;
1151
1152 clear_inode(inode);
1153
1154 if (e) {
1155 struct binfmt_misc *misc;
1156
1157 misc = i_binfmt_misc(inode);
1158 spin_lock(&misc->entries_lock);
1159 if (!hlist_unhashed(&e->node))
1160 hlist_del_init_rcu(&e->node);
1161 spin_unlock(&misc->entries_lock);
1162 put_binfmt_handler(e);
1163 }
1164 }
1165
1166 /**
1167 * unlink_binfmt_handler - unhash a binary type handler
1168 * @misc: handle to binfmt_misc instance
1169 * @e: binary type handler to unhash
1170 *
1171 * Adding and removing entries via bm_{entry,register,status}_write() and
1172 * unlink(2) happens under the exclusively held inode lock of the root
1173 * dentry keeping the list stable for writers. load_misc_binary() walks it
1174 * concurrently under SRCU. The entries_lock is only held around the actual
1175 * unlink to serialize against bm_evict_inode() which unlinks entries
1176 * during umount without holding the root inode lock.
1177 */
unlink_binfmt_handler(struct binfmt_misc * misc,struct binfmt_misc_entry * e)1178 static void unlink_binfmt_handler(struct binfmt_misc *misc,
1179 struct binfmt_misc_entry *e)
1180 {
1181 spin_lock(&misc->entries_lock);
1182 hlist_del_init_rcu(&e->node);
1183 spin_unlock(&misc->entries_lock);
1184 }
1185
1186 /**
1187 * remove_binfmt_handler - remove a binary type handler
1188 * @misc: handle to binfmt_misc instance
1189 * @e: binary type handler to remove
1190 *
1191 * Remove a binary type handler from the list of binary type handlers and
1192 * remove its associated dentry.
1193 */
remove_binfmt_handler(struct binfmt_misc * misc,struct binfmt_misc_entry * e)1194 static void remove_binfmt_handler(struct binfmt_misc *misc,
1195 struct binfmt_misc_entry *e)
1196 {
1197 unlink_binfmt_handler(misc, e);
1198 locked_recursive_removal(e->dentry, NULL);
1199 }
1200
1201 /* Remove @e unless it was already removed. */
bm_remove_entry(struct binfmt_misc_entry * e,struct super_block * sb)1202 static void bm_remove_entry(struct binfmt_misc_entry *e, struct super_block *sb)
1203 {
1204 struct inode *root = bm_root_inode(sb);
1205
1206 inode_lock_nested(root, I_MUTEX_PARENT);
1207 /* A staged entry is not hashed; the dentry says if it was removed. */
1208 if (!d_unhashed(e->dentry))
1209 remove_binfmt_handler(i_binfmt_misc(root), e);
1210 inode_unlock(root);
1211 }
1212
1213 /* Remove all entries of the binfmt_misc instance @misc belonging to @sb. */
bm_remove_all_entries(struct binfmt_misc * misc,struct super_block * sb)1214 static void bm_remove_all_entries(struct binfmt_misc *misc,
1215 struct super_block *sb)
1216 {
1217 struct inode *root = bm_root_inode(sb);
1218 struct dentry *child = NULL;
1219
1220 inode_lock_nested(root, I_MUTEX_PARENT);
1221 /*
1222 * Walk the directory rather than the search list: a staged entry
1223 * is in the former but not yet in the latter. The control files
1224 * carry no entry and stay.
1225 */
1226 while ((child = find_next_child(sb->s_root, child))) {
1227 struct binfmt_misc_entry *e = d_inode(child)->i_private;
1228
1229 if (e)
1230 remove_binfmt_handler(misc, e);
1231 }
1232 inode_unlock(root);
1233 }
1234
1235 /**
1236 * bm_unlink - remove a binary type handler via unlink(2)
1237 * @dir: inode of the root directory
1238 * @dentry: entry file to remove
1239 *
1240 * Removing the entry file removes its binary type handler, exactly like
1241 * writing -1 to it does. The status and register control files can't be
1242 * removed. The VFS calls this with the root inode lock held which
1243 * serializes against the write based add and remove paths.
1244 */
bm_unlink(struct inode * dir,struct dentry * dentry)1245 static int bm_unlink(struct inode *dir, struct dentry *dentry)
1246 {
1247 struct binfmt_misc_entry *e = d_inode(dentry)->i_private;
1248
1249 if (!e)
1250 return -EPERM;
1251
1252 unlink_binfmt_handler(i_binfmt_misc(dir), e);
1253 return simple_unlink(dir, dentry);
1254 }
1255
1256 static const struct inode_operations bm_dir_inode_operations = {
1257 .lookup = simple_lookup,
1258 .unlink = bm_unlink,
1259 };
1260
1261 /* /<entry> */
1262
bm_entry_open(struct inode * inode,struct file * file)1263 static int bm_entry_open(struct inode *inode, struct file *file)
1264 {
1265 int ret;
1266
1267 ret = single_open(file, bm_entry_show, inode->i_private);
1268 if (ret)
1269 return ret;
1270
1271 /* seq_open() clears FMODE_PWRITE, bm_entry_write() takes any offset */
1272 if (file->f_mode & FMODE_WRITE)
1273 file->f_mode |= FMODE_PWRITE;
1274 return 0;
1275 }
1276
1277 /*
1278 * Longest '+<name> <path>' a write can spell, and with it the longest
1279 * command an entry file takes: the two delimiters and a newline on top of
1280 * the two names.
1281 */
1282 #define MAX_BINDING_LENGTH (BINFMT_MISC_INTERP_NAME_MAX + PATH_MAX + 3)
1283
1284 /**
1285 * bm_entry_add_interp - bind another interpreter to a staged entry
1286 * @e: the entry
1287 * @file: the entry file being written to, for its credentials
1288 * @buf: the '+<name> <path>' command, parsed in place and owned by the caller
1289 * @count: its length
1290 *
1291 * A 'D' entry is registered outside the search list, which is what leaves
1292 * it open to being configured: it cannot be matched, so no exec can be
1293 * holding its interpreters and the set can still grow. Its first enable
1294 * publishes it and ends that. One interpreter per write, up to
1295 * BINFMT_MISC_INTERP_MAX of them, none of which has to fit in a register
1296 * string.
1297 *
1298 * Return: @count on success, a negative errno on failure
1299 */
bm_entry_add_interp(struct binfmt_misc_entry * e,struct file * file,char * buf,size_t count)1300 static ssize_t bm_entry_add_interp(struct binfmt_misc_entry *e,
1301 struct file *file, char *buf, size_t count)
1302 {
1303 struct file *f __free(close_interp_file) = NULL;
1304 struct inode *root = bm_root_inode(file_inode(file)->i_sb);
1305 size_t nlen, plen;
1306 char *name, *path;
1307 int retval;
1308
1309 /* Settled before the open: type is fixed, publication is permanent. */
1310 if (!test_bit(MISC_FMT_BPF_BIT, &e->flags))
1311 return -EINVAL;
1312 if (!hlist_unhashed_lockless(&e->node))
1313 return -EBUSY;
1314
1315 /* '+<name> <path>': the path is everything past the first space. */
1316 name = buf + 1;
1317 path = strchr(name, ' ');
1318 if (!path)
1319 return -EINVAL;
1320 *path++ = '\0';
1321
1322 plen = strlen(path);
1323 /* The command has to end at the write, like a register string. */
1324 if (path + plen != buf + count)
1325 return -EINVAL;
1326 if (plen && path[plen - 1] == '\n')
1327 path[--plen] = '\0';
1328 /* Resolved now, so a relative path would name the writer's cwd. */
1329 if (path[0] != '/')
1330 return -EINVAL;
1331
1332 nlen = path - name - 1;
1333 if (!nlen || nlen > BINFMT_MISC_INTERP_NAME_MAX)
1334 return -EINVAL;
1335 /* The name prints between delimiters, so keep it a printable word. */
1336 for (const char *p = name; *p; p++)
1337 if (!isascii(*p) || !isgraph(*p))
1338 return -EINVAL;
1339
1340 /* Opened before the lock: resolving it may walk this very filesystem. */
1341 f = open_interp_file(file->f_cred, path);
1342 if (IS_ERR(f))
1343 return PTR_ERR(f);
1344
1345 inode_lock(root);
1346 if (d_unhashed(e->dentry))
1347 retval = -ENOENT; /* removed while we were opening it */
1348 else if (!hlist_unhashed(&e->node))
1349 retval = -EBUSY; /* published while we were opening it */
1350 else
1351 retval = entry_attach_interpreter(e, name, path, f);
1352 inode_unlock(root);
1353 if (retval)
1354 return retval;
1355
1356 /* The file is owned by the entry now. */
1357 retain_and_null_ptr(f);
1358 return count;
1359 }
1360
bm_entry_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)1361 static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
1362 size_t count, loff_t *ppos)
1363 {
1364 struct inode *inode = file_inode(file);
1365 struct binfmt_misc_entry *e = inode->i_private;
1366 char *buf __free(kfree) = NULL;
1367 int res;
1368
1369 /* A binding is the longest command this file takes. */
1370 if (count > MAX_BINDING_LENGTH)
1371 return -E2BIG;
1372
1373 buf = memdup_user_nul(buffer, count);
1374 if (IS_ERR(buf))
1375 return PTR_ERR(buf);
1376
1377 /* '+<name> <path>' binds an interpreter, everything else toggles. */
1378 if (buf[0] == '+')
1379 return bm_entry_add_interp(e, file, buf, count);
1380
1381 res = parse_command(buf, count);
1382
1383 switch (res) {
1384 case BM_CMD_DISABLE:
1385 clear_bit(MISC_FMT_ENABLED_BIT, &e->flags);
1386 break;
1387 case BM_CMD_ENABLE: {
1388 struct inode *root = bm_root_inode(inode->i_sb);
1389
1390 /*
1391 * The first enable publishes a 'D' entry into the search
1392 * list, whole. The lock keeps that ordered against a second
1393 * enable, against removal - a removed entry has nothing left
1394 * to publish - and against binding: what can be matched can
1395 * no longer be configured.
1396 */
1397 inode_lock(root);
1398 set_bit(MISC_FMT_ENABLED_BIT, &e->flags);
1399 if (hlist_unhashed(&e->node) && !d_unhashed(e->dentry)) {
1400 struct binfmt_misc *misc = i_binfmt_misc(inode);
1401
1402 spin_lock(&misc->entries_lock);
1403 hlist_add_head_rcu(&e->node, &misc->entries);
1404 spin_unlock(&misc->entries_lock);
1405 }
1406 inode_unlock(root);
1407 break;
1408 }
1409 case BM_CMD_REMOVE:
1410 bm_remove_entry(e, inode->i_sb);
1411 break;
1412 default:
1413 return res;
1414 }
1415
1416 return count;
1417 }
1418
1419 static const struct file_operations bm_entry_operations = {
1420 .open = bm_entry_open,
1421 .read = seq_read,
1422 .write = bm_entry_write,
1423 .llseek = seq_lseek,
1424 .release = single_release,
1425 };
1426
1427 /* /register */
1428
1429 /* add to filesystem */
add_entry(struct binfmt_misc_entry * e,struct super_block * sb)1430 static int add_entry(struct binfmt_misc_entry *e, struct super_block *sb)
1431 {
1432 struct dentry *dentry = simple_start_creating(sb->s_root, e->name);
1433 struct inode *inode;
1434 struct binfmt_misc *misc;
1435
1436 if (IS_ERR(dentry))
1437 return PTR_ERR(dentry);
1438
1439 inode = bm_get_inode(sb, S_IFREG | 0644);
1440 if (unlikely(!inode)) {
1441 simple_done_creating(dentry);
1442 return -ENOMEM;
1443 }
1444
1445 e->dentry = dentry;
1446 inode->i_private = e;
1447 inode->i_fop = &bm_entry_operations;
1448
1449 d_make_persistent(dentry, inode);
1450 /* A 'D' entry stays out of the search list until its first enable. */
1451 if (test_bit(MISC_FMT_ENABLED_BIT, &e->flags)) {
1452 misc = i_binfmt_misc(inode);
1453 spin_lock(&misc->entries_lock);
1454 hlist_add_head_rcu(&e->node, &misc->entries);
1455 spin_unlock(&misc->entries_lock);
1456 }
1457 simple_done_creating(dentry);
1458 return 0;
1459 }
1460
bm_register_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)1461 static ssize_t bm_register_write(struct file *file, const char __user *buffer,
1462 size_t count, loff_t *ppos)
1463 {
1464 struct binfmt_misc_entry *e __free(put_binfmt_handler) = NULL;
1465 struct super_block *sb = file_inode(file)->i_sb;
1466 int err;
1467
1468 e = create_entry(buffer, count);
1469 if (IS_ERR(e))
1470 return PTR_ERR(e);
1471
1472 if (test_bit(MISC_FMT_BPF_BIT, &e->flags)) {
1473 e->bpf_ops = binfmt_misc_get_ops(sb->s_user_ns, e->bpf_ops_name);
1474 if (!e->bpf_ops) {
1475 pr_notice("register: no bpf handler named %s\n",
1476 e->bpf_ops_name);
1477 return -ENOENT;
1478 }
1479 }
1480
1481 if (e->flags & MISC_FMT_OPEN_FILE) {
1482 struct file *f = open_interp_file(file->f_cred, e->interpreter);
1483
1484 if (IS_ERR(f))
1485 return PTR_ERR(f);
1486 err = entry_attach_interpreter(e, "", e->interpreter, f);
1487 if (err) {
1488 close_interp_file(f);
1489 return err;
1490 }
1491 }
1492
1493 err = add_entry(e, sb);
1494 if (err)
1495 return err;
1496
1497 /* The entry is owned by its inode now. */
1498 retain_and_null_ptr(e);
1499 return count;
1500 }
1501
1502 static const struct file_operations bm_register_operations = {
1503 .write = bm_register_write,
1504 .llseek = noop_llseek,
1505 };
1506
1507 /* /status */
1508
1509 static ssize_t
bm_status_read(struct file * file,char __user * buf,size_t nbytes,loff_t * ppos)1510 bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
1511 {
1512 struct binfmt_misc *misc;
1513 const char *s;
1514
1515 misc = i_binfmt_misc(file_inode(file));
1516 s = READ_ONCE(misc->enabled) ? "enabled\n" : "disabled\n";
1517 return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
1518 }
1519
bm_status_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)1520 static ssize_t bm_status_write(struct file *file, const char __user *buffer,
1521 size_t count, loff_t *ppos)
1522 {
1523 struct binfmt_misc *misc;
1524 int res = read_command(buffer, count);
1525
1526 misc = i_binfmt_misc(file_inode(file));
1527 switch (res) {
1528 case BM_CMD_DISABLE:
1529 WRITE_ONCE(misc->enabled, false);
1530 break;
1531 case BM_CMD_ENABLE:
1532 WRITE_ONCE(misc->enabled, true);
1533 break;
1534 case BM_CMD_REMOVE:
1535 bm_remove_all_entries(misc, file_inode(file)->i_sb);
1536 break;
1537 default:
1538 return res;
1539 }
1540
1541 return count;
1542 }
1543
1544 static const struct file_operations bm_status_operations = {
1545 .read = bm_status_read,
1546 .write = bm_status_write,
1547 .llseek = default_llseek,
1548 };
1549
1550 /* Superblock handling */
1551
1552 static const struct super_operations bm_super_ops = {
1553 .statfs = simple_statfs,
1554 .evict_inode = bm_evict_inode,
1555 };
1556
bm_fill_super(struct super_block * sb,struct fs_context * fc)1557 static int bm_fill_super(struct super_block *sb, struct fs_context *fc)
1558 {
1559 int err;
1560 struct user_namespace *user_ns = sb->s_user_ns;
1561 struct binfmt_misc *misc;
1562 static const struct tree_descr bm_files[] = {
1563 [2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
1564 [3] = {"register", &bm_register_operations, S_IWUSR},
1565 /* last one */ {""}
1566 };
1567
1568 /* The fscontext fd may have been passed to another user namespace. */
1569 if (user_ns != current_user_ns())
1570 return -EINVAL;
1571
1572 /* Never exec off this instance and never let anything stack on it. */
1573 sb->s_iflags |= SB_I_NOEXEC | SB_I_NODEV;
1574 sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH;
1575
1576 /*
1577 * Lazily allocate a new binfmt_misc instance for this namespace, i.e.
1578 * do it here during the first mount of binfmt_misc. We don't need to
1579 * waste memory for every user namespace allocation. It's likely much
1580 * more common to not mount a separate binfmt_misc instance than it is
1581 * to mount one.
1582 *
1583 * While multiple superblocks can exist they are keyed by userns in
1584 * s_fs_info for binfmt_misc. Hence, the vfs guarantees that
1585 * bm_fill_super() is called exactly once whenever a binfmt_misc
1586 * superblock for a userns is created. This in turn lets us conclude
1587 * that when a binfmt_misc superblock is created for the first time for
1588 * a userns there's no one racing us. Therefore we don't need any
1589 * barriers when we dereference binfmt_misc.
1590 */
1591 misc = user_ns->binfmt_misc;
1592 if (!misc) {
1593 /*
1594 * If it turns out that most user namespaces actually want to
1595 * register their own binary type handler and therefore all
1596 * create their own separate binfmt_misc mounts we should
1597 * consider turning this into a kmem cache.
1598 */
1599 misc = kzalloc_obj(struct binfmt_misc);
1600 if (!misc)
1601 return -ENOMEM;
1602
1603 INIT_HLIST_HEAD(&misc->entries);
1604 spin_lock_init(&misc->entries_lock);
1605
1606 /* Pairs with smp_load_acquire() in current_binfmt_misc(). */
1607 smp_store_release(&user_ns->binfmt_misc, misc);
1608 }
1609
1610 /*
1611 * When the binfmt_misc superblock for this userns is shutdown
1612 * ->enabled might have been set to false and we don't reinitialize
1613 * ->enabled again during shutdown as someone might already be mounting
1614 * binfmt_misc again. It also would be pointless since by then we know
1615 * that the binary type list for this binfmt_misc mount is empty making
1616 * load_misc_binary() return -ENOEXEC independent of whether ->enabled
1617 * is true. Instead, if someone mounts binfmt_misc for the first time or
1618 * again we simply reset ->enabled to true.
1619 */
1620 WRITE_ONCE(misc->enabled, true);
1621
1622 err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
1623 if (err)
1624 return err;
1625
1626 sb->s_op = &bm_super_ops;
1627 d_inode(sb->s_root)->i_op = &bm_dir_inode_operations;
1628 return 0;
1629 }
1630
bm_free(struct fs_context * fc)1631 static void bm_free(struct fs_context *fc)
1632 {
1633 if (fc->s_fs_info)
1634 put_user_ns(fc->s_fs_info);
1635 }
1636
bm_get_tree(struct fs_context * fc)1637 static int bm_get_tree(struct fs_context *fc)
1638 {
1639 return get_tree_keyed(fc, bm_fill_super, get_user_ns(fc->user_ns));
1640 }
1641
1642 static const struct fs_context_operations bm_context_ops = {
1643 .free = bm_free,
1644 .get_tree = bm_get_tree,
1645 };
1646
bm_kill_sb(struct super_block * sb)1647 static void bm_kill_sb(struct super_block *sb)
1648 {
1649 struct user_namespace *user_ns = sb->s_fs_info;
1650
1651 kill_anon_super(sb);
1652 put_user_ns(user_ns);
1653 }
1654
bm_init_fs_context(struct fs_context * fc)1655 static int bm_init_fs_context(struct fs_context *fc)
1656 {
1657 fc->ops = &bm_context_ops;
1658 return 0;
1659 }
1660
1661 static struct linux_binfmt misc_format = {
1662 .module = THIS_MODULE,
1663 .load_binary = load_misc_binary,
1664 };
1665
1666 static struct file_system_type bm_fs_type = {
1667 .owner = THIS_MODULE,
1668 .name = "binfmt_misc",
1669 .init_fs_context = bm_init_fs_context,
1670 .fs_flags = FS_USERNS_MOUNT,
1671 .kill_sb = bm_kill_sb,
1672 };
1673 MODULE_ALIAS_FS("binfmt_misc");
1674
init_misc_binfmt(void)1675 static int __init init_misc_binfmt(void)
1676 {
1677 int err = register_filesystem(&bm_fs_type);
1678 if (!err)
1679 insert_binfmt(&misc_format);
1680 return err;
1681 }
1682
exit_misc_binfmt(void)1683 static void __exit exit_misc_binfmt(void)
1684 {
1685 unregister_binfmt(&misc_format);
1686 unregister_filesystem(&bm_fs_type);
1687 /* Flush pending bm_entry_free_rcu() callbacks before the text goes. */
1688 srcu_barrier(&bm_entries_srcu);
1689 }
1690
1691 core_initcall(init_misc_binfmt);
1692 module_exit(exit_misc_binfmt);
1693 MODULE_DESCRIPTION("Kernel support for miscellaneous binaries");
1694 MODULE_LICENSE("GPL");
1695