1 #include <linux/slab.h>
2 #include <linux/file.h>
3 #include <linux/fdtable.h>
4 #include <linux/freezer.h>
6 #include <linux/stat.h>
7 #include <linux/fcntl.h>
8 #include <linux/swap.h>
9 #include <linux/string.h>
10 #include <linux/init.h>
11 #include <linux/pagemap.h>
12 #include <linux/perf_event.h>
13 #include <linux/highmem.h>
14 #include <linux/spinlock.h>
15 #include <linux/key.h>
16 #include <linux/personality.h>
17 #include <linux/binfmts.h>
18 #include <linux/coredump.h>
19 #include <linux/sched/coredump.h>
20 #include <linux/sched/signal.h>
21 #include <linux/sched/task_stack.h>
22 #include <linux/utsname.h>
23 #include <linux/pid_namespace.h>
24 #include <linux/module.h>
25 #include <linux/namei.h>
26 #include <linux/mount.h>
27 #include <linux/security.h>
28 #include <linux/syscalls.h>
29 #include <linux/tsacct_kern.h>
30 #include <linux/cn_proc.h>
31 #include <linux/audit.h>
32 #include <linux/tracehook.h>
33 #include <linux/kmod.h>
34 #include <linux/fsnotify.h>
35 #include <linux/fs_struct.h>
36 #include <linux/pipe_fs_i.h>
37 #include <linux/oom.h>
38 #include <linux/compat.h>
40 #include <linux/path.h>
41 #include <linux/timekeeping.h>
43 #include <linux/uaccess.h>
44 #include <asm/mmu_context.h>
48 #include <trace/events/task.h>
51 #include <trace/events/sched.h>
54 unsigned int core_pipe_limit;
55 char core_pattern[CORENAME_MAX_SIZE] = "core";
56 static int core_name_size = CORENAME_MAX_SIZE;
63 /* The maximal length of core_pattern is also specified in sysctl.c */
65 static int expand_corename(struct core_name *cn, int size)
67 char *corename = krealloc(cn->corename, size, GFP_KERNEL);
72 if (size > core_name_size) /* racy but harmless */
73 core_name_size = size;
75 cn->size = ksize(corename);
76 cn->corename = corename;
80 static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
87 free = cn->size - cn->used;
89 va_copy(arg_copy, arg);
90 need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
98 if (!expand_corename(cn, cn->size + need - free + 1))
104 static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
110 ret = cn_vprintf(cn, fmt, arg);
116 static __printf(2, 3)
117 int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
124 ret = cn_vprintf(cn, fmt, arg);
129 * Ensure that this coredump name component can't cause the
130 * resulting corefile path to consist of a ".." or ".".
132 if ((cn->used - cur == 1 && cn->corename[cur] == '.') ||
133 (cn->used - cur == 2 && cn->corename[cur] == '.'
134 && cn->corename[cur+1] == '.'))
135 cn->corename[cur] = '!';
138 * Empty names are fishy and could be used to create a "//" in a
139 * corefile name, causing the coredump to happen one directory
140 * level too high. Enforce that all components of the core
141 * pattern are at least one character long.
144 ret = cn_printf(cn, "!");
147 for (; cur < cn->used; ++cur) {
148 if (cn->corename[cur] == '/')
149 cn->corename[cur] = '!';
154 static int cn_print_exe_file(struct core_name *cn)
156 struct file *exe_file;
157 char *pathbuf, *path;
160 exe_file = get_mm_exe_file(current->mm);
162 return cn_esc_printf(cn, "%s (path unknown)", current->comm);
164 pathbuf = kmalloc(PATH_MAX, GFP_TEMPORARY);
170 path = file_path(exe_file, pathbuf, PATH_MAX);
176 ret = cn_esc_printf(cn, "%s", path);
185 /* format_corename will inspect the pattern parameter, and output a
186 * name into corename, which must have space for at least
187 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
189 static int format_corename(struct core_name *cn, struct coredump_params *cprm)
191 const struct cred *cred = current_cred();
192 const char *pat_ptr = core_pattern;
193 int ispipe = (*pat_ptr == '|');
194 int pid_in_pattern = 0;
199 if (expand_corename(cn, core_name_size))
201 cn->corename[0] = '\0';
206 /* Repeat as long as we have more pattern to process and more output
209 if (*pat_ptr != '%') {
210 err = cn_printf(cn, "%c", *pat_ptr++);
212 switch (*++pat_ptr) {
213 /* single % at the end, drop that */
216 /* Double percent, output one percent */
218 err = cn_printf(cn, "%c", '%');
223 err = cn_printf(cn, "%d",
224 task_tgid_vnr(current));
228 err = cn_printf(cn, "%d",
229 task_tgid_nr(current));
232 err = cn_printf(cn, "%d",
233 task_pid_vnr(current));
236 err = cn_printf(cn, "%d",
237 task_pid_nr(current));
241 err = cn_printf(cn, "%u",
242 from_kuid(&init_user_ns,
247 err = cn_printf(cn, "%u",
248 from_kgid(&init_user_ns,
252 err = cn_printf(cn, "%d",
253 __get_dumpable(cprm->mm_flags));
255 /* signal that caused the coredump */
257 err = cn_printf(cn, "%d",
258 cprm->siginfo->si_signo);
260 /* UNIX time of coredump */
264 time = ktime_get_real_seconds();
265 err = cn_printf(cn, "%lld", time);
271 err = cn_esc_printf(cn, "%s",
272 utsname()->nodename);
277 err = cn_esc_printf(cn, "%s", current->comm);
280 err = cn_print_exe_file(cn);
282 /* core limit size */
284 err = cn_printf(cn, "%lu",
285 rlimit(RLIMIT_CORE));
298 /* Backward compatibility with core_uses_pid:
300 * If core_pattern does not include a %p (as is the default)
301 * and core_uses_pid is set, then .%pid will be appended to
302 * the filename. Do not do this for piped commands. */
303 if (!ispipe && !pid_in_pattern && core_uses_pid) {
304 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
311 static int zap_process(struct task_struct *start, int exit_code, int flags)
313 struct task_struct *t;
316 /* ignore all signals except SIGKILL, see prepare_signal() */
317 start->signal->flags = SIGNAL_GROUP_COREDUMP | flags;
318 start->signal->group_exit_code = exit_code;
319 start->signal->group_stop_count = 0;
321 for_each_thread(start, t) {
322 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
323 if (t != current && t->mm) {
324 sigaddset(&t->pending.signal, SIGKILL);
325 signal_wake_up(t, 1);
333 static int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
334 struct core_state *core_state, int exit_code)
336 struct task_struct *g, *p;
340 spin_lock_irq(&tsk->sighand->siglock);
341 if (!signal_group_exit(tsk->signal)) {
342 mm->core_state = core_state;
343 tsk->signal->group_exit_task = tsk;
344 nr = zap_process(tsk, exit_code, 0);
345 clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
347 spin_unlock_irq(&tsk->sighand->siglock);
348 if (unlikely(nr < 0))
351 tsk->flags |= PF_DUMPCORE;
352 if (atomic_read(&mm->mm_users) == nr + 1)
355 * We should find and kill all tasks which use this mm, and we should
356 * count them correctly into ->nr_threads. We don't take tasklist
357 * lock, but this is safe wrt:
360 * None of sub-threads can fork after zap_process(leader). All
361 * processes which were created before this point should be
362 * visible to zap_threads() because copy_process() adds the new
363 * process to the tail of init_task.tasks list, and lock/unlock
364 * of ->siglock provides a memory barrier.
367 * The caller holds mm->mmap_sem. This means that the task which
368 * uses this mm can't pass exit_mm(), so it can't exit or clear
372 * It does list_replace_rcu(&leader->tasks, ¤t->tasks),
373 * we must see either old or new leader, this does not matter.
374 * However, it can change p->sighand, so lock_task_sighand(p)
375 * must be used. Since p->mm != NULL and we hold ->mmap_sem
378 * Note also that "g" can be the old leader with ->mm == NULL
379 * and already unhashed and thus removed from ->thread_group.
380 * This is OK, __unhash_process()->list_del_rcu() does not
381 * clear the ->next pointer, we will find the new leader via
385 for_each_process(g) {
386 if (g == tsk->group_leader)
388 if (g->flags & PF_KTHREAD)
391 for_each_thread(g, p) {
392 if (unlikely(!p->mm))
394 if (unlikely(p->mm == mm)) {
395 lock_task_sighand(p, &flags);
396 nr += zap_process(p, exit_code,
398 unlock_task_sighand(p, &flags);
405 atomic_set(&core_state->nr_threads, nr);
409 static int coredump_wait(int exit_code, struct core_state *core_state)
411 struct task_struct *tsk = current;
412 struct mm_struct *mm = tsk->mm;
413 int core_waiters = -EBUSY;
415 init_completion(&core_state->startup);
416 core_state->dumper.task = tsk;
417 core_state->dumper.next = NULL;
419 if (down_write_killable(&mm->mmap_sem))
423 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
424 up_write(&mm->mmap_sem);
426 if (core_waiters > 0) {
427 struct core_thread *ptr;
429 freezer_do_not_count();
430 wait_for_completion(&core_state->startup);
433 * Wait for all the threads to become inactive, so that
434 * all the thread context (extended register state, like
435 * fpu etc) gets copied to the memory.
437 ptr = core_state->dumper.next;
438 while (ptr != NULL) {
439 wait_task_inactive(ptr->task, 0);
447 static void coredump_finish(struct mm_struct *mm, bool core_dumped)
449 struct core_thread *curr, *next;
450 struct task_struct *task;
452 spin_lock_irq(¤t->sighand->siglock);
453 if (core_dumped && !__fatal_signal_pending(current))
454 current->signal->group_exit_code |= 0x80;
455 current->signal->group_exit_task = NULL;
456 current->signal->flags = SIGNAL_GROUP_EXIT;
457 spin_unlock_irq(¤t->sighand->siglock);
459 next = mm->core_state->dumper.next;
460 while ((curr = next) != NULL) {
464 * see exit_mm(), curr->task must not see
465 * ->task == NULL before we read ->next.
469 wake_up_process(task);
472 mm->core_state = NULL;
475 static bool dump_interrupted(void)
478 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
479 * can do try_to_freeze() and check __fatal_signal_pending(),
480 * but then we need to teach dump_write() to restart and clear
483 return signal_pending(current);
486 static void wait_for_dump_helpers(struct file *file)
488 struct pipe_inode_info *pipe = file->private_data;
493 wake_up_interruptible_sync(&pipe->wait);
494 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
498 * We actually want wait_event_freezable() but then we need
499 * to clear TIF_SIGPENDING and improve dump_interrupted().
501 wait_event_interruptible(pipe->wait, pipe->readers == 1);
511 * helper function to customize the process used
512 * to collect the core in userspace. Specifically
513 * it sets up a pipe and installs it as fd 0 (stdin)
514 * for the process. Returns 0 on success, or
515 * PTR_ERR on failure.
516 * Note that it also sets the core limit to 1. This
517 * is a special value that we use to trap recursive
520 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
522 struct file *files[2];
523 struct coredump_params *cp = (struct coredump_params *)info->data;
524 int err = create_pipe_files(files, 0);
530 err = replace_fd(0, files[0], 0);
532 /* and disallow core files too */
533 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
538 void do_coredump(const siginfo_t *siginfo)
540 struct core_state core_state;
542 struct mm_struct *mm = current->mm;
543 struct linux_binfmt * binfmt;
544 const struct cred *old_cred;
548 struct files_struct *displaced;
549 /* require nonrelative corefile path and be extra careful */
550 bool need_suid_safe = false;
551 bool core_dumped = false;
552 static atomic_t core_dump_count = ATOMIC_INIT(0);
553 struct coredump_params cprm = {
555 .regs = signal_pt_regs(),
556 .limit = rlimit(RLIMIT_CORE),
558 * We must use the same mm->flags while dumping core to avoid
559 * inconsistency of bit flags, since this flag is not protected
562 .mm_flags = mm->flags,
565 audit_core_dumps(siginfo->si_signo);
568 if (!binfmt || !binfmt->core_dump)
570 if (!__get_dumpable(cprm.mm_flags))
573 cred = prepare_creds();
577 * We cannot trust fsuid as being the "true" uid of the process
578 * nor do we know its entire history. We only know it was tainted
579 * so we dump it as root in mode 2, and only into a controlled
580 * environment (pipe handler or fully qualified path).
582 if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
583 /* Setuid core dump mode */
584 cred->fsuid = GLOBAL_ROOT_UID; /* Dump root private */
585 need_suid_safe = true;
588 retval = coredump_wait(siginfo->si_signo, &core_state);
592 old_cred = override_creds(cred);
594 ispipe = format_corename(&cn, &cprm);
599 struct subprocess_info *sub_info;
602 printk(KERN_WARNING "format_corename failed\n");
603 printk(KERN_WARNING "Aborting core\n");
607 if (cprm.limit == 1) {
608 /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
610 * Normally core limits are irrelevant to pipes, since
611 * we're not writing to the file system, but we use
612 * cprm.limit of 1 here as a special value, this is a
613 * consistent way to catch recursive crashes.
614 * We can still crash if the core_pattern binary sets
615 * RLIM_CORE = !1, but it runs as root, and can do
616 * lots of stupid things.
618 * Note that we use task_tgid_vnr here to grab the pid
619 * of the process group leader. That way we get the
620 * right pid if a thread in a multi-threaded
621 * core_pattern process dies.
624 "Process %d(%s) has RLIMIT_CORE set to 1\n",
625 task_tgid_vnr(current), current->comm);
626 printk(KERN_WARNING "Aborting core\n");
629 cprm.limit = RLIM_INFINITY;
631 dump_count = atomic_inc_return(&core_dump_count);
632 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
633 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
634 task_tgid_vnr(current), current->comm);
635 printk(KERN_WARNING "Skipping core dump\n");
639 helper_argv = argv_split(GFP_KERNEL, cn.corename, NULL);
641 printk(KERN_WARNING "%s failed to allocate memory\n",
647 sub_info = call_usermodehelper_setup(helper_argv[0],
648 helper_argv, NULL, GFP_KERNEL,
649 umh_pipe_setup, NULL, &cprm);
651 retval = call_usermodehelper_exec(sub_info,
654 argv_free(helper_argv);
656 printk(KERN_INFO "Core dump to |%s pipe failed\n",
662 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
663 O_LARGEFILE | O_EXCL;
665 if (cprm.limit < binfmt->min_coredump)
668 if (need_suid_safe && cn.corename[0] != '/') {
669 printk(KERN_WARNING "Pid %d(%s) can only dump core "\
670 "to fully qualified path!\n",
671 task_tgid_vnr(current), current->comm);
672 printk(KERN_WARNING "Skipping core dump\n");
677 * Unlink the file if it exists unless this is a SUID
678 * binary - in that case, we're running around with root
679 * privs and don't want to unlink another user's coredump.
681 if (!need_suid_safe) {
687 * If it doesn't exist, that's fine. If there's some
688 * other problem, we'll catch it at the filp_open().
690 (void) sys_unlink((const char __user *)cn.corename);
695 * There is a race between unlinking and creating the
696 * file, but if that causes an EEXIST here, that's
697 * fine - another process raced with us while creating
698 * the corefile, and the other process won. To userspace,
699 * what matters is that at least one of the two processes
700 * writes its coredump successfully, not which one.
702 if (need_suid_safe) {
704 * Using user namespaces, normal user tasks can change
705 * their current->fs->root to point to arbitrary
706 * directories. Since the intention of the "only dump
707 * with a fully qualified path" rule is to control where
708 * coredumps may be placed using root privileges,
709 * current->fs->root must not be used. Instead, use the
710 * root directory of init_task.
714 task_lock(&init_task);
715 get_fs_root(init_task.fs, &root);
716 task_unlock(&init_task);
717 cprm.file = file_open_root(root.dentry, root.mnt,
718 cn.corename, open_flags, 0600);
721 cprm.file = filp_open(cn.corename, open_flags, 0600);
723 if (IS_ERR(cprm.file))
726 inode = file_inode(cprm.file);
727 if (inode->i_nlink > 1)
729 if (d_unhashed(cprm.file->f_path.dentry))
732 * AK: actually i see no reason to not allow this for named
733 * pipes etc, but keep the previous behaviour for now.
735 if (!S_ISREG(inode->i_mode))
738 * Don't dump core if the filesystem changed owner or mode
739 * of the file during file creation. This is an issue when
740 * a process dumps core while its cwd is e.g. on a vfat
743 if (!uid_eq(inode->i_uid, current_fsuid()))
745 if ((inode->i_mode & 0677) != 0600)
747 if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
749 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
753 /* get us an unshared descriptor table; almost always a no-op */
754 retval = unshare_files(&displaced);
758 put_files_struct(displaced);
759 if (!dump_interrupted()) {
760 file_start_write(cprm.file);
761 core_dumped = binfmt->core_dump(&cprm);
762 file_end_write(cprm.file);
764 if (ispipe && core_pipe_limit)
765 wait_for_dump_helpers(cprm.file);
768 filp_close(cprm.file, NULL);
771 atomic_dec(&core_dump_count);
774 coredump_finish(mm, core_dumped);
775 revert_creds(old_cred);
783 * Core dumping helper functions. These are the only things you should
784 * do on a core-file: use only these functions to write out all the
787 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
789 struct file *file = cprm->file;
790 loff_t pos = file->f_pos;
792 if (cprm->written + nr > cprm->limit)
795 if (dump_interrupted())
797 n = __kernel_write(file, addr, nr, &pos);
807 EXPORT_SYMBOL(dump_emit);
809 int dump_skip(struct coredump_params *cprm, size_t nr)
811 static char zeroes[PAGE_SIZE];
812 struct file *file = cprm->file;
813 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
814 if (dump_interrupted() ||
815 file->f_op->llseek(file, nr, SEEK_CUR) < 0)
820 while (nr > PAGE_SIZE) {
821 if (!dump_emit(cprm, zeroes, PAGE_SIZE))
825 return dump_emit(cprm, zeroes, nr);
828 EXPORT_SYMBOL(dump_skip);
830 int dump_align(struct coredump_params *cprm, int align)
832 unsigned mod = cprm->pos & (align - 1);
833 if (align & (align - 1))
835 return mod ? dump_skip(cprm, align - mod) : 1;
837 EXPORT_SYMBOL(dump_align);
840 * Ensures that file size is big enough to contain the current file
841 * postion. This prevents gdb from complaining about a truncated file
842 * if the last "write" to the file was dump_skip.
844 void dump_truncate(struct coredump_params *cprm)
846 struct file *file = cprm->file;
849 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
850 offset = file->f_op->llseek(file, 0, SEEK_CUR);
851 if (i_size_read(file->f_mapping->host) < offset)
852 do_truncate(file->f_path.dentry, offset, 0, file);
855 EXPORT_SYMBOL(dump_truncate);