1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1997 Richard Günther
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.
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/init.h>
16 #include <linux/sched/mm.h>
17 #include <linux/magic.h>
18 #include <linux/binfmts.h>
19 #include <linux/slab.h>
20 #include <linux/ctype.h>
21 #include <linux/string_helpers.h>
22 #include <linux/file.h>
23 #include <linux/pagemap.h>
24 #include <linux/namei.h>
25 #include <linux/mount.h>
26 #include <linux/fs_context.h>
27 #include <linux/syscalls.h>
29 #include <linux/uaccess.h>
40 VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */
43 static LIST_HEAD(entries);
44 static int enabled = 1;
46 enum {Enabled, Magic};
47 #define MISC_FMT_PRESERVE_ARGV0 (1UL << 31)
48 #define MISC_FMT_OPEN_BINARY (1UL << 30)
49 #define MISC_FMT_CREDENTIALS (1UL << 29)
50 #define MISC_FMT_OPEN_FILE (1UL << 28)
53 struct list_head list;
54 unsigned long flags; /* type, status, etc. */
55 int offset; /* offset of magic */
56 int size; /* size of magic/mask */
57 char *magic; /* magic or filename extension */
58 char *mask; /* mask, NULL for exact match */
59 const char *interpreter; /* filename of interpreter */
61 struct dentry *dentry;
62 struct file *interp_file;
65 static DEFINE_RWLOCK(entries_lock);
66 static struct file_system_type bm_fs_type;
67 static struct vfsmount *bm_mnt;
68 static int entry_count;
71 * Max length of the register string. Determined by:
75 * - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE)
76 * - magic: 128 bytes (512 in escaped form)
77 * - mask: 128 bytes (512 in escaped form)
80 * Round that up a bit, and then back off to hold the internal data
83 #define MAX_REGISTER_LENGTH 1920
86 * Check if we support the binfmt
87 * if we do, return the node, else NULL
88 * locking is done in load_misc_binary
90 static Node *check_file(struct linux_binprm *bprm)
92 char *p = strrchr(bprm->interp, '.');
95 /* Walk all the registered handlers. */
96 list_for_each(l, &entries) {
97 Node *e = list_entry(l, Node, list);
101 /* Make sure this one is currently enabled. */
102 if (!test_bit(Enabled, &e->flags))
105 /* Do matching based on extension if applicable. */
106 if (!test_bit(Magic, &e->flags)) {
107 if (p && !strcmp(e->magic, p + 1))
112 /* Do matching based on magic & mask. */
113 s = bprm->buf + e->offset;
115 for (j = 0; j < e->size; j++)
116 if ((*s++ ^ e->magic[j]) & e->mask[j])
119 for (j = 0; j < e->size; j++)
120 if ((*s++ ^ e->magic[j]))
132 static int load_misc_binary(struct linux_binprm *bprm)
135 struct file *interp_file = NULL;
142 /* to keep locking time low, we copy the interpreter string */
143 read_lock(&entries_lock);
144 fmt = check_file(bprm);
147 read_unlock(&entries_lock);
151 /* Need to be able to load the file after exec */
153 if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
156 if (fmt->flags & MISC_FMT_PRESERVE_ARGV0) {
157 bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0;
159 retval = remove_arg_zero(bprm);
164 if (fmt->flags & MISC_FMT_OPEN_BINARY)
165 bprm->have_execfd = 1;
167 /* make argv[1] be the path to the binary */
168 retval = copy_string_kernel(bprm->interp, bprm);
173 /* add the interp as argv[0] */
174 retval = copy_string_kernel(fmt->interpreter, bprm);
179 /* Update interp in case binfmt_script needs it. */
180 retval = bprm_change_interp(fmt->interpreter, bprm);
184 if (fmt->flags & MISC_FMT_OPEN_FILE) {
185 interp_file = file_clone_open(fmt->interp_file);
186 if (!IS_ERR(interp_file))
187 deny_write_access(interp_file);
189 interp_file = open_exec(fmt->interpreter);
191 retval = PTR_ERR(interp_file);
192 if (IS_ERR(interp_file))
195 bprm->interpreter = interp_file;
196 if (fmt->flags & MISC_FMT_CREDENTIALS)
197 bprm->execfd_creds = 1;
205 /* Command parsers */
208 * parses and copies one argument enclosed in del from *sp to *dp,
209 * recognising the \x special.
210 * returns pointer to the copied argument or NULL in case of an
211 * error (and sets err) or null argument length.
213 static char *scanarg(char *s, char del)
217 while ((c = *s++) != del) {
218 if (c == '\\' && *s == 'x') {
230 static char *check_special_flags(char *sfs, Node *e)
239 pr_debug("register: flag: P (preserve argv0)\n");
241 e->flags |= MISC_FMT_PRESERVE_ARGV0;
244 pr_debug("register: flag: O (open binary)\n");
246 e->flags |= MISC_FMT_OPEN_BINARY;
249 pr_debug("register: flag: C (preserve creds)\n");
251 /* this flags also implies the
253 e->flags |= (MISC_FMT_CREDENTIALS |
254 MISC_FMT_OPEN_BINARY);
257 pr_debug("register: flag: F: open interpreter file now\n");
259 e->flags |= MISC_FMT_OPEN_FILE;
270 * This registers a new binary format, it recognises the syntax
271 * ':name:type:offset:magic:mask:interpreter:flags'
272 * where the ':' is the IFS, that can be chosen with the first char
274 static Node *create_entry(const char __user *buffer, size_t count)
281 pr_debug("register: received %zu bytes\n", count);
283 /* some sanity checks */
285 if ((count < 11) || (count > MAX_REGISTER_LENGTH))
289 memsize = sizeof(Node) + count + 8;
290 e = kmalloc(memsize, GFP_KERNEL);
294 p = buf = (char *)e + sizeof(Node);
296 memset(e, 0, sizeof(Node));
297 if (copy_from_user(buf, buffer, count))
300 del = *p++; /* delimeter */
302 pr_debug("register: delim: %#x {%c}\n", del, del);
304 /* Pad the buffer with the delim to simplify parsing below. */
305 memset(buf + count, del, 8);
307 /* Parse the 'name' field. */
314 !strcmp(e->name, ".") ||
315 !strcmp(e->name, "..") ||
316 strchr(e->name, '/'))
319 pr_debug("register: name: {%s}\n", e->name);
321 /* Parse the 'type' field. */
324 pr_debug("register: type: E (extension)\n");
325 e->flags = 1 << Enabled;
328 pr_debug("register: type: M (magic)\n");
329 e->flags = (1 << Enabled) | (1 << Magic);
337 if (test_bit(Magic, &e->flags)) {
338 /* Handle the 'M' (magic) format. */
341 /* Parse the 'offset' field. */
347 int r = kstrtoint(p, 10, &e->offset);
348 if (r != 0 || e->offset < 0)
354 pr_debug("register: offset: %#x\n", e->offset);
356 /* Parse the 'magic' field. */
364 print_hex_dump_bytes(
365 KBUILD_MODNAME ": register: magic[raw]: ",
366 DUMP_PREFIX_NONE, e->magic, p - e->magic);
368 /* Parse the 'mask' field. */
375 pr_debug("register: mask[raw]: none\n");
376 } else if (USE_DEBUG)
377 print_hex_dump_bytes(
378 KBUILD_MODNAME ": register: mask[raw]: ",
379 DUMP_PREFIX_NONE, e->mask, p - e->mask);
382 * Decode the magic & mask fields.
383 * Note: while we might have accepted embedded NUL bytes from
384 * above, the unescape helpers here will stop at the first one
387 e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX);
389 string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size)
391 if (e->size > BINPRM_BUF_SIZE ||
392 BINPRM_BUF_SIZE - e->size < e->offset)
394 pr_debug("register: magic/mask length: %i\n", e->size);
396 print_hex_dump_bytes(
397 KBUILD_MODNAME ": register: magic[decoded]: ",
398 DUMP_PREFIX_NONE, e->magic, e->size);
402 char *masked = kmalloc(e->size, GFP_KERNEL);
404 print_hex_dump_bytes(
405 KBUILD_MODNAME ": register: mask[decoded]: ",
406 DUMP_PREFIX_NONE, e->mask, e->size);
409 for (i = 0; i < e->size; ++i)
410 masked[i] = e->magic[i] & e->mask[i];
411 print_hex_dump_bytes(
412 KBUILD_MODNAME ": register: magic[masked]: ",
413 DUMP_PREFIX_NONE, masked, e->size);
420 /* Handle the 'E' (extension) format. */
422 /* Skip the 'offset' field. */
428 /* Parse the 'magic' field. */
434 if (!e->magic[0] || strchr(e->magic, '/'))
436 pr_debug("register: extension: {%s}\n", e->magic);
438 /* Skip the 'mask' field. */
445 /* Parse the 'interpreter' field. */
451 if (!e->interpreter[0])
453 pr_debug("register: interpreter: {%s}\n", e->interpreter);
455 /* Parse the 'flags' field. */
456 p = check_special_flags(p, e);
459 if (p != buf + count)
469 return ERR_PTR(-EFAULT);
472 return ERR_PTR(-EINVAL);
476 * Set status of entry/binfmt_misc:
477 * '1' enables, '0' disables and '-1' clears entry/binfmt_misc
479 static int parse_command(const char __user *buffer, size_t count)
485 if (copy_from_user(s, buffer, count))
489 if (s[count - 1] == '\n')
491 if (count == 1 && s[0] == '0')
493 if (count == 1 && s[0] == '1')
495 if (count == 2 && s[0] == '-' && s[1] == '1')
502 static void entry_status(Node *e, char *page)
505 const char *status = "disabled";
507 if (test_bit(Enabled, &e->flags))
510 if (!VERBOSE_STATUS) {
511 sprintf(page, "%s\n", status);
515 dp += sprintf(dp, "%s\ninterpreter %s\n", status, e->interpreter);
517 /* print the special flags */
518 dp += sprintf(dp, "flags: ");
519 if (e->flags & MISC_FMT_PRESERVE_ARGV0)
521 if (e->flags & MISC_FMT_OPEN_BINARY)
523 if (e->flags & MISC_FMT_CREDENTIALS)
525 if (e->flags & MISC_FMT_OPEN_FILE)
529 if (!test_bit(Magic, &e->flags)) {
530 sprintf(dp, "extension .%s\n", e->magic);
532 dp += sprintf(dp, "offset %i\nmagic ", e->offset);
533 dp = bin2hex(dp, e->magic, e->size);
535 dp += sprintf(dp, "\nmask ");
536 dp = bin2hex(dp, e->mask, e->size);
543 static struct inode *bm_get_inode(struct super_block *sb, int mode)
545 struct inode *inode = new_inode(sb);
548 inode->i_ino = get_next_ino();
549 inode->i_mode = mode;
550 inode->i_atime = inode->i_mtime = inode->i_ctime =
556 static void bm_evict_inode(struct inode *inode)
558 Node *e = inode->i_private;
560 if (e && e->flags & MISC_FMT_OPEN_FILE)
561 filp_close(e->interp_file, NULL);
567 static void kill_node(Node *e)
569 struct dentry *dentry;
571 write_lock(&entries_lock);
572 list_del_init(&e->list);
573 write_unlock(&entries_lock);
576 drop_nlink(d_inode(dentry));
579 simple_release_fs(&bm_mnt, &entry_count);
585 bm_entry_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
587 Node *e = file_inode(file)->i_private;
591 page = (char *) __get_free_page(GFP_KERNEL);
595 entry_status(e, page);
597 res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page));
599 free_page((unsigned long) page);
603 static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
604 size_t count, loff_t *ppos)
607 Node *e = file_inode(file)->i_private;
608 int res = parse_command(buffer, count);
612 /* Disable this handler. */
613 clear_bit(Enabled, &e->flags);
616 /* Enable this handler. */
617 set_bit(Enabled, &e->flags);
620 /* Delete this handler. */
621 root = file_inode(file)->i_sb->s_root;
622 inode_lock(d_inode(root));
624 if (!list_empty(&e->list))
627 inode_unlock(d_inode(root));
636 static const struct file_operations bm_entry_operations = {
637 .read = bm_entry_read,
638 .write = bm_entry_write,
639 .llseek = default_llseek,
644 static ssize_t bm_register_write(struct file *file, const char __user *buffer,
645 size_t count, loff_t *ppos)
649 struct super_block *sb = file_inode(file)->i_sb;
650 struct dentry *root = sb->s_root, *dentry;
652 struct file *f = NULL;
654 e = create_entry(buffer, count);
659 if (e->flags & MISC_FMT_OPEN_FILE) {
660 f = open_exec(e->interpreter);
662 pr_notice("register: failed to install interpreter file %s\n",
670 inode_lock(d_inode(root));
671 dentry = lookup_one_len(e->name, root, strlen(e->name));
672 err = PTR_ERR(dentry);
677 if (d_really_is_positive(dentry))
680 inode = bm_get_inode(sb, S_IFREG | 0644);
686 err = simple_pin_fs(&bm_fs_type, &bm_mnt, &entry_count);
693 e->dentry = dget(dentry);
694 inode->i_private = e;
695 inode->i_fop = &bm_entry_operations;
697 d_instantiate(dentry, inode);
698 write_lock(&entries_lock);
699 list_add(&e->list, &entries);
700 write_unlock(&entries_lock);
706 inode_unlock(d_inode(root));
717 static const struct file_operations bm_register_operations = {
718 .write = bm_register_write,
719 .llseek = noop_llseek,
725 bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
727 char *s = enabled ? "enabled\n" : "disabled\n";
729 return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
732 static ssize_t bm_status_write(struct file *file, const char __user *buffer,
733 size_t count, loff_t *ppos)
735 int res = parse_command(buffer, count);
740 /* Disable all handlers. */
744 /* Enable all handlers. */
748 /* Delete all handlers. */
749 root = file_inode(file)->i_sb->s_root;
750 inode_lock(d_inode(root));
752 while (!list_empty(&entries))
753 kill_node(list_first_entry(&entries, Node, list));
755 inode_unlock(d_inode(root));
764 static const struct file_operations bm_status_operations = {
765 .read = bm_status_read,
766 .write = bm_status_write,
767 .llseek = default_llseek,
770 /* Superblock handling */
772 static const struct super_operations s_ops = {
773 .statfs = simple_statfs,
774 .evict_inode = bm_evict_inode,
777 static int bm_fill_super(struct super_block *sb, struct fs_context *fc)
780 static const struct tree_descr bm_files[] = {
781 [2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
782 [3] = {"register", &bm_register_operations, S_IWUSR},
786 err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
792 static int bm_get_tree(struct fs_context *fc)
794 return get_tree_single(fc, bm_fill_super);
797 static const struct fs_context_operations bm_context_ops = {
798 .get_tree = bm_get_tree,
801 static int bm_init_fs_context(struct fs_context *fc)
803 fc->ops = &bm_context_ops;
807 static struct linux_binfmt misc_format = {
808 .module = THIS_MODULE,
809 .load_binary = load_misc_binary,
812 static struct file_system_type bm_fs_type = {
813 .owner = THIS_MODULE,
814 .name = "binfmt_misc",
815 .init_fs_context = bm_init_fs_context,
816 .kill_sb = kill_litter_super,
818 MODULE_ALIAS_FS("binfmt_misc");
820 static int __init init_misc_binfmt(void)
822 int err = register_filesystem(&bm_fs_type);
824 insert_binfmt(&misc_format);
828 static void __exit exit_misc_binfmt(void)
830 unregister_binfmt(&misc_format);
831 unregister_filesystem(&bm_fs_type);
834 core_initcall(init_misc_binfmt);
835 module_exit(exit_misc_binfmt);
836 MODULE_LICENSE("GPL");