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