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