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/string.h>
11 #include <linux/init.h>
12 #include <linux/pagemap.h>
13 #include <linux/perf_event.h>
14 #include <linux/highmem.h>
15 #include <linux/spinlock.h>
16 #include <linux/key.h>
17 #include <linux/personality.h>
18 #include <linux/binfmts.h>
19 #include <linux/coredump.h>
20 #include <linux/sched/coredump.h>
21 #include <linux/sched/signal.h>
22 #include <linux/sched/task_stack.h>
23 #include <linux/utsname.h>
24 #include <linux/pid_namespace.h>
25 #include <linux/module.h>
26 #include <linux/namei.h>
27 #include <linux/mount.h>
28 #include <linux/security.h>
29 #include <linux/syscalls.h>
30 #include <linux/tsacct_kern.h>
31 #include <linux/cn_proc.h>
32 #include <linux/audit.h>
33 #include <linux/tracehook.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>
41 #include <linux/path.h>
42 #include <linux/timekeeping.h>
44 #include <linux/uaccess.h>
45 #include <asm/mmu_context.h>
49 #include <trace/events/task.h>
52 #include <trace/events/sched.h>
55 unsigned int core_pipe_limit;
56 char core_pattern[CORENAME_MAX_SIZE] = "core";
57 static int core_name_size = CORENAME_MAX_SIZE;
64 /* The maximal length of core_pattern is also specified in sysctl.c */
66 static int expand_corename(struct core_name *cn, int size)
68 char *corename = krealloc(cn->corename, size, GFP_KERNEL);
73 if (size > core_name_size) /* racy but harmless */
74 core_name_size = size;
76 cn->size = ksize(corename);
77 cn->corename = corename;
81 static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
88 free = cn->size - cn->used;
90 va_copy(arg_copy, arg);
91 need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
99 if (!expand_corename(cn, cn->size + need - free + 1))
105 static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
111 ret = cn_vprintf(cn, fmt, arg);
117 static __printf(2, 3)
118 int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
125 ret = cn_vprintf(cn, fmt, arg);
130 * Ensure that this coredump name component can't cause the
131 * resulting corefile path to consist of a ".." or ".".
133 if ((cn->used - cur == 1 && cn->corename[cur] == '.') ||
134 (cn->used - cur == 2 && cn->corename[cur] == '.'
135 && cn->corename[cur+1] == '.'))
136 cn->corename[cur] = '!';
139 * Empty names are fishy and could be used to create a "//" in a
140 * corefile name, causing the coredump to happen one directory
141 * level too high. Enforce that all components of the core
142 * pattern are at least one character long.
145 ret = cn_printf(cn, "!");
148 for (; cur < cn->used; ++cur) {
149 if (cn->corename[cur] == '/')
150 cn->corename[cur] = '!';
155 static int cn_print_exe_file(struct core_name *cn)
157 struct file *exe_file;
158 char *pathbuf, *path;
161 exe_file = get_mm_exe_file(current->mm);
163 return cn_esc_printf(cn, "%s (path unknown)", current->comm);
165 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
171 path = file_path(exe_file, pathbuf, PATH_MAX);
177 ret = cn_esc_printf(cn, "%s", path);
186 /* format_corename will inspect the pattern parameter, and output a
187 * name into corename, which must have space for at least
188 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
190 static int format_corename(struct core_name *cn, struct coredump_params *cprm)
192 const struct cred *cred = current_cred();
193 const char *pat_ptr = core_pattern;
194 int ispipe = (*pat_ptr == '|');
195 int pid_in_pattern = 0;
200 if (expand_corename(cn, core_name_size))
202 cn->corename[0] = '\0';
207 /* Repeat as long as we have more pattern to process and more output
210 if (*pat_ptr != '%') {
211 err = cn_printf(cn, "%c", *pat_ptr++);
213 switch (*++pat_ptr) {
214 /* single % at the end, drop that */
217 /* Double percent, output one percent */
219 err = cn_printf(cn, "%c", '%');
224 err = cn_printf(cn, "%d",
225 task_tgid_vnr(current));
229 err = cn_printf(cn, "%d",
230 task_tgid_nr(current));
233 err = cn_printf(cn, "%d",
234 task_pid_vnr(current));
237 err = cn_printf(cn, "%d",
238 task_pid_nr(current));
242 err = cn_printf(cn, "%u",
243 from_kuid(&init_user_ns,
248 err = cn_printf(cn, "%u",
249 from_kgid(&init_user_ns,
253 err = cn_printf(cn, "%d",
254 __get_dumpable(cprm->mm_flags));
256 /* signal that caused the coredump */
258 err = cn_printf(cn, "%d",
259 cprm->siginfo->si_signo);
261 /* UNIX time of coredump */
265 time = ktime_get_real_seconds();
266 err = cn_printf(cn, "%lld", time);
272 err = cn_esc_printf(cn, "%s",
273 utsname()->nodename);
278 err = cn_esc_printf(cn, "%s", current->comm);
281 err = cn_print_exe_file(cn);
283 /* core limit size */
285 err = cn_printf(cn, "%lu",
286 rlimit(RLIMIT_CORE));
299 /* Backward compatibility with core_uses_pid:
301 * If core_pattern does not include a %p (as is the default)
302 * and core_uses_pid is set, then .%pid will be appended to
303 * the filename. Do not do this for piped commands. */
304 if (!ispipe && !pid_in_pattern && core_uses_pid) {
305 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
312 static int zap_process(struct task_struct *start, int exit_code, int flags)
314 struct task_struct *t;
317 /* ignore all signals except SIGKILL, see prepare_signal() */
318 start->signal->flags = SIGNAL_GROUP_COREDUMP | flags;
319 start->signal->group_exit_code = exit_code;
320 start->signal->group_stop_count = 0;
322 for_each_thread(start, t) {
323 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
324 if (t != current && t->mm) {
325 sigaddset(&t->pending.signal, SIGKILL);
326 signal_wake_up(t, 1);
334 static int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
335 struct core_state *core_state, int exit_code)
337 struct task_struct *g, *p;
341 spin_lock_irq(&tsk->sighand->siglock);
342 if (!signal_group_exit(tsk->signal)) {
343 mm->core_state = core_state;
344 tsk->signal->group_exit_task = tsk;
345 nr = zap_process(tsk, exit_code, 0);
346 clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
348 spin_unlock_irq(&tsk->sighand->siglock);
349 if (unlikely(nr < 0))
352 tsk->flags |= PF_DUMPCORE;
353 if (atomic_read(&mm->mm_users) == nr + 1)
356 * We should find and kill all tasks which use this mm, and we should
357 * count them correctly into ->nr_threads. We don't take tasklist
358 * lock, but this is safe wrt:
361 * None of sub-threads can fork after zap_process(leader). All
362 * processes which were created before this point should be
363 * visible to zap_threads() because copy_process() adds the new
364 * process to the tail of init_task.tasks list, and lock/unlock
365 * of ->siglock provides a memory barrier.
368 * The caller holds mm->mmap_sem. This means that the task which
369 * uses this mm can't pass exit_mm(), so it can't exit or clear
373 * It does list_replace_rcu(&leader->tasks, ¤t->tasks),
374 * we must see either old or new leader, this does not matter.
375 * However, it can change p->sighand, so lock_task_sighand(p)
376 * must be used. Since p->mm != NULL and we hold ->mmap_sem
379 * Note also that "g" can be the old leader with ->mm == NULL
380 * and already unhashed and thus removed from ->thread_group.
381 * This is OK, __unhash_process()->list_del_rcu() does not
382 * clear the ->next pointer, we will find the new leader via
386 for_each_process(g) {
387 if (g == tsk->group_leader)
389 if (g->flags & PF_KTHREAD)
392 for_each_thread(g, p) {
393 if (unlikely(!p->mm))
395 if (unlikely(p->mm == mm)) {
396 lock_task_sighand(p, &flags);
397 nr += zap_process(p, exit_code,
399 unlock_task_sighand(p, &flags);
406 atomic_set(&core_state->nr_threads, nr);
410 static int coredump_wait(int exit_code, struct core_state *core_state)
412 struct task_struct *tsk = current;
413 struct mm_struct *mm = tsk->mm;
414 int core_waiters = -EBUSY;
416 init_completion(&core_state->startup);
417 core_state->dumper.task = tsk;
418 core_state->dumper.next = NULL;
420 if (down_write_killable(&mm->mmap_sem))
424 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
425 up_write(&mm->mmap_sem);
427 if (core_waiters > 0) {
428 struct core_thread *ptr;
430 freezer_do_not_count();
431 wait_for_completion(&core_state->startup);
434 * Wait for all the threads to become inactive, so that
435 * all the thread context (extended register state, like
436 * fpu etc) gets copied to the memory.
438 ptr = core_state->dumper.next;
439 while (ptr != NULL) {
440 wait_task_inactive(ptr->task, 0);
448 static void coredump_finish(struct mm_struct *mm, bool core_dumped)
450 struct core_thread *curr, *next;
451 struct task_struct *task;
453 spin_lock_irq(¤t->sighand->siglock);
454 if (core_dumped && !__fatal_signal_pending(current))
455 current->signal->group_exit_code |= 0x80;
456 current->signal->group_exit_task = NULL;
457 current->signal->flags = SIGNAL_GROUP_EXIT;
458 spin_unlock_irq(¤t->sighand->siglock);
460 next = mm->core_state->dumper.next;
461 while ((curr = next) != NULL) {
465 * see exit_mm(), curr->task must not see
466 * ->task == NULL before we read ->next.
470 wake_up_process(task);
473 mm->core_state = NULL;
476 static bool dump_interrupted(void)
479 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
480 * can do try_to_freeze() and check __fatal_signal_pending(),
481 * but then we need to teach dump_write() to restart and clear
484 return signal_pending(current);
487 static void wait_for_dump_helpers(struct file *file)
489 struct pipe_inode_info *pipe = file->private_data;
494 wake_up_interruptible_sync(&pipe->wait);
495 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
499 * We actually want wait_event_freezable() but then we need
500 * to clear TIF_SIGPENDING and improve dump_interrupted().
502 wait_event_interruptible(pipe->wait, pipe->readers == 1);
512 * helper function to customize the process used
513 * to collect the core in userspace. Specifically
514 * it sets up a pipe and installs it as fd 0 (stdin)
515 * for the process. Returns 0 on success, or
516 * PTR_ERR on failure.
517 * Note that it also sets the core limit to 1. This
518 * is a special value that we use to trap recursive
521 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
523 struct file *files[2];
524 struct coredump_params *cp = (struct coredump_params *)info->data;
525 int err = create_pipe_files(files, 0);
531 err = replace_fd(0, files[0], 0);
533 /* and disallow core files too */
534 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
539 void do_coredump(const siginfo_t *siginfo)
541 struct core_state core_state;
543 struct mm_struct *mm = current->mm;
544 struct linux_binfmt * binfmt;
545 const struct cred *old_cred;
549 struct files_struct *displaced;
550 /* require nonrelative corefile path and be extra careful */
551 bool need_suid_safe = false;
552 bool core_dumped = false;
553 static atomic_t core_dump_count = ATOMIC_INIT(0);
554 struct coredump_params cprm = {
556 .regs = signal_pt_regs(),
557 .limit = rlimit(RLIMIT_CORE),
559 * We must use the same mm->flags while dumping core to avoid
560 * inconsistency of bit flags, since this flag is not protected
563 .mm_flags = mm->flags,
566 audit_core_dumps(siginfo->si_signo);
569 if (!binfmt || !binfmt->core_dump)
571 if (!__get_dumpable(cprm.mm_flags))
574 cred = prepare_creds();
578 * We cannot trust fsuid as being the "true" uid of the process
579 * nor do we know its entire history. We only know it was tainted
580 * so we dump it as root in mode 2, and only into a controlled
581 * environment (pipe handler or fully qualified path).
583 if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
584 /* Setuid core dump mode */
585 cred->fsuid = GLOBAL_ROOT_UID; /* Dump root private */
586 need_suid_safe = true;
589 retval = coredump_wait(siginfo->si_signo, &core_state);
593 old_cred = override_creds(cred);
595 ispipe = format_corename(&cn, &cprm);
600 struct subprocess_info *sub_info;
603 printk(KERN_WARNING "format_corename failed\n");
604 printk(KERN_WARNING "Aborting core\n");
608 if (cprm.limit == 1) {
609 /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
611 * Normally core limits are irrelevant to pipes, since
612 * we're not writing to the file system, but we use
613 * cprm.limit of 1 here as a special value, this is a
614 * consistent way to catch recursive crashes.
615 * We can still crash if the core_pattern binary sets
616 * RLIM_CORE = !1, but it runs as root, and can do
617 * lots of stupid things.
619 * Note that we use task_tgid_vnr here to grab the pid
620 * of the process group leader. That way we get the
621 * right pid if a thread in a multi-threaded
622 * core_pattern process dies.
625 "Process %d(%s) has RLIMIT_CORE set to 1\n",
626 task_tgid_vnr(current), current->comm);
627 printk(KERN_WARNING "Aborting core\n");
630 cprm.limit = RLIM_INFINITY;
632 dump_count = atomic_inc_return(&core_dump_count);
633 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
634 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
635 task_tgid_vnr(current), current->comm);
636 printk(KERN_WARNING "Skipping core dump\n");
640 helper_argv = argv_split(GFP_KERNEL, cn.corename, NULL);
642 printk(KERN_WARNING "%s failed to allocate memory\n",
648 sub_info = call_usermodehelper_setup(helper_argv[0],
649 helper_argv, NULL, GFP_KERNEL,
650 umh_pipe_setup, NULL, &cprm);
652 retval = call_usermodehelper_exec(sub_info,
655 argv_free(helper_argv);
657 printk(KERN_INFO "Core dump to |%s pipe failed\n",
663 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
664 O_LARGEFILE | O_EXCL;
666 if (cprm.limit < binfmt->min_coredump)
669 if (need_suid_safe && cn.corename[0] != '/') {
670 printk(KERN_WARNING "Pid %d(%s) can only dump core "\
671 "to fully qualified path!\n",
672 task_tgid_vnr(current), current->comm);
673 printk(KERN_WARNING "Skipping core dump\n");
678 * Unlink the file if it exists unless this is a SUID
679 * binary - in that case, we're running around with root
680 * privs and don't want to unlink another user's coredump.
682 if (!need_suid_safe) {
688 * If it doesn't exist, that's fine. If there's some
689 * other problem, we'll catch it at the filp_open().
691 (void) sys_unlink((const char __user *)cn.corename);
696 * There is a race between unlinking and creating the
697 * file, but if that causes an EEXIST here, that's
698 * fine - another process raced with us while creating
699 * the corefile, and the other process won. To userspace,
700 * what matters is that at least one of the two processes
701 * writes its coredump successfully, not which one.
703 if (need_suid_safe) {
705 * Using user namespaces, normal user tasks can change
706 * their current->fs->root to point to arbitrary
707 * directories. Since the intention of the "only dump
708 * with a fully qualified path" rule is to control where
709 * coredumps may be placed using root privileges,
710 * current->fs->root must not be used. Instead, use the
711 * root directory of init_task.
715 task_lock(&init_task);
716 get_fs_root(init_task.fs, &root);
717 task_unlock(&init_task);
718 cprm.file = file_open_root(root.dentry, root.mnt,
719 cn.corename, open_flags, 0600);
722 cprm.file = filp_open(cn.corename, open_flags, 0600);
724 if (IS_ERR(cprm.file))
727 inode = file_inode(cprm.file);
728 if (inode->i_nlink > 1)
730 if (d_unhashed(cprm.file->f_path.dentry))
733 * AK: actually i see no reason to not allow this for named
734 * pipes etc, but keep the previous behaviour for now.
736 if (!S_ISREG(inode->i_mode))
739 * Don't dump core if the filesystem changed owner or mode
740 * of the file during file creation. This is an issue when
741 * a process dumps core while its cwd is e.g. on a vfat
744 if (!uid_eq(inode->i_uid, current_fsuid()))
746 if ((inode->i_mode & 0677) != 0600)
748 if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
750 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
754 /* get us an unshared descriptor table; almost always a no-op */
755 retval = unshare_files(&displaced);
759 put_files_struct(displaced);
760 if (!dump_interrupted()) {
761 file_start_write(cprm.file);
762 core_dumped = binfmt->core_dump(&cprm);
763 file_end_write(cprm.file);
765 if (ispipe && core_pipe_limit)
766 wait_for_dump_helpers(cprm.file);
769 filp_close(cprm.file, NULL);
772 atomic_dec(&core_dump_count);
775 coredump_finish(mm, core_dumped);
776 revert_creds(old_cred);
784 * Core dumping helper functions. These are the only things you should
785 * do on a core-file: use only these functions to write out all the
788 int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
790 struct file *file = cprm->file;
791 loff_t pos = file->f_pos;
793 if (cprm->written + nr > cprm->limit)
796 if (dump_interrupted())
798 n = __kernel_write(file, addr, nr, &pos);
808 EXPORT_SYMBOL(dump_emit);
810 int dump_skip(struct coredump_params *cprm, size_t nr)
812 static char zeroes[PAGE_SIZE];
813 struct file *file = cprm->file;
814 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
815 if (dump_interrupted() ||
816 file->f_op->llseek(file, nr, SEEK_CUR) < 0)
821 while (nr > PAGE_SIZE) {
822 if (!dump_emit(cprm, zeroes, PAGE_SIZE))
826 return dump_emit(cprm, zeroes, nr);
829 EXPORT_SYMBOL(dump_skip);
831 int dump_align(struct coredump_params *cprm, int align)
833 unsigned mod = cprm->pos & (align - 1);
834 if (align & (align - 1))
836 return mod ? dump_skip(cprm, align - mod) : 1;
838 EXPORT_SYMBOL(dump_align);
841 * Ensures that file size is big enough to contain the current file
842 * postion. This prevents gdb from complaining about a truncated file
843 * if the last "write" to the file was dump_skip.
845 void dump_truncate(struct coredump_params *cprm)
847 struct file *file = cprm->file;
850 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
851 offset = file->f_op->llseek(file, 0, SEEK_CUR);
852 if (i_size_read(file->f_mapping->host) < offset)
853 do_truncate(file->f_path.dentry, offset, 0, file);
856 EXPORT_SYMBOL(dump_truncate);