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/kernel.h> 14 #include <linux/module.h> 15 #include <linux/hex.h> 16 #include <linux/init.h> 17 #include <linux/sched/mm.h> 18 #include <linux/magic.h> 19 #include <linux/binfmts.h> 20 #include <linux/slab.h> 21 #include <linux/ctype.h> 22 #include <linux/string_helpers.h> 23 #include <linux/file.h> 24 #include <linux/pagemap.h> 25 #include <linux/namei.h> 26 #include <linux/mount.h> 27 #include <linux/fs_context.h> 28 #include <linux/syscalls.h> 29 #include <linux/fs.h> 30 #include <linux/uaccess.h> 31 32 #include "internal.h" 33 34 #ifdef DEBUG 35 # define USE_DEBUG 1 36 #else 37 # define USE_DEBUG 0 38 #endif 39 40 enum { 41 VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */ 42 }; 43 44 enum {Enabled, Magic}; 45 #define MISC_FMT_PRESERVE_ARGV0 (1UL << 31) 46 #define MISC_FMT_OPEN_BINARY (1UL << 30) 47 #define MISC_FMT_CREDENTIALS (1UL << 29) 48 #define MISC_FMT_OPEN_FILE (1UL << 28) 49 50 typedef struct { 51 struct list_head list; 52 unsigned long flags; /* type, status, etc. */ 53 int offset; /* offset of magic */ 54 int size; /* size of magic/mask */ 55 char *magic; /* magic or filename extension */ 56 char *mask; /* mask, NULL for exact match */ 57 const char *interpreter; /* filename of interpreter */ 58 char *name; 59 struct dentry *dentry; 60 struct file *interp_file; 61 refcount_t users; /* sync removal with load_misc_binary() */ 62 } Node; 63 64 static struct file_system_type bm_fs_type; 65 66 /* 67 * Max length of the register string. Determined by: 68 * - 7 delimiters 69 * - name: ~50 bytes 70 * - type: 1 byte 71 * - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE) 72 * - magic: 128 bytes (512 in escaped form) 73 * - mask: 128 bytes (512 in escaped form) 74 * - interp: ~50 bytes 75 * - flags: 5 bytes 76 * Round that up a bit, and then back off to hold the internal data 77 * (like struct Node). 78 */ 79 #define MAX_REGISTER_LENGTH 1920 80 81 /** 82 * search_binfmt_handler - search for a binary handler for @bprm 83 * @misc: handle to binfmt_misc instance 84 * @bprm: binary for which we are looking for a handler 85 * 86 * Search for a binary type handler for @bprm in the list of registered binary 87 * type handlers. 88 * 89 * Return: binary type list entry on success, NULL on failure 90 */ 91 static Node *search_binfmt_handler(struct binfmt_misc *misc, 92 struct linux_binprm *bprm) 93 { 94 char *p = strrchr(bprm->interp, '.'); 95 Node *e; 96 97 /* Walk all the registered handlers. */ 98 list_for_each_entry(e, &misc->entries, list) { 99 char *s; 100 int j; 101 102 /* Make sure this one is currently enabled. */ 103 if (!test_bit(Enabled, &e->flags)) 104 continue; 105 106 /* Do matching based on extension if applicable. */ 107 if (!test_bit(Magic, &e->flags)) { 108 if (p && !strcmp(e->magic, p + 1)) 109 return e; 110 continue; 111 } 112 113 /* Do matching based on magic & mask. */ 114 s = bprm->buf + e->offset; 115 if (e->mask) { 116 for (j = 0; j < e->size; j++) 117 if ((*s++ ^ e->magic[j]) & e->mask[j]) 118 break; 119 } else { 120 for (j = 0; j < e->size; j++) 121 if ((*s++ ^ e->magic[j])) 122 break; 123 } 124 if (j == e->size) 125 return e; 126 } 127 128 return NULL; 129 } 130 131 /** 132 * get_binfmt_handler - try to find a binary type handler 133 * @misc: handle to binfmt_misc instance 134 * @bprm: binary for which we are looking for a handler 135 * 136 * Try to find a binfmt handler for the binary type. If one is found take a 137 * reference to protect against removal via bm_{entry,status}_write(). 138 * 139 * Return: binary type list entry on success, NULL on failure 140 */ 141 static Node *get_binfmt_handler(struct binfmt_misc *misc, 142 struct linux_binprm *bprm) 143 { 144 Node *e; 145 146 read_lock(&misc->entries_lock); 147 e = search_binfmt_handler(misc, bprm); 148 if (e) 149 refcount_inc(&e->users); 150 read_unlock(&misc->entries_lock); 151 return e; 152 } 153 154 /** 155 * put_binfmt_handler - put binary handler node 156 * @e: node to put 157 * 158 * Free node syncing with load_misc_binary() and defer final free to 159 * load_misc_binary() in case it is using the binary type handler we were 160 * requested to remove. 161 */ 162 static void put_binfmt_handler(Node *e) 163 { 164 if (refcount_dec_and_test(&e->users)) { 165 if (e->flags & MISC_FMT_OPEN_FILE) { 166 exe_file_allow_write_access(e->interp_file); 167 filp_close(e->interp_file, NULL); 168 } 169 kfree(e); 170 } 171 } 172 173 /** 174 * load_binfmt_misc - load the binfmt_misc of the caller's user namespace 175 * 176 * To be called in load_misc_binary() to load the relevant struct binfmt_misc. 177 * If a user namespace doesn't have its own binfmt_misc mount it can make use 178 * of its ancestor's binfmt_misc handlers. This mimicks the behavior of 179 * pre-namespaced binfmt_misc where all registered binfmt_misc handlers where 180 * available to all user and user namespaces on the system. 181 * 182 * Return: the binfmt_misc instance of the caller's user namespace 183 */ 184 static struct binfmt_misc *load_binfmt_misc(void) 185 { 186 const struct user_namespace *user_ns; 187 struct binfmt_misc *misc; 188 189 user_ns = current_user_ns(); 190 while (user_ns) { 191 /* Pairs with smp_store_release() in bm_fill_super(). */ 192 misc = smp_load_acquire(&user_ns->binfmt_misc); 193 if (misc) 194 return misc; 195 196 user_ns = user_ns->parent; 197 } 198 199 return &init_binfmt_misc; 200 } 201 202 /* 203 * the loader itself 204 */ 205 static int load_misc_binary(struct linux_binprm *bprm) 206 { 207 Node *fmt; 208 struct file *interp_file = NULL; 209 int retval = -ENOEXEC; 210 struct binfmt_misc *misc; 211 212 misc = load_binfmt_misc(); 213 if (!misc->enabled) 214 return retval; 215 216 fmt = get_binfmt_handler(misc, bprm); 217 if (!fmt) 218 return retval; 219 220 /* Need to be able to load the file after exec */ 221 retval = -ENOENT; 222 if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE) 223 goto ret; 224 225 if (fmt->flags & MISC_FMT_PRESERVE_ARGV0) { 226 bprm->interp_flags |= BINPRM_FLAGS_PRESERVE_ARGV0; 227 } else { 228 retval = remove_arg_zero(bprm); 229 if (retval) 230 goto ret; 231 } 232 233 /* make argv[1] be the path to the binary */ 234 retval = copy_string_kernel(bprm->interp, bprm); 235 if (retval < 0) 236 goto ret; 237 bprm->argc++; 238 239 /* add the interp as argv[0] */ 240 retval = copy_string_kernel(fmt->interpreter, bprm); 241 if (retval < 0) 242 goto ret; 243 bprm->argc++; 244 245 /* Update interp in case binfmt_script needs it. */ 246 retval = bprm_change_interp(fmt->interpreter, bprm); 247 if (retval < 0) 248 goto ret; 249 250 if (fmt->flags & MISC_FMT_OPEN_FILE) { 251 interp_file = file_clone_open(fmt->interp_file); 252 if (!IS_ERR(interp_file)) { 253 int err = exe_file_deny_write_access(interp_file); 254 255 if (err) { 256 fput(interp_file); 257 interp_file = ERR_PTR(err); 258 } 259 } 260 } else { 261 interp_file = open_exec(fmt->interpreter); 262 } 263 retval = PTR_ERR(interp_file); 264 if (IS_ERR(interp_file)) 265 goto ret; 266 267 bprm->interpreter = interp_file; 268 if (fmt->flags & MISC_FMT_OPEN_BINARY) 269 bprm->have_execfd = 1; 270 if (fmt->flags & MISC_FMT_CREDENTIALS) 271 bprm->execfd_creds = 1; 272 273 retval = 0; 274 ret: 275 276 /* 277 * If we actually put the node here all concurrent calls to 278 * load_misc_binary() will have finished. We also know 279 * that for the refcount to be zero someone must have concurently 280 * removed the binary type handler from the list and it's our job to 281 * free it. 282 */ 283 put_binfmt_handler(fmt); 284 285 return retval; 286 } 287 288 /* Command parsers */ 289 290 /* 291 * parses and copies one argument enclosed in del from *sp to *dp, 292 * recognising the \x special. 293 * returns pointer to the copied argument or NULL in case of an 294 * error (and sets err) or null argument length. 295 */ 296 static char *scanarg(char *s, char del) 297 { 298 char c; 299 300 while ((c = *s++) != del) { 301 if (c == '\\' && *s == 'x') { 302 s++; 303 if (!isxdigit(*s++)) 304 return NULL; 305 if (!isxdigit(*s++)) 306 return NULL; 307 } 308 } 309 s[-1] ='\0'; 310 return s; 311 } 312 313 static char *check_special_flags(char *sfs, Node *e) 314 { 315 char *p = sfs; 316 int cont = 1; 317 318 /* special flags */ 319 while (cont) { 320 switch (*p) { 321 case 'P': 322 pr_debug("register: flag: P (preserve argv0)\n"); 323 p++; 324 e->flags |= MISC_FMT_PRESERVE_ARGV0; 325 break; 326 case 'O': 327 pr_debug("register: flag: O (open binary)\n"); 328 p++; 329 e->flags |= MISC_FMT_OPEN_BINARY; 330 break; 331 case 'C': 332 pr_debug("register: flag: C (preserve creds)\n"); 333 p++; 334 /* this flags also implies the 335 open-binary flag */ 336 e->flags |= (MISC_FMT_CREDENTIALS | 337 MISC_FMT_OPEN_BINARY); 338 break; 339 case 'F': 340 pr_debug("register: flag: F: open interpreter file now\n"); 341 p++; 342 e->flags |= MISC_FMT_OPEN_FILE; 343 break; 344 default: 345 cont = 0; 346 } 347 } 348 349 return p; 350 } 351 352 /* 353 * This registers a new binary format, it recognises the syntax 354 * ':name:type:offset:magic:mask:interpreter:flags' 355 * where the ':' is the IFS, that can be chosen with the first char 356 */ 357 static Node *create_entry(const char __user *buffer, size_t count) 358 { 359 Node *e; 360 int memsize, err; 361 char *buf, *p; 362 char del; 363 364 pr_debug("register: received %zu bytes\n", count); 365 366 /* some sanity checks */ 367 err = -EINVAL; 368 if ((count < 11) || (count > MAX_REGISTER_LENGTH)) 369 goto out; 370 371 err = -ENOMEM; 372 memsize = sizeof(Node) + count + 8; 373 e = kmalloc(memsize, GFP_KERNEL_ACCOUNT); 374 if (!e) 375 goto out; 376 377 p = buf = (char *)e + sizeof(Node); 378 379 memset(e, 0, sizeof(Node)); 380 if (copy_from_user(buf, buffer, count)) 381 goto efault; 382 383 del = *p++; /* delimeter */ 384 385 pr_debug("register: delim: %#x {%c}\n", del, del); 386 387 /* A flag-char delimiter runs the flag scan off the buffer. */ 388 if (del == 'P' || del == 'O' || del == 'C' || del == 'F') 389 goto einval; 390 391 /* Pad the buffer with the delim to simplify parsing below. */ 392 memset(buf + count, del, 8); 393 394 /* Parse the 'name' field. */ 395 e->name = p; 396 p = strchr(p, del); 397 if (!p) 398 goto einval; 399 *p++ = '\0'; 400 if (!e->name[0] || 401 !strcmp(e->name, ".") || 402 !strcmp(e->name, "..") || 403 strchr(e->name, '/')) 404 goto einval; 405 406 pr_debug("register: name: {%s}\n", e->name); 407 408 /* Parse the 'type' field. */ 409 switch (*p++) { 410 case 'E': 411 pr_debug("register: type: E (extension)\n"); 412 e->flags = 1 << Enabled; 413 break; 414 case 'M': 415 pr_debug("register: type: M (magic)\n"); 416 e->flags = (1 << Enabled) | (1 << Magic); 417 break; 418 default: 419 goto einval; 420 } 421 if (*p++ != del) 422 goto einval; 423 424 if (test_bit(Magic, &e->flags)) { 425 /* Handle the 'M' (magic) format. */ 426 char *s; 427 428 /* Parse the 'offset' field. */ 429 s = strchr(p, del); 430 if (!s) 431 goto einval; 432 *s = '\0'; 433 if (p != s) { 434 int r = kstrtoint(p, 10, &e->offset); 435 if (r != 0 || e->offset < 0) 436 goto einval; 437 } 438 p = s; 439 if (*p++) 440 goto einval; 441 pr_debug("register: offset: %#x\n", e->offset); 442 443 /* Parse the 'magic' field. */ 444 e->magic = p; 445 p = scanarg(p, del); 446 if (!p) 447 goto einval; 448 if (!e->magic[0]) 449 goto einval; 450 if (USE_DEBUG) 451 print_hex_dump_bytes( 452 KBUILD_MODNAME ": register: magic[raw]: ", 453 DUMP_PREFIX_NONE, e->magic, p - e->magic); 454 455 /* Parse the 'mask' field. */ 456 e->mask = p; 457 p = scanarg(p, del); 458 if (!p) 459 goto einval; 460 if (!e->mask[0]) { 461 e->mask = NULL; 462 pr_debug("register: mask[raw]: none\n"); 463 } else if (USE_DEBUG) 464 print_hex_dump_bytes( 465 KBUILD_MODNAME ": register: mask[raw]: ", 466 DUMP_PREFIX_NONE, e->mask, p - e->mask); 467 468 /* 469 * Decode the magic & mask fields. 470 * Note: while we might have accepted embedded NUL bytes from 471 * above, the unescape helpers here will stop at the first one 472 * it encounters. 473 */ 474 e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX); 475 if (e->mask && 476 string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size) 477 goto einval; 478 if (e->size > BINPRM_BUF_SIZE || 479 BINPRM_BUF_SIZE - e->size < e->offset) 480 goto einval; 481 pr_debug("register: magic/mask length: %i\n", e->size); 482 if (USE_DEBUG) { 483 print_hex_dump_bytes( 484 KBUILD_MODNAME ": register: magic[decoded]: ", 485 DUMP_PREFIX_NONE, e->magic, e->size); 486 487 if (e->mask) { 488 int i; 489 char *masked = kmalloc(e->size, GFP_KERNEL_ACCOUNT); 490 491 print_hex_dump_bytes( 492 KBUILD_MODNAME ": register: mask[decoded]: ", 493 DUMP_PREFIX_NONE, e->mask, e->size); 494 495 if (masked) { 496 for (i = 0; i < e->size; ++i) 497 masked[i] = e->magic[i] & e->mask[i]; 498 print_hex_dump_bytes( 499 KBUILD_MODNAME ": register: magic[masked]: ", 500 DUMP_PREFIX_NONE, masked, e->size); 501 502 kfree(masked); 503 } 504 } 505 } 506 } else { 507 /* Handle the 'E' (extension) format. */ 508 509 /* Skip the 'offset' field. */ 510 p = strchr(p, del); 511 if (!p) 512 goto einval; 513 *p++ = '\0'; 514 515 /* Parse the 'magic' field. */ 516 e->magic = p; 517 p = strchr(p, del); 518 if (!p) 519 goto einval; 520 *p++ = '\0'; 521 if (!e->magic[0] || strchr(e->magic, '/')) 522 goto einval; 523 pr_debug("register: extension: {%s}\n", e->magic); 524 525 /* Skip the 'mask' field. */ 526 p = strchr(p, del); 527 if (!p) 528 goto einval; 529 *p++ = '\0'; 530 } 531 532 /* Parse the 'interpreter' field. */ 533 e->interpreter = p; 534 p = strchr(p, del); 535 if (!p) 536 goto einval; 537 *p++ = '\0'; 538 if (!e->interpreter[0]) 539 goto einval; 540 pr_debug("register: interpreter: {%s}\n", e->interpreter); 541 542 /* Parse the 'flags' field. */ 543 p = check_special_flags(p, e); 544 if (*p == '\n') 545 p++; 546 if (p != buf + count) 547 goto einval; 548 549 return e; 550 551 out: 552 return ERR_PTR(err); 553 554 efault: 555 kfree(e); 556 return ERR_PTR(-EFAULT); 557 einval: 558 kfree(e); 559 return ERR_PTR(-EINVAL); 560 } 561 562 /* 563 * Set status of entry/binfmt_misc: 564 * '1' enables, '0' disables and '-1' clears entry/binfmt_misc 565 */ 566 static int parse_command(const char __user *buffer, size_t count) 567 { 568 char s[4]; 569 570 if (count > 3) 571 return -EINVAL; 572 if (copy_from_user(s, buffer, count)) 573 return -EFAULT; 574 if (!count) 575 return 0; 576 if (s[count - 1] == '\n') 577 count--; 578 if (count == 1 && s[0] == '0') 579 return 1; 580 if (count == 1 && s[0] == '1') 581 return 2; 582 if (count == 2 && s[0] == '-' && s[1] == '1') 583 return 3; 584 return -EINVAL; 585 } 586 587 /* generic stuff */ 588 589 static void entry_status(Node *e, char *page) 590 { 591 char *dp = page; 592 const char *status = "disabled"; 593 594 if (test_bit(Enabled, &e->flags)) 595 status = "enabled"; 596 597 if (!VERBOSE_STATUS) { 598 sprintf(page, "%s\n", status); 599 return; 600 } 601 602 dp += sprintf(dp, "%s\ninterpreter %s\n", status, e->interpreter); 603 604 /* print the special flags */ 605 dp += sprintf(dp, "flags: "); 606 if (e->flags & MISC_FMT_PRESERVE_ARGV0) 607 *dp++ = 'P'; 608 if (e->flags & MISC_FMT_OPEN_BINARY) 609 *dp++ = 'O'; 610 if (e->flags & MISC_FMT_CREDENTIALS) 611 *dp++ = 'C'; 612 if (e->flags & MISC_FMT_OPEN_FILE) 613 *dp++ = 'F'; 614 *dp++ = '\n'; 615 616 if (!test_bit(Magic, &e->flags)) { 617 sprintf(dp, "extension .%s\n", e->magic); 618 } else { 619 dp += sprintf(dp, "offset %i\nmagic ", e->offset); 620 dp = bin2hex(dp, e->magic, e->size); 621 if (e->mask) { 622 dp += sprintf(dp, "\nmask "); 623 dp = bin2hex(dp, e->mask, e->size); 624 } 625 *dp++ = '\n'; 626 *dp = '\0'; 627 } 628 } 629 630 static struct inode *bm_get_inode(struct super_block *sb, int mode) 631 { 632 struct inode *inode = new_inode(sb); 633 634 if (inode) { 635 inode->i_ino = get_next_ino(); 636 inode->i_mode = mode; 637 simple_inode_init_ts(inode); 638 } 639 return inode; 640 } 641 642 /** 643 * i_binfmt_misc - retrieve struct binfmt_misc from a binfmt_misc inode 644 * @inode: inode of the relevant binfmt_misc instance 645 * 646 * This helper retrieves struct binfmt_misc from a binfmt_misc inode. This can 647 * be done without any memory barriers because we are guaranteed that 648 * user_ns->binfmt_misc is fully initialized. It was fully initialized when the 649 * binfmt_misc mount was first created. 650 * 651 * Return: struct binfmt_misc of the relevant binfmt_misc instance 652 */ 653 static struct binfmt_misc *i_binfmt_misc(struct inode *inode) 654 { 655 return inode->i_sb->s_user_ns->binfmt_misc; 656 } 657 658 /** 659 * bm_evict_inode - cleanup data associated with @inode 660 * @inode: inode to which the data is attached 661 * 662 * Cleanup the binary type handler data associated with @inode if a binary type 663 * entry is removed or the filesystem is unmounted and the super block is 664 * shutdown. 665 * 666 * If the ->evict call was not caused by a super block shutdown but by a write 667 * to remove the entry or all entries via bm_{entry,status}_write() the entry 668 * will have already been removed from the list. We keep the list_empty() check 669 * to make that explicit. 670 */ 671 static void bm_evict_inode(struct inode *inode) 672 { 673 Node *e = inode->i_private; 674 675 clear_inode(inode); 676 677 if (e) { 678 struct binfmt_misc *misc; 679 680 misc = i_binfmt_misc(inode); 681 write_lock(&misc->entries_lock); 682 if (!list_empty(&e->list)) 683 list_del_init(&e->list); 684 write_unlock(&misc->entries_lock); 685 put_binfmt_handler(e); 686 } 687 } 688 689 /** 690 * remove_binfmt_handler - remove a binary type handler 691 * @misc: handle to binfmt_misc instance 692 * @e: binary type handler to remove 693 * 694 * Remove a binary type handler from the list of binary type handlers and 695 * remove its associated dentry. This is called from 696 * binfmt_{entry,status}_write(). In the future, we might want to think about 697 * adding a proper ->unlink() method to binfmt_misc instead of forcing caller's 698 * to use writes to files in order to delete binary type handlers. But it has 699 * worked for so long that it's not a pressing issue. 700 */ 701 static void remove_binfmt_handler(struct binfmt_misc *misc, Node *e) 702 { 703 write_lock(&misc->entries_lock); 704 list_del_init(&e->list); 705 write_unlock(&misc->entries_lock); 706 locked_recursive_removal(e->dentry, NULL); 707 } 708 709 /* /<entry> */ 710 711 static ssize_t 712 bm_entry_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) 713 { 714 Node *e = file_inode(file)->i_private; 715 ssize_t res; 716 char *page; 717 718 page = kmalloc(PAGE_SIZE, GFP_KERNEL); 719 if (!page) 720 return -ENOMEM; 721 722 entry_status(e, page); 723 724 res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page)); 725 726 kfree(page); 727 return res; 728 } 729 730 static ssize_t bm_entry_write(struct file *file, const char __user *buffer, 731 size_t count, loff_t *ppos) 732 { 733 struct inode *inode = file_inode(file); 734 Node *e = inode->i_private; 735 int res = parse_command(buffer, count); 736 737 switch (res) { 738 case 1: 739 /* Disable this handler. */ 740 clear_bit(Enabled, &e->flags); 741 break; 742 case 2: 743 /* Enable this handler. */ 744 set_bit(Enabled, &e->flags); 745 break; 746 case 3: 747 /* Delete this handler. */ 748 inode = d_inode(inode->i_sb->s_root); 749 inode_lock_nested(inode, I_MUTEX_PARENT); 750 751 /* 752 * In order to add new element or remove elements from the list 753 * via bm_{entry,register,status}_write() inode_lock() on the 754 * root inode must be held. 755 * The lock is exclusive ensuring that the list can't be 756 * modified. Only load_misc_binary() can access but does so 757 * read-only. So we only need to take the write lock when we 758 * actually remove the entry from the list. 759 */ 760 if (!list_empty(&e->list)) 761 remove_binfmt_handler(i_binfmt_misc(inode), e); 762 763 inode_unlock(inode); 764 break; 765 default: 766 return res; 767 } 768 769 return count; 770 } 771 772 static const struct file_operations bm_entry_operations = { 773 .read = bm_entry_read, 774 .write = bm_entry_write, 775 .llseek = default_llseek, 776 }; 777 778 /* /register */ 779 780 /* add to filesystem */ 781 static int add_entry(Node *e, struct super_block *sb) 782 { 783 struct dentry *dentry = simple_start_creating(sb->s_root, e->name); 784 struct inode *inode; 785 struct binfmt_misc *misc; 786 787 if (IS_ERR(dentry)) 788 return PTR_ERR(dentry); 789 790 inode = bm_get_inode(sb, S_IFREG | 0644); 791 if (unlikely(!inode)) { 792 simple_done_creating(dentry); 793 return -ENOMEM; 794 } 795 796 refcount_set(&e->users, 1); 797 e->dentry = dentry; 798 inode->i_private = e; 799 inode->i_fop = &bm_entry_operations; 800 801 d_make_persistent(dentry, inode); 802 misc = i_binfmt_misc(inode); 803 write_lock(&misc->entries_lock); 804 list_add(&e->list, &misc->entries); 805 write_unlock(&misc->entries_lock); 806 simple_done_creating(dentry); 807 return 0; 808 } 809 810 static ssize_t bm_register_write(struct file *file, const char __user *buffer, 811 size_t count, loff_t *ppos) 812 { 813 Node *e; 814 struct super_block *sb = file_inode(file)->i_sb; 815 int err = 0; 816 struct file *f = NULL; 817 818 e = create_entry(buffer, count); 819 820 if (IS_ERR(e)) 821 return PTR_ERR(e); 822 823 if (e->flags & MISC_FMT_OPEN_FILE) { 824 /* 825 * Now that we support unprivileged binfmt_misc mounts make 826 * sure we use the credentials that the register @file was 827 * opened with to also open the interpreter. Before that this 828 * didn't matter much as only a privileged process could open 829 * the register file. 830 */ 831 scoped_with_creds(file->f_cred) 832 f = open_exec(e->interpreter); 833 if (IS_ERR(f)) { 834 pr_notice("register: failed to install interpreter file %s\n", 835 e->interpreter); 836 kfree(e); 837 return PTR_ERR(f); 838 } 839 e->interp_file = f; 840 } 841 842 err = add_entry(e, sb); 843 if (err) { 844 if (f) { 845 exe_file_allow_write_access(f); 846 filp_close(f, NULL); 847 } 848 kfree(e); 849 return err; 850 } 851 return count; 852 } 853 854 static const struct file_operations bm_register_operations = { 855 .write = bm_register_write, 856 .llseek = noop_llseek, 857 }; 858 859 /* /status */ 860 861 static ssize_t 862 bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) 863 { 864 struct binfmt_misc *misc; 865 char *s; 866 867 misc = i_binfmt_misc(file_inode(file)); 868 s = misc->enabled ? "enabled\n" : "disabled\n"; 869 return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s)); 870 } 871 872 static ssize_t bm_status_write(struct file *file, const char __user *buffer, 873 size_t count, loff_t *ppos) 874 { 875 struct binfmt_misc *misc; 876 int res = parse_command(buffer, count); 877 Node *e, *next; 878 struct inode *inode; 879 880 misc = i_binfmt_misc(file_inode(file)); 881 switch (res) { 882 case 1: 883 /* Disable all handlers. */ 884 misc->enabled = false; 885 break; 886 case 2: 887 /* Enable all handlers. */ 888 misc->enabled = true; 889 break; 890 case 3: 891 /* Delete all handlers. */ 892 inode = d_inode(file_inode(file)->i_sb->s_root); 893 inode_lock_nested(inode, I_MUTEX_PARENT); 894 895 /* 896 * In order to add new element or remove elements from the list 897 * via bm_{entry,register,status}_write() inode_lock() on the 898 * root inode must be held. 899 * The lock is exclusive ensuring that the list can't be 900 * modified. Only load_misc_binary() can access but does so 901 * read-only. So we only need to take the write lock when we 902 * actually remove the entry from the list. 903 */ 904 list_for_each_entry_safe(e, next, &misc->entries, list) 905 remove_binfmt_handler(misc, e); 906 907 inode_unlock(inode); 908 break; 909 default: 910 return res; 911 } 912 913 return count; 914 } 915 916 static const struct file_operations bm_status_operations = { 917 .read = bm_status_read, 918 .write = bm_status_write, 919 .llseek = default_llseek, 920 }; 921 922 /* Superblock handling */ 923 924 static const struct super_operations s_ops = { 925 .statfs = simple_statfs, 926 .evict_inode = bm_evict_inode, 927 }; 928 929 static int bm_fill_super(struct super_block *sb, struct fs_context *fc) 930 { 931 int err; 932 struct user_namespace *user_ns = sb->s_user_ns; 933 struct binfmt_misc *misc; 934 static const struct tree_descr bm_files[] = { 935 [2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO}, 936 [3] = {"register", &bm_register_operations, S_IWUSR}, 937 /* last one */ {""} 938 }; 939 940 if (WARN_ON(user_ns != current_user_ns())) 941 return -EINVAL; 942 943 /* Never exec off this instance and never let anything stack on it. */ 944 sb->s_iflags |= SB_I_NOEXEC | SB_I_NODEV; 945 sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH; 946 947 /* 948 * Lazily allocate a new binfmt_misc instance for this namespace, i.e. 949 * do it here during the first mount of binfmt_misc. We don't need to 950 * waste memory for every user namespace allocation. It's likely much 951 * more common to not mount a separate binfmt_misc instance than it is 952 * to mount one. 953 * 954 * While multiple superblocks can exist they are keyed by userns in 955 * s_fs_info for binfmt_misc. Hence, the vfs guarantees that 956 * bm_fill_super() is called exactly once whenever a binfmt_misc 957 * superblock for a userns is created. This in turn lets us conclude 958 * that when a binfmt_misc superblock is created for the first time for 959 * a userns there's no one racing us. Therefore we don't need any 960 * barriers when we dereference binfmt_misc. 961 */ 962 misc = user_ns->binfmt_misc; 963 if (!misc) { 964 /* 965 * If it turns out that most user namespaces actually want to 966 * register their own binary type handler and therefore all 967 * create their own separate binfmt_misc mounts we should 968 * consider turning this into a kmem cache. 969 */ 970 misc = kzalloc_obj(struct binfmt_misc); 971 if (!misc) 972 return -ENOMEM; 973 974 INIT_LIST_HEAD(&misc->entries); 975 rwlock_init(&misc->entries_lock); 976 977 /* Pairs with smp_load_acquire() in load_binfmt_misc(). */ 978 smp_store_release(&user_ns->binfmt_misc, misc); 979 } 980 981 /* 982 * When the binfmt_misc superblock for this userns is shutdown 983 * ->enabled might have been set to false and we don't reinitialize 984 * ->enabled again during shutdown as someone might already be mounting 985 * binfmt_misc again. It also would be pointless since by then we know 986 * that the binary type list for this binfmt_misc mount is empty making 987 * load_misc_binary() return -ENOEXEC independent of whether ->enabled 988 * is true. Instead, if someone mounts binfmt_misc for the first time or 989 * again we simply reset ->enabled to true. 990 */ 991 misc->enabled = true; 992 993 err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files); 994 if (!err) 995 sb->s_op = &s_ops; 996 return err; 997 } 998 999 static void bm_free(struct fs_context *fc) 1000 { 1001 if (fc->s_fs_info) 1002 put_user_ns(fc->s_fs_info); 1003 } 1004 1005 static int bm_get_tree(struct fs_context *fc) 1006 { 1007 return get_tree_keyed(fc, bm_fill_super, get_user_ns(fc->user_ns)); 1008 } 1009 1010 static const struct fs_context_operations bm_context_ops = { 1011 .free = bm_free, 1012 .get_tree = bm_get_tree, 1013 }; 1014 1015 static void bm_kill_sb(struct super_block *sb) 1016 { 1017 struct user_namespace *user_ns = sb->s_fs_info; 1018 1019 kill_anon_super(sb); 1020 put_user_ns(user_ns); 1021 } 1022 1023 static int bm_init_fs_context(struct fs_context *fc) 1024 { 1025 fc->ops = &bm_context_ops; 1026 return 0; 1027 } 1028 1029 static struct linux_binfmt misc_format = { 1030 .module = THIS_MODULE, 1031 .load_binary = load_misc_binary, 1032 }; 1033 1034 static struct file_system_type bm_fs_type = { 1035 .owner = THIS_MODULE, 1036 .name = "binfmt_misc", 1037 .init_fs_context = bm_init_fs_context, 1038 .fs_flags = FS_USERNS_MOUNT, 1039 .kill_sb = bm_kill_sb, 1040 }; 1041 MODULE_ALIAS_FS("binfmt_misc"); 1042 1043 static int __init init_misc_binfmt(void) 1044 { 1045 int err = register_filesystem(&bm_fs_type); 1046 if (!err) 1047 insert_binfmt(&misc_format); 1048 return err; 1049 } 1050 1051 static void __exit exit_misc_binfmt(void) 1052 { 1053 unregister_binfmt(&misc_format); 1054 unregister_filesystem(&bm_fs_type); 1055 } 1056 1057 core_initcall(init_misc_binfmt); 1058 module_exit(exit_misc_binfmt); 1059 MODULE_DESCRIPTION("Kernel support for miscellaneous binaries"); 1060 MODULE_LICENSE("GPL"); 1061