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