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