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