1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * linux/fs/exec.c 4 * 5 * Copyright (C) 1991, 1992 Linus Torvalds 6 */ 7 8 /* 9 * #!-checking implemented by tytso. 10 */ 11 /* 12 * Demand-loading implemented 01.12.91 - no need to read anything but 13 * the header into memory. The inode of the executable is put into 14 * "current->executable", and page faults do the actual loading. Clean. 15 * 16 * Once more I can proudly say that linux stood up to being changed: it 17 * was less than 2 hours work to get demand-loading completely implemented. 18 * 19 * Demand loading changed July 1993 by Eric Youngdale. Use mmap instead, 20 * current->executable is only used by the procfs. This allows a dispatch 21 * table to check for several different types of binary formats. We keep 22 * trying until we recognize the file or we run out of supported binary 23 * formats. 24 */ 25 26 #include <linux/kernel_read_file.h> 27 #include <linux/slab.h> 28 #include <linux/file.h> 29 #include <linux/fdtable.h> 30 #include <linux/mm.h> 31 #include <linux/stat.h> 32 #include <linux/fcntl.h> 33 #include <linux/swap.h> 34 #include <linux/string.h> 35 #include <linux/init.h> 36 #include <linux/sched/mm.h> 37 #include <linux/sched/coredump.h> 38 #include <linux/sched/exec_state.h> 39 #include <linux/sched/signal.h> 40 #include <linux/sched/numa_balancing.h> 41 #include <linux/sched/task.h> 42 #include <linux/pagemap.h> 43 #include <linux/perf_event.h> 44 #include <linux/highmem.h> 45 #include <linux/spinlock.h> 46 #include <linux/key.h> 47 #include <linux/personality.h> 48 #include <linux/binfmts.h> 49 #include <linux/utsname.h> 50 #include <linux/pid_namespace.h> 51 #include <linux/module.h> 52 #include <linux/namei.h> 53 #include <linux/mount.h> 54 #include <linux/security.h> 55 #include <linux/syscalls.h> 56 #include <linux/tsacct_kern.h> 57 #include <linux/cn_proc.h> 58 #include <linux/audit.h> 59 #include <linux/kmod.h> 60 #include <linux/fsnotify.h> 61 #include <linux/fs_struct.h> 62 #include <linux/oom.h> 63 #include <linux/compat.h> 64 #include <linux/vmalloc.h> 65 #include <linux/io_uring.h> 66 #include <linux/syscall_user_dispatch.h> 67 #include <linux/coredump.h> 68 #include <linux/time_namespace.h> 69 #include <linux/user_events.h> 70 #include <linux/rseq.h> 71 #include <linux/ksm.h> 72 73 #include <linux/uaccess.h> 74 #include <asm/mmu_context.h> 75 #include <asm/tlb.h> 76 77 #include <trace/events/task.h> 78 #include "internal.h" 79 80 #include <trace/events/sched.h> 81 82 /* For vma exec functions. */ 83 #include "../mm/internal.h" 84 85 static int bprm_creds_from_file(struct linux_binprm *bprm); 86 87 int suid_dumpable = 0; 88 89 static LIST_HEAD(formats); 90 static DEFINE_RWLOCK(binfmt_lock); 91 92 void __register_binfmt(struct linux_binfmt * fmt, int insert) 93 { 94 write_lock(&binfmt_lock); 95 insert ? list_add(&fmt->lh, &formats) : 96 list_add_tail(&fmt->lh, &formats); 97 write_unlock(&binfmt_lock); 98 } 99 100 EXPORT_SYMBOL(__register_binfmt); 101 102 void unregister_binfmt(struct linux_binfmt * fmt) 103 { 104 write_lock(&binfmt_lock); 105 list_del(&fmt->lh); 106 write_unlock(&binfmt_lock); 107 } 108 109 EXPORT_SYMBOL(unregister_binfmt); 110 111 static inline void put_binfmt(struct linux_binfmt * fmt) 112 { 113 module_put(fmt->module); 114 } 115 116 bool path_noexec(const struct path *path) 117 { 118 /* If it's an anonymous inode make sure that we catch any shenanigans. */ 119 VFS_WARN_ON_ONCE(IS_ANON_FILE(d_inode(path->dentry)) && 120 !(path->mnt->mnt_sb->s_iflags & SB_I_NOEXEC)); 121 return (path->mnt->mnt_flags & MNT_NOEXEC) || 122 (path->mnt->mnt_sb->s_iflags & SB_I_NOEXEC); 123 } 124 125 #ifdef CONFIG_MMU 126 /* 127 * The nascent bprm->mm is not visible until exec_mmap() but it can 128 * use a lot of memory, account these pages in current->mm temporary 129 * for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we 130 * change the counter back via acct_arg_size(0). 131 */ 132 static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages) 133 { 134 struct mm_struct *mm = current->mm; 135 long diff = (long)(pages - bprm->vma_pages); 136 137 if (!mm || !diff) 138 return; 139 140 bprm->vma_pages = pages; 141 add_mm_counter(mm, MM_ANONPAGES, diff); 142 } 143 144 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos, 145 int write) 146 { 147 struct page *page; 148 struct vm_area_struct *vma = bprm->vma; 149 struct mm_struct *mm = bprm->mm; 150 int ret; 151 152 /* 153 * Avoid relying on expanding the stack down in GUP (which 154 * does not work for STACK_GROWSUP anyway), and just do it 155 * ahead of time. 156 */ 157 if (!mmap_read_lock_maybe_expand(mm, vma, pos, write)) 158 return NULL; 159 160 /* 161 * We are doing an exec(). 'current' is the process 162 * doing the exec and 'mm' is the new process's mm. 163 */ 164 ret = get_user_pages_remote(mm, pos, 1, 165 write ? FOLL_WRITE : 0, 166 &page, NULL); 167 mmap_read_unlock(mm); 168 if (ret <= 0) 169 return NULL; 170 171 if (write) 172 acct_arg_size(bprm, vma_pages(vma)); 173 174 return page; 175 } 176 177 static void put_arg_page(struct page *page) 178 { 179 put_page(page); 180 } 181 182 static void free_arg_pages(struct linux_binprm *bprm) 183 { 184 } 185 186 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, 187 struct page *page) 188 { 189 flush_cache_page(bprm->vma, pos, page_to_pfn(page)); 190 } 191 192 static bool valid_arg_len(struct linux_binprm *bprm, long len) 193 { 194 return len <= MAX_ARG_STRLEN; 195 } 196 197 #else 198 199 static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages) 200 { 201 } 202 203 static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos, 204 int write) 205 { 206 struct page *page; 207 208 page = bprm->page[pos / PAGE_SIZE]; 209 if (!page && write) { 210 page = alloc_page(GFP_HIGHUSER|__GFP_ZERO); 211 if (!page) 212 return NULL; 213 bprm->page[pos / PAGE_SIZE] = page; 214 } 215 216 return page; 217 } 218 219 static void put_arg_page(struct page *page) 220 { 221 } 222 223 static void free_arg_page(struct linux_binprm *bprm, int i) 224 { 225 if (bprm->page[i]) { 226 __free_page(bprm->page[i]); 227 bprm->page[i] = NULL; 228 } 229 } 230 231 static void free_arg_pages(struct linux_binprm *bprm) 232 { 233 int i; 234 235 for (i = 0; i < MAX_ARG_PAGES; i++) 236 free_arg_page(bprm, i); 237 } 238 239 static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, 240 struct page *page) 241 { 242 } 243 244 static bool valid_arg_len(struct linux_binprm *bprm, long len) 245 { 246 return len <= bprm->p; 247 } 248 249 #endif /* CONFIG_MMU */ 250 251 /* 252 * Create a new mm_struct and populate it with a temporary stack 253 * vm_area_struct. We don't have enough context at this point to set the stack 254 * flags, permissions, and offset, so we use temporary values. We'll update 255 * them later in setup_arg_pages(). 256 */ 257 static int bprm_mm_init(struct linux_binprm *bprm) 258 { 259 int err; 260 struct mm_struct *mm = NULL; 261 262 bprm->mm = mm = mm_alloc(); 263 err = -ENOMEM; 264 if (!mm) 265 goto err; 266 267 /* Staged for would_dump() narrowing; consumed by begin_new_exec(). */ 268 bprm->user_ns = get_user_ns(current_user_ns()); 269 270 /* Save current stack limit for all calculations made during exec. */ 271 task_lock(current->group_leader); 272 bprm->rlim_stack = current->signal->rlim[RLIMIT_STACK]; 273 task_unlock(current->group_leader); 274 275 #ifndef CONFIG_MMU 276 bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *); 277 #else 278 err = create_init_stack_vma(bprm->mm, &bprm->vma, &bprm->p); 279 if (err) 280 goto err; 281 #endif 282 283 return 0; 284 285 err: 286 if (mm) { 287 bprm->mm = NULL; 288 mmdrop(mm); 289 } 290 291 return err; 292 } 293 294 struct user_arg_ptr { 295 #ifdef CONFIG_COMPAT 296 bool is_compat; 297 #endif 298 union { 299 const char __user *const __user *native; 300 #ifdef CONFIG_COMPAT 301 const compat_uptr_t __user *compat; 302 #endif 303 } ptr; 304 }; 305 306 static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr) 307 { 308 const char __user *native; 309 310 #ifdef CONFIG_COMPAT 311 if (unlikely(argv.is_compat)) { 312 compat_uptr_t compat; 313 314 if (get_user(compat, argv.ptr.compat + nr)) 315 return ERR_PTR(-EFAULT); 316 317 return compat_ptr(compat); 318 } 319 #endif 320 321 if (get_user(native, argv.ptr.native + nr)) 322 return ERR_PTR(-EFAULT); 323 324 return native; 325 } 326 327 /* 328 * count() counts the number of strings in array ARGV. 329 */ 330 static int count(struct user_arg_ptr argv, int max) 331 { 332 int i = 0; 333 334 if (argv.ptr.native != NULL) { 335 for (;;) { 336 const char __user *p = get_user_arg_ptr(argv, i); 337 338 if (!p) 339 break; 340 341 if (IS_ERR(p)) 342 return -EFAULT; 343 344 if (i >= max) 345 return -E2BIG; 346 ++i; 347 348 if (fatal_signal_pending(current)) 349 return -ERESTARTNOHAND; 350 cond_resched(); 351 } 352 } 353 return i; 354 } 355 356 static int count_strings_kernel(const char *const *argv) 357 { 358 int i; 359 360 if (!argv) 361 return 0; 362 363 for (i = 0; argv[i]; ++i) { 364 if (i >= MAX_ARG_STRINGS) 365 return -E2BIG; 366 if (fatal_signal_pending(current)) 367 return -ERESTARTNOHAND; 368 cond_resched(); 369 } 370 return i; 371 } 372 373 static inline int bprm_set_stack_limit(struct linux_binprm *bprm, 374 unsigned long limit) 375 { 376 #ifdef CONFIG_MMU 377 /* Avoid a pathological bprm->p. */ 378 if (bprm->p < limit) 379 return -E2BIG; 380 bprm->argmin = bprm->p - limit; 381 #endif 382 return 0; 383 } 384 static inline bool bprm_hit_stack_limit(struct linux_binprm *bprm) 385 { 386 #ifdef CONFIG_MMU 387 return bprm->p < bprm->argmin; 388 #else 389 return false; 390 #endif 391 } 392 393 /* 394 * Calculate bprm->argmin from: 395 * - _STK_LIM 396 * - ARG_MAX 397 * - bprm->rlim_stack.rlim_cur 398 * - bprm->argc 399 * - bprm->envc 400 * - bprm->p 401 */ 402 static int bprm_stack_limits(struct linux_binprm *bprm) 403 { 404 unsigned long limit, ptr_size; 405 406 /* 407 * Limit to 1/4 of the max stack size or 3/4 of _STK_LIM 408 * (whichever is smaller) for the argv+env strings. 409 * This ensures that: 410 * - the remaining binfmt code will not run out of stack space, 411 * - the program will have a reasonable amount of stack left 412 * to work from. 413 */ 414 limit = _STK_LIM / 4 * 3; 415 limit = min(limit, bprm->rlim_stack.rlim_cur / 4); 416 /* 417 * We've historically supported up to 32 pages (ARG_MAX) 418 * of argument strings even with small stacks 419 */ 420 limit = max_t(unsigned long, limit, ARG_MAX); 421 /* Reject totally pathological counts. */ 422 if (bprm->argc < 0 || bprm->envc < 0) 423 return -E2BIG; 424 /* 425 * We must account for the size of all the argv and envp pointers to 426 * the argv and envp strings, since they will also take up space in 427 * the stack. They aren't stored until much later when we can't 428 * signal to the parent that the child has run out of stack space. 429 * Instead, calculate it here so it's possible to fail gracefully. 430 * 431 * In the case of argc = 0, make sure there is space for adding a 432 * empty string (which will bump argc to 1), to ensure confused 433 * userspace programs don't start processing from argv[1], thinking 434 * argc can never be 0, to keep them from walking envp by accident. 435 * See do_execveat_common(). 436 */ 437 if (check_add_overflow(max(bprm->argc, 1), bprm->envc, &ptr_size) || 438 check_mul_overflow(ptr_size, sizeof(void *), &ptr_size)) 439 return -E2BIG; 440 if (limit <= ptr_size) 441 return -E2BIG; 442 limit -= ptr_size; 443 444 return bprm_set_stack_limit(bprm, limit); 445 } 446 447 /* 448 * 'copy_strings()' copies argument/environment strings from the old 449 * processes's memory to the new process's stack. The call to get_user_pages() 450 * ensures the destination page is created and not swapped out. 451 */ 452 static int copy_strings(int argc, struct user_arg_ptr argv, 453 struct linux_binprm *bprm) 454 { 455 struct page *kmapped_page = NULL; 456 char *kaddr = NULL; 457 unsigned long kpos = 0; 458 int ret; 459 460 while (argc-- > 0) { 461 const char __user *str; 462 int len; 463 unsigned long pos; 464 465 ret = -EFAULT; 466 str = get_user_arg_ptr(argv, argc); 467 if (IS_ERR(str)) 468 goto out; 469 470 len = strnlen_user(str, MAX_ARG_STRLEN); 471 if (!len) 472 goto out; 473 474 ret = -E2BIG; 475 if (!valid_arg_len(bprm, len)) 476 goto out; 477 478 /* We're going to work our way backwards. */ 479 pos = bprm->p; 480 str += len; 481 bprm->p -= len; 482 if (bprm_hit_stack_limit(bprm)) 483 goto out; 484 485 while (len > 0) { 486 int offset, bytes_to_copy; 487 488 if (fatal_signal_pending(current)) { 489 ret = -ERESTARTNOHAND; 490 goto out; 491 } 492 cond_resched(); 493 494 offset = pos % PAGE_SIZE; 495 if (offset == 0) 496 offset = PAGE_SIZE; 497 498 bytes_to_copy = offset; 499 if (bytes_to_copy > len) 500 bytes_to_copy = len; 501 502 offset -= bytes_to_copy; 503 pos -= bytes_to_copy; 504 str -= bytes_to_copy; 505 len -= bytes_to_copy; 506 507 if (!kmapped_page || kpos != (pos & PAGE_MASK)) { 508 struct page *page; 509 510 page = get_arg_page(bprm, pos, 1); 511 if (!page) { 512 ret = -E2BIG; 513 goto out; 514 } 515 516 if (kmapped_page) { 517 flush_dcache_page(kmapped_page); 518 kunmap_local(kaddr); 519 put_arg_page(kmapped_page); 520 } 521 kmapped_page = page; 522 kaddr = kmap_local_page(kmapped_page); 523 kpos = pos & PAGE_MASK; 524 flush_arg_page(bprm, kpos, kmapped_page); 525 } 526 if (copy_from_user(kaddr+offset, str, bytes_to_copy)) { 527 ret = -EFAULT; 528 goto out; 529 } 530 } 531 } 532 ret = 0; 533 out: 534 if (kmapped_page) { 535 flush_dcache_page(kmapped_page); 536 kunmap_local(kaddr); 537 put_arg_page(kmapped_page); 538 } 539 return ret; 540 } 541 542 /* 543 * Copy and argument/environment string from the kernel to the processes stack. 544 */ 545 int copy_string_kernel(const char *arg, struct linux_binprm *bprm) 546 { 547 int len = strnlen(arg, MAX_ARG_STRLEN) + 1 /* terminating NUL */; 548 unsigned long pos = bprm->p; 549 550 if (len == 0) 551 return -EFAULT; 552 if (!valid_arg_len(bprm, len)) 553 return -E2BIG; 554 555 /* We're going to work our way backwards. */ 556 arg += len; 557 bprm->p -= len; 558 if (bprm_hit_stack_limit(bprm)) 559 return -E2BIG; 560 561 while (len > 0) { 562 unsigned int bytes_to_copy = min(len, 563 min_not_zero(offset_in_page(pos), PAGE_SIZE)); 564 struct page *page; 565 566 pos -= bytes_to_copy; 567 arg -= bytes_to_copy; 568 len -= bytes_to_copy; 569 570 page = get_arg_page(bprm, pos, 1); 571 if (!page) 572 return -E2BIG; 573 flush_arg_page(bprm, pos & PAGE_MASK, page); 574 memcpy_to_page(page, offset_in_page(pos), arg, bytes_to_copy); 575 put_arg_page(page); 576 } 577 578 return 0; 579 } 580 EXPORT_SYMBOL(copy_string_kernel); 581 582 static int copy_strings_kernel(int argc, const char *const *argv, 583 struct linux_binprm *bprm) 584 { 585 while (argc-- > 0) { 586 int ret = copy_string_kernel(argv[argc], bprm); 587 if (ret < 0) 588 return ret; 589 if (fatal_signal_pending(current)) 590 return -ERESTARTNOHAND; 591 cond_resched(); 592 } 593 return 0; 594 } 595 596 #ifdef CONFIG_MMU 597 598 /* 599 * Finalizes the stack vm_area_struct. The flags and permissions are updated, 600 * the stack is optionally relocated, and some extra space is added. 601 */ 602 int setup_arg_pages(struct linux_binprm *bprm, 603 unsigned long stack_top, 604 int executable_stack) 605 { 606 int ret; 607 unsigned long stack_shift; 608 struct mm_struct *mm = current->mm; 609 struct vm_area_struct *vma = bprm->vma; 610 struct vm_area_struct *prev = NULL; 611 vm_flags_t vm_flags; 612 unsigned long stack_base; 613 unsigned long stack_size; 614 unsigned long stack_expand; 615 unsigned long rlim_stack; 616 struct mmu_gather tlb; 617 struct vma_iterator vmi; 618 619 #ifdef CONFIG_STACK_GROWSUP 620 /* Limit stack size */ 621 stack_base = bprm->rlim_stack.rlim_max; 622 623 stack_base = calc_max_stack_size(stack_base); 624 625 /* Add space for stack randomization. */ 626 if (current->flags & PF_RANDOMIZE) 627 stack_base += (STACK_RND_MASK << PAGE_SHIFT); 628 629 /* Make sure we didn't let the argument array grow too large. */ 630 if (vma->vm_end - vma->vm_start > stack_base) 631 return -ENOMEM; 632 633 stack_base = PAGE_ALIGN(stack_top - stack_base); 634 635 stack_shift = vma->vm_start - stack_base; 636 mm->arg_start = bprm->p - stack_shift; 637 bprm->p = vma->vm_end - stack_shift; 638 #else 639 stack_top = arch_align_stack(stack_top); 640 stack_top = PAGE_ALIGN(stack_top); 641 642 if (unlikely(stack_top < mmap_min_addr) || 643 unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr)) 644 return -ENOMEM; 645 646 stack_shift = vma->vm_end - stack_top; 647 648 bprm->p -= stack_shift; 649 mm->arg_start = bprm->p; 650 #endif 651 652 bprm->exec -= stack_shift; 653 654 if (mmap_write_lock_killable(mm)) 655 return -EINTR; 656 657 vm_flags = VM_STACK_FLAGS; 658 659 /* 660 * Adjust stack execute permissions; explicitly enable for 661 * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone 662 * (arch default) otherwise. 663 */ 664 if (unlikely(executable_stack == EXSTACK_ENABLE_X)) 665 vm_flags |= VM_EXEC; 666 else if (executable_stack == EXSTACK_DISABLE_X) 667 vm_flags &= ~VM_EXEC; 668 vm_flags |= mm->def_flags; 669 vm_flags |= VM_STACK_INCOMPLETE_SETUP; 670 671 vma_iter_init(&vmi, mm, vma->vm_start); 672 673 tlb_gather_mmu(&tlb, mm); 674 ret = mprotect_fixup(&vmi, &tlb, vma, &prev, vma->vm_start, vma->vm_end, 675 vm_flags); 676 tlb_finish_mmu(&tlb); 677 678 if (ret) 679 goto out_unlock; 680 BUG_ON(prev != vma); 681 682 if (unlikely(vm_flags & VM_EXEC)) { 683 pr_warn_once("process '%pD4' started with executable stack\n", 684 bprm->file); 685 } 686 687 /* Move stack pages down in memory. */ 688 if (stack_shift) { 689 /* 690 * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once 691 * the binfmt code determines where the new stack should reside, we shift it to 692 * its final location. 693 */ 694 ret = relocate_vma_down(vma, stack_shift); 695 if (ret) 696 goto out_unlock; 697 } 698 699 /* mprotect_fixup is overkill to remove the temporary stack flags */ 700 vm_flags_clear(vma, VM_STACK_INCOMPLETE_SETUP); 701 702 stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */ 703 stack_size = vma->vm_end - vma->vm_start; 704 /* 705 * Align this down to a page boundary as expand_stack 706 * will align it up. 707 */ 708 rlim_stack = bprm->rlim_stack.rlim_cur & PAGE_MASK; 709 710 stack_expand = min(rlim_stack, stack_size + stack_expand); 711 712 #ifdef CONFIG_STACK_GROWSUP 713 stack_base = vma->vm_start + stack_expand; 714 #else 715 stack_base = vma->vm_end - stack_expand; 716 #endif 717 current->mm->start_stack = bprm->p; 718 ret = expand_stack_locked(vma, stack_base); 719 if (ret) 720 ret = -EFAULT; 721 722 out_unlock: 723 mmap_write_unlock(mm); 724 return ret; 725 } 726 EXPORT_SYMBOL(setup_arg_pages); 727 728 #else 729 730 /* 731 * Transfer the program arguments and environment from the holding pages 732 * onto the stack. The provided stack pointer is adjusted accordingly. 733 */ 734 int transfer_args_to_stack(struct linux_binprm *bprm, 735 unsigned long *sp_location) 736 { 737 unsigned long index, stop, sp; 738 int ret = 0; 739 740 stop = bprm->p >> PAGE_SHIFT; 741 sp = *sp_location; 742 743 for (index = MAX_ARG_PAGES; index-- > stop; ) { 744 unsigned int offset = index == stop ? bprm->p & ~PAGE_MASK : 0; 745 char *src = kmap_local_page(bprm->page[index]) + offset; 746 sp -= PAGE_SIZE - offset; 747 if (copy_to_user((void *) sp, src, PAGE_SIZE - offset) != 0) 748 ret = -EFAULT; 749 kunmap_local(src); 750 if (ret) 751 goto out; 752 } 753 754 bprm->exec += *sp_location - MAX_ARG_PAGES * PAGE_SIZE; 755 *sp_location = sp; 756 757 out: 758 return ret; 759 } 760 EXPORT_SYMBOL(transfer_args_to_stack); 761 762 #endif /* CONFIG_MMU */ 763 764 /* 765 * On success, caller must call do_close_execat() on the returned 766 * struct file to close it. 767 */ 768 static struct file *do_open_execat(int fd, struct filename *name, int flags) 769 { 770 int err; 771 struct file *file __free(fput) = NULL; 772 struct open_flags open_exec_flags = { 773 .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC, 774 .acc_mode = MAY_EXEC, 775 .intent = LOOKUP_OPEN, 776 .lookup_flags = LOOKUP_FOLLOW, 777 }; 778 779 if ((flags & 780 ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH | AT_EXECVE_CHECK)) != 0) 781 return ERR_PTR(-EINVAL); 782 if (flags & AT_SYMLINK_NOFOLLOW) 783 open_exec_flags.lookup_flags &= ~LOOKUP_FOLLOW; 784 785 file = do_file_open(fd, name, &open_exec_flags); 786 if (IS_ERR(file)) 787 return file; 788 789 if (path_noexec(&file->f_path)) 790 return ERR_PTR(-EACCES); 791 792 /* 793 * In the past the regular type check was here. It moved to may_open() in 794 * 633fb6ac3980 ("exec: move S_ISREG() check earlier"). Since then it is 795 * an invariant that all non-regular files error out before we get here. 796 */ 797 if (WARN_ON_ONCE(!S_ISREG(file_inode(file)->i_mode))) 798 return ERR_PTR(-EACCES); 799 800 err = exe_file_deny_write_access(file); 801 if (err) 802 return ERR_PTR(err); 803 804 return no_free_ptr(file); 805 } 806 807 /** 808 * open_exec - Open a path name for execution 809 * 810 * @name: path name to open with the intent of executing it. 811 * 812 * Returns ERR_PTR on failure or allocated struct file on success. 813 * 814 * As this is a wrapper for the internal do_open_execat(), callers 815 * must call exe_file_allow_write_access() before fput() on release. Also see 816 * do_close_execat(). 817 */ 818 struct file *open_exec(const char *name) 819 { 820 CLASS(filename_kernel, filename)(name); 821 return do_open_execat(AT_FDCWD, filename, 0); 822 } 823 EXPORT_SYMBOL(open_exec); 824 825 #if defined(CONFIG_BINFMT_FLAT) || defined(CONFIG_BINFMT_ELF_FDPIC) 826 ssize_t read_code(struct file *file, unsigned long addr, loff_t pos, size_t len) 827 { 828 ssize_t res = vfs_read(file, (void __user *)addr, len, &pos); 829 if (res > 0) 830 flush_icache_user_range(addr, addr + len); 831 return res; 832 } 833 EXPORT_SYMBOL(read_code); 834 #endif 835 836 /* 837 * Maps the mm_struct mm into the current task struct. 838 * On success, this function returns with exec_update_lock 839 * held for writing. The replaced address space is stashed in 840 * bprm->old_mm for setup_new_exec() to release outside the lock. 841 */ 842 static int exec_mmap(struct linux_binprm *bprm) 843 { 844 struct task_exec_state *exec_state __free(put_task_exec_state) = NULL; 845 struct mm_struct *mm = bprm->mm; 846 struct task_struct *tsk; 847 struct mm_struct *old_mm, *active_mm; 848 int ret; 849 850 exec_state = alloc_task_exec_state(bprm->user_ns); 851 if (!exec_state) 852 return -ENOMEM; 853 854 /* Notify parent that we're no longer interested in the old VM */ 855 tsk = current; 856 old_mm = current->mm; 857 exec_mm_release(tsk, old_mm); 858 859 ret = down_write_killable(&tsk->signal->exec_update_lock); 860 if (ret) 861 return ret; 862 863 if (old_mm) { 864 /* 865 * If there is a pending fatal signal perhaps a signal 866 * whose default action is to create a coredump get 867 * out and die instead of going through with the exec. 868 */ 869 ret = mmap_read_lock_killable(old_mm); 870 if (ret) { 871 up_write(&tsk->signal->exec_update_lock); 872 return ret; 873 } 874 } 875 876 task_lock(tsk); 877 membarrier_exec_mmap(mm); 878 879 local_irq_disable(); 880 active_mm = tsk->active_mm; 881 tsk->active_mm = mm; 882 tsk->mm = mm; 883 mm_init_cid(mm, tsk); 884 exec_state = task_exec_state_replace(tsk, exec_state); 885 /* 886 * This prevents preemption while active_mm is being loaded and 887 * it and mm are being updated, which could cause problems for 888 * lazy tlb mm refcounting when these are updated by context 889 * switches. Not all architectures can handle irqs off over 890 * activate_mm yet. 891 */ 892 if (!IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM)) 893 local_irq_enable(); 894 activate_mm(active_mm, mm); 895 if (IS_ENABLED(CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM)) 896 local_irq_enable(); 897 lru_gen_add_mm(mm); 898 task_unlock(tsk); 899 lru_gen_use_mm(mm); 900 if (old_mm) { 901 mmap_read_unlock(old_mm); 902 BUG_ON(active_mm != old_mm); 903 /* Defer teardown to setup_new_exec(), outside the exec locks. */ 904 bprm->old_mm = old_mm; 905 return 0; 906 } 907 mmdrop_lazy_tlb(active_mm); 908 return 0; 909 } 910 911 /* Release the address space replaced by exec, outside the exec locks. */ 912 static void exec_mm_put_old(struct mm_struct *old_mm) 913 { 914 setmax_mm_hiwater_rss(¤t->signal->maxrss, old_mm); 915 mm_update_next_owner(old_mm); 916 mmput(old_mm); 917 } 918 919 static int de_thread(struct task_struct *tsk) 920 { 921 struct signal_struct *sig = tsk->signal; 922 struct sighand_struct *oldsighand = tsk->sighand; 923 spinlock_t *lock = &oldsighand->siglock; 924 925 if (thread_group_empty(tsk)) 926 goto no_thread_group; 927 928 /* 929 * Kill all other threads in the thread group. 930 */ 931 spin_lock_irq(lock); 932 if ((sig->flags & SIGNAL_GROUP_EXIT) || sig->group_exec_task) { 933 /* 934 * Another group action in progress, just 935 * return so that the signal is processed. 936 */ 937 spin_unlock_irq(lock); 938 return -EAGAIN; 939 } 940 941 sig->group_exec_task = tsk; 942 sig->notify_count = zap_other_threads(tsk); 943 if (!thread_group_leader(tsk)) 944 sig->notify_count--; 945 946 while (sig->notify_count) { 947 __set_current_state(TASK_KILLABLE); 948 spin_unlock_irq(lock); 949 schedule(); 950 if (__fatal_signal_pending(tsk)) 951 goto killed; 952 spin_lock_irq(lock); 953 } 954 spin_unlock_irq(lock); 955 956 /* 957 * At this point all other threads have exited, all we have to 958 * do is to wait for the thread group leader to become inactive, 959 * and to assume its PID: 960 */ 961 if (!thread_group_leader(tsk)) { 962 struct task_struct *leader = tsk->group_leader; 963 964 for (;;) { 965 cgroup_threadgroup_change_begin(tsk); 966 write_lock_irq(&tasklist_lock); 967 /* 968 * Do this under tasklist_lock to ensure that 969 * exit_notify() can't miss ->group_exec_task 970 */ 971 sig->notify_count = -1; 972 if (likely(leader->exit_state)) 973 break; 974 __set_current_state(TASK_KILLABLE); 975 write_unlock_irq(&tasklist_lock); 976 cgroup_threadgroup_change_end(tsk); 977 schedule(); 978 if (__fatal_signal_pending(tsk)) 979 goto killed; 980 } 981 982 /* 983 * The only record we have of the real-time age of a 984 * process, regardless of execs it's done, is start_time. 985 * All the past CPU time is accumulated in signal_struct 986 * from sister threads now dead. But in this non-leader 987 * exec, nothing survives from the original leader thread, 988 * whose birth marks the true age of this process now. 989 * When we take on its identity by switching to its PID, we 990 * also take its birthdate (always earlier than our own). 991 */ 992 tsk->start_time = leader->start_time; 993 tsk->start_boottime = leader->start_boottime; 994 995 BUG_ON(!same_thread_group(leader, tsk)); 996 /* 997 * An exec() starts a new thread group with the 998 * TGID of the previous thread group. Rehash the 999 * two threads with a switched PID, and release 1000 * the former thread group leader: 1001 */ 1002 1003 /* Become a process group leader with the old leader's pid. 1004 * The old leader becomes a thread of the this thread group. 1005 */ 1006 exchange_tids(tsk, leader); 1007 transfer_pid(leader, tsk, PIDTYPE_TGID); 1008 transfer_pid(leader, tsk, PIDTYPE_PGID); 1009 transfer_pid(leader, tsk, PIDTYPE_SID); 1010 1011 list_replace_rcu(&leader->tasks, &tsk->tasks); 1012 list_replace_init(&leader->sibling, &tsk->sibling); 1013 1014 tsk->group_leader = tsk; 1015 leader->group_leader = tsk; 1016 1017 tsk->exit_signal = SIGCHLD; 1018 leader->exit_signal = -1; 1019 1020 BUG_ON(leader->exit_state != EXIT_ZOMBIE); 1021 leader->exit_state = EXIT_DEAD; 1022 /* 1023 * We are going to release_task()->ptrace_unlink() silently, 1024 * the tracer can sleep in do_wait(). EXIT_DEAD guarantees 1025 * the tracer won't block again waiting for this thread. 1026 */ 1027 if (unlikely(leader->ptrace)) 1028 __wake_up_parent(leader, leader->parent); 1029 write_unlock_irq(&tasklist_lock); 1030 cgroup_threadgroup_change_end(tsk); 1031 1032 release_task(leader); 1033 } 1034 1035 sig->group_exec_task = NULL; 1036 sig->notify_count = 0; 1037 1038 no_thread_group: 1039 /* we have changed execution domain */ 1040 tsk->exit_signal = SIGCHLD; 1041 1042 BUG_ON(!thread_group_leader(tsk)); 1043 return 0; 1044 1045 killed: 1046 /* protects against exit_notify() and __exit_signal() */ 1047 read_lock(&tasklist_lock); 1048 sig->group_exec_task = NULL; 1049 sig->notify_count = 0; 1050 read_unlock(&tasklist_lock); 1051 return -EAGAIN; 1052 } 1053 1054 1055 /* 1056 * This function makes sure the current process has its own signal table, 1057 * so that flush_signal_handlers can later reset the handlers without 1058 * disturbing other processes. (Other processes might share the signal 1059 * table via the CLONE_SIGHAND option to clone().) 1060 */ 1061 static int unshare_sighand(struct task_struct *me) 1062 { 1063 struct sighand_struct *oldsighand = me->sighand; 1064 1065 if (refcount_read(&oldsighand->count) != 1) { 1066 struct sighand_struct *newsighand; 1067 /* 1068 * This ->sighand is shared with the CLONE_SIGHAND 1069 * but not CLONE_THREAD task, switch to the new one. 1070 */ 1071 newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); 1072 if (!newsighand) 1073 return -ENOMEM; 1074 1075 refcount_set(&newsighand->count, 1); 1076 1077 write_lock_irq(&tasklist_lock); 1078 spin_lock(&oldsighand->siglock); 1079 memcpy(newsighand->action, oldsighand->action, 1080 sizeof(newsighand->action)); 1081 rcu_assign_pointer(me->sighand, newsighand); 1082 spin_unlock(&oldsighand->siglock); 1083 write_unlock_irq(&tasklist_lock); 1084 1085 __cleanup_sighand(oldsighand); 1086 } 1087 return 0; 1088 } 1089 1090 /* 1091 * This is unlocked -- the string will always be NUL-terminated, but 1092 * may show overlapping contents if racing concurrent reads. 1093 */ 1094 void __set_task_comm(struct task_struct *tsk, const char *buf, bool exec) 1095 { 1096 size_t len = strnlen(buf, sizeof(tsk->comm) - 1); 1097 1098 trace_task_rename(tsk, buf); 1099 memcpy(tsk->comm, buf, len); 1100 memset(&tsk->comm[len], 0, sizeof(tsk->comm) - len); 1101 perf_event_comm(tsk, exec); 1102 } 1103 1104 /* 1105 * The file the process presents as: its exe link and comm. A transparent 1106 * dispatch presents as the binary, which is bprm->executable. 1107 */ 1108 static struct file *bprm_identity_file(const struct linux_binprm *bprm) 1109 { 1110 if (bprm->interp_flags & BINPRM_FLAGS_TRANSPARENT_INTERP) 1111 return bprm->executable; 1112 return bprm->file; 1113 } 1114 1115 /* 1116 * Calling this is the point of no return. None of the failures will be 1117 * seen by userspace since either the process is already taking a fatal 1118 * signal (via de_thread() or coredump), or will have SEGV raised 1119 * (after exec_mmap()) by search_binary_handler (see below). 1120 */ 1121 int begin_new_exec(struct linux_binprm * bprm) 1122 { 1123 struct task_struct *me = current; 1124 int retval; 1125 1126 /* A pending PT_INTERP substitution this format cannot consume. */ 1127 if (bprm->loader) 1128 return -ENOEXEC; 1129 1130 /* Once we are committed compute the creds */ 1131 retval = bprm_creds_from_file(bprm); 1132 if (retval) 1133 return retval; 1134 1135 /* 1136 * This tracepoint marks the point before flushing the old exec where 1137 * the current task is still unchanged, but errors are fatal (point of 1138 * no return). The later "sched_process_exec" tracepoint is called after 1139 * the current task has successfully switched to the new exec. 1140 */ 1141 trace_sched_prepare_exec(current, bprm); 1142 1143 /* 1144 * Ensure all future errors are fatal. 1145 */ 1146 bprm->point_of_no_return = true; 1147 1148 /* Make this the only thread in the thread group */ 1149 retval = de_thread(me); 1150 if (retval) 1151 goto out; 1152 /* see the comment in check_unsafe_exec() */ 1153 current->fs->in_exec = 0; 1154 /* 1155 * Cancel any io_uring activity across execve 1156 */ 1157 io_uring_task_cancel(); 1158 1159 /* Ensure the files table is not shared. */ 1160 retval = unshare_files(); 1161 if (retval) 1162 goto out; 1163 1164 /* 1165 * Must be called _before_ exec_mmap() as bprm->mm is 1166 * not visible until then. Doing it here also ensures 1167 * we don't race against replace_mm_exe_file(). 1168 */ 1169 retval = set_mm_exe_file(bprm->mm, bprm_identity_file(bprm)); 1170 if (retval) 1171 goto out; 1172 1173 /* If the binary is not readable then enforce mm->dumpable=0 */ 1174 would_dump(bprm, bprm->file); 1175 if (bprm->have_execfd) 1176 would_dump(bprm, bprm->executable); 1177 1178 /* 1179 * Release all of the old mmap stuff 1180 */ 1181 acct_arg_size(bprm, 0); 1182 retval = exec_mmap(bprm); 1183 if (retval) 1184 goto out; 1185 1186 bprm->mm = NULL; 1187 1188 retval = exec_task_namespaces(); 1189 if (retval) 1190 goto out_unlock; 1191 1192 #ifdef CONFIG_POSIX_TIMERS 1193 spin_lock_irq(&me->sighand->siglock); 1194 posix_cpu_timers_exit(me); 1195 spin_unlock_irq(&me->sighand->siglock); 1196 exit_itimers(me); 1197 flush_itimer_signals(); 1198 #endif 1199 1200 /* 1201 * Make the signal table private. 1202 */ 1203 retval = unshare_sighand(me); 1204 if (retval) 1205 goto out_unlock; 1206 1207 me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC | 1208 PF_NOFREEZE | PF_NO_SETAFFINITY); 1209 flush_thread(); 1210 me->personality &= ~bprm->per_clear; 1211 1212 clear_syscall_work_syscall_user_dispatch(me); 1213 1214 /* 1215 * We have to apply CLOEXEC before we change whether the process is 1216 * dumpable (in setup_new_exec) to avoid a race with a process in userspace 1217 * trying to access the should-be-closed file descriptors of a process 1218 * undergoing exec(2). 1219 */ 1220 do_close_on_exec(me->files); 1221 1222 if (bprm->secureexec) { 1223 /* Make sure parent cannot signal privileged process. */ 1224 me->pdeath_signal = 0; 1225 1226 /* 1227 * For secureexec, reset the stack limit to sane default to 1228 * avoid bad behavior from the prior rlimits. This has to 1229 * happen before arch_pick_mmap_layout(), which examines 1230 * RLIMIT_STACK, but after the point of no return to avoid 1231 * needing to clean up the change on failure. 1232 */ 1233 if (bprm->rlim_stack.rlim_cur > _STK_LIM) 1234 bprm->rlim_stack.rlim_cur = _STK_LIM; 1235 } 1236 1237 me->sas_ss_sp = me->sas_ss_size = 0; 1238 1239 /* 1240 * Figure out dumpability. Note that this checking only of current 1241 * is wrong, but userspace depends on it. This should be testing 1242 * bprm->secureexec instead. 1243 */ 1244 if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP || 1245 !(uid_eq(current_euid(), current_uid()) && 1246 gid_eq(current_egid(), current_gid()))) 1247 task_exec_state_set_dumpable(suid_dumpable); 1248 else 1249 task_exec_state_set_dumpable(TASK_DUMPABLE_OWNER); 1250 1251 perf_event_exec(); 1252 1253 /* 1254 * If the original filename was empty, alloc_bprm() made up a path 1255 * that will probably not be useful to admins running ps or similar. 1256 * Let's fix it up to be something reasonable. 1257 */ 1258 if (bprm->comm_from_dentry) { 1259 struct file *comm_file = bprm_identity_file(bprm); 1260 1261 /* 1262 * Hold RCU lock to keep the name from being freed behind our back. 1263 * Use acquire semantics to make sure the terminating NUL from 1264 * __d_alloc() is seen. 1265 * 1266 * Note, we're deliberately sloppy here. We don't need to care about 1267 * detecting a concurrent rename and just want a terminated name. 1268 */ 1269 rcu_read_lock(); 1270 __set_task_comm(me, smp_load_acquire(&comm_file->f_path.dentry->d_name.name), 1271 true); 1272 rcu_read_unlock(); 1273 } else { 1274 __set_task_comm(me, kbasename(bprm->filename), true); 1275 } 1276 1277 /* An exec changes our domain. We are no longer part of the thread 1278 group */ 1279 WRITE_ONCE(me->self_exec_id, me->self_exec_id + 1); 1280 flush_signal_handlers(me, 0); 1281 1282 retval = set_cred_ucounts(bprm->cred); 1283 if (retval < 0) 1284 goto out_unlock; 1285 1286 /* 1287 * install the new credentials for this executable 1288 */ 1289 security_bprm_committing_creds(bprm); 1290 1291 commit_creds(bprm->cred); 1292 bprm->cred = NULL; 1293 1294 /* 1295 * Disable monitoring for regular users 1296 * when executing setuid binaries. Must 1297 * wait until new credentials are committed 1298 * by commit_creds() above 1299 */ 1300 if (task_exec_state_get_dumpable(me) != TASK_DUMPABLE_OWNER) 1301 perf_event_exit_task(me); 1302 /* 1303 * cred_guard_mutex must be held at least to this point to prevent 1304 * ptrace_attach() from altering our determination of the task's 1305 * credentials; any time after this it may be unlocked. 1306 */ 1307 security_bprm_committed_creds(bprm); 1308 1309 /* Pass the opened binary to the interpreter. */ 1310 if (bprm->have_execfd) { 1311 struct file *executable = bprm->executable; 1312 1313 /* mm->exe_file carries its own write denial now so drop it. */ 1314 exe_file_allow_write_access(executable); 1315 bprm->executable = NULL; 1316 retval = FD_ADD(0, executable); 1317 if (retval < 0) { 1318 /* The reference was not consumed. */ 1319 fput(executable); 1320 goto out_unlock; 1321 } 1322 bprm->execfd = retval; 1323 } 1324 return 0; 1325 1326 out_unlock: 1327 up_write(&me->signal->exec_update_lock); 1328 if (!bprm->cred) 1329 mutex_unlock(&me->signal->cred_guard_mutex); 1330 1331 out: 1332 return retval; 1333 } 1334 EXPORT_SYMBOL(begin_new_exec); 1335 1336 void would_dump(struct linux_binprm *bprm, struct file *file) 1337 { 1338 struct inode *inode = file_inode(file); 1339 struct mnt_idmap *idmap = file_mnt_idmap(file); 1340 if (inode_permission(idmap, inode, MAY_READ) < 0) { 1341 struct user_namespace *old, *user_ns; 1342 bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP; 1343 1344 /* Ensure bprm->user_ns contains the executable. */ 1345 user_ns = old = bprm->user_ns; 1346 while ((user_ns != &init_user_ns) && 1347 !privileged_wrt_inode_uidgid(user_ns, idmap, inode)) 1348 user_ns = user_ns->parent; 1349 1350 if (old != user_ns) { 1351 bprm->user_ns = get_user_ns(user_ns); 1352 put_user_ns(old); 1353 } 1354 } 1355 } 1356 EXPORT_SYMBOL(would_dump); 1357 1358 void setup_new_exec(struct linux_binprm * bprm) 1359 { 1360 /* Setup things that can depend upon the personality */ 1361 struct task_struct *me = current; 1362 1363 arch_pick_mmap_layout(me->mm, &bprm->rlim_stack); 1364 1365 arch_setup_new_exec(); 1366 1367 /* Set the new mm task size. We have to do that late because it may 1368 * depend on TIF_32BIT which is only updated in flush_thread() on 1369 * some architectures like powerpc 1370 */ 1371 me->mm->task_size = TASK_SIZE; 1372 up_write(&me->signal->exec_update_lock); 1373 mutex_unlock(&me->signal->cred_guard_mutex); 1374 1375 /* The exec locks are dropped: release the old address space now. */ 1376 if (bprm->old_mm) { 1377 exec_mm_put_old(bprm->old_mm); 1378 bprm->old_mm = NULL; 1379 } 1380 } 1381 EXPORT_SYMBOL(setup_new_exec); 1382 1383 /* Runs immediately before start_thread() takes over. */ 1384 void finalize_exec(struct linux_binprm *bprm) 1385 { 1386 /* Store any stack rlimit changes before starting thread. */ 1387 task_lock(current->group_leader); 1388 current->signal->rlim[RLIMIT_STACK] = bprm->rlim_stack; 1389 task_unlock(current->group_leader); 1390 } 1391 EXPORT_SYMBOL(finalize_exec); 1392 1393 /* 1394 * Prepare credentials and lock ->cred_guard_mutex. 1395 * setup_new_exec() commits the new creds and drops the lock. 1396 * Or, if exec fails before, free_bprm() should release ->cred 1397 * and unlock. 1398 */ 1399 static int prepare_bprm_creds(struct linux_binprm *bprm) 1400 { 1401 if (mutex_lock_interruptible(¤t->signal->cred_guard_mutex)) 1402 return -ERESTARTNOINTR; 1403 1404 bprm->cred = prepare_exec_creds(); 1405 if (likely(bprm->cred)) 1406 return 0; 1407 1408 mutex_unlock(¤t->signal->cred_guard_mutex); 1409 return -ENOMEM; 1410 } 1411 1412 /* Matches do_open_execat() */ 1413 static void do_close_execat(struct file *file) 1414 { 1415 if (!file) 1416 return; 1417 exe_file_allow_write_access(file); 1418 fput(file); 1419 } 1420 1421 /** 1422 * bprm_open_interpreter - open the interpreter the binary asks for 1423 * @bprm: binary that is being executed 1424 * @path: the interpreter path named in the binary's PT_INTERP 1425 * 1426 * A binfmt_misc loader entry substitutes for the interpreter the binary 1427 * names. Hand out the stashed substitute if there is one and open @path 1428 * if there is not. The caller owns the reference either way and releases 1429 * it like any other open_exec() one. 1430 * 1431 * Return: the interpreter on success, an ERR_PTR on failure 1432 */ 1433 struct file *bprm_open_interpreter(struct linux_binprm *bprm, const char *path) 1434 { 1435 if (bprm->loader) 1436 return no_free_ptr(bprm->loader); 1437 return open_exec(path); 1438 } 1439 1440 /** 1441 * bprm_drop_loader - discard a PT_INTERP substitute that does not apply 1442 * @bprm: binary that is being executed 1443 * 1444 * A binary without PT_INTERP has nothing to substitute for, so drop the 1445 * override and let the binary load natively rather than have 1446 * begin_new_exec() refuse it. A no-op once bprm_open_interpreter() took 1447 * the substitute. 1448 */ 1449 void bprm_drop_loader(struct linux_binprm *bprm) 1450 { 1451 do_close_execat(no_free_ptr(bprm->loader)); 1452 } 1453 1454 static void free_bprm(struct linux_binprm *bprm) 1455 { 1456 if (bprm->mm) { 1457 acct_arg_size(bprm, 0); 1458 mmput(bprm->mm); 1459 } 1460 if (bprm->user_ns) 1461 put_user_ns(bprm->user_ns); 1462 free_arg_pages(bprm); 1463 if (bprm->cred) { 1464 /* in case exec fails before de_thread() succeeds */ 1465 current->fs->in_exec = 0; 1466 mutex_unlock(¤t->signal->cred_guard_mutex); 1467 abort_creds(bprm->cred); 1468 } 1469 /* exec swapped the mm but failed before setup_new_exec() freed it */ 1470 if (bprm->old_mm) 1471 exec_mm_put_old(bprm->old_mm); 1472 do_close_execat(bprm->file); 1473 /* An unconsumed PT_INTERP substitute from a binfmt_misc loader entry. */ 1474 bprm_drop_loader(bprm); 1475 do_close_execat(bprm->executable); 1476 /* If a binfmt changed the interp, free it. */ 1477 if (bprm->interp != bprm->filename) 1478 kfree(bprm->interp); 1479 kfree(bprm->bpf_interp); 1480 if (bprm->bpf_interp_file) 1481 fput(bprm->bpf_interp_file); 1482 kfree(bprm->bpf_interp_arg); 1483 kfree(bprm->fdpath); 1484 kfree(bprm); 1485 } 1486 1487 static struct linux_binprm *alloc_bprm(int fd, struct filename *filename, int flags) 1488 { 1489 struct linux_binprm *bprm; 1490 struct file *file; 1491 int retval = -ENOMEM; 1492 1493 file = do_open_execat(fd, filename, flags); 1494 if (IS_ERR(file)) 1495 return ERR_CAST(file); 1496 1497 bprm = kzalloc_obj(*bprm); 1498 if (!bprm) { 1499 do_close_execat(file); 1500 return ERR_PTR(-ENOMEM); 1501 } 1502 1503 bprm->file = file; 1504 1505 if (fd == AT_FDCWD || filename->name[0] == '/') { 1506 bprm->filename = filename->name; 1507 } else { 1508 if (filename->name[0] == '\0') { 1509 bprm->fdpath = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd); 1510 bprm->comm_from_dentry = 1; 1511 } else { 1512 bprm->fdpath = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s", 1513 fd, filename->name); 1514 } 1515 if (!bprm->fdpath) 1516 goto out_free; 1517 1518 /* 1519 * Record that a name derived from an O_CLOEXEC fd will be 1520 * inaccessible after exec. This allows the code in exec to 1521 * choose to fail when the executable is not mmaped into the 1522 * interpreter and an open file descriptor is not passed to 1523 * the interpreter. This makes for a better user experience 1524 * than having the interpreter start and then immediately fail 1525 * when it finds the executable is inaccessible. 1526 */ 1527 if (get_close_on_exec(fd)) 1528 bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE; 1529 1530 bprm->filename = bprm->fdpath; 1531 } 1532 bprm->interp = bprm->filename; 1533 1534 /* 1535 * At this point, security_file_open() has already been called (with 1536 * __FMODE_EXEC) and access control checks for AT_EXECVE_CHECK will 1537 * stop just after the security_bprm_creds_for_exec() call in 1538 * bprm_execve(). Indeed, the kernel should not try to parse the 1539 * content of the file with exec_binprm() nor change the calling 1540 * thread, which means that the following security functions will not 1541 * be called: 1542 * - security_bprm_check() 1543 * - security_bprm_creds_from_file() 1544 * - security_bprm_committing_creds() 1545 * - security_bprm_committed_creds() 1546 */ 1547 bprm->is_check = !!(flags & AT_EXECVE_CHECK); 1548 1549 retval = bprm_mm_init(bprm); 1550 if (!retval) 1551 return bprm; 1552 1553 out_free: 1554 free_bprm(bprm); 1555 return ERR_PTR(retval); 1556 } 1557 1558 DEFINE_CLASS(bprm, struct linux_binprm *, if (!IS_ERR(_T)) free_bprm(_T), 1559 alloc_bprm(fd, name, flags), int fd, struct filename *name, int flags) 1560 1561 int bprm_change_interp(const char *interp, struct linux_binprm *bprm) 1562 { 1563 /* If a binfmt changed the interp, free it first. */ 1564 if (bprm->interp != bprm->filename) 1565 kfree(bprm->interp); 1566 bprm->interp = kstrdup(interp, GFP_KERNEL); 1567 if (!bprm->interp) 1568 return -ENOMEM; 1569 return 0; 1570 } 1571 EXPORT_SYMBOL(bprm_change_interp); 1572 1573 /* 1574 * determine how safe it is to execute the proposed program 1575 * - the caller must hold ->cred_guard_mutex to protect against 1576 * PTRACE_ATTACH or seccomp thread-sync 1577 */ 1578 static void check_unsafe_exec(struct linux_binprm *bprm) 1579 { 1580 struct task_struct *p = current, *t; 1581 unsigned n_fs; 1582 1583 if (p->ptrace) 1584 bprm->unsafe |= LSM_UNSAFE_PTRACE; 1585 1586 /* 1587 * This isn't strictly necessary, but it makes it harder for LSMs to 1588 * mess up. 1589 */ 1590 if (task_no_new_privs(current)) 1591 bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS; 1592 1593 /* 1594 * If another task is sharing our fs, we cannot safely 1595 * suid exec because the differently privileged task 1596 * will be able to manipulate the current directory, etc. 1597 * It would be nice to force an unshare instead... 1598 * 1599 * Otherwise we set fs->in_exec = 1 to deny clone(CLONE_FS) 1600 * from another sub-thread until de_thread() succeeds, this 1601 * state is protected by cred_guard_mutex we hold. 1602 */ 1603 n_fs = 1; 1604 read_seqlock_excl(&p->fs->seq); 1605 rcu_read_lock(); 1606 for_other_threads(p, t) { 1607 if (t->fs == p->fs) 1608 n_fs++; 1609 } 1610 rcu_read_unlock(); 1611 1612 /* "users" and "in_exec" locked for copy_fs() */ 1613 if (p->fs->users > n_fs) 1614 bprm->unsafe |= LSM_UNSAFE_SHARE; 1615 else 1616 p->fs->in_exec = 1; 1617 read_sequnlock_excl(&p->fs->seq); 1618 } 1619 1620 static void bprm_fill_uid(struct linux_binprm *bprm, struct file *file) 1621 { 1622 /* Handle suid and sgid on files */ 1623 struct mnt_idmap *idmap; 1624 struct inode *inode = file_inode(file); 1625 unsigned int mode; 1626 vfsuid_t vfsuid; 1627 vfsgid_t vfsgid; 1628 int err; 1629 1630 if (!mnt_may_suid(file->f_path.mnt)) 1631 return; 1632 1633 if (task_no_new_privs(current)) 1634 return; 1635 1636 mode = READ_ONCE(inode->i_mode); 1637 if (!(mode & (S_ISUID|S_ISGID))) 1638 return; 1639 1640 idmap = file_mnt_idmap(file); 1641 1642 /* Be careful if suid/sgid is set */ 1643 inode_lock(inode); 1644 1645 /* Atomically reload and check mode/uid/gid now that lock held. */ 1646 mode = inode->i_mode; 1647 vfsuid = i_uid_into_vfsuid(idmap, inode); 1648 vfsgid = i_gid_into_vfsgid(idmap, inode); 1649 err = inode_permission(idmap, inode, MAY_EXEC); 1650 inode_unlock(inode); 1651 1652 /* Did the exec bit vanish out from under us? Give up. */ 1653 if (err) 1654 return; 1655 1656 /* We ignore suid/sgid if there are no mappings for them in the ns */ 1657 if (!vfsuid_has_mapping(bprm->cred->user_ns, vfsuid) || 1658 !vfsgid_has_mapping(bprm->cred->user_ns, vfsgid)) 1659 return; 1660 1661 if (mode & S_ISUID) { 1662 bprm->per_clear |= PER_CLEAR_ON_SETID; 1663 bprm->cred->euid = vfsuid_into_kuid(vfsuid); 1664 } 1665 1666 if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { 1667 bprm->per_clear |= PER_CLEAR_ON_SETID; 1668 bprm->cred->egid = vfsgid_into_kgid(vfsgid); 1669 } 1670 } 1671 1672 /* 1673 * Compute brpm->cred based upon the final binary. 1674 */ 1675 static int bprm_creds_from_file(struct linux_binprm *bprm) 1676 { 1677 /* Compute creds based on which file? */ 1678 struct file *file = bprm->execfd_creds ? bprm->executable : bprm->file; 1679 1680 bprm_fill_uid(bprm, file); 1681 return security_bprm_creds_from_file(bprm, file); 1682 } 1683 1684 /* 1685 * Fill the binprm structure from the inode. 1686 * Read the first BINPRM_BUF_SIZE bytes 1687 * 1688 * This may be called multiple times for binary chains (scripts for example). 1689 */ 1690 static int prepare_binprm(struct linux_binprm *bprm) 1691 { 1692 loff_t pos = 0; 1693 1694 memset(bprm->buf, 0, BINPRM_BUF_SIZE); 1695 return kernel_read(bprm->file, bprm->buf, BINPRM_BUF_SIZE, &pos); 1696 } 1697 1698 /* 1699 * Arguments are '\0' separated strings found at the location bprm->p 1700 * points to; chop off the first by relocating brpm->p to right after 1701 * the first '\0' encountered. 1702 */ 1703 int remove_arg_zero(struct linux_binprm *bprm) 1704 { 1705 unsigned long offset; 1706 char *kaddr; 1707 struct page *page; 1708 1709 if (!bprm->argc) 1710 return 0; 1711 1712 do { 1713 offset = bprm->p & ~PAGE_MASK; 1714 page = get_arg_page(bprm, bprm->p, 0); 1715 if (!page) 1716 return -EFAULT; 1717 kaddr = kmap_local_page(page); 1718 1719 for (; offset < PAGE_SIZE && kaddr[offset]; 1720 offset++, bprm->p++) 1721 ; 1722 1723 kunmap_local(kaddr); 1724 put_arg_page(page); 1725 } while (offset == PAGE_SIZE); 1726 1727 bprm->p++; 1728 bprm->argc--; 1729 1730 return 0; 1731 } 1732 EXPORT_SYMBOL(remove_arg_zero); 1733 1734 /* 1735 * cycle the list of binary formats handler, until one recognizes the image 1736 */ 1737 static int search_binary_handler(struct linux_binprm *bprm) 1738 { 1739 struct linux_binfmt *fmt; 1740 int retval; 1741 1742 retval = prepare_binprm(bprm); 1743 if (retval < 0) 1744 return retval; 1745 1746 retval = security_bprm_check(bprm); 1747 if (retval) 1748 return retval; 1749 1750 read_lock(&binfmt_lock); 1751 list_for_each_entry(fmt, &formats, lh) { 1752 if (!try_module_get(fmt->module)) 1753 continue; 1754 read_unlock(&binfmt_lock); 1755 1756 retval = fmt->load_binary(bprm); 1757 1758 read_lock(&binfmt_lock); 1759 put_binfmt(fmt); 1760 if (bprm->point_of_no_return || (retval != -ENOEXEC)) { 1761 read_unlock(&binfmt_lock); 1762 return retval; 1763 } 1764 } 1765 read_unlock(&binfmt_lock); 1766 1767 return -ENOEXEC; 1768 } 1769 1770 /* binfmt handlers will call back into begin_new_exec() on success. */ 1771 static int exec_binprm(struct linux_binprm *bprm) 1772 { 1773 pid_t old_pid, old_vpid; 1774 int ret, depth; 1775 1776 /* Need to fetch pid before load_binary changes it */ 1777 old_pid = current->pid; 1778 rcu_read_lock(); 1779 old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent)); 1780 rcu_read_unlock(); 1781 1782 /* This allows 5 levels of binfmt rewrites before failing hard. */ 1783 for (depth = 0;; depth++) { 1784 struct file *exec; 1785 if (depth > 5) 1786 return -ELOOP; 1787 1788 ret = search_binary_handler(bprm); 1789 if (ret < 0) 1790 return ret; 1791 if (!bprm->interpreter) 1792 break; 1793 1794 /* A stashed PT_INTERP substitute belonged to the replaced file. */ 1795 bprm_drop_loader(bprm); 1796 1797 exec = bprm->file; 1798 bprm->file = bprm->interpreter; 1799 bprm->interpreter = NULL; 1800 1801 if (unlikely(bprm->have_execfd)) { 1802 if (bprm->executable) { 1803 do_close_execat(exec); 1804 return -ENOEXEC; 1805 } 1806 /* Kept for AT_EXECFD; the write denial rides along until hand-over. */ 1807 bprm->executable = exec; 1808 } else { 1809 do_close_execat(exec); 1810 } 1811 } 1812 1813 audit_bprm(bprm); 1814 trace_sched_process_exec(current, old_pid, bprm); 1815 ptrace_event(PTRACE_EVENT_EXEC, old_vpid); 1816 proc_exec_connector(current); 1817 return 0; 1818 } 1819 1820 static int bprm_execve(struct linux_binprm *bprm) 1821 { 1822 int retval; 1823 1824 retval = prepare_bprm_creds(bprm); 1825 if (retval) 1826 return retval; 1827 1828 /* 1829 * Check for unsafe execution states before exec_binprm(), which 1830 * will call back into begin_new_exec(), into bprm_creds_from_file(), 1831 * where setuid-ness is evaluated. 1832 */ 1833 check_unsafe_exec(bprm); 1834 current->in_execve = 1; 1835 sched_mm_cid_before_execve(current); 1836 1837 sched_exec(); 1838 1839 /* Set the unchanging part of bprm->cred */ 1840 retval = security_bprm_creds_for_exec(bprm); 1841 if (retval || bprm->is_check) 1842 goto out; 1843 1844 retval = exec_binprm(bprm); 1845 if (retval < 0) 1846 goto out; 1847 1848 sched_mm_cid_after_execve(current); 1849 rseq_execve(current); 1850 /* execve succeeded */ 1851 current->in_execve = 0; 1852 user_events_execve(current); 1853 acct_update_integrals(current); 1854 task_numa_free(current, false); 1855 return retval; 1856 1857 out: 1858 /* 1859 * If past the point of no return ensure the code never 1860 * returns to the userspace process. Use an existing fatal 1861 * signal if present otherwise terminate the process with 1862 * SIGSEGV. 1863 */ 1864 if (bprm->point_of_no_return && !fatal_signal_pending(current)) 1865 force_fatal_sig(SIGSEGV); 1866 1867 sched_mm_cid_after_execve(current); 1868 rseq_force_update(); 1869 current->in_execve = 0; 1870 1871 return retval; 1872 } 1873 1874 static int do_execveat_common(int fd, struct filename *filename, 1875 struct user_arg_ptr argv, 1876 struct user_arg_ptr envp, 1877 int flags) 1878 { 1879 int retval; 1880 1881 /* 1882 * We move the actual failure in case of RLIMIT_NPROC excess from 1883 * set*uid() to execve() because too many poorly written programs 1884 * don't check setuid() return code. Here we additionally recheck 1885 * whether NPROC limit is still exceeded. 1886 */ 1887 if ((current->flags & PF_NPROC_EXCEEDED) && 1888 is_rlimit_overlimit(current_ucounts(), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) 1889 return -EAGAIN; 1890 1891 /* We're below the limit (still or again), so we don't want to make 1892 * further execve() calls fail. */ 1893 current->flags &= ~PF_NPROC_EXCEEDED; 1894 1895 CLASS(bprm, bprm)(fd, filename, flags); 1896 if (IS_ERR(bprm)) 1897 return PTR_ERR(bprm); 1898 1899 retval = count(argv, MAX_ARG_STRINGS); 1900 if (retval < 0) 1901 return retval; 1902 bprm->argc = retval; 1903 1904 retval = count(envp, MAX_ARG_STRINGS); 1905 if (retval < 0) 1906 return retval; 1907 bprm->envc = retval; 1908 1909 retval = bprm_stack_limits(bprm); 1910 if (retval < 0) 1911 return retval; 1912 1913 retval = copy_string_kernel(bprm->filename, bprm); 1914 if (retval < 0) 1915 return retval; 1916 bprm->exec = bprm->p; 1917 1918 retval = copy_strings(bprm->envc, envp, bprm); 1919 if (retval < 0) 1920 return retval; 1921 1922 retval = copy_strings(bprm->argc, argv, bprm); 1923 if (retval < 0) 1924 return retval; 1925 1926 /* 1927 * When argv is empty, add an empty string ("") as argv[0] to 1928 * ensure confused userspace programs that start processing 1929 * from argv[1] won't end up walking envp. See also 1930 * bprm_stack_limits(). 1931 */ 1932 if (bprm->argc == 0) { 1933 retval = copy_string_kernel("", bprm); 1934 if (retval < 0) 1935 return retval; 1936 bprm->argc = 1; 1937 1938 pr_warn_once("process '%s' launched '%s' with NULL argv: empty string added\n", 1939 current->comm, bprm->filename); 1940 } 1941 1942 return bprm_execve(bprm); 1943 } 1944 1945 int kernel_execve(const char *kernel_filename, 1946 const char *const *argv, const char *const *envp) 1947 { 1948 int retval; 1949 1950 /* It is non-sense for kernel threads to call execve */ 1951 if (WARN_ON_ONCE(current->flags & PF_KTHREAD)) 1952 return -EINVAL; 1953 1954 CLASS(filename_kernel, filename)(kernel_filename); 1955 CLASS(bprm, bprm)(AT_FDCWD, filename, 0); 1956 if (IS_ERR(bprm)) 1957 return PTR_ERR(bprm); 1958 1959 retval = count_strings_kernel(argv); 1960 if (WARN_ON_ONCE(retval == 0)) 1961 return -EINVAL; 1962 if (retval < 0) 1963 return retval; 1964 bprm->argc = retval; 1965 1966 retval = count_strings_kernel(envp); 1967 if (retval < 0) 1968 return retval; 1969 bprm->envc = retval; 1970 1971 retval = bprm_stack_limits(bprm); 1972 if (retval < 0) 1973 return retval; 1974 1975 retval = copy_string_kernel(bprm->filename, bprm); 1976 if (retval < 0) 1977 return retval; 1978 bprm->exec = bprm->p; 1979 1980 retval = copy_strings_kernel(bprm->envc, envp, bprm); 1981 if (retval < 0) 1982 return retval; 1983 1984 retval = copy_strings_kernel(bprm->argc, argv, bprm); 1985 if (retval < 0) 1986 return retval; 1987 1988 return bprm_execve(bprm); 1989 } 1990 1991 void set_binfmt(struct linux_binfmt *new) 1992 { 1993 struct mm_struct *mm = current->mm; 1994 1995 if (mm->binfmt) 1996 module_put(mm->binfmt->module); 1997 1998 mm->binfmt = new; 1999 if (new) 2000 __module_get(new->module); 2001 } 2002 EXPORT_SYMBOL(set_binfmt); 2003 2004 static inline struct user_arg_ptr native_arg(const char __user *const __user *p) 2005 { 2006 return (struct user_arg_ptr){.ptr.native = p}; 2007 } 2008 2009 SYSCALL_DEFINE3(execve, 2010 const char __user *, filename, 2011 const char __user *const __user *, argv, 2012 const char __user *const __user *, envp) 2013 { 2014 CLASS(filename, name)(filename); 2015 return do_execveat_common(AT_FDCWD, name, 2016 native_arg(argv), native_arg(envp), 0); 2017 } 2018 2019 SYSCALL_DEFINE5(execveat, 2020 int, fd, const char __user *, filename, 2021 const char __user *const __user *, argv, 2022 const char __user *const __user *, envp, 2023 int, flags) 2024 { 2025 CLASS(filename_uflags, name)(filename, flags); 2026 return do_execveat_common(fd, name, 2027 native_arg(argv), native_arg(envp), flags); 2028 } 2029 2030 #ifdef CONFIG_COMPAT 2031 2032 static inline struct user_arg_ptr compat_arg(const compat_uptr_t __user *p) 2033 { 2034 return (struct user_arg_ptr){.is_compat = true, .ptr.compat = p}; 2035 } 2036 2037 COMPAT_SYSCALL_DEFINE3(execve, const char __user *, filename, 2038 const compat_uptr_t __user *, argv, 2039 const compat_uptr_t __user *, envp) 2040 { 2041 CLASS(filename, name)(filename); 2042 return do_execveat_common(AT_FDCWD, name, 2043 compat_arg(argv), compat_arg(envp), 0); 2044 } 2045 2046 COMPAT_SYSCALL_DEFINE5(execveat, int, fd, 2047 const char __user *, filename, 2048 const compat_uptr_t __user *, argv, 2049 const compat_uptr_t __user *, envp, 2050 int, flags) 2051 { 2052 CLASS(filename_uflags, name)(filename, flags); 2053 return do_execveat_common(fd, name, 2054 compat_arg(argv), compat_arg(envp), flags); 2055 } 2056 #endif 2057 2058 #ifdef CONFIG_SYSCTL 2059 2060 static int proc_dointvec_minmax_coredump(const struct ctl_table *table, int write, 2061 void *buffer, size_t *lenp, loff_t *ppos) 2062 { 2063 int error, old = READ_ONCE(suid_dumpable); 2064 2065 error = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 2066 2067 if (!error && write && (old != READ_ONCE(suid_dumpable))) 2068 validate_coredump_safety(); 2069 return error; 2070 } 2071 2072 static const struct ctl_table fs_exec_sysctls[] = { 2073 { 2074 .procname = "suid_dumpable", 2075 .data = &suid_dumpable, 2076 .maxlen = sizeof(int), 2077 .mode = 0644, 2078 .proc_handler = proc_dointvec_minmax_coredump, 2079 .extra1 = SYSCTL_ZERO, 2080 .extra2 = SYSCTL_TWO, 2081 }, 2082 }; 2083 2084 static int __init init_fs_exec_sysctls(void) 2085 { 2086 register_sysctl_init("fs", fs_exec_sysctls); 2087 return 0; 2088 } 2089 2090 fs_initcall(init_fs_exec_sysctls); 2091 #endif /* CONFIG_SYSCTL */ 2092 2093 #ifdef CONFIG_EXEC_KUNIT_TEST 2094 #include "tests/exec_kunit.c" 2095 #endif 2096