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