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