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