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>
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/tracehook.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>
42 #include <linux/path.h>
43 #include <linux/timekeeping.h>
45 #include <linux/uaccess.h>
46 #include <asm/mmu_context.h>
50 #include <trace/events/task.h>
53 #include <trace/events/sched.h>
56 unsigned int core_pipe_limit;
57 char core_pattern[CORENAME_MAX_SIZE] = "core";
58 static int core_name_size = CORENAME_MAX_SIZE;
65 /* The maximal length of core_pattern is also specified in sysctl.c */
67 static int expand_corename(struct core_name *cn, int size)
69 char *corename = krealloc(cn->corename, size, GFP_KERNEL);
74 if (size > core_name_size) /* racy but harmless */
75 core_name_size = size;
77 cn->size = ksize(corename);
78 cn->corename = corename;
82 static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
89 free = cn->size - cn->used;
91 va_copy(arg_copy, arg);
92 need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
100 if (!expand_corename(cn, cn->size + need - free + 1))
106 static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
112 ret = cn_vprintf(cn, fmt, arg);
118 static __printf(2, 3)
119 int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
126 ret = cn_vprintf(cn, fmt, arg);
131 * Ensure that this coredump name component can't cause the
132 * resulting corefile path to consist of a ".." or ".".
134 if ((cn->used - cur == 1 && cn->corename[cur] == '.') ||
135 (cn->used - cur == 2 && cn->corename[cur] == '.'
136 && cn->corename[cur+1] == '.'))
137 cn->corename[cur] = '!';
140 * Empty names are fishy and could be used to create a "//" in a
141 * corefile name, causing the coredump to happen one directory
142 * level too high. Enforce that all components of the core
143 * pattern are at least one character long.
146 ret = cn_printf(cn, "!");
149 for (; cur < cn->used; ++cur) {
150 if (cn->corename[cur] == '/')
151 cn->corename[cur] = '!';
156 static int cn_print_exe_file(struct core_name *cn)
158 struct file *exe_file;
159 char *pathbuf, *path;
162 exe_file = get_mm_exe_file(current->mm);
164 return cn_esc_printf(cn, "%s (path unknown)", current->comm);
166 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
172 path = file_path(exe_file, pathbuf, PATH_MAX);
178 ret = cn_esc_printf(cn, "%s", path);
187 /* format_corename will inspect the pattern parameter, and output a
188 * name into corename, which must have space for at least
189 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
191 static int format_corename(struct core_name *cn, struct coredump_params *cprm,
192 size_t **argv, int *argc)
194 const struct cred *cred = current_cred();
195 const char *pat_ptr = core_pattern;
196 int ispipe = (*pat_ptr == '|');
197 bool was_space = false;
198 int pid_in_pattern = 0;
203 if (expand_corename(cn, core_name_size))
205 cn->corename[0] = '\0';
208 int argvs = sizeof(core_pattern) / 2;
209 (*argv) = kmalloc_array(argvs, sizeof(**argv), GFP_KERNEL);
212 (*argv)[(*argc)++] = 0;
216 /* Repeat as long as we have more pattern to process and more output
220 * Split on spaces before doing template expansion so that
221 * %e and %E don't get split if they have spaces in them
224 if (isspace(*pat_ptr)) {
228 } else if (was_space) {
230 err = cn_printf(cn, "%c", '\0');
233 (*argv)[(*argc)++] = cn->used;
236 if (*pat_ptr != '%') {
237 err = cn_printf(cn, "%c", *pat_ptr++);
239 switch (*++pat_ptr) {
240 /* single % at the end, drop that */
243 /* Double percent, output one percent */
245 err = cn_printf(cn, "%c", '%');
250 err = cn_printf(cn, "%d",
251 task_tgid_vnr(current));
255 err = cn_printf(cn, "%d",
256 task_tgid_nr(current));
259 err = cn_printf(cn, "%d",
260 task_pid_vnr(current));
263 err = cn_printf(cn, "%d",
264 task_pid_nr(current));
268 err = cn_printf(cn, "%u",
269 from_kuid(&init_user_ns,
274 err = cn_printf(cn, "%u",
275 from_kgid(&init_user_ns,
279 err = cn_printf(cn, "%d",
280 __get_dumpable(cprm->mm_flags));
282 /* signal that caused the coredump */
284 err = cn_printf(cn, "%d",
285 cprm->siginfo->si_signo);
287 /* UNIX time of coredump */
291 time = ktime_get_real_seconds();
292 err = cn_printf(cn, "%lld", time);
298 err = cn_esc_printf(cn, "%s",
299 utsname()->nodename);
304 err = cn_esc_printf(cn, "%s", current->comm);
307 err = cn_print_exe_file(cn);
309 /* core limit size */
311 err = cn_printf(cn, "%lu",
312 rlimit(RLIMIT_CORE));
325 /* Backward compatibility with core_uses_pid:
327 * If core_pattern does not include a %p (as is the default)
328 * and core_uses_pid is set, then .%pid will be appended to
329 * the filename. Do not do this for piped commands. */
330 if (!ispipe && !pid_in_pattern && core_uses_pid) {
331 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
338 static int zap_process(struct task_struct *start, int exit_code, int flags)
340 struct task_struct *t;
343 /* ignore all signals except SIGKILL, see prepare_signal() */
344 start->signal->flags = SIGNAL_GROUP_COREDUMP | flags;
345 start->signal->group_exit_code = exit_code;
346 start->signal->group_stop_count = 0;
348 for_each_thread(start, t) {
349 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
350 if (t != current && t->mm) {
351 sigaddset(&t->pending.signal, SIGKILL);
352 signal_wake_up(t, 1);
360 static int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
361 struct core_state *core_state, int exit_code)
363 struct task_struct *g, *p;
367 spin_lock_irq(&tsk->sighand->siglock);
368 if (!signal_group_exit(tsk->signal)) {
369 mm->core_state = core_state;
370 tsk->signal->group_exit_task = tsk;
371 nr = zap_process(tsk, exit_code, 0);
372 clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
374 spin_unlock_irq(&tsk->sighand->siglock);
375 if (unlikely(nr < 0))
378 tsk->flags |= PF_DUMPCORE;
379 if (atomic_read(&mm->mm_users) == nr + 1)
382 * We should find and kill all tasks which use this mm, and we should
383 * count them correctly into ->nr_threads. We don't take tasklist
384 * lock, but this is safe wrt:
387 * None of sub-threads can fork after zap_process(leader). All
388 * processes which were created before this point should be
389 * visible to zap_threads() because copy_process() adds the new
390 * process to the tail of init_task.tasks list, and lock/unlock
391 * of ->siglock provides a memory barrier.
394 * The caller holds mm->mmap_sem. This means that the task which
395 * uses this mm can't pass exit_mm(), so it can't exit or clear
399 * It does list_replace_rcu(&leader->tasks, ¤t->tasks),
400 * we must see either old or new leader, this does not matter.
401 * However, it can change p->sighand, so lock_task_sighand(p)
402 * must be used. Since p->mm != NULL and we hold ->mmap_sem
405 * Note also that "g" can be the old leader with ->mm == NULL
406 * and already unhashed and thus removed from ->thread_group.
407 * This is OK, __unhash_process()->list_del_rcu() does not
408 * clear the ->next pointer, we will find the new leader via
412 for_each_process(g) {
413 if (g == tsk->group_leader)
415 if (g->flags & PF_KTHREAD)
418 for_each_thread(g, p) {
419 if (unlikely(!p->mm))
421 if (unlikely(p->mm == mm)) {
422 lock_task_sighand(p, &flags);
423 nr += zap_process(p, exit_code,
425 unlock_task_sighand(p, &flags);
432 atomic_set(&core_state->nr_threads, nr);
436 static int coredump_wait(int exit_code, struct core_state *core_state)
438 struct task_struct *tsk = current;
439 struct mm_struct *mm = tsk->mm;
440 int core_waiters = -EBUSY;
442 init_completion(&core_state->startup);
443 core_state->dumper.task = tsk;
444 core_state->dumper.next = NULL;
446 if (down_write_killable(&mm->mmap_sem))
450 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
451 up_write(&mm->mmap_sem);
453 if (core_waiters > 0) {
454 struct core_thread *ptr;
456 freezer_do_not_count();
457 wait_for_completion(&core_state->startup);
460 * Wait for all the threads to become inactive, so that
461 * all the thread context (extended register state, like
462 * fpu etc) gets copied to the memory.
464 ptr = core_state->dumper.next;
465 while (ptr != NULL) {
466 wait_task_inactive(ptr->task, 0);
474 static void coredump_finish(struct mm_struct *mm, bool core_dumped)
476 struct core_thread *curr, *next;
477 struct task_struct *task;
479 spin_lock_irq(¤t->sighand->siglock);
480 if (core_dumped && !__fatal_signal_pending(current))
481 current->signal->group_exit_code |= 0x80;
482 current->signal->group_exit_task = NULL;
483 current->signal->flags = SIGNAL_GROUP_EXIT;
484 spin_unlock_irq(¤t->sighand->siglock);
486 next = mm->core_state->dumper.next;
487 while ((curr = next) != NULL) {
491 * see exit_mm(), curr->task must not see
492 * ->task == NULL before we read ->next.
496 wake_up_process(task);
499 mm->core_state = NULL;
502 static bool dump_interrupted(void)
505 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
506 * can do try_to_freeze() and check __fatal_signal_pending(),
507 * but then we need to teach dump_write() to restart and clear
510 return signal_pending(current);
513 static void wait_for_dump_helpers(struct file *file)
515 struct pipe_inode_info *pipe = file->private_data;
520 wake_up_interruptible_sync(&pipe->wait);
521 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
525 * We actually want wait_event_freezable() but then we need
526 * to clear TIF_SIGPENDING and improve dump_interrupted().
528 wait_event_interruptible(pipe->wait, pipe->readers == 1);
538 * helper function to customize the process used
539 * to collect the core in userspace. Specifically
540 * it sets up a pipe and installs it as fd 0 (stdin)
541 * for the process. Returns 0 on success, or
542 * PTR_ERR on failure.
543 * Note that it also sets the core limit to 1. This
544 * is a special value that we use to trap recursive
547 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
549 struct file *files[2];
550 struct coredump_params *cp = (struct coredump_params *)info->data;
551 int err = create_pipe_files(files, 0);
557 err = replace_fd(0, files[0], 0);
559 /* and disallow core files too */
560 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
565 void do_coredump(const kernel_siginfo_t *siginfo)
567 struct core_state core_state;
569 struct mm_struct *mm = current->mm;
570 struct linux_binfmt * binfmt;
571 const struct cred *old_cred;
577 struct files_struct *displaced;
578 /* require nonrelative corefile path and be extra careful */
579 bool need_suid_safe = false;
580 bool core_dumped = false;
581 static atomic_t core_dump_count = ATOMIC_INIT(0);
582 struct coredump_params cprm = {
584 .regs = signal_pt_regs(),
585 .limit = rlimit(RLIMIT_CORE),
587 * We must use the same mm->flags while dumping core to avoid
588 * inconsistency of bit flags, since this flag is not protected
591 .mm_flags = mm->flags,
594 audit_core_dumps(siginfo->si_signo);
597 if (!binfmt || !binfmt->core_dump)
599 if (!__get_dumpable(cprm.mm_flags))
602 cred = prepare_creds();
606 * We cannot trust fsuid as being the "true" uid of the process
607 * nor do we know its entire history. We only know it was tainted
608 * so we dump it as root in mode 2, and only into a controlled
609 * environment (pipe handler or fully qualified path).
611 if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
612 /* Setuid core dump mode */
613 cred->fsuid = GLOBAL_ROOT_UID; /* Dump root private */
614 need_suid_safe = true;
617 retval = coredump_wait(siginfo->si_signo, &core_state);
621 old_cred = override_creds(cred);
623 ispipe = format_corename(&cn, &cprm, &argv, &argc);
629 struct subprocess_info *sub_info;
632 printk(KERN_WARNING "format_corename failed\n");
633 printk(KERN_WARNING "Aborting core\n");
637 if (cprm.limit == 1) {
638 /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
640 * Normally core limits are irrelevant to pipes, since
641 * we're not writing to the file system, but we use
642 * cprm.limit of 1 here as a special value, this is a
643 * consistent way to catch recursive crashes.
644 * We can still crash if the core_pattern binary sets
645 * RLIM_CORE = !1, but it runs as root, and can do
646 * lots of stupid things.
648 * Note that we use task_tgid_vnr here to grab the pid
649 * of the process group leader. That way we get the
650 * right pid if a thread in a multi-threaded
651 * core_pattern process dies.
654 "Process %d(%s) has RLIMIT_CORE set to 1\n",
655 task_tgid_vnr(current), current->comm);
656 printk(KERN_WARNING "Aborting core\n");
659 cprm.limit = RLIM_INFINITY;
661 dump_count = atomic_inc_return(&core_dump_count);
662 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
663 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
664 task_tgid_vnr(current), current->comm);
665 printk(KERN_WARNING "Skipping core dump\n");
669 helper_argv = kmalloc_array(argc + 1, sizeof(*helper_argv),
672 printk(KERN_WARNING "%s failed to allocate memory\n",
676 for (argi = 0; argi < argc; argi++)
677 helper_argv[argi] = cn.corename + argv[argi];
678 helper_argv[argi] = NULL;
681 sub_info = call_usermodehelper_setup(helper_argv[0],
682 helper_argv, NULL, GFP_KERNEL,
683 umh_pipe_setup, NULL, &cprm);
685 retval = call_usermodehelper_exec(sub_info,
690 printk(KERN_INFO "Core dump to |%s pipe failed\n",
696 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
697 O_LARGEFILE | O_EXCL;
699 if (cprm.limit < binfmt->min_coredump)
702 if (need_suid_safe && cn.corename[0] != '/') {
703 printk(KERN_WARNING "Pid %d(%s) can only dump core "\
704 "to fully qualified path!\n",
705 task_tgid_vnr(current), current->comm);
706 printk(KERN_WARNING "Skipping core dump\n");
711 * Unlink the file if it exists unless this is a SUID
712 * binary - in that case, we're running around with root
713 * privs and don't want to unlink another user's coredump.
715 if (!need_suid_safe) {
717 * If it doesn't exist, that's fine. If there's some
718 * other problem, we'll catch it at the filp_open().
720 do_unlinkat(AT_FDCWD, getname_kernel(cn.corename));
724 * There is a race between unlinking and creating the
725 * file, but if that causes an EEXIST here, that's
726 * fine - another process raced with us while creating
727 * the corefile, and the other process won. To userspace,
728 * what matters is that at least one of the two processes
729 * writes its coredump successfully, not which one.
731 if (need_suid_safe) {
733 * Using user namespaces, normal user tasks can change
734 * their current->fs->root to point to arbitrary
735 * directories. Since the intention of the "only dump
736 * with a fully qualified path" rule is to control where
737 * coredumps may be placed using root privileges,
738 * current->fs->root must not be used. Instead, use the
739 * root directory of init_task.
743 task_lock(&init_task);
744 get_fs_root(init_task.fs, &root);
745 task_unlock(&init_task);
746 cprm.file = file_open_root(root.dentry, root.mnt,
747 cn.corename, open_flags, 0600);
750 cprm.file = filp_open(cn.corename, open_flags, 0600);
752 if (IS_ERR(cprm.file))
755 inode = file_inode(cprm.file);
756 if (inode->i_nlink > 1)
758 if (d_unhashed(cprm.file->f_path.dentry))
761 * AK: actually i see no reason to not allow this for named
762 * pipes etc, but keep the previous behaviour for now.
764 if (!S_ISREG(inode->i_mode))
767 * Don't dump core if the filesystem changed owner or mode
768 * of the file during file creation. This is an issue when
769 * a process dumps core while its cwd is e.g. on a vfat
772 if (!uid_eq(inode->i_uid, current_fsuid()))
774 if ((inode->i_mode & 0677) != 0600)
776 if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
778 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
782 /* get us an unshared descriptor table; almost always a no-op */
783 retval = unshare_files(&displaced);
787 put_files_struct(displaced);
788 if (!dump_interrupted()) {
789 file_start_write(cprm.file);
790 core_dumped = binfmt->core_dump(&cprm);
791 file_end_write(cprm.file);
793 if (ispipe && core_pipe_limit)
794 wait_for_dump_helpers(cprm.file);
797 filp_close(cprm.file, NULL);
800 atomic_dec(&core_dump_count);
804 coredump_finish(mm, core_dumped);
805 revert_creds(old_cred);
813 * Core dumping helper functions. These are the only things you should
814 * do on a core-file: use only these functions to write out all the
817 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
819 struct file *file = cprm->file;
820 loff_t pos = file->f_pos;
822 if (cprm->written + nr > cprm->limit)
825 if (dump_interrupted())
827 n = __kernel_write(file, addr, nr, &pos);
837 EXPORT_SYMBOL(dump_emit);
839 int dump_skip(struct coredump_params *cprm, size_t nr)
841 static char zeroes[PAGE_SIZE];
842 struct file *file = cprm->file;
843 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
844 if (dump_interrupted() ||
845 file->f_op->llseek(file, nr, SEEK_CUR) < 0)
850 while (nr > PAGE_SIZE) {
851 if (!dump_emit(cprm, zeroes, PAGE_SIZE))
855 return dump_emit(cprm, zeroes, nr);
858 EXPORT_SYMBOL(dump_skip);
860 int dump_align(struct coredump_params *cprm, int align)
862 unsigned mod = cprm->pos & (align - 1);
863 if (align & (align - 1))
865 return mod ? dump_skip(cprm, align - mod) : 1;
867 EXPORT_SYMBOL(dump_align);
870 * Ensures that file size is big enough to contain the current file
871 * postion. This prevents gdb from complaining about a truncated file
872 * if the last "write" to the file was dump_skip.
874 void dump_truncate(struct coredump_params *cprm)
876 struct file *file = cprm->file;
879 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
880 offset = file->f_op->llseek(file, 0, SEEK_CUR);
881 if (i_size_read(file->f_mapping->host) < offset)
882 do_truncate(file->f_path.dentry, offset, 0, file);
885 EXPORT_SYMBOL(dump_truncate);