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