• 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 	/*
1262 	 * Make this the only thread in the thread group.
1263 	 */
1264 	retval = de_thread(me);
1265 	if (retval)
1266 		goto out;
1267 
1268 	/*
1269 	 * Cancel any io_uring activity across execve
1270 	 */
1271 	io_uring_task_cancel();
1272 
1273 	/* Ensure the files table is not shared. */
1274 	retval = unshare_files();
1275 	if (retval)
1276 		goto out;
1277 
1278 	/*
1279 	 * Must be called _before_ exec_mmap() as bprm->mm is
1280 	 * not visible until then. Doing it here also ensures
1281 	 * we don't race against replace_mm_exe_file().
1282 	 */
1283 	retval = set_mm_exe_file(bprm->mm, bprm->file);
1284 	if (retval)
1285 		goto out;
1286 
1287 	/* If the binary is not readable then enforce mm->dumpable=0 */
1288 	would_dump(bprm, bprm->file);
1289 	if (bprm->have_execfd)
1290 		would_dump(bprm, bprm->executable);
1291 
1292 	/*
1293 	 * Release all of the old mmap stuff
1294 	 */
1295 	acct_arg_size(bprm, 0);
1296 	retval = exec_mmap(bprm->mm);
1297 	if (retval)
1298 		goto out;
1299 
1300 	bprm->mm = NULL;
1301 
1302 	retval = exec_task_namespaces();
1303 	if (retval)
1304 		goto out_unlock;
1305 
1306 #ifdef CONFIG_POSIX_TIMERS
1307 	spin_lock_irq(&me->sighand->siglock);
1308 	posix_cpu_timers_exit(me);
1309 	spin_unlock_irq(&me->sighand->siglock);
1310 	exit_itimers(me);
1311 	flush_itimer_signals();
1312 #endif
1313 
1314 	/*
1315 	 * Make the signal table private.
1316 	 */
1317 	retval = unshare_sighand(me);
1318 	if (retval)
1319 		goto out_unlock;
1320 
1321 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
1322 					PF_NOFREEZE | PF_NO_SETAFFINITY);
1323 	flush_thread();
1324 	me->personality &= ~bprm->per_clear;
1325 
1326 	clear_syscall_work_syscall_user_dispatch(me);
1327 
1328 	/*
1329 	 * We have to apply CLOEXEC before we change whether the process is
1330 	 * dumpable (in setup_new_exec) to avoid a race with a process in userspace
1331 	 * trying to access the should-be-closed file descriptors of a process
1332 	 * undergoing exec(2).
1333 	 */
1334 	do_close_on_exec(me->files);
1335 
1336 	if (bprm->secureexec) {
1337 		/* Make sure parent cannot signal privileged process. */
1338 		me->pdeath_signal = 0;
1339 
1340 		/*
1341 		 * For secureexec, reset the stack limit to sane default to
1342 		 * avoid bad behavior from the prior rlimits. This has to
1343 		 * happen before arch_pick_mmap_layout(), which examines
1344 		 * RLIMIT_STACK, but after the point of no return to avoid
1345 		 * needing to clean up the change on failure.
1346 		 */
1347 		if (bprm->rlim_stack.rlim_cur > _STK_LIM)
1348 			bprm->rlim_stack.rlim_cur = _STK_LIM;
1349 	}
1350 
1351 	me->sas_ss_sp = me->sas_ss_size = 0;
1352 
1353 	/*
1354 	 * Figure out dumpability. Note that this checking only of current
1355 	 * is wrong, but userspace depends on it. This should be testing
1356 	 * bprm->secureexec instead.
1357 	 */
1358 	if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP ||
1359 	    !(uid_eq(current_euid(), current_uid()) &&
1360 	      gid_eq(current_egid(), current_gid())))
1361 		set_dumpable(current->mm, suid_dumpable);
1362 	else
1363 		set_dumpable(current->mm, SUID_DUMP_USER);
1364 
1365 	perf_event_exec();
1366 
1367 	/*
1368 	 * If the original filename was empty, alloc_bprm() made up a path
1369 	 * that will probably not be useful to admins running ps or similar.
1370 	 * Let's fix it up to be something reasonable.
1371 	 */
1372 	if (bprm->comm_from_dentry) {
1373 		/*
1374 		 * Hold RCU lock to keep the name from being freed behind our back.
1375 		 * Use acquire semantics to make sure the terminating NUL from
1376 		 * __d_alloc() is seen.
1377 		 *
1378 		 * Note, we're deliberately sloppy here. We don't need to care about
1379 		 * detecting a concurrent rename and just want a terminated name.
1380 		 */
1381 		rcu_read_lock();
1382 		__set_task_comm(me, smp_load_acquire(&bprm->file->f_path.dentry->d_name.name),
1383 				true);
1384 		rcu_read_unlock();
1385 	} else {
1386 		__set_task_comm(me, kbasename(bprm->filename), true);
1387 	}
1388 
1389 	/* An exec changes our domain. We are no longer part of the thread
1390 	   group */
1391 	WRITE_ONCE(me->self_exec_id, me->self_exec_id + 1);
1392 	flush_signal_handlers(me, 0);
1393 
1394 	retval = set_cred_ucounts(bprm->cred);
1395 	if (retval < 0)
1396 		goto out_unlock;
1397 
1398 	/*
1399 	 * install the new credentials for this executable
1400 	 */
1401 	security_bprm_committing_creds(bprm);
1402 
1403 	commit_creds(bprm->cred);
1404 	bprm->cred = NULL;
1405 
1406 	/*
1407 	 * Disable monitoring for regular users
1408 	 * when executing setuid binaries. Must
1409 	 * wait until new credentials are committed
1410 	 * by commit_creds() above
1411 	 */
1412 	if (get_dumpable(me->mm) != SUID_DUMP_USER)
1413 		perf_event_exit_task(me);
1414 	/*
1415 	 * cred_guard_mutex must be held at least to this point to prevent
1416 	 * ptrace_attach() from altering our determination of the task's
1417 	 * credentials; any time after this it may be unlocked.
1418 	 */
1419 	security_bprm_committed_creds(bprm);
1420 
1421 	/* Pass the opened binary to the interpreter. */
1422 	if (bprm->have_execfd) {
1423 		retval = get_unused_fd_flags(0);
1424 		if (retval < 0)
1425 			goto out_unlock;
1426 		fd_install(retval, bprm->executable);
1427 		bprm->executable = NULL;
1428 		bprm->execfd = retval;
1429 	}
1430 	return 0;
1431 
1432 out_unlock:
1433 	up_write(&me->signal->exec_update_lock);
1434 	if (!bprm->cred)
1435 		mutex_unlock(&me->signal->cred_guard_mutex);
1436 
1437 out:
1438 	return retval;
1439 }
1440 EXPORT_SYMBOL(begin_new_exec);
1441 
would_dump(struct linux_binprm * bprm,struct file * file)1442 void would_dump(struct linux_binprm *bprm, struct file *file)
1443 {
1444 	struct inode *inode = file_inode(file);
1445 	struct mnt_idmap *idmap = file_mnt_idmap(file);
1446 	if (inode_permission(idmap, inode, MAY_READ) < 0) {
1447 		struct user_namespace *old, *user_ns;
1448 		bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP;
1449 
1450 		/* Ensure mm->user_ns contains the executable */
1451 		user_ns = old = bprm->mm->user_ns;
1452 		while ((user_ns != &init_user_ns) &&
1453 		       !privileged_wrt_inode_uidgid(user_ns, idmap, inode))
1454 			user_ns = user_ns->parent;
1455 
1456 		if (old != user_ns) {
1457 			bprm->mm->user_ns = get_user_ns(user_ns);
1458 			put_user_ns(old);
1459 		}
1460 	}
1461 }
1462 EXPORT_SYMBOL(would_dump);
1463 
setup_new_exec(struct linux_binprm * bprm)1464 void setup_new_exec(struct linux_binprm * bprm)
1465 {
1466 	/* Setup things that can depend upon the personality */
1467 	struct task_struct *me = current;
1468 
1469 	arch_pick_mmap_layout(me->mm, &bprm->rlim_stack);
1470 
1471 	arch_setup_new_exec();
1472 
1473 	/* Set the new mm task size. We have to do that late because it may
1474 	 * depend on TIF_32BIT which is only updated in flush_thread() on
1475 	 * some architectures like powerpc
1476 	 */
1477 	me->mm->task_size = TASK_SIZE;
1478 	up_write(&me->signal->exec_update_lock);
1479 	mutex_unlock(&me->signal->cred_guard_mutex);
1480 }
1481 EXPORT_SYMBOL(setup_new_exec);
1482 
1483 /* Runs immediately before start_thread() takes over. */
finalize_exec(struct linux_binprm * bprm)1484 void finalize_exec(struct linux_binprm *bprm)
1485 {
1486 	/* Store any stack rlimit changes before starting thread. */
1487 	task_lock(current->group_leader);
1488 	current->signal->rlim[RLIMIT_STACK] = bprm->rlim_stack;
1489 	task_unlock(current->group_leader);
1490 }
1491 EXPORT_SYMBOL(finalize_exec);
1492 
1493 /*
1494  * Prepare credentials and lock ->cred_guard_mutex.
1495  * setup_new_exec() commits the new creds and drops the lock.
1496  * Or, if exec fails before, free_bprm() should release ->cred
1497  * and unlock.
1498  */
prepare_bprm_creds(struct linux_binprm * bprm)1499 static int prepare_bprm_creds(struct linux_binprm *bprm)
1500 {
1501 	if (mutex_lock_interruptible(&current->signal->cred_guard_mutex))
1502 		return -ERESTARTNOINTR;
1503 
1504 	bprm->cred = prepare_exec_creds();
1505 	if (likely(bprm->cred))
1506 		return 0;
1507 
1508 	mutex_unlock(&current->signal->cred_guard_mutex);
1509 	return -ENOMEM;
1510 }
1511 
free_bprm(struct linux_binprm * bprm)1512 static void free_bprm(struct linux_binprm *bprm)
1513 {
1514 	if (bprm->mm) {
1515 		acct_arg_size(bprm, 0);
1516 		mmput(bprm->mm);
1517 	}
1518 	free_arg_pages(bprm);
1519 	if (bprm->cred) {
1520 		mutex_unlock(&current->signal->cred_guard_mutex);
1521 		abort_creds(bprm->cred);
1522 	}
1523 	if (bprm->file) {
1524 		allow_write_access(bprm->file);
1525 		fput(bprm->file);
1526 	}
1527 	if (bprm->executable)
1528 		fput(bprm->executable);
1529 	/* If a binfmt changed the interp, free it. */
1530 	if (bprm->interp != bprm->filename)
1531 		kfree(bprm->interp);
1532 	kfree(bprm->fdpath);
1533 	kfree(bprm);
1534 }
1535 
alloc_bprm(int fd,struct filename * filename)1536 static struct linux_binprm *alloc_bprm(int fd, struct filename *filename)
1537 {
1538 	struct linux_binprm *bprm = kzalloc(sizeof(*bprm), GFP_KERNEL);
1539 	int retval = -ENOMEM;
1540 	if (!bprm)
1541 		goto out;
1542 
1543 	if (fd == AT_FDCWD || filename->name[0] == '/') {
1544 		bprm->filename = filename->name;
1545 	} else {
1546 		if (filename->name[0] == '\0') {
1547 			bprm->fdpath = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd);
1548 			bprm->comm_from_dentry = 1;
1549 		} else {
1550 			bprm->fdpath = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s",
1551 						  fd, filename->name);
1552 		}
1553 		if (!bprm->fdpath)
1554 			goto out_free;
1555 
1556 		bprm->filename = bprm->fdpath;
1557 	}
1558 	bprm->interp = bprm->filename;
1559 
1560 	retval = bprm_mm_init(bprm);
1561 	if (retval)
1562 		goto out_free;
1563 	return bprm;
1564 
1565 out_free:
1566 	free_bprm(bprm);
1567 out:
1568 	return ERR_PTR(retval);
1569 }
1570 
bprm_change_interp(const char * interp,struct linux_binprm * bprm)1571 int bprm_change_interp(const char *interp, struct linux_binprm *bprm)
1572 {
1573 	/* If a binfmt changed the interp, free it first. */
1574 	if (bprm->interp != bprm->filename)
1575 		kfree(bprm->interp);
1576 	bprm->interp = kstrdup(interp, GFP_KERNEL);
1577 	if (!bprm->interp)
1578 		return -ENOMEM;
1579 	return 0;
1580 }
1581 EXPORT_SYMBOL(bprm_change_interp);
1582 
1583 /*
1584  * determine how safe it is to execute the proposed program
1585  * - the caller must hold ->cred_guard_mutex to protect against
1586  *   PTRACE_ATTACH or seccomp thread-sync
1587  */
check_unsafe_exec(struct linux_binprm * bprm)1588 static void check_unsafe_exec(struct linux_binprm *bprm)
1589 {
1590 	struct task_struct *p = current, *t;
1591 	unsigned n_fs;
1592 
1593 	if (p->ptrace)
1594 		bprm->unsafe |= LSM_UNSAFE_PTRACE;
1595 
1596 	/*
1597 	 * This isn't strictly necessary, but it makes it harder for LSMs to
1598 	 * mess up.
1599 	 */
1600 	if (task_no_new_privs(current))
1601 		bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS;
1602 
1603 	/*
1604 	 * If another task is sharing our fs, we cannot safely
1605 	 * suid exec because the differently privileged task
1606 	 * will be able to manipulate the current directory, etc.
1607 	 * It would be nice to force an unshare instead...
1608 	 */
1609 	t = p;
1610 	n_fs = 1;
1611 	spin_lock(&p->fs->lock);
1612 	rcu_read_lock();
1613 	while_each_thread(p, t) {
1614 		if (t->fs == p->fs)
1615 			n_fs++;
1616 	}
1617 	rcu_read_unlock();
1618 
1619 	if (p->fs->users > n_fs)
1620 		bprm->unsafe |= LSM_UNSAFE_SHARE;
1621 	else
1622 		p->fs->in_exec = 1;
1623 	spin_unlock(&p->fs->lock);
1624 }
1625 
bprm_fill_uid(struct linux_binprm * bprm,struct file * file)1626 static void bprm_fill_uid(struct linux_binprm *bprm, struct file *file)
1627 {
1628 	/* Handle suid and sgid on files */
1629 	struct mnt_idmap *idmap;
1630 	struct inode *inode = file_inode(file);
1631 	unsigned int mode;
1632 	vfsuid_t vfsuid;
1633 	vfsgid_t vfsgid;
1634 	int err;
1635 
1636 	if (!mnt_may_suid(file->f_path.mnt))
1637 		return;
1638 
1639 	if (task_no_new_privs(current))
1640 		return;
1641 
1642 	mode = READ_ONCE(inode->i_mode);
1643 	if (!(mode & (S_ISUID|S_ISGID)))
1644 		return;
1645 
1646 	idmap = file_mnt_idmap(file);
1647 
1648 	/* Be careful if suid/sgid is set */
1649 	inode_lock(inode);
1650 
1651 	/* Atomically reload and check mode/uid/gid now that lock held. */
1652 	mode = inode->i_mode;
1653 	vfsuid = i_uid_into_vfsuid(idmap, inode);
1654 	vfsgid = i_gid_into_vfsgid(idmap, inode);
1655 	err = inode_permission(idmap, inode, MAY_EXEC);
1656 	inode_unlock(inode);
1657 
1658 	/* Did the exec bit vanish out from under us? Give up. */
1659 	if (err)
1660 		return;
1661 
1662 	/* We ignore suid/sgid if there are no mappings for them in the ns */
1663 	if (!vfsuid_has_mapping(bprm->cred->user_ns, vfsuid) ||
1664 	    !vfsgid_has_mapping(bprm->cred->user_ns, vfsgid))
1665 		return;
1666 
1667 	if (mode & S_ISUID) {
1668 		bprm->per_clear |= PER_CLEAR_ON_SETID;
1669 		bprm->cred->euid = vfsuid_into_kuid(vfsuid);
1670 	}
1671 
1672 	if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
1673 		bprm->per_clear |= PER_CLEAR_ON_SETID;
1674 		bprm->cred->egid = vfsgid_into_kgid(vfsgid);
1675 	}
1676 }
1677 
1678 /*
1679  * Compute brpm->cred based upon the final binary.
1680  */
bprm_creds_from_file(struct linux_binprm * bprm)1681 static int bprm_creds_from_file(struct linux_binprm *bprm)
1682 {
1683 	/* Compute creds based on which file? */
1684 	struct file *file = bprm->execfd_creds ? bprm->executable : bprm->file;
1685 
1686 	bprm_fill_uid(bprm, file);
1687 	return security_bprm_creds_from_file(bprm, file);
1688 }
1689 
1690 /*
1691  * Fill the binprm structure from the inode.
1692  * Read the first BINPRM_BUF_SIZE bytes
1693  *
1694  * This may be called multiple times for binary chains (scripts for example).
1695  */
prepare_binprm(struct linux_binprm * bprm)1696 static int prepare_binprm(struct linux_binprm *bprm)
1697 {
1698 	loff_t pos = 0;
1699 
1700 	memset(bprm->buf, 0, BINPRM_BUF_SIZE);
1701 	return kernel_read(bprm->file, bprm->buf, BINPRM_BUF_SIZE, &pos);
1702 }
1703 
1704 /*
1705  * Arguments are '\0' separated strings found at the location bprm->p
1706  * points to; chop off the first by relocating brpm->p to right after
1707  * the first '\0' encountered.
1708  */
remove_arg_zero(struct linux_binprm * bprm)1709 int remove_arg_zero(struct linux_binprm *bprm)
1710 {
1711 	int ret = 0;
1712 	unsigned long offset;
1713 	char *kaddr;
1714 	struct page *page;
1715 
1716 	if (!bprm->argc)
1717 		return 0;
1718 
1719 	do {
1720 		offset = bprm->p & ~PAGE_MASK;
1721 		page = get_arg_page(bprm, bprm->p, 0);
1722 		if (!page) {
1723 			ret = -EFAULT;
1724 			goto out;
1725 		}
1726 		kaddr = kmap_local_page(page);
1727 
1728 		for (; offset < PAGE_SIZE && kaddr[offset];
1729 				offset++, bprm->p++)
1730 			;
1731 
1732 		kunmap_local(kaddr);
1733 		put_arg_page(page);
1734 	} while (offset == PAGE_SIZE);
1735 
1736 	bprm->p++;
1737 	bprm->argc--;
1738 	ret = 0;
1739 
1740 out:
1741 	return ret;
1742 }
1743 EXPORT_SYMBOL(remove_arg_zero);
1744 
1745 #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e))
1746 /*
1747  * cycle the list of binary formats handler, until one recognizes the image
1748  */
search_binary_handler(struct linux_binprm * bprm)1749 static int search_binary_handler(struct linux_binprm *bprm)
1750 {
1751 	bool need_retry = IS_ENABLED(CONFIG_MODULES);
1752 	struct linux_binfmt *fmt;
1753 	int retval;
1754 
1755 	retval = prepare_binprm(bprm);
1756 	if (retval < 0)
1757 		return retval;
1758 
1759 	retval = security_bprm_check(bprm);
1760 	if (retval)
1761 		return retval;
1762 
1763 	retval = -ENOENT;
1764  retry:
1765 	read_lock(&binfmt_lock);
1766 	list_for_each_entry(fmt, &formats, lh) {
1767 		if (!try_module_get(fmt->module))
1768 			continue;
1769 		read_unlock(&binfmt_lock);
1770 
1771 		retval = fmt->load_binary(bprm);
1772 
1773 		read_lock(&binfmt_lock);
1774 		put_binfmt(fmt);
1775 		if (bprm->point_of_no_return || (retval != -ENOEXEC)) {
1776 			read_unlock(&binfmt_lock);
1777 			return retval;
1778 		}
1779 	}
1780 	read_unlock(&binfmt_lock);
1781 
1782 	if (need_retry) {
1783 		if (printable(bprm->buf[0]) && printable(bprm->buf[1]) &&
1784 		    printable(bprm->buf[2]) && printable(bprm->buf[3]))
1785 			return retval;
1786 		if (request_module("binfmt-%04x", *(ushort *)(bprm->buf + 2)) < 0)
1787 			return retval;
1788 		need_retry = false;
1789 		goto retry;
1790 	}
1791 
1792 	return retval;
1793 }
1794 
1795 /* binfmt handlers will call back into begin_new_exec() on success. */
exec_binprm(struct linux_binprm * bprm)1796 static int exec_binprm(struct linux_binprm *bprm)
1797 {
1798 	pid_t old_pid, old_vpid;
1799 	int ret, depth;
1800 
1801 	/* Need to fetch pid before load_binary changes it */
1802 	old_pid = current->pid;
1803 	rcu_read_lock();
1804 	old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent));
1805 	rcu_read_unlock();
1806 
1807 	/* This allows 4 levels of binfmt rewrites before failing hard. */
1808 	for (depth = 0;; depth++) {
1809 		struct file *exec;
1810 		if (depth > 5)
1811 			return -ELOOP;
1812 
1813 		ret = search_binary_handler(bprm);
1814 		if (ret < 0)
1815 			return ret;
1816 		if (!bprm->interpreter)
1817 			break;
1818 
1819 		exec = bprm->file;
1820 		bprm->file = bprm->interpreter;
1821 		bprm->interpreter = NULL;
1822 
1823 		allow_write_access(exec);
1824 		if (unlikely(bprm->have_execfd)) {
1825 			if (bprm->executable) {
1826 				fput(exec);
1827 				return -ENOEXEC;
1828 			}
1829 			bprm->executable = exec;
1830 		} else
1831 			fput(exec);
1832 	}
1833 
1834 	audit_bprm(bprm);
1835 	trace_sched_process_exec(current, old_pid, bprm);
1836 	ptrace_event(PTRACE_EVENT_EXEC, old_vpid);
1837 	proc_exec_connector(current);
1838 	return 0;
1839 }
1840 
1841 /*
1842  * sys_execve() executes a new program.
1843  */
bprm_execve(struct linux_binprm * bprm,int fd,struct filename * filename,int flags)1844 static int bprm_execve(struct linux_binprm *bprm,
1845 		       int fd, struct filename *filename, int flags)
1846 {
1847 	struct file *file;
1848 	int retval;
1849 
1850 	retval = prepare_bprm_creds(bprm);
1851 	if (retval)
1852 		return retval;
1853 
1854 	/*
1855 	 * Check for unsafe execution states before exec_binprm(), which
1856 	 * will call back into begin_new_exec(), into bprm_creds_from_file(),
1857 	 * where setuid-ness is evaluated.
1858 	 */
1859 	check_unsafe_exec(bprm);
1860 	current->in_execve = 1;
1861 	sched_mm_cid_before_execve(current);
1862 
1863 	file = do_open_execat(fd, filename, flags);
1864 	retval = PTR_ERR(file);
1865 	if (IS_ERR(file))
1866 		goto out_unmark;
1867 
1868 	sched_exec();
1869 
1870 	bprm->file = file;
1871 	/*
1872 	 * Record that a name derived from an O_CLOEXEC fd will be
1873 	 * inaccessible after exec.  This allows the code in exec to
1874 	 * choose to fail when the executable is not mmaped into the
1875 	 * interpreter and an open file descriptor is not passed to
1876 	 * the interpreter.  This makes for a better user experience
1877 	 * than having the interpreter start and then immediately fail
1878 	 * when it finds the executable is inaccessible.
1879 	 */
1880 	if (bprm->fdpath && get_close_on_exec(fd))
1881 		bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE;
1882 
1883 	/* Set the unchanging part of bprm->cred */
1884 	retval = security_bprm_creds_for_exec(bprm);
1885 	if (retval)
1886 		goto out;
1887 
1888 	retval = exec_binprm(bprm);
1889 	if (retval < 0)
1890 		goto out;
1891 
1892 	sched_mm_cid_after_execve(current);
1893 	/* execve succeeded */
1894 	current->fs->in_exec = 0;
1895 	current->in_execve = 0;
1896 	rseq_execve(current);
1897 	user_events_execve(current);
1898 	acct_update_integrals(current);
1899 	task_numa_free(current, false);
1900 	CALL_HCK_LITE_HOOK(ced_detection_lhck, current);
1901 	return retval;
1902 
1903 out:
1904 	/*
1905 	 * If past the point of no return ensure the code never
1906 	 * returns to the userspace process.  Use an existing fatal
1907 	 * signal if present otherwise terminate the process with
1908 	 * SIGSEGV.
1909 	 */
1910 	if (bprm->point_of_no_return && !fatal_signal_pending(current))
1911 		force_fatal_sig(SIGSEGV);
1912 
1913 out_unmark:
1914 	sched_mm_cid_after_execve(current);
1915 	current->fs->in_exec = 0;
1916 	current->in_execve = 0;
1917 
1918 	return retval;
1919 }
1920 
do_execveat_common(int fd,struct filename * filename,struct user_arg_ptr argv,struct user_arg_ptr envp,int flags)1921 static int do_execveat_common(int fd, struct filename *filename,
1922 			      struct user_arg_ptr argv,
1923 			      struct user_arg_ptr envp,
1924 			      int flags)
1925 {
1926 	struct linux_binprm *bprm;
1927 	int retval;
1928 
1929 	if (IS_ERR(filename))
1930 		return PTR_ERR(filename);
1931 
1932 	/*
1933 	 * We move the actual failure in case of RLIMIT_NPROC excess from
1934 	 * set*uid() to execve() because too many poorly written programs
1935 	 * don't check setuid() return code.  Here we additionally recheck
1936 	 * whether NPROC limit is still exceeded.
1937 	 */
1938 	if ((current->flags & PF_NPROC_EXCEEDED) &&
1939 	    is_rlimit_overlimit(current_ucounts(), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
1940 		retval = -EAGAIN;
1941 		goto out_ret;
1942 	}
1943 
1944 	/* We're below the limit (still or again), so we don't want to make
1945 	 * further execve() calls fail. */
1946 	current->flags &= ~PF_NPROC_EXCEEDED;
1947 
1948 	bprm = alloc_bprm(fd, filename);
1949 	if (IS_ERR(bprm)) {
1950 		retval = PTR_ERR(bprm);
1951 		goto out_ret;
1952 	}
1953 
1954 	retval = count(argv, MAX_ARG_STRINGS);
1955 	if (retval == 0)
1956 		pr_warn_once("process '%s' launched '%s' with NULL argv: empty string added\n",
1957 			     current->comm, bprm->filename);
1958 	if (retval < 0)
1959 		goto out_free;
1960 	bprm->argc = retval;
1961 
1962 	retval = count(envp, MAX_ARG_STRINGS);
1963 	if (retval < 0)
1964 		goto out_free;
1965 	bprm->envc = retval;
1966 
1967 	retval = bprm_stack_limits(bprm);
1968 	if (retval < 0)
1969 		goto out_free;
1970 
1971 	retval = copy_string_kernel(bprm->filename, bprm);
1972 	if (retval < 0)
1973 		goto out_free;
1974 	bprm->exec = bprm->p;
1975 
1976 	retval = copy_strings(bprm->envc, envp, bprm);
1977 	if (retval < 0)
1978 		goto out_free;
1979 
1980 	retval = copy_strings(bprm->argc, argv, bprm);
1981 	if (retval < 0)
1982 		goto out_free;
1983 
1984 	/*
1985 	 * When argv is empty, add an empty string ("") as argv[0] to
1986 	 * ensure confused userspace programs that start processing
1987 	 * from argv[1] won't end up walking envp. See also
1988 	 * bprm_stack_limits().
1989 	 */
1990 	if (bprm->argc == 0) {
1991 		retval = copy_string_kernel("", bprm);
1992 		if (retval < 0)
1993 			goto out_free;
1994 		bprm->argc = 1;
1995 	}
1996 
1997 	retval = bprm_execve(bprm, fd, filename, flags);
1998 out_free:
1999 	free_bprm(bprm);
2000 
2001 out_ret:
2002 	putname(filename);
2003 	return retval;
2004 }
2005 
kernel_execve(const char * kernel_filename,const char * const * argv,const char * const * envp)2006 int kernel_execve(const char *kernel_filename,
2007 		  const char *const *argv, const char *const *envp)
2008 {
2009 	struct filename *filename;
2010 	struct linux_binprm *bprm;
2011 	int fd = AT_FDCWD;
2012 	int retval;
2013 
2014 	/* It is non-sense for kernel threads to call execve */
2015 	if (WARN_ON_ONCE(current->flags & PF_KTHREAD))
2016 		return -EINVAL;
2017 
2018 	filename = getname_kernel(kernel_filename);
2019 	if (IS_ERR(filename))
2020 		return PTR_ERR(filename);
2021 
2022 	bprm = alloc_bprm(fd, filename);
2023 	if (IS_ERR(bprm)) {
2024 		retval = PTR_ERR(bprm);
2025 		goto out_ret;
2026 	}
2027 
2028 	retval = count_strings_kernel(argv);
2029 	if (WARN_ON_ONCE(retval == 0))
2030 		retval = -EINVAL;
2031 	if (retval < 0)
2032 		goto out_free;
2033 	bprm->argc = retval;
2034 
2035 	retval = count_strings_kernel(envp);
2036 	if (retval < 0)
2037 		goto out_free;
2038 	bprm->envc = retval;
2039 
2040 	retval = bprm_stack_limits(bprm);
2041 	if (retval < 0)
2042 		goto out_free;
2043 
2044 	retval = copy_string_kernel(bprm->filename, bprm);
2045 	if (retval < 0)
2046 		goto out_free;
2047 	bprm->exec = bprm->p;
2048 
2049 	retval = copy_strings_kernel(bprm->envc, envp, bprm);
2050 	if (retval < 0)
2051 		goto out_free;
2052 
2053 	retval = copy_strings_kernel(bprm->argc, argv, bprm);
2054 	if (retval < 0)
2055 		goto out_free;
2056 
2057 	retval = bprm_execve(bprm, fd, filename, 0);
2058 out_free:
2059 	free_bprm(bprm);
2060 out_ret:
2061 	putname(filename);
2062 	return retval;
2063 }
2064 
do_execve(struct filename * filename,const char __user * const __user * __argv,const char __user * const __user * __envp)2065 static int do_execve(struct filename *filename,
2066 	const char __user *const __user *__argv,
2067 	const char __user *const __user *__envp)
2068 {
2069 	struct user_arg_ptr argv = { .ptr.native = __argv };
2070 	struct user_arg_ptr envp = { .ptr.native = __envp };
2071 	return do_execveat_common(AT_FDCWD, filename, argv, envp, 0);
2072 }
2073 
do_execveat(int fd,struct filename * filename,const char __user * const __user * __argv,const char __user * const __user * __envp,int flags)2074 static int do_execveat(int fd, struct filename *filename,
2075 		const char __user *const __user *__argv,
2076 		const char __user *const __user *__envp,
2077 		int flags)
2078 {
2079 	struct user_arg_ptr argv = { .ptr.native = __argv };
2080 	struct user_arg_ptr envp = { .ptr.native = __envp };
2081 
2082 	return do_execveat_common(fd, filename, argv, envp, flags);
2083 }
2084 
2085 #ifdef CONFIG_COMPAT
compat_do_execve(struct filename * filename,const compat_uptr_t __user * __argv,const compat_uptr_t __user * __envp)2086 static int compat_do_execve(struct filename *filename,
2087 	const compat_uptr_t __user *__argv,
2088 	const compat_uptr_t __user *__envp)
2089 {
2090 	struct user_arg_ptr argv = {
2091 		.is_compat = true,
2092 		.ptr.compat = __argv,
2093 	};
2094 	struct user_arg_ptr envp = {
2095 		.is_compat = true,
2096 		.ptr.compat = __envp,
2097 	};
2098 	return do_execveat_common(AT_FDCWD, filename, argv, envp, 0);
2099 }
2100 
compat_do_execveat(int fd,struct filename * filename,const compat_uptr_t __user * __argv,const compat_uptr_t __user * __envp,int flags)2101 static int compat_do_execveat(int fd, struct filename *filename,
2102 			      const compat_uptr_t __user *__argv,
2103 			      const compat_uptr_t __user *__envp,
2104 			      int flags)
2105 {
2106 	struct user_arg_ptr argv = {
2107 		.is_compat = true,
2108 		.ptr.compat = __argv,
2109 	};
2110 	struct user_arg_ptr envp = {
2111 		.is_compat = true,
2112 		.ptr.compat = __envp,
2113 	};
2114 	return do_execveat_common(fd, filename, argv, envp, flags);
2115 }
2116 #endif
2117 
set_binfmt(struct linux_binfmt * new)2118 void set_binfmt(struct linux_binfmt *new)
2119 {
2120 	struct mm_struct *mm = current->mm;
2121 
2122 	if (mm->binfmt)
2123 		module_put(mm->binfmt->module);
2124 
2125 	mm->binfmt = new;
2126 	if (new)
2127 		__module_get(new->module);
2128 }
2129 EXPORT_SYMBOL(set_binfmt);
2130 
2131 /*
2132  * set_dumpable stores three-value SUID_DUMP_* into mm->flags.
2133  */
set_dumpable(struct mm_struct * mm,int value)2134 void set_dumpable(struct mm_struct *mm, int value)
2135 {
2136 	if (WARN_ON((unsigned)value > SUID_DUMP_ROOT))
2137 		return;
2138 
2139 	set_mask_bits(&mm->flags, MMF_DUMPABLE_MASK, value);
2140 }
2141 
SYSCALL_DEFINE3(execve,const char __user *,filename,const char __user * const __user *,argv,const char __user * const __user *,envp)2142 SYSCALL_DEFINE3(execve,
2143 		const char __user *, filename,
2144 		const char __user *const __user *, argv,
2145 		const char __user *const __user *, envp)
2146 {
2147 	return do_execve(getname(filename), argv, envp);
2148 }
2149 
SYSCALL_DEFINE5(execveat,int,fd,const char __user *,filename,const char __user * const __user *,argv,const char __user * const __user *,envp,int,flags)2150 SYSCALL_DEFINE5(execveat,
2151 		int, fd, const char __user *, filename,
2152 		const char __user *const __user *, argv,
2153 		const char __user *const __user *, envp,
2154 		int, flags)
2155 {
2156 	return do_execveat(fd,
2157 			   getname_uflags(filename, flags),
2158 			   argv, envp, flags);
2159 }
2160 
2161 #ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE3(execve,const char __user *,filename,const compat_uptr_t __user *,argv,const compat_uptr_t __user *,envp)2162 COMPAT_SYSCALL_DEFINE3(execve, const char __user *, filename,
2163 	const compat_uptr_t __user *, argv,
2164 	const compat_uptr_t __user *, envp)
2165 {
2166 	return compat_do_execve(getname(filename), argv, envp);
2167 }
2168 
COMPAT_SYSCALL_DEFINE5(execveat,int,fd,const char __user *,filename,const compat_uptr_t __user *,argv,const compat_uptr_t __user *,envp,int,flags)2169 COMPAT_SYSCALL_DEFINE5(execveat, int, fd,
2170 		       const char __user *, filename,
2171 		       const compat_uptr_t __user *, argv,
2172 		       const compat_uptr_t __user *, envp,
2173 		       int,  flags)
2174 {
2175 	return compat_do_execveat(fd,
2176 				  getname_uflags(filename, flags),
2177 				  argv, envp, flags);
2178 }
2179 #endif
2180 
2181 #ifdef CONFIG_SYSCTL
2182 
proc_dointvec_minmax_coredump(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)2183 static int proc_dointvec_minmax_coredump(struct ctl_table *table, int write,
2184 		void *buffer, size_t *lenp, loff_t *ppos)
2185 {
2186 	int error = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
2187 
2188 	if (!error)
2189 		validate_coredump_safety();
2190 	return error;
2191 }
2192 
2193 static struct ctl_table fs_exec_sysctls[] = {
2194 	{
2195 		.procname	= "suid_dumpable",
2196 		.data		= &suid_dumpable,
2197 		.maxlen		= sizeof(int),
2198 		.mode		= 0644,
2199 		.proc_handler	= proc_dointvec_minmax_coredump,
2200 		.extra1		= SYSCTL_ZERO,
2201 		.extra2		= SYSCTL_TWO,
2202 	},
2203 	{ }
2204 };
2205 
init_fs_exec_sysctls(void)2206 static int __init init_fs_exec_sysctls(void)
2207 {
2208 	register_sysctl_init("fs", fs_exec_sysctls);
2209 	return 0;
2210 }
2211 
2212 fs_initcall(init_fs_exec_sysctls);
2213 #endif /* CONFIG_SYSCTL */
2214