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