]> git.ipfire.org Git - people/ms/linux.git/blame - fs/coredump.c
tracehook: Remove tracehook.h
[people/ms/linux.git] / fs / coredump.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
10c28d93
AK
2#include <linux/slab.h>
3#include <linux/file.h>
4#include <linux/fdtable.h>
70d78fe7 5#include <linux/freezer.h>
10c28d93
AK
6#include <linux/mm.h>
7#include <linux/stat.h>
8#include <linux/fcntl.h>
9#include <linux/swap.h>
315c6926 10#include <linux/ctype.h>
10c28d93
AK
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>
179899fd 20#include <linux/coredump.h>
f7ccbae4 21#include <linux/sched/coredump.h>
3f07c014 22#include <linux/sched/signal.h>
68db0cf1 23#include <linux/sched/task_stack.h>
10c28d93
AK
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>
10c28d93
AK
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>
378c6520
JH
40#include <linux/fs.h>
41#include <linux/path.h>
03927c8a 42#include <linux/timekeeping.h>
f0bc21b2 43#include <linux/sysctl.h>
10c28d93 44
7c0f6ba6 45#include <linux/uaccess.h>
10c28d93
AK
46#include <asm/mmu_context.h>
47#include <asm/tlb.h>
48#include <asm/exec.h>
49
50#include <trace/events/task.h>
51#include "internal.h"
52
53#include <trace/events/sched.h>
54
f0bc21b2
XN
55static int core_uses_pid;
56static unsigned int core_pipe_limit;
57static char core_pattern[CORENAME_MAX_SIZE] = "core";
3ceadcf6 58static int core_name_size = CORENAME_MAX_SIZE;
10c28d93
AK
59
60struct core_name {
61 char *corename;
62 int used, size;
63};
10c28d93 64
3ceadcf6 65static int expand_corename(struct core_name *cn, int size)
10c28d93 66{
e7fd1549 67 char *corename = krealloc(cn->corename, size, GFP_KERNEL);
10c28d93 68
e7fd1549 69 if (!corename)
10c28d93 70 return -ENOMEM;
10c28d93 71
3ceadcf6
ON
72 if (size > core_name_size) /* racy but harmless */
73 core_name_size = size;
74
75 cn->size = ksize(corename);
e7fd1549 76 cn->corename = corename;
10c28d93
AK
77 return 0;
78}
79
b4176b7c
NI
80static __printf(2, 0) int cn_vprintf(struct core_name *cn, const char *fmt,
81 va_list arg)
10c28d93 82{
5fe9d8ca 83 int free, need;
404ca80e 84 va_list arg_copy;
10c28d93 85
5fe9d8ca
ON
86again:
87 free = cn->size - cn->used;
404ca80e
ED
88
89 va_copy(arg_copy, arg);
90 need = vsnprintf(cn->corename + cn->used, free, fmt, arg_copy);
91 va_end(arg_copy);
92
5fe9d8ca
ON
93 if (need < free) {
94 cn->used += need;
95 return 0;
96 }
10c28d93 97
3ceadcf6 98 if (!expand_corename(cn, cn->size + need - free + 1))
5fe9d8ca 99 goto again;
10c28d93 100
5fe9d8ca 101 return -ENOMEM;
10c28d93
AK
102}
103
b4176b7c 104static __printf(2, 3) int cn_printf(struct core_name *cn, const char *fmt, ...)
bc03c691
ON
105{
106 va_list arg;
107 int ret;
108
109 va_start(arg, fmt);
110 ret = cn_vprintf(cn, fmt, arg);
111 va_end(arg);
112
113 return ret;
114}
115
b4176b7c
NI
116static __printf(2, 3)
117int cn_esc_printf(struct core_name *cn, const char *fmt, ...)
10c28d93 118{
923bed03
ON
119 int cur = cn->used;
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
ac94b6e3
JH
127 if (ret == 0) {
128 /*
129 * Ensure that this coredump name component can't cause the
130 * resulting corefile path to consist of a ".." or ".".
131 */
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] = '!';
136
137 /*
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.
142 */
143 if (cn->used == cur)
144 ret = cn_printf(cn, "!");
145 }
146
923bed03
ON
147 for (; cur < cn->used; ++cur) {
148 if (cn->corename[cur] == '/')
149 cn->corename[cur] = '!';
150 }
151 return ret;
10c28d93
AK
152}
153
f38c85f1 154static int cn_print_exe_file(struct core_name *cn, bool name_only)
10c28d93
AK
155{
156 struct file *exe_file;
f38c85f1 157 char *pathbuf, *path, *ptr;
10c28d93
AK
158 int ret;
159
160 exe_file = get_mm_exe_file(current->mm);
923bed03
ON
161 if (!exe_file)
162 return cn_esc_printf(cn, "%s (path unknown)", current->comm);
10c28d93 163
0ee931c4 164 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
10c28d93
AK
165 if (!pathbuf) {
166 ret = -ENOMEM;
167 goto put_exe_file;
168 }
169
9bf39ab2 170 path = file_path(exe_file, pathbuf, PATH_MAX);
10c28d93
AK
171 if (IS_ERR(path)) {
172 ret = PTR_ERR(path);
173 goto free_buf;
174 }
175
f38c85f1
LW
176 if (name_only) {
177 ptr = strrchr(path, '/');
178 if (ptr)
179 path = ptr + 1;
180 }
923bed03 181 ret = cn_esc_printf(cn, "%s", path);
10c28d93
AK
182
183free_buf:
184 kfree(pathbuf);
185put_exe_file:
186 fput(exe_file);
187 return ret;
188}
189
190/* format_corename will inspect the pattern parameter, and output a
191 * name into corename, which must have space for at least
192 * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
193 */
315c6926
PW
194static int format_corename(struct core_name *cn, struct coredump_params *cprm,
195 size_t **argv, int *argc)
10c28d93
AK
196{
197 const struct cred *cred = current_cred();
198 const char *pat_ptr = core_pattern;
199 int ispipe = (*pat_ptr == '|');
315c6926 200 bool was_space = false;
10c28d93
AK
201 int pid_in_pattern = 0;
202 int err = 0;
203
e7fd1549 204 cn->used = 0;
3ceadcf6
ON
205 cn->corename = NULL;
206 if (expand_corename(cn, core_name_size))
10c28d93 207 return -ENOMEM;
888ffc59
ON
208 cn->corename[0] = '\0';
209
315c6926
PW
210 if (ispipe) {
211 int argvs = sizeof(core_pattern) / 2;
212 (*argv) = kmalloc_array(argvs, sizeof(**argv), GFP_KERNEL);
213 if (!(*argv))
214 return -ENOMEM;
215 (*argv)[(*argc)++] = 0;
888ffc59 216 ++pat_ptr;
db973a72
SM
217 if (!(*pat_ptr))
218 return -ENOMEM;
315c6926 219 }
10c28d93
AK
220
221 /* Repeat as long as we have more pattern to process and more output
222 space */
223 while (*pat_ptr) {
315c6926
PW
224 /*
225 * Split on spaces before doing template expansion so that
226 * %e and %E don't get split if they have spaces in them
227 */
228 if (ispipe) {
229 if (isspace(*pat_ptr)) {
2bf509d9
MD
230 if (cn->used != 0)
231 was_space = true;
315c6926
PW
232 pat_ptr++;
233 continue;
234 } else if (was_space) {
235 was_space = false;
236 err = cn_printf(cn, "%c", '\0');
237 if (err)
238 return err;
239 (*argv)[(*argc)++] = cn->used;
240 }
241 }
10c28d93 242 if (*pat_ptr != '%') {
10c28d93
AK
243 err = cn_printf(cn, "%c", *pat_ptr++);
244 } else {
245 switch (*++pat_ptr) {
246 /* single % at the end, drop that */
247 case 0:
248 goto out;
249 /* Double percent, output one percent */
250 case '%':
251 err = cn_printf(cn, "%c", '%');
252 break;
253 /* pid */
254 case 'p':
255 pid_in_pattern = 1;
256 err = cn_printf(cn, "%d",
257 task_tgid_vnr(current));
258 break;
65aafb1e
SG
259 /* global pid */
260 case 'P':
261 err = cn_printf(cn, "%d",
262 task_tgid_nr(current));
263 break;
b03023ec
ON
264 case 'i':
265 err = cn_printf(cn, "%d",
266 task_pid_vnr(current));
267 break;
268 case 'I':
269 err = cn_printf(cn, "%d",
270 task_pid_nr(current));
271 break;
10c28d93
AK
272 /* uid */
273 case 'u':
5202efe5
NI
274 err = cn_printf(cn, "%u",
275 from_kuid(&init_user_ns,
276 cred->uid));
10c28d93
AK
277 break;
278 /* gid */
279 case 'g':
5202efe5
NI
280 err = cn_printf(cn, "%u",
281 from_kgid(&init_user_ns,
282 cred->gid));
10c28d93 283 break;
12a2b4b2
ON
284 case 'd':
285 err = cn_printf(cn, "%d",
286 __get_dumpable(cprm->mm_flags));
287 break;
10c28d93
AK
288 /* signal that caused the coredump */
289 case 's':
b4176b7c
NI
290 err = cn_printf(cn, "%d",
291 cprm->siginfo->si_signo);
10c28d93
AK
292 break;
293 /* UNIX time of coredump */
294 case 't': {
03927c8a
AB
295 time64_t time;
296
297 time = ktime_get_real_seconds();
298 err = cn_printf(cn, "%lld", time);
10c28d93
AK
299 break;
300 }
301 /* hostname */
923bed03 302 case 'h':
10c28d93 303 down_read(&uts_sem);
923bed03 304 err = cn_esc_printf(cn, "%s",
10c28d93
AK
305 utsname()->nodename);
306 up_read(&uts_sem);
10c28d93 307 break;
f38c85f1 308 /* executable, could be changed by prctl PR_SET_NAME etc */
923bed03
ON
309 case 'e':
310 err = cn_esc_printf(cn, "%s", current->comm);
10c28d93 311 break;
f38c85f1
LW
312 /* file name of executable */
313 case 'f':
314 err = cn_print_exe_file(cn, true);
315 break;
10c28d93 316 case 'E':
f38c85f1 317 err = cn_print_exe_file(cn, false);
10c28d93
AK
318 break;
319 /* core limit size */
320 case 'c':
321 err = cn_printf(cn, "%lu",
322 rlimit(RLIMIT_CORE));
323 break;
324 default:
325 break;
326 }
327 ++pat_ptr;
328 }
329
330 if (err)
331 return err;
332 }
333
888ffc59 334out:
10c28d93
AK
335 /* Backward compatibility with core_uses_pid:
336 *
337 * If core_pattern does not include a %p (as is the default)
338 * and core_uses_pid is set, then .%pid will be appended to
339 * the filename. Do not do this for piped commands. */
340 if (!ispipe && !pid_in_pattern && core_uses_pid) {
341 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
342 if (err)
343 return err;
344 }
10c28d93
AK
345 return ispipe;
346}
347
752dc970 348static int zap_process(struct task_struct *start, int exit_code)
10c28d93
AK
349{
350 struct task_struct *t;
351 int nr = 0;
352
5fa534c9 353 /* ignore all signals except SIGKILL, see prepare_signal() */
2f824d4d 354 start->signal->flags = SIGNAL_GROUP_EXIT;
10c28d93
AK
355 start->signal->group_exit_code = exit_code;
356 start->signal->group_stop_count = 0;
357
d61ba589 358 for_each_thread(start, t) {
10c28d93 359 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
92307383 360 if (t != current && !(t->flags & PF_POSTCOREDUMP)) {
10c28d93
AK
361 sigaddset(&t->pending.signal, SIGKILL);
362 signal_wake_up(t, 1);
363 nr++;
364 }
d61ba589 365 }
10c28d93
AK
366
367 return nr;
368}
369
0258b5fd 370static int zap_threads(struct task_struct *tsk,
403bad72 371 struct core_state *core_state, int exit_code)
10c28d93 372{
49697335 373 struct signal_struct *signal = tsk->signal;
10c28d93
AK
374 int nr = -EAGAIN;
375
376 spin_lock_irq(&tsk->sighand->siglock);
49697335
EB
377 if (!(signal->flags & SIGNAL_GROUP_EXIT) && !signal->group_exec_task) {
378 signal->core_state = core_state;
752dc970 379 nr = zap_process(tsk, exit_code);
403bad72 380 clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
0258b5fd
EB
381 tsk->flags |= PF_DUMPCORE;
382 atomic_set(&core_state->nr_threads, nr);
10c28d93
AK
383 }
384 spin_unlock_irq(&tsk->sighand->siglock);
10c28d93
AK
385 return nr;
386}
387
388static int coredump_wait(int exit_code, struct core_state *core_state)
389{
390 struct task_struct *tsk = current;
10c28d93
AK
391 int core_waiters = -EBUSY;
392
393 init_completion(&core_state->startup);
394 core_state->dumper.task = tsk;
395 core_state->dumper.next = NULL;
396
0258b5fd 397 core_waiters = zap_threads(tsk, core_state, exit_code);
10c28d93
AK
398 if (core_waiters > 0) {
399 struct core_thread *ptr;
400
70d78fe7 401 freezer_do_not_count();
10c28d93 402 wait_for_completion(&core_state->startup);
70d78fe7 403 freezer_count();
10c28d93
AK
404 /*
405 * Wait for all the threads to become inactive, so that
406 * all the thread context (extended register state, like
407 * fpu etc) gets copied to the memory.
408 */
409 ptr = core_state->dumper.next;
410 while (ptr != NULL) {
411 wait_task_inactive(ptr->task, 0);
412 ptr = ptr->next;
413 }
414 }
415
416 return core_waiters;
417}
418
0258b5fd 419static void coredump_finish(bool core_dumped)
10c28d93
AK
420{
421 struct core_thread *curr, *next;
422 struct task_struct *task;
423
6cd8f0ac 424 spin_lock_irq(&current->sighand->siglock);
acdedd99
ON
425 if (core_dumped && !__fatal_signal_pending(current))
426 current->signal->group_exit_code |= 0x80;
0258b5fd
EB
427 next = current->signal->core_state->dumper.next;
428 current->signal->core_state = NULL;
6cd8f0ac
ON
429 spin_unlock_irq(&current->sighand->siglock);
430
10c28d93
AK
431 while ((curr = next) != NULL) {
432 next = curr->next;
433 task = curr->task;
434 /*
92307383 435 * see coredump_task_exit(), curr->task must not see
10c28d93
AK
436 * ->task == NULL before we read ->next.
437 */
438 smp_mb();
439 curr->task = NULL;
440 wake_up_process(task);
441 }
10c28d93
AK
442}
443
528f827e
ON
444static bool dump_interrupted(void)
445{
446 /*
447 * SIGKILL or freezing() interrupt the coredumping. Perhaps we
448 * can do try_to_freeze() and check __fatal_signal_pending(),
449 * but then we need to teach dump_write() to restart and clear
450 * TIF_SIGPENDING.
451 */
06af8679 452 return fatal_signal_pending(current) || freezing(current);
528f827e
ON
453}
454
10c28d93
AK
455static void wait_for_dump_helpers(struct file *file)
456{
de32ec4c 457 struct pipe_inode_info *pipe = file->private_data;
10c28d93
AK
458
459 pipe_lock(pipe);
460 pipe->readers++;
461 pipe->writers--;
0ddad21d 462 wake_up_interruptible_sync(&pipe->rd_wait);
dc7ee2aa
ON
463 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
464 pipe_unlock(pipe);
10c28d93 465
dc7ee2aa
ON
466 /*
467 * We actually want wait_event_freezable() but then we need
468 * to clear TIF_SIGPENDING and improve dump_interrupted().
469 */
0ddad21d 470 wait_event_interruptible(pipe->rd_wait, pipe->readers == 1);
10c28d93 471
dc7ee2aa 472 pipe_lock(pipe);
10c28d93
AK
473 pipe->readers--;
474 pipe->writers++;
475 pipe_unlock(pipe);
10c28d93
AK
476}
477
478/*
479 * umh_pipe_setup
480 * helper function to customize the process used
481 * to collect the core in userspace. Specifically
482 * it sets up a pipe and installs it as fd 0 (stdin)
483 * for the process. Returns 0 on success, or
484 * PTR_ERR on failure.
485 * Note that it also sets the core limit to 1. This
486 * is a special value that we use to trap recursive
487 * core dumps
488 */
489static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
490{
491 struct file *files[2];
492 struct coredump_params *cp = (struct coredump_params *)info->data;
493 int err = create_pipe_files(files, 0);
494 if (err)
495 return err;
496
497 cp->file = files[1];
498
45525b26
AV
499 err = replace_fd(0, files[0], 0);
500 fput(files[0]);
10c28d93
AK
501 /* and disallow core files too */
502 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
503
45525b26 504 return err;
10c28d93
AK
505}
506
ae7795bc 507void do_coredump(const kernel_siginfo_t *siginfo)
10c28d93
AK
508{
509 struct core_state core_state;
510 struct core_name cn;
511 struct mm_struct *mm = current->mm;
512 struct linux_binfmt * binfmt;
513 const struct cred *old_cred;
514 struct cred *cred;
515 int retval = 0;
10c28d93 516 int ispipe;
315c6926
PW
517 size_t *argv = NULL;
518 int argc = 0;
fbb18169
JH
519 /* require nonrelative corefile path and be extra careful */
520 bool need_suid_safe = false;
acdedd99 521 bool core_dumped = false;
10c28d93
AK
522 static atomic_t core_dump_count = ATOMIC_INIT(0);
523 struct coredump_params cprm = {
5ab1c309 524 .siginfo = siginfo,
541880d9 525 .regs = signal_pt_regs(),
10c28d93
AK
526 .limit = rlimit(RLIMIT_CORE),
527 /*
528 * We must use the same mm->flags while dumping core to avoid
529 * inconsistency of bit flags, since this flag is not protected
530 * by any locks.
531 */
532 .mm_flags = mm->flags,
533 };
534
5ab1c309 535 audit_core_dumps(siginfo->si_signo);
10c28d93
AK
536
537 binfmt = mm->binfmt;
538 if (!binfmt || !binfmt->core_dump)
539 goto fail;
540 if (!__get_dumpable(cprm.mm_flags))
541 goto fail;
542
543 cred = prepare_creds();
544 if (!cred)
545 goto fail;
546 /*
547 * We cannot trust fsuid as being the "true" uid of the process
548 * nor do we know its entire history. We only know it was tainted
549 * so we dump it as root in mode 2, and only into a controlled
550 * environment (pipe handler or fully qualified path).
551 */
e579d2c2 552 if (__get_dumpable(cprm.mm_flags) == SUID_DUMP_ROOT) {
10c28d93 553 /* Setuid core dump mode */
10c28d93 554 cred->fsuid = GLOBAL_ROOT_UID; /* Dump root private */
fbb18169 555 need_suid_safe = true;
10c28d93
AK
556 }
557
5ab1c309 558 retval = coredump_wait(siginfo->si_signo, &core_state);
10c28d93
AK
559 if (retval < 0)
560 goto fail_creds;
561
562 old_cred = override_creds(cred);
563
315c6926 564 ispipe = format_corename(&cn, &cprm, &argv, &argc);
10c28d93 565
fb96c475 566 if (ispipe) {
315c6926 567 int argi;
10c28d93
AK
568 int dump_count;
569 char **helper_argv;
907ed132 570 struct subprocess_info *sub_info;
10c28d93
AK
571
572 if (ispipe < 0) {
573 printk(KERN_WARNING "format_corename failed\n");
574 printk(KERN_WARNING "Aborting core\n");
e7fd1549 575 goto fail_unlock;
10c28d93
AK
576 }
577
578 if (cprm.limit == 1) {
579 /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
580 *
581 * Normally core limits are irrelevant to pipes, since
582 * we're not writing to the file system, but we use
fcbc32bc 583 * cprm.limit of 1 here as a special value, this is a
10c28d93
AK
584 * consistent way to catch recursive crashes.
585 * We can still crash if the core_pattern binary sets
586 * RLIM_CORE = !1, but it runs as root, and can do
587 * lots of stupid things.
588 *
589 * Note that we use task_tgid_vnr here to grab the pid
590 * of the process group leader. That way we get the
591 * right pid if a thread in a multi-threaded
592 * core_pattern process dies.
593 */
594 printk(KERN_WARNING
595 "Process %d(%s) has RLIMIT_CORE set to 1\n",
596 task_tgid_vnr(current), current->comm);
597 printk(KERN_WARNING "Aborting core\n");
598 goto fail_unlock;
599 }
600 cprm.limit = RLIM_INFINITY;
601
602 dump_count = atomic_inc_return(&core_dump_count);
603 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
604 printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
605 task_tgid_vnr(current), current->comm);
606 printk(KERN_WARNING "Skipping core dump\n");
607 goto fail_dropcount;
608 }
609
315c6926
PW
610 helper_argv = kmalloc_array(argc + 1, sizeof(*helper_argv),
611 GFP_KERNEL);
10c28d93
AK
612 if (!helper_argv) {
613 printk(KERN_WARNING "%s failed to allocate memory\n",
614 __func__);
615 goto fail_dropcount;
616 }
315c6926
PW
617 for (argi = 0; argi < argc; argi++)
618 helper_argv[argi] = cn.corename + argv[argi];
619 helper_argv[argi] = NULL;
10c28d93 620
907ed132
LDM
621 retval = -ENOMEM;
622 sub_info = call_usermodehelper_setup(helper_argv[0],
623 helper_argv, NULL, GFP_KERNEL,
624 umh_pipe_setup, NULL, &cprm);
625 if (sub_info)
626 retval = call_usermodehelper_exec(sub_info,
627 UMH_WAIT_EXEC);
628
315c6926 629 kfree(helper_argv);
10c28d93 630 if (retval) {
888ffc59 631 printk(KERN_INFO "Core dump to |%s pipe failed\n",
10c28d93
AK
632 cn.corename);
633 goto close_fail;
fb96c475 634 }
10c28d93 635 } else {
643fe55a 636 struct user_namespace *mnt_userns;
10c28d93 637 struct inode *inode;
378c6520
JH
638 int open_flags = O_CREAT | O_RDWR | O_NOFOLLOW |
639 O_LARGEFILE | O_EXCL;
10c28d93
AK
640
641 if (cprm.limit < binfmt->min_coredump)
642 goto fail_unlock;
643
fbb18169 644 if (need_suid_safe && cn.corename[0] != '/') {
10c28d93
AK
645 printk(KERN_WARNING "Pid %d(%s) can only dump core "\
646 "to fully qualified path!\n",
647 task_tgid_vnr(current), current->comm);
648 printk(KERN_WARNING "Skipping core dump\n");
649 goto fail_unlock;
650 }
651
fbb18169
JH
652 /*
653 * Unlink the file if it exists unless this is a SUID
654 * binary - in that case, we're running around with root
655 * privs and don't want to unlink another user's coredump.
656 */
657 if (!need_suid_safe) {
fbb18169
JH
658 /*
659 * If it doesn't exist, that's fine. If there's some
660 * other problem, we'll catch it at the filp_open().
661 */
96271654 662 do_unlinkat(AT_FDCWD, getname_kernel(cn.corename));
fbb18169
JH
663 }
664
665 /*
666 * There is a race between unlinking and creating the
667 * file, but if that causes an EEXIST here, that's
668 * fine - another process raced with us while creating
669 * the corefile, and the other process won. To userspace,
670 * what matters is that at least one of the two processes
671 * writes its coredump successfully, not which one.
672 */
378c6520
JH
673 if (need_suid_safe) {
674 /*
675 * Using user namespaces, normal user tasks can change
676 * their current->fs->root to point to arbitrary
677 * directories. Since the intention of the "only dump
678 * with a fully qualified path" rule is to control where
679 * coredumps may be placed using root privileges,
680 * current->fs->root must not be used. Instead, use the
681 * root directory of init_task.
682 */
683 struct path root;
684
685 task_lock(&init_task);
686 get_fs_root(init_task.fs, &root);
687 task_unlock(&init_task);
ffb37ca3
AV
688 cprm.file = file_open_root(&root, cn.corename,
689 open_flags, 0600);
378c6520
JH
690 path_put(&root);
691 } else {
692 cprm.file = filp_open(cn.corename, open_flags, 0600);
693 }
10c28d93
AK
694 if (IS_ERR(cprm.file))
695 goto fail_unlock;
696
496ad9aa 697 inode = file_inode(cprm.file);
10c28d93
AK
698 if (inode->i_nlink > 1)
699 goto close_fail;
700 if (d_unhashed(cprm.file->f_path.dentry))
701 goto close_fail;
702 /*
703 * AK: actually i see no reason to not allow this for named
704 * pipes etc, but keep the previous behaviour for now.
705 */
706 if (!S_ISREG(inode->i_mode))
707 goto close_fail;
708 /*
40f705a7
JH
709 * Don't dump core if the filesystem changed owner or mode
710 * of the file during file creation. This is an issue when
711 * a process dumps core while its cwd is e.g. on a vfat
712 * filesystem.
10c28d93 713 */
643fe55a 714 mnt_userns = file_mnt_user_ns(cprm.file);
dbd9d6f8
DO
715 if (!uid_eq(i_uid_into_mnt(mnt_userns, inode),
716 current_fsuid())) {
717 pr_info_ratelimited("Core dump to %s aborted: cannot preserve file owner\n",
718 cn.corename);
10c28d93 719 goto close_fail;
dbd9d6f8
DO
720 }
721 if ((inode->i_mode & 0677) != 0600) {
722 pr_info_ratelimited("Core dump to %s aborted: cannot preserve file permissions\n",
723 cn.corename);
40f705a7 724 goto close_fail;
dbd9d6f8 725 }
86cc0584 726 if (!(cprm.file->f_mode & FMODE_CAN_WRITE))
10c28d93 727 goto close_fail;
643fe55a
CB
728 if (do_truncate(mnt_userns, cprm.file->f_path.dentry,
729 0, 0, cprm.file))
10c28d93
AK
730 goto close_fail;
731 }
732
733 /* get us an unshared descriptor table; almost always a no-op */
c39ab6de 734 /* The cell spufs coredump code reads the file descriptor tables */
1f702603 735 retval = unshare_files();
10c28d93
AK
736 if (retval)
737 goto close_fail;
e86d35c3 738 if (!dump_interrupted()) {
3740d93e
LC
739 /*
740 * umh disabled with CONFIG_STATIC_USERMODEHELPER_PATH="" would
741 * have this set to NULL.
742 */
743 if (!cprm.file) {
744 pr_info("Core dump to |%s disabled\n", cn.corename);
745 goto close_fail;
746 }
e86d35c3
AV
747 file_start_write(cprm.file);
748 core_dumped = binfmt->core_dump(&cprm);
d0f1088b
AV
749 /*
750 * Ensures that file size is big enough to contain the current
751 * file postion. This prevents gdb from complaining about
752 * a truncated file if the last "write" to the file was
753 * dump_skip.
754 */
755 if (cprm.to_skip) {
756 cprm.to_skip--;
757 dump_emit(&cprm, "", 1);
758 }
e86d35c3
AV
759 file_end_write(cprm.file);
760 }
10c28d93
AK
761 if (ispipe && core_pipe_limit)
762 wait_for_dump_helpers(cprm.file);
763close_fail:
764 if (cprm.file)
765 filp_close(cprm.file, NULL);
766fail_dropcount:
767 if (ispipe)
768 atomic_dec(&core_dump_count);
769fail_unlock:
315c6926 770 kfree(argv);
10c28d93 771 kfree(cn.corename);
0258b5fd 772 coredump_finish(core_dumped);
10c28d93
AK
773 revert_creds(old_cred);
774fail_creds:
775 put_cred(cred);
776fail:
777 return;
778}
779
780/*
781 * Core dumping helper functions. These are the only things you should
782 * do on a core-file: use only these functions to write out all the
783 * necessary info.
784 */
d0f1088b 785static int __dump_emit(struct coredump_params *cprm, const void *addr, int nr)
ecc8c772
AV
786{
787 struct file *file = cprm->file;
2507a4fb
AV
788 loff_t pos = file->f_pos;
789 ssize_t n;
2c4cb043 790 if (cprm->written + nr > cprm->limit)
ecc8c772 791 return 0;
df0c09c0
JH
792
793
794 if (dump_interrupted())
795 return 0;
796 n = __kernel_write(file, addr, nr, &pos);
797 if (n != nr)
798 return 0;
799 file->f_pos = pos;
800 cprm->written += n;
801 cprm->pos += n;
802
ecc8c772
AV
803 return 1;
804}
ecc8c772 805
d0f1088b 806static int __dump_skip(struct coredump_params *cprm, size_t nr)
10c28d93 807{
9b56d543
AV
808 static char zeroes[PAGE_SIZE];
809 struct file *file = cprm->file;
10c28d93 810 if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
528f827e 811 if (dump_interrupted() ||
9b56d543 812 file->f_op->llseek(file, nr, SEEK_CUR) < 0)
10c28d93 813 return 0;
1607f09c 814 cprm->pos += nr;
9b56d543 815 return 1;
10c28d93 816 } else {
9b56d543 817 while (nr > PAGE_SIZE) {
d0f1088b 818 if (!__dump_emit(cprm, zeroes, PAGE_SIZE))
9b56d543
AV
819 return 0;
820 nr -= PAGE_SIZE;
10c28d93 821 }
d0f1088b 822 return __dump_emit(cprm, zeroes, nr);
10c28d93 823 }
10c28d93 824}
d0f1088b
AV
825
826int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
827{
828 if (cprm->to_skip) {
829 if (!__dump_skip(cprm, cprm->to_skip))
830 return 0;
831 cprm->to_skip = 0;
832 }
833 return __dump_emit(cprm, addr, nr);
834}
835EXPORT_SYMBOL(dump_emit);
836
837void dump_skip_to(struct coredump_params *cprm, unsigned long pos)
838{
839 cprm->to_skip = pos - cprm->pos;
840}
841EXPORT_SYMBOL(dump_skip_to);
842
843void dump_skip(struct coredump_params *cprm, size_t nr)
844{
845 cprm->to_skip += nr;
846}
9b56d543 847EXPORT_SYMBOL(dump_skip);
22a8cb82 848
afc63a97
JH
849#ifdef CONFIG_ELF_CORE
850int dump_user_range(struct coredump_params *cprm, unsigned long start,
851 unsigned long len)
852{
853 unsigned long addr;
854
855 for (addr = start; addr < start + len; addr += PAGE_SIZE) {
856 struct page *page;
857 int stop;
858
859 /*
860 * To avoid having to allocate page tables for virtual address
861 * ranges that have never been used yet, and also to make it
862 * easy to generate sparse core files, use a helper that returns
863 * NULL when encountering an empty page table entry that would
864 * otherwise have been filled with the zero page.
865 */
866 page = get_dump_page(addr);
867 if (page) {
3159ed57 868 void *kaddr = kmap_local_page(page);
afc63a97
JH
869
870 stop = !dump_emit(cprm, kaddr, PAGE_SIZE);
3159ed57 871 kunmap_local(kaddr);
afc63a97 872 put_page(page);
d0f1088b
AV
873 if (stop)
874 return 0;
afc63a97 875 } else {
d0f1088b 876 dump_skip(cprm, PAGE_SIZE);
afc63a97 877 }
afc63a97
JH
878 }
879 return 1;
880}
881#endif
882
22a8cb82
AV
883int dump_align(struct coredump_params *cprm, int align)
884{
d0f1088b 885 unsigned mod = (cprm->pos + cprm->to_skip) & (align - 1);
22a8cb82 886 if (align & (align - 1))
db51242d 887 return 0;
d0f1088b
AV
888 if (mod)
889 cprm->to_skip += align - mod;
890 return 1;
22a8cb82
AV
891}
892EXPORT_SYMBOL(dump_align);
4d22c75d 893
f0bc21b2
XN
894#ifdef CONFIG_SYSCTL
895
896void validate_coredump_safety(void)
897{
898 if (suid_dumpable == SUID_DUMP_ROOT &&
899 core_pattern[0] != '/' && core_pattern[0] != '|') {
900 pr_warn(
901"Unsafe core_pattern used with fs.suid_dumpable=2.\n"
902"Pipe handler or fully qualified core dump path required.\n"
903"Set kernel.core_pattern before fs.suid_dumpable.\n"
904 );
905 }
906}
907
908static int proc_dostring_coredump(struct ctl_table *table, int write,
909 void *buffer, size_t *lenp, loff_t *ppos)
910{
911 int error = proc_dostring(table, write, buffer, lenp, ppos);
912
913 if (!error)
914 validate_coredump_safety();
915 return error;
916}
917
918static struct ctl_table coredump_sysctls[] = {
919 {
920 .procname = "core_uses_pid",
921 .data = &core_uses_pid,
922 .maxlen = sizeof(int),
923 .mode = 0644,
924 .proc_handler = proc_dointvec,
925 },
926 {
927 .procname = "core_pattern",
928 .data = core_pattern,
929 .maxlen = CORENAME_MAX_SIZE,
930 .mode = 0644,
931 .proc_handler = proc_dostring_coredump,
932 },
933 {
934 .procname = "core_pipe_limit",
935 .data = &core_pipe_limit,
936 .maxlen = sizeof(unsigned int),
937 .mode = 0644,
938 .proc_handler = proc_dointvec,
939 },
940 { }
941};
942
943static int __init init_fs_coredump_sysctls(void)
944{
945 register_sysctl_init("kernel", coredump_sysctls);
946 return 0;
947}
948fs_initcall(init_fs_coredump_sysctls);
949#endif /* CONFIG_SYSCTL */
950
429a22e7
JH
951/*
952 * The purpose of always_dump_vma() is to make sure that special kernel mappings
953 * that are useful for post-mortem analysis are included in every core dump.
954 * In that way we ensure that the core dump is fully interpretable later
955 * without matching up the same kernel and hardware config to see what PC values
956 * meant. These special mappings include - vDSO, vsyscall, and other
957 * architecture specific mappings
958 */
959static bool always_dump_vma(struct vm_area_struct *vma)
960{
961 /* Any vsyscall mappings? */
962 if (vma == get_gate_vma(vma->vm_mm))
963 return true;
964
965 /*
966 * Assume that all vmas with a .name op should always be dumped.
967 * If this changes, a new vm_ops field can easily be added.
968 */
969 if (vma->vm_ops && vma->vm_ops->name && vma->vm_ops->name(vma))
970 return true;
971
972 /*
973 * arch_vma_name() returns non-NULL for special architecture mappings,
974 * such as vDSO sections.
975 */
976 if (arch_vma_name(vma))
977 return true;
978
979 return false;
980}
981
982/*
983 * Decide how much of @vma's contents should be included in a core dump.
984 */
a07279c9
JH
985static unsigned long vma_dump_size(struct vm_area_struct *vma,
986 unsigned long mm_flags)
429a22e7
JH
987{
988#define FILTER(type) (mm_flags & (1UL << MMF_DUMP_##type))
989
990 /* always dump the vdso and vsyscall sections */
991 if (always_dump_vma(vma))
992 goto whole;
993
994 if (vma->vm_flags & VM_DONTDUMP)
995 return 0;
996
997 /* support for DAX */
998 if (vma_is_dax(vma)) {
999 if ((vma->vm_flags & VM_SHARED) && FILTER(DAX_SHARED))
1000 goto whole;
1001 if (!(vma->vm_flags & VM_SHARED) && FILTER(DAX_PRIVATE))
1002 goto whole;
1003 return 0;
1004 }
1005
1006 /* Hugetlb memory check */
1007 if (is_vm_hugetlb_page(vma)) {
1008 if ((vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_SHARED))
1009 goto whole;
1010 if (!(vma->vm_flags & VM_SHARED) && FILTER(HUGETLB_PRIVATE))
1011 goto whole;
1012 return 0;
1013 }
1014
1015 /* Do not dump I/O mapped devices or special mappings */
1016 if (vma->vm_flags & VM_IO)
1017 return 0;
1018
1019 /* By default, dump shared memory if mapped from an anonymous file. */
1020 if (vma->vm_flags & VM_SHARED) {
1021 if (file_inode(vma->vm_file)->i_nlink == 0 ?
1022 FILTER(ANON_SHARED) : FILTER(MAPPED_SHARED))
1023 goto whole;
1024 return 0;
1025 }
1026
1027 /* Dump segments that have been written to. */
1028 if ((!IS_ENABLED(CONFIG_MMU) || vma->anon_vma) && FILTER(ANON_PRIVATE))
1029 goto whole;
1030 if (vma->vm_file == NULL)
1031 return 0;
1032
1033 if (FILTER(MAPPED_PRIVATE))
1034 goto whole;
1035
1036 /*
1037 * If this is the beginning of an executable file mapping,
1038 * dump the first page to aid in determining what was mapped here.
1039 */
1040 if (FILTER(ELF_HEADERS) &&
1041 vma->vm_pgoff == 0 && (vma->vm_flags & VM_READ) &&
1042 (READ_ONCE(file_inode(vma->vm_file)->i_mode) & 0111) != 0)
1043 return PAGE_SIZE;
1044
1045#undef FILTER
1046
1047 return 0;
1048
1049whole:
1050 return vma->vm_end - vma->vm_start;
1051}
a07279c9
JH
1052
1053static struct vm_area_struct *first_vma(struct task_struct *tsk,
1054 struct vm_area_struct *gate_vma)
1055{
1056 struct vm_area_struct *ret = tsk->mm->mmap;
1057
1058 if (ret)
1059 return ret;
1060 return gate_vma;
1061}
1062
1063/*
1064 * Helper function for iterating across a vma list. It ensures that the caller
1065 * will visit `gate_vma' prior to terminating the search.
1066 */
1067static struct vm_area_struct *next_vma(struct vm_area_struct *this_vma,
1068 struct vm_area_struct *gate_vma)
1069{
1070 struct vm_area_struct *ret;
1071
1072 ret = this_vma->vm_next;
1073 if (ret)
1074 return ret;
1075 if (this_vma == gate_vma)
1076 return NULL;
1077 return gate_vma;
1078}
1079
1080/*
1081 * Under the mmap_lock, take a snapshot of relevant information about the task's
1082 * VMAs.
1083 */
1084int dump_vma_snapshot(struct coredump_params *cprm, int *vma_count,
1085 struct core_vma_metadata **vma_meta,
1086 size_t *vma_data_size_ptr)
1087{
1088 struct vm_area_struct *vma, *gate_vma;
1089 struct mm_struct *mm = current->mm;
1090 int i;
1091 size_t vma_data_size = 0;
1092
1093 /*
1094 * Once the stack expansion code is fixed to not change VMA bounds
1095 * under mmap_lock in read mode, this can be changed to take the
1096 * mmap_lock in read mode.
1097 */
1098 if (mmap_write_lock_killable(mm))
1099 return -EINTR;
1100
1101 gate_vma = get_gate_vma(mm);
1102 *vma_count = mm->map_count + (gate_vma ? 1 : 0);
1103
1104 *vma_meta = kvmalloc_array(*vma_count, sizeof(**vma_meta), GFP_KERNEL);
1105 if (!*vma_meta) {
1106 mmap_write_unlock(mm);
1107 return -ENOMEM;
1108 }
1109
1110 for (i = 0, vma = first_vma(current, gate_vma); vma != NULL;
1111 vma = next_vma(vma, gate_vma), i++) {
1112 struct core_vma_metadata *m = (*vma_meta) + i;
1113
1114 m->start = vma->vm_start;
1115 m->end = vma->vm_end;
1116 m->flags = vma->vm_flags;
1117 m->dump_size = vma_dump_size(vma, cprm->mm_flags);
1118
1119 vma_data_size += m->dump_size;
1120 }
1121
1122 mmap_write_unlock(mm);
1123
6fcac87e
Q
1124 if (WARN_ON(i != *vma_count)) {
1125 kvfree(*vma_meta);
a07279c9 1126 return -EFAULT;
6fcac87e 1127 }
a07279c9
JH
1128
1129 *vma_data_size_ptr = vma_data_size;
1130 return 0;
1131}