xref: /linux/fs/coredump.c (revision 570172569238c66a482ec3eb5d766cc9cf255f69)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/slab.h>
3 #include <linux/file.h>
4 #include <linux/fdtable.h>
5 #include <linux/freezer.h>
6 #include <linux/mm.h>
7 #include <linux/stat.h>
8 #include <linux/fcntl.h>
9 #include <linux/swap.h>
10 #include <linux/ctype.h>
11 #include <linux/string.h>
12 #include <linux/init.h>
13 #include <linux/pagemap.h>
14 #include <linux/perf_event.h>
15 #include <linux/highmem.h>
16 #include <linux/spinlock.h>
17 #include <linux/key.h>
18 #include <linux/personality.h>
19 #include <linux/binfmts.h>
20 #include <linux/coredump.h>
21 #include <linux/sort.h>
22 #include <linux/sched/coredump.h>
23 #include <linux/sched/signal.h>
24 #include <linux/sched/task_stack.h>
25 #include <linux/utsname.h>
26 #include <linux/pid_namespace.h>
27 #include <linux/module.h>
28 #include <linux/namei.h>
29 #include <linux/mount.h>
30 #include <linux/security.h>
31 #include <linux/syscalls.h>
32 #include <linux/tsacct_kern.h>
33 #include <linux/cn_proc.h>
34 #include <linux/audit.h>
35 #include <linux/kmod.h>
36 #include <linux/fsnotify.h>
37 #include <linux/fs_struct.h>
38 #include <linux/pipe_fs_i.h>
39 #include <linux/oom.h>
40 #include <linux/compat.h>
41 #include <linux/fs.h>
42 #include <linux/path.h>
43 #include <linux/timekeeping.h>
44 #include <linux/sysctl.h>
45 #include <linux/elf.h>
46 
47 #include <linux/uaccess.h>
48 #include <asm/mmu_context.h>
49 #include <asm/tlb.h>
50 #include <asm/exec.h>
51 
52 #include <trace/events/task.h>
53 #include "internal.h"
54 
55 #include <trace/events/sched.h>
56 
57 static bool dump_vma_snapshot(struct coredump_params *cprm);
58 static void free_vma_snapshot(struct coredump_params *cprm);
59 
60 #define CORE_FILE_NOTE_SIZE_DEFAULT (4*1024*1024)
61 /* Define a reasonable max cap */
62 #define CORE_FILE_NOTE_SIZE_MAX (16*1024*1024)
63 
64 static int core_uses_pid;
65 static unsigned int core_pipe_limit;
66 static char core_pattern[CORENAME_MAX_SIZE] = "core";
67 static int core_name_size = CORENAME_MAX_SIZE;
68 unsigned int core_file_note_size_limit = CORE_FILE_NOTE_SIZE_DEFAULT;
69 
70 struct core_name {
71 	char *corename;
72 	int used, size;
73 };
74 
75 static int expand_corename(struct core_name *cn, int size)
76 {
77 	char *corename;
78 
79 	size = kmalloc_size_roundup(size);
80 	corename = krealloc(cn->corename, size, GFP_KERNEL);
81 
82 	if (!corename)
83 		return -ENOMEM;
84 
85 	if (size > core_name_size) /* racy but harmless */
86 		core_name_size = size;
87 
88 	cn->size = size;
89 	cn->corename = corename;
90 	return 0;
91 }
92 
93 static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
94 				     va_list arg)
95 {
96 	int free, need;
97 	va_list arg_copy;
98 
99 again:
100 	free = cn->size - cn->used;
101 
102 	va_copy(arg_copy, arg);
103 	need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
104 	va_end(arg_copy);
105 
106 	if (need < free) {
107 		cn->used += need;
108 		return 0;
109 	}
110 
111 	if (!expand_corename(cn, cn->size + need - free + 1))
112 		goto again;
113 
114 	return -ENOMEM;
115 }
116 
117 static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
118 {
119 	va_list arg;
120 	int ret;
121 
122 	va_start(arg, fmt);
123 	ret = cn_vprintf(cn, fmt, arg);
124 	va_end(arg);
125 
126 	return ret;
127 }
128 
129 static __printf(2, 3)
130 int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
131 {
132 	int cur = cn->used;
133 	va_list arg;
134 	int ret;
135 
136 	va_start(arg, fmt);
137 	ret = cn_vprintf(cn, fmt, arg);
138 	va_end(arg);
139 
140 	if (ret == 0) {
141 		/*
142 		 * Ensure that this coredump name component can't cause the
143 		 * resulting corefile path to consist of a ".." or ".".
144 		 */
145 		if ((cn->used - cur == 1 && cn->corename[cur] == '.') ||
146 				(cn->used - cur == 2 && cn->corename[cur] == '.'
147 				&& cn->corename[cur+1] == '.'))
148 			cn->corename[cur] = '!';
149 
150 		/*
151 		 * Empty names are fishy and could be used to create a "//" in a
152 		 * corefile name, causing the coredump to happen one directory
153 		 * level too high. Enforce that all components of the core
154 		 * pattern are at least one character long.
155 		 */
156 		if (cn->used == cur)
157 			ret = cn_printf(cn, "!");
158 	}
159 
160 	for (; cur < cn->used; ++cur) {
161 		if (cn->corename[cur] == '/')
162 			cn->corename[cur] = '!';
163 	}
164 	return ret;
165 }
166 
167 static int cn_print_exe_file(struct core_name *cn, bool name_only)
168 {
169 	struct file *exe_file;
170 	char *pathbuf, *path, *ptr;
171 	int ret;
172 
173 	exe_file = get_mm_exe_file(current->mm);
174 	if (!exe_file)
175 		return cn_esc_printf(cn, "%s (path unknown)", current->comm);
176 
177 	pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
178 	if (!pathbuf) {
179 		ret = -ENOMEM;
180 		goto put_exe_file;
181 	}
182 
183 	path = file_path(exe_file, pathbuf, PATH_MAX);
184 	if (IS_ERR(path)) {
185 		ret = PTR_ERR(path);
186 		goto free_buf;
187 	}
188 
189 	if (name_only) {
190 		ptr = strrchr(path, '/');
191 		if (ptr)
192 			path = ptr + 1;
193 	}
194 	ret = cn_esc_printf(cn, "%s", path);
195 
196 free_buf:
197 	kfree(pathbuf);
198 put_exe_file:
199 	fput(exe_file);
200 	return ret;
201 }
202 
203 /* format_corename will inspect the pattern parameter, and output a
204  * name into corename, which must have space for at least
205  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
206  */
207 static int format_corename(struct core_name *cn, struct coredump_params *cprm,
208 			   size_t **argv, int *argc)
209 {
210 	const struct cred *cred = current_cred();
211 	const char *pat_ptr = core_pattern;
212 	int ispipe = (*pat_ptr == '|');
213 	bool was_space = false;
214 	int pid_in_pattern = 0;
215 	int err = 0;
216 
217 	cn->used = 0;
218 	cn->corename = NULL;
219 	if (expand_corename(cn, core_name_size))
220 		return -ENOMEM;
221 	cn->corename[0] = '\0';
222 
223 	if (ispipe) {
224 		int argvs = sizeof(core_pattern) / 2;
225 		(*argv) = kmalloc_array(argvs, sizeof(**argv), GFP_KERNEL);
226 		if (!(*argv))
227 			return -ENOMEM;
228 		(*argv)[(*argc)++] = 0;
229 		++pat_ptr;
230 		if (!(*pat_ptr))
231 			return -ENOMEM;
232 	}
233 
234 	/* Repeat as long as we have more pattern to process and more output
235 	   space */
236 	while (*pat_ptr) {
237 		/*
238 		 * Split on spaces before doing template expansion so that
239 		 * %e and %E don't get split if they have spaces in them
240 		 */
241 		if (ispipe) {
242 			if (isspace(*pat_ptr)) {
243 				if (cn->used != 0)
244 					was_space = true;
245 				pat_ptr++;
246 				continue;
247 			} else if (was_space) {
248 				was_space = false;
249 				err = cn_printf(cn, "%c", '\0');
250 				if (err)
251 					return err;
252 				(*argv)[(*argc)++] = cn->used;
253 			}
254 		}
255 		if (*pat_ptr != '%') {
256 			err = cn_printf(cn, "%c", *pat_ptr++);
257 		} else {
258 			switch (*++pat_ptr) {
259 			/* single % at the end, drop that */
260 			case 0:
261 				goto out;
262 			/* Double percent, output one percent */
263 			case '%':
264 				err = cn_printf(cn, "%c", '%');
265 				break;
266 			/* pid */
267 			case 'p':
268 				pid_in_pattern = 1;
269 				err = cn_printf(cn, "%d",
270 					      task_tgid_vnr(current));
271 				break;
272 			/* global pid */
273 			case 'P':
274 				err = cn_printf(cn, "%d",
275 					      task_tgid_nr(current));
276 				break;
277 			case 'i':
278 				err = cn_printf(cn, "%d",
279 					      task_pid_vnr(current));
280 				break;
281 			case 'I':
282 				err = cn_printf(cn, "%d",
283 					      task_pid_nr(current));
284 				break;
285 			/* uid */
286 			case 'u':
287 				err = cn_printf(cn, "%u",
288 						from_kuid(&init_user_ns,
289 							  cred->uid));
290 				break;
291 			/* gid */
292 			case 'g':
293 				err = cn_printf(cn, "%u",
294 						from_kgid(&init_user_ns,
295 							  cred->gid));
296 				break;
297 			case 'd':
298 				err = cn_printf(cn, "%d",
299 					__get_dumpable(cprm->mm_flags));
300 				break;
301 			/* signal that caused the coredump */
302 			case 's':
303 				err = cn_printf(cn, "%d",
304 						cprm->siginfo->si_signo);
305 				break;
306 			/* UNIX time of coredump */
307 			case 't': {
308 				time64_t time;
309 
310 				time = ktime_get_real_seconds();
311 				err = cn_printf(cn, "%lld", time);
312 				break;
313 			}
314 			/* hostname */
315 			case 'h':
316 				down_read(&uts_sem);
317 				err = cn_esc_printf(cn, "%s",
318 					      utsname()->nodename);
319 				up_read(&uts_sem);
320 				break;
321 			/* executable, could be changed by prctl PR_SET_NAME etc */
322 			case 'e':
323 				err = cn_esc_printf(cn, "%s", current->comm);
324 				break;
325 			/* file name of executable */
326 			case 'f':
327 				err = cn_print_exe_file(cn, true);
328 				break;
329 			case 'E':
330 				err = cn_print_exe_file(cn, false);
331 				break;
332 			/* core limit size */
333 			case 'c':
334 				err = cn_printf(cn, "%lu",
335 					      rlimit(RLIMIT_CORE));
336 				break;
337 			/* CPU the task ran on */
338 			case 'C':
339 				err = cn_printf(cn, "%d", cprm->cpu);
340 				break;
341 			default:
342 				break;
343 			}
344 			++pat_ptr;
345 		}
346 
347 		if (err)
348 			return err;
349 	}
350 
351 out:
352 	/* Backward compatibility with core_uses_pid:
353 	 *
354 	 * If core_pattern does not include a %p (as is the default)
355 	 * and core_uses_pid is set, then .%pid will be appended to
356 	 * the filename. Do not do this for piped commands. */
357 	if (!ispipe && !pid_in_pattern && core_uses_pid) {
358 		err = cn_printf(cn, ".%d", task_tgid_vnr(current));
359 		if (err)
360 			return err;
361 	}
362 	return ispipe;
363 }
364 
365 static int zap_process(struct signal_struct *signal, int exit_code)
366 {
367 	struct task_struct *t;
368 	int nr = 0;
369 
370 	signal->flags = SIGNAL_GROUP_EXIT;
371 	signal->group_exit_code = exit_code;
372 	signal->group_stop_count = 0;
373 
374 	__for_each_thread(signal, t) {
375 		task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
376 		if (t != current && !(t->flags & PF_POSTCOREDUMP)) {
377 			sigaddset(&t->pending.signal, SIGKILL);
378 			signal_wake_up(t, 1);
379 			nr++;
380 		}
381 	}
382 
383 	return nr;
384 }
385 
386 static int zap_threads(struct task_struct *tsk,
387 			struct core_state *core_state, int exit_code)
388 {
389 	struct signal_struct *signal = tsk->signal;
390 	int nr = -EAGAIN;
391 
392 	spin_lock_irq(&tsk->sighand->siglock);
393 	if (!(signal->flags & SIGNAL_GROUP_EXIT) && !signal->group_exec_task) {
394 		/* Allow SIGKILL, see prepare_signal() */
395 		signal->core_state = core_state;
396 		nr = zap_process(signal, exit_code);
397 		clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
398 		tsk->flags |= PF_DUMPCORE;
399 		atomic_set(&core_state->nr_threads, nr);
400 	}
401 	spin_unlock_irq(&tsk->sighand->siglock);
402 	return nr;
403 }
404 
405 static int coredump_wait(int exit_code, struct core_state *core_state)
406 {
407 	struct task_struct *tsk = current;
408 	int core_waiters = -EBUSY;
409 
410 	init_completion(&core_state->startup);
411 	core_state->dumper.task = tsk;
412 	core_state->dumper.next = NULL;
413 
414 	core_waiters = zap_threads(tsk, core_state, exit_code);
415 	if (core_waiters > 0) {
416 		struct core_thread *ptr;
417 
418 		wait_for_completion_state(&core_state->startup,
419 					  TASK_UNINTERRUPTIBLE|TASK_FREEZABLE);
420 		/*
421 		 * Wait for all the threads to become inactive, so that
422 		 * all the thread context (extended register state, like
423 		 * fpu etc) gets copied to the memory.
424 		 */
425 		ptr = core_state->dumper.next;
426 		while (ptr != NULL) {
427 			wait_task_inactive(ptr->task, TASK_ANY);
428 			ptr = ptr->next;
429 		}
430 	}
431 
432 	return core_waiters;
433 }
434 
435 static void coredump_finish(bool core_dumped)
436 {
437 	struct core_thread *curr, *next;
438 	struct task_struct *task;
439 
440 	spin_lock_irq(&current->sighand->siglock);
441 	if (core_dumped && !__fatal_signal_pending(current))
442 		current->signal->group_exit_code |= 0x80;
443 	next = current->signal->core_state->dumper.next;
444 	current->signal->core_state = NULL;
445 	spin_unlock_irq(&current->sighand->siglock);
446 
447 	while ((curr = next) != NULL) {
448 		next = curr->next;
449 		task = curr->task;
450 		/*
451 		 * see coredump_task_exit(), curr->task must not see
452 		 * ->task == NULL before we read ->next.
453 		 */
454 		smp_mb();
455 		curr->task = NULL;
456 		wake_up_process(task);
457 	}
458 }
459 
460 static bool dump_interrupted(void)
461 {
462 	/*
463 	 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
464 	 * can do try_to_freeze() and check __fatal_signal_pending(),
465 	 * but then we need to teach dump_write() to restart and clear
466 	 * TIF_SIGPENDING.
467 	 */
468 	if (fatal_signal_pending(current)) {
469 		coredump_report_failure("interrupted: fatal signal pending");
470 		return true;
471 	}
472 
473 	if (freezing(current)) {
474 		coredump_report_failure("interrupted: freezing");
475 		return true;
476 	}
477 
478 	return false;
479 }
480 
481 static void wait_for_dump_helpers(struct file *file)
482 {
483 	struct pipe_inode_info *pipe = file->private_data;
484 
485 	pipe_lock(pipe);
486 	pipe->readers++;
487 	pipe->writers--;
488 	wake_up_interruptible_sync(&pipe->rd_wait);
489 	kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
490 	pipe_unlock(pipe);
491 
492 	/*
493 	 * We actually want wait_event_freezable() but then we need
494 	 * to clear TIF_SIGPENDING and improve dump_interrupted().
495 	 */
496 	wait_event_interruptible(pipe->rd_wait, pipe->readers == 1);
497 
498 	pipe_lock(pipe);
499 	pipe->readers--;
500 	pipe->writers++;
501 	pipe_unlock(pipe);
502 }
503 
504 /*
505  * umh_pipe_setup
506  * helper function to customize the process used
507  * to collect the core in userspace.  Specifically
508  * it sets up a pipe and installs it as fd 0 (stdin)
509  * for the process.  Returns 0 on success, or
510  * PTR_ERR on failure.
511  * Note that it also sets the core limit to 1.  This
512  * is a special value that we use to trap recursive
513  * core dumps
514  */
515 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
516 {
517 	struct file *files[2];
518 	struct coredump_params *cp = (struct coredump_params *)info->data;
519 	int err = create_pipe_files(files, 0);
520 	if (err)
521 		return err;
522 
523 	cp->file = files[1];
524 
525 	err = replace_fd(0, files[0], 0);
526 	fput(files[0]);
527 	/* and disallow core files too */
528 	current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
529 
530 	return err;
531 }
532 
533 int do_coredump(const kernel_siginfo_t *siginfo)
534 {
535 	struct core_state core_state;
536 	struct core_name cn;
537 	struct mm_struct *mm = current->mm;
538 	struct linux_binfmt * binfmt;
539 	const struct cred *old_cred;
540 	struct cred *cred;
541 	int retval;
542 	int ispipe;
543 	size_t *argv = NULL;
544 	int argc = 0;
545 	/* require nonrelative corefile path and be extra careful */
546 	bool need_suid_safe = false;
547 	bool core_dumped = false;
548 	static atomic_t core_dump_count = ATOMIC_INIT(0);
549 	struct coredump_params cprm = {
550 		.siginfo = siginfo,
551 		.limit = rlimit(RLIMIT_CORE),
552 		/*
553 		 * We must use the same mm->flags while dumping core to avoid
554 		 * inconsistency of bit flags, since this flag is not protected
555 		 * by any locks.
556 		 */
557 		.mm_flags = mm->flags,
558 		.vma_meta = NULL,
559 		.cpu = raw_smp_processor_id(),
560 	};
561 
562 	audit_core_dumps(siginfo->si_signo);
563 
564 	binfmt = mm->binfmt;
565 	if (!binfmt || !binfmt->core_dump) {
566 		retval = -ENOEXEC;
567 		goto fail;
568 	}
569 	if (!__get_dumpable(cprm.mm_flags)) {
570 		retval = -EACCES;
571 		goto fail;
572 	}
573 
574 	cred = prepare_creds();
575 	if (!cred) {
576 		retval = -EPERM;
577 		goto fail;
578 	}
579 	/*
580 	 * We cannot trust fsuid as being the "true" uid of the process
581 	 * nor do we know its entire history. We only know it was tainted
582 	 * so we dump it as root in mode 2, and only into a controlled
583 	 * environment (pipe handler or fully qualified path).
584 	 */
585 	if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
586 		/* Setuid core dump mode */
587 		cred->fsuid = GLOBAL_ROOT_UID;	/* Dump root private */
588 		need_suid_safe = true;
589 	}
590 
591 	retval = coredump_wait(siginfo->si_signo, &core_state);
592 	if (retval < 0)
593 		goto fail_creds;
594 
595 	old_cred = override_creds(cred);
596 
597 	ispipe = format_corename(&cn, &cprm, &argv, &argc);
598 
599 	if (ispipe) {
600 		int argi;
601 		int dump_count;
602 		char **helper_argv;
603 		struct subprocess_info *sub_info;
604 
605 		if (ispipe < 0) {
606 			coredump_report_failure("format_corename failed, aborting core");
607 			retval = ispipe;
608 			goto fail_unlock;
609 		}
610 
611 		if (cprm.limit == 1) {
612 			/* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
613 			 *
614 			 * Normally core limits are irrelevant to pipes, since
615 			 * we're not writing to the file system, but we use
616 			 * cprm.limit of 1 here as a special value, this is a
617 			 * consistent way to catch recursive crashes.
618 			 * We can still crash if the core_pattern binary sets
619 			 * RLIM_CORE = !1, but it runs as root, and can do
620 			 * lots of stupid things.
621 			 *
622 			 * Note that we use task_tgid_vnr here to grab the pid
623 			 * of the process group leader.  That way we get the
624 			 * right pid if a thread in a multi-threaded
625 			 * core_pattern process dies.
626 			 */
627 			coredump_report_failure("RLIMIT_CORE is set to 1, aborting core");
628 			retval = -EPERM;
629 			goto fail_unlock;
630 		}
631 		cprm.limit = RLIM_INFINITY;
632 
633 		dump_count = atomic_inc_return(&core_dump_count);
634 		if (core_pipe_limit && (core_pipe_limit < dump_count)) {
635 			coredump_report_failure("over core_pipe_limit, skipping core dump");
636 			retval = -E2BIG;
637 			goto fail_dropcount;
638 		}
639 
640 		helper_argv = kmalloc_array(argc + 1, sizeof(*helper_argv),
641 					    GFP_KERNEL);
642 		if (!helper_argv) {
643 			coredump_report_failure("%s failed to allocate memory", __func__);
644 			retval = -ENOMEM;
645 			goto fail_dropcount;
646 		}
647 		for (argi = 0; argi < argc; argi++)
648 			helper_argv[argi] = cn.corename + argv[argi];
649 		helper_argv[argi] = NULL;
650 
651 		retval = -ENOMEM;
652 		sub_info = call_usermodehelper_setup(helper_argv[0],
653 						helper_argv, NULL, GFP_KERNEL,
654 						umh_pipe_setup, NULL, &cprm);
655 		if (sub_info)
656 			retval = call_usermodehelper_exec(sub_info,
657 							  UMH_WAIT_EXEC);
658 
659 		kfree(helper_argv);
660 		if (retval) {
661 			coredump_report_failure("|%s pipe failed", cn.corename);
662 			goto close_fail;
663 		}
664 	} else {
665 		struct mnt_idmap *idmap;
666 		struct inode *inode;
667 		int open_flags = O_CREAT | O_WRONLY | O_NOFOLLOW |
668 				 O_LARGEFILE | O_EXCL;
669 
670 		if (cprm.limit < binfmt->min_coredump) {
671 			coredump_report_failure("over coredump resource limit, skipping core dump");
672 			retval = -E2BIG;
673 			goto fail_unlock;
674 		}
675 
676 		if (need_suid_safe && cn.corename[0] != '/') {
677 			coredump_report_failure(
678 				"this process can only dump core to a fully qualified path, skipping core dump");
679 			retval = -EPERM;
680 			goto fail_unlock;
681 		}
682 
683 		/*
684 		 * Unlink the file if it exists unless this is a SUID
685 		 * binary - in that case, we're running around with root
686 		 * privs and don't want to unlink another user's coredump.
687 		 */
688 		if (!need_suid_safe) {
689 			/*
690 			 * If it doesn't exist, that's fine. If there's some
691 			 * other problem, we'll catch it at the filp_open().
692 			 */
693 			do_unlinkat(AT_FDCWD, getname_kernel(cn.corename));
694 		}
695 
696 		/*
697 		 * There is a race between unlinking and creating the
698 		 * file, but if that causes an EEXIST here, that's
699 		 * fine - another process raced with us while creating
700 		 * the corefile, and the other process won. To userspace,
701 		 * what matters is that at least one of the two processes
702 		 * writes its coredump successfully, not which one.
703 		 */
704 		if (need_suid_safe) {
705 			/*
706 			 * Using user namespaces, normal user tasks can change
707 			 * their current->fs->root to point to arbitrary
708 			 * directories. Since the intention of the "only dump
709 			 * with a fully qualified path" rule is to control where
710 			 * coredumps may be placed using root privileges,
711 			 * current->fs->root must not be used. Instead, use the
712 			 * root directory of init_task.
713 			 */
714 			struct path root;
715 
716 			task_lock(&init_task);
717 			get_fs_root(init_task.fs, &root);
718 			task_unlock(&init_task);
719 			cprm.file = file_open_root(&root, cn.corename,
720 						   open_flags, 0600);
721 			path_put(&root);
722 		} else {
723 			cprm.file = filp_open(cn.corename, open_flags, 0600);
724 		}
725 		if (IS_ERR(cprm.file)) {
726 			retval = PTR_ERR(cprm.file);
727 			goto fail_unlock;
728 		}
729 
730 		inode = file_inode(cprm.file);
731 		if (inode->i_nlink > 1) {
732 			retval = -EMLINK;
733 			goto close_fail;
734 		}
735 		if (d_unhashed(cprm.file->f_path.dentry)) {
736 			retval = -EEXIST;
737 			goto close_fail;
738 		}
739 		/*
740 		 * AK: actually i see no reason to not allow this for named
741 		 * pipes etc, but keep the previous behaviour for now.
742 		 */
743 		if (!S_ISREG(inode->i_mode)) {
744 			retval = -EISDIR;
745 			goto close_fail;
746 		}
747 		/*
748 		 * Don't dump core if the filesystem changed owner or mode
749 		 * of the file during file creation. This is an issue when
750 		 * a process dumps core while its cwd is e.g. on a vfat
751 		 * filesystem.
752 		 */
753 		idmap = file_mnt_idmap(cprm.file);
754 		if (!vfsuid_eq_kuid(i_uid_into_vfsuid(idmap, inode),
755 				    current_fsuid())) {
756 			coredump_report_failure("Core dump to %s aborted: "
757 				"cannot preserve file owner", cn.corename);
758 			retval = -EPERM;
759 			goto close_fail;
760 		}
761 		if ((inode->i_mode & 0677) != 0600) {
762 			coredump_report_failure("Core dump to %s aborted: "
763 				"cannot preserve file permissions", cn.corename);
764 			retval = -EPERM;
765 			goto close_fail;
766 		}
767 		if (!(cprm.file->f_mode & FMODE_CAN_WRITE)) {
768 			retval = -EACCES;
769 			goto close_fail;
770 		}
771 		retval = do_truncate(idmap, cprm.file->f_path.dentry,
772 				0, 0, cprm.file);
773 		if (retval)
774 			goto close_fail;
775 	}
776 
777 	/* get us an unshared descriptor table; almost always a no-op */
778 	/* The cell spufs coredump code reads the file descriptor tables */
779 	retval = unshare_files();
780 	if (retval)
781 		goto close_fail;
782 	if (!dump_interrupted()) {
783 		/*
784 		 * umh disabled with CONFIG_STATIC_USERMODEHELPER_PATH="" would
785 		 * have this set to NULL.
786 		 */
787 		if (!cprm.file) {
788 			coredump_report_failure("Core dump to |%s disabled", cn.corename);
789 			retval = -EPERM;
790 			goto close_fail;
791 		}
792 		if (!dump_vma_snapshot(&cprm)) {
793 			coredump_report_failure("Can't get VMA snapshot for core dump |%s",
794 				cn.corename);
795 			retval = -EACCES;
796 			goto close_fail;
797 		}
798 
799 		file_start_write(cprm.file);
800 		core_dumped = binfmt->core_dump(&cprm);
801 		/*
802 		 * Ensures that file size is big enough to contain the current
803 		 * file postion. This prevents gdb from complaining about
804 		 * a truncated file if the last "write" to the file was
805 		 * dump_skip.
806 		 */
807 		if (cprm.to_skip) {
808 			cprm.to_skip--;
809 			dump_emit(&cprm, "", 1);
810 		}
811 		file_end_write(cprm.file);
812 		free_vma_snapshot(&cprm);
813 	} else {
814 		coredump_report_failure("Core dump to %s%s has been interrupted",
815 			ispipe ? "|" : "", cn.corename);
816 		retval = -EAGAIN;
817 		goto fail;
818 	}
819 	coredump_report(
820 		"written to %s%s: VMAs: %d, size %zu; core: %lld bytes, pos %lld",
821 		ispipe ? "|" : "", cn.corename,
822 		cprm.vma_count, cprm.vma_data_size, cprm.written, cprm.pos);
823 	if (ispipe && core_pipe_limit)
824 		wait_for_dump_helpers(cprm.file);
825 
826 	retval = 0;
827 
828 close_fail:
829 	if (cprm.file)
830 		filp_close(cprm.file, NULL);
831 fail_dropcount:
832 	if (ispipe)
833 		atomic_dec(&core_dump_count);
834 fail_unlock:
835 	kfree(argv);
836 	kfree(cn.corename);
837 	coredump_finish(core_dumped);
838 	revert_creds(old_cred);
839 fail_creds:
840 	put_cred(cred);
841 fail:
842 	return retval;
843 }
844 
845 /*
846  * Core dumping helper functions.  These are the only things you should
847  * do on a core-file: use only these functions to write out all the
848  * necessary info.
849  */
850 static int __dump_emit(struct coredump_params *cprm, const void *addr, int nr)
851 {
852 	struct file *file = cprm->file;
853 	loff_t pos = file->f_pos;
854 	ssize_t n;
855 	if (cprm->written + nr > cprm->limit)
856 		return 0;
857 
858 
859 	if (dump_interrupted())
860 		return 0;
861 	n = __kernel_write(file, addr, nr, &pos);
862 	if (n != nr) {
863 		if (n < 0)
864 			coredump_report_failure("failed when writing out, error %zd", n);
865 		else
866 			coredump_report_failure(
867 				"partially written out, only %zd(of %d) bytes written",
868 				n, nr);
869 
870 		return 0;
871 	}
872 	file->f_pos = pos;
873 	cprm->written += n;
874 	cprm->pos += n;
875 
876 	return 1;
877 }
878 
879 static int __dump_skip(struct coredump_params *cprm, size_t nr)
880 {
881 	static char zeroes[PAGE_SIZE];
882 	struct file *file = cprm->file;
883 	if (file->f_mode & FMODE_LSEEK) {
884 		int ret;
885 
886 		if (dump_interrupted())
887 			return 0;
888 
889 		ret = vfs_llseek(file, nr, SEEK_CUR);
890 		if (ret < 0) {
891 			coredump_report_failure("failed when seeking, error %d", ret);
892 			return 0;
893 		}
894 		cprm->pos += nr;
895 		return 1;
896 	} else {
897 		while (nr > PAGE_SIZE) {
898 			if (!__dump_emit(cprm, zeroes, PAGE_SIZE))
899 				return 0;
900 			nr -= PAGE_SIZE;
901 		}
902 		return __dump_emit(cprm, zeroes, nr);
903 	}
904 }
905 
906 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
907 {
908 	if (cprm->to_skip) {
909 		if (!__dump_skip(cprm, cprm->to_skip))
910 			return 0;
911 		cprm->to_skip = 0;
912 	}
913 	return __dump_emit(cprm, addr, nr);
914 }
915 EXPORT_SYMBOL(dump_emit);
916 
917 void dump_skip_to(struct coredump_params *cprm, unsigned long pos)
918 {
919 	cprm->to_skip = pos - cprm->pos;
920 }
921 EXPORT_SYMBOL(dump_skip_to);
922 
923 void dump_skip(struct coredump_params *cprm, size_t nr)
924 {
925 	cprm->to_skip += nr;
926 }
927 EXPORT_SYMBOL(dump_skip);
928 
929 #ifdef CONFIG_ELF_CORE
930 static int dump_emit_page(struct coredump_params *cprm, struct page *page)
931 {
932 	struct bio_vec bvec;
933 	struct iov_iter iter;
934 	struct file *file = cprm->file;
935 	loff_t pos;
936 	ssize_t n;
937 
938 	if (!page)
939 		return 0;
940 
941 	if (cprm->to_skip) {
942 		if (!__dump_skip(cprm, cprm->to_skip))
943 			return 0;
944 		cprm->to_skip = 0;
945 	}
946 	if (cprm->written + PAGE_SIZE > cprm->limit)
947 		return 0;
948 	if (dump_interrupted())
949 		return 0;
950 	pos = file->f_pos;
951 	bvec_set_page(&bvec, page, PAGE_SIZE, 0);
952 	iov_iter_bvec(&iter, ITER_SOURCE, &bvec, 1, PAGE_SIZE);
953 	n = __kernel_write_iter(cprm->file, &iter, &pos);
954 	if (n != PAGE_SIZE)
955 		return 0;
956 	file->f_pos = pos;
957 	cprm->written += PAGE_SIZE;
958 	cprm->pos += PAGE_SIZE;
959 
960 	return 1;
961 }
962 
963 /*
964  * If we might get machine checks from kernel accesses during the
965  * core dump, let's get those errors early rather than during the
966  * IO. This is not performance-critical enough to warrant having
967  * all the machine check logic in the iovec paths.
968  */
969 #ifdef copy_mc_to_kernel
970 
971 #define dump_page_alloc() alloc_page(GFP_KERNEL)
972 #define dump_page_free(x) __free_page(x)
973 static struct page *dump_page_copy(struct page *src, struct page *dst)
974 {
975 	void *buf = kmap_local_page(src);
976 	size_t left = copy_mc_to_kernel(page_address(dst), buf, PAGE_SIZE);
977 	kunmap_local(buf);
978 	return left ? NULL : dst;
979 }
980 
981 #else
982 
983 /* We just want to return non-NULL; it's never used. */
984 #define dump_page_alloc() ERR_PTR(-EINVAL)
985 #define dump_page_free(x) ((void)(x))
986 static inline struct page *dump_page_copy(struct page *src, struct page *dst)
987 {
988 	return src;
989 }
990 #endif
991 
992 int dump_user_range(struct coredump_params *cprm, unsigned long start,
993 		    unsigned long len)
994 {
995 	unsigned long addr;
996 	struct page *dump_page;
997 
998 	dump_page = dump_page_alloc();
999 	if (!dump_page)
1000 		return 0;
1001 
1002 	for (addr = start; addr < start + len; addr += PAGE_SIZE) {
1003 		struct page *page;
1004 
1005 		/*
1006 		 * To avoid having to allocate page tables for virtual address
1007 		 * ranges that have never been used yet, and also to make it
1008 		 * easy to generate sparse core files, use a helper that returns
1009 		 * NULL when encountering an empty page table entry that would
1010 		 * otherwise have been filled with the zero page.
1011 		 */
1012 		page = get_dump_page(addr);
1013 		if (page) {
1014 			int stop = !dump_emit_page(cprm, dump_page_copy(page, dump_page));
1015 			put_page(page);
1016 			if (stop) {
1017 				dump_page_free(dump_page);
1018 				return 0;
1019 			}
1020 		} else {
1021 			dump_skip(cprm, PAGE_SIZE);
1022 		}
1023 	}
1024 	dump_page_free(dump_page);
1025 	return 1;
1026 }
1027 #endif
1028 
1029 int dump_align(struct coredump_params *cprm, int align)
1030 {
1031 	unsigned mod = (cprm->pos + cprm->to_skip) & (align - 1);
1032 	if (align & (align - 1))
1033 		return 0;
1034 	if (mod)
1035 		cprm->to_skip += align - mod;
1036 	return 1;
1037 }
1038 EXPORT_SYMBOL(dump_align);
1039 
1040 #ifdef CONFIG_SYSCTL
1041 
1042 void validate_coredump_safety(void)
1043 {
1044 	if (suid_dumpable == SUID_DUMP_ROOT &&
1045 	    core_pattern[0] != '/' && core_pattern[0] != '|') {
1046 
1047 		coredump_report_failure("Unsafe core_pattern used with fs.suid_dumpable=2: "
1048 			"pipe handler or fully qualified core dump path required. "
1049 			"Set kernel.core_pattern before fs.suid_dumpable.");
1050 	}
1051 }
1052 
1053 static int proc_dostring_coredump(const struct ctl_table *table, int write,
1054 		  void *buffer, size_t *lenp, loff_t *ppos)
1055 {
1056 	int error = proc_dostring(table, write, buffer, lenp, ppos);
1057 
1058 	if (!error)
1059 		validate_coredump_safety();
1060 	return error;
1061 }
1062 
1063 static const unsigned int core_file_note_size_min = CORE_FILE_NOTE_SIZE_DEFAULT;
1064 static const unsigned int core_file_note_size_max = CORE_FILE_NOTE_SIZE_MAX;
1065 
1066 static struct ctl_table coredump_sysctls[] = {
1067 	{
1068 		.procname	= "core_uses_pid",
1069 		.data		= &core_uses_pid,
1070 		.maxlen		= sizeof(int),
1071 		.mode		= 0644,
1072 		.proc_handler	= proc_dointvec,
1073 	},
1074 	{
1075 		.procname	= "core_pattern",
1076 		.data		= core_pattern,
1077 		.maxlen		= CORENAME_MAX_SIZE,
1078 		.mode		= 0644,
1079 		.proc_handler	= proc_dostring_coredump,
1080 	},
1081 	{
1082 		.procname	= "core_pipe_limit",
1083 		.data		= &core_pipe_limit,
1084 		.maxlen		= sizeof(unsigned int),
1085 		.mode		= 0644,
1086 		.proc_handler	= proc_dointvec,
1087 	},
1088 	{
1089 		.procname       = "core_file_note_size_limit",
1090 		.data           = &core_file_note_size_limit,
1091 		.maxlen         = sizeof(unsigned int),
1092 		.mode           = 0644,
1093 		.proc_handler	= proc_douintvec_minmax,
1094 		.extra1		= (unsigned int *)&core_file_note_size_min,
1095 		.extra2		= (unsigned int *)&core_file_note_size_max,
1096 	},
1097 };
1098 
1099 static int __init init_fs_coredump_sysctls(void)
1100 {
1101 	register_sysctl_init("kernel", coredump_sysctls);
1102 	return 0;
1103 }
1104 fs_initcall(init_fs_coredump_sysctls);
1105 #endif /* CONFIG_SYSCTL */
1106 
1107 /*
1108  * The purpose of always_dump_vma() is to make sure that special kernel mappings
1109  * that are useful for post-mortem analysis are included in every core dump.
1110  * In that way we ensure that the core dump is fully interpretable later
1111  * without matching up the same kernel and hardware config to see what PC values
1112  * meant. These special mappings include - vDSO, vsyscall, and other
1113  * architecture specific mappings
1114  */
1115 static bool always_dump_vma(struct vm_area_struct *vma)
1116 {
1117 	/* Any vsyscall mappings? */
1118 	if (vma == get_gate_vma(vma->vm_mm))
1119 		return true;
1120 
1121 	/*
1122 	 * Assume that all vmas with a .name op should always be dumped.
1123 	 * If this changes, a new vm_ops field can easily be added.
1124 	 */
1125 	if (vma->vm_ops && vma->vm_ops->name && vma->vm_ops->name(vma))
1126 		return true;
1127 
1128 	/*
1129 	 * arch_vma_name() returns non-NULL for special architecture mappings,
1130 	 * such as vDSO sections.
1131 	 */
1132 	if (arch_vma_name(vma))
1133 		return true;
1134 
1135 	return false;
1136 }
1137 
1138 #define DUMP_SIZE_MAYBE_ELFHDR_PLACEHOLDER 1
1139 
1140 /*
1141  * Decide how much of @vma's contents should be included in a core dump.
1142  */
1143 static unsigned long vma_dump_size(struct vm_area_struct *vma,
1144 				   unsigned long mm_flags)
1145 {
1146 #define FILTER(type)	(mm_flags & (1UL << MMF_DUMP_##type))
1147 
1148 	/* always dump the vdso and vsyscall sections */
1149 	if (always_dump_vma(vma))
1150 		goto whole;
1151 
1152 	if (vma->vm_flags & VM_DONTDUMP)
1153 		return 0;
1154 
1155 	/* support for DAX */
1156 	if (vma_is_dax(vma)) {
1157 		if ((vma->vm_flags & VM_SHARED) && FILTER(DAX_SHARED))
1158 			goto whole;
1159 		if (!(vma->vm_flags & VM_SHARED) && FILTER(DAX_PRIVATE))
1160 			goto whole;
1161 		return 0;
1162 	}
1163 
1164 	/* Hugetlb memory check */
1165 	if (is_vm_hugetlb_page(vma)) {
1166 		if ((vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_SHARED))
1167 			goto whole;
1168 		if (!(vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_PRIVATE))
1169 			goto whole;
1170 		return 0;
1171 	}
1172 
1173 	/* Do not dump I/O mapped devices or special mappings */
1174 	if (vma->vm_flags & VM_IO)
1175 		return 0;
1176 
1177 	/* By default, dump shared memory if mapped from an anonymous file. */
1178 	if (vma->vm_flags & VM_SHARED) {
1179 		if (file_inode(vma->vm_file)->i_nlink == 0 ?
1180 		    FILTER(ANON_SHARED) : FILTER(MAPPED_SHARED))
1181 			goto whole;
1182 		return 0;
1183 	}
1184 
1185 	/* Dump segments that have been written to.  */
1186 	if ((!IS_ENABLED(CONFIG_MMU) || vma->anon_vma) && FILTER(ANON_PRIVATE))
1187 		goto whole;
1188 	if (vma->vm_file == NULL)
1189 		return 0;
1190 
1191 	if (FILTER(MAPPED_PRIVATE))
1192 		goto whole;
1193 
1194 	/*
1195 	 * If this is the beginning of an executable file mapping,
1196 	 * dump the first page to aid in determining what was mapped here.
1197 	 */
1198 	if (FILTER(ELF_HEADERS) &&
1199 	    vma->vm_pgoff == 0 && (vma->vm_flags & VM_READ)) {
1200 		if ((READ_ONCE(file_inode(vma->vm_file)->i_mode) & 0111) != 0)
1201 			return PAGE_SIZE;
1202 
1203 		/*
1204 		 * ELF libraries aren't always executable.
1205 		 * We'll want to check whether the mapping starts with the ELF
1206 		 * magic, but not now - we're holding the mmap lock,
1207 		 * so copy_from_user() doesn't work here.
1208 		 * Use a placeholder instead, and fix it up later in
1209 		 * dump_vma_snapshot().
1210 		 */
1211 		return DUMP_SIZE_MAYBE_ELFHDR_PLACEHOLDER;
1212 	}
1213 
1214 #undef	FILTER
1215 
1216 	return 0;
1217 
1218 whole:
1219 	return vma->vm_end - vma->vm_start;
1220 }
1221 
1222 /*
1223  * Helper function for iterating across a vma list.  It ensures that the caller
1224  * will visit `gate_vma' prior to terminating the search.
1225  */
1226 static struct vm_area_struct *coredump_next_vma(struct vma_iterator *vmi,
1227 				       struct vm_area_struct *vma,
1228 				       struct vm_area_struct *gate_vma)
1229 {
1230 	if (gate_vma && (vma == gate_vma))
1231 		return NULL;
1232 
1233 	vma = vma_next(vmi);
1234 	if (vma)
1235 		return vma;
1236 	return gate_vma;
1237 }
1238 
1239 static void free_vma_snapshot(struct coredump_params *cprm)
1240 {
1241 	if (cprm->vma_meta) {
1242 		int i;
1243 		for (i = 0; i < cprm->vma_count; i++) {
1244 			struct file *file = cprm->vma_meta[i].file;
1245 			if (file)
1246 				fput(file);
1247 		}
1248 		kvfree(cprm->vma_meta);
1249 		cprm->vma_meta = NULL;
1250 	}
1251 }
1252 
1253 static int cmp_vma_size(const void *vma_meta_lhs_ptr, const void *vma_meta_rhs_ptr)
1254 {
1255 	const struct core_vma_metadata *vma_meta_lhs = vma_meta_lhs_ptr;
1256 	const struct core_vma_metadata *vma_meta_rhs = vma_meta_rhs_ptr;
1257 
1258 	if (vma_meta_lhs->dump_size < vma_meta_rhs->dump_size)
1259 		return -1;
1260 	if (vma_meta_lhs->dump_size > vma_meta_rhs->dump_size)
1261 		return 1;
1262 	return 0;
1263 }
1264 
1265 /*
1266  * Under the mmap_lock, take a snapshot of relevant information about the task's
1267  * VMAs.
1268  */
1269 static bool dump_vma_snapshot(struct coredump_params *cprm)
1270 {
1271 	struct vm_area_struct *gate_vma, *vma = NULL;
1272 	struct mm_struct *mm = current->mm;
1273 	VMA_ITERATOR(vmi, mm, 0);
1274 	int i = 0;
1275 
1276 	/*
1277 	 * Once the stack expansion code is fixed to not change VMA bounds
1278 	 * under mmap_lock in read mode, this can be changed to take the
1279 	 * mmap_lock in read mode.
1280 	 */
1281 	if (mmap_write_lock_killable(mm))
1282 		return false;
1283 
1284 	cprm->vma_data_size = 0;
1285 	gate_vma = get_gate_vma(mm);
1286 	cprm->vma_count = mm->map_count + (gate_vma ? 1 : 0);
1287 
1288 	cprm->vma_meta = kvmalloc_array(cprm->vma_count, sizeof(*cprm->vma_meta), GFP_KERNEL);
1289 	if (!cprm->vma_meta) {
1290 		mmap_write_unlock(mm);
1291 		return false;
1292 	}
1293 
1294 	while ((vma = coredump_next_vma(&vmi, vma, gate_vma)) != NULL) {
1295 		struct core_vma_metadata *m = cprm->vma_meta + i;
1296 
1297 		m->start = vma->vm_start;
1298 		m->end = vma->vm_end;
1299 		m->flags = vma->vm_flags;
1300 		m->dump_size = vma_dump_size(vma, cprm->mm_flags);
1301 		m->pgoff = vma->vm_pgoff;
1302 		m->file = vma->vm_file;
1303 		if (m->file)
1304 			get_file(m->file);
1305 		i++;
1306 	}
1307 
1308 	mmap_write_unlock(mm);
1309 
1310 	for (i = 0; i < cprm->vma_count; i++) {
1311 		struct core_vma_metadata *m = cprm->vma_meta + i;
1312 
1313 		if (m->dump_size == DUMP_SIZE_MAYBE_ELFHDR_PLACEHOLDER) {
1314 			char elfmag[SELFMAG];
1315 
1316 			if (copy_from_user(elfmag, (void __user *)m->start, SELFMAG) ||
1317 					memcmp(elfmag, ELFMAG, SELFMAG) != 0) {
1318 				m->dump_size = 0;
1319 			} else {
1320 				m->dump_size = PAGE_SIZE;
1321 			}
1322 		}
1323 
1324 		cprm->vma_data_size += m->dump_size;
1325 	}
1326 
1327 	sort(cprm->vma_meta, cprm->vma_count, sizeof(*cprm->vma_meta),
1328 		cmp_vma_size, NULL);
1329 
1330 	return true;
1331 }
1332