]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - fs/coredump.c
coredump: move core dump functionality into its own file
[karo-tx-linux.git] / fs / coredump.c
1 #include <linux/slab.h>
2 #include <linux/file.h>
3 #include <linux/fdtable.h>
4 #include <linux/mm.h>
5 #include <linux/stat.h>
6 #include <linux/fcntl.h>
7 #include <linux/swap.h>
8 #include <linux/string.h>
9 #include <linux/init.h>
10 #include <linux/pagemap.h>
11 #include <linux/perf_event.h>
12 #include <linux/highmem.h>
13 #include <linux/spinlock.h>
14 #include <linux/key.h>
15 #include <linux/personality.h>
16 #include <linux/binfmts.h>
17 #include <linux/utsname.h>
18 #include <linux/pid_namespace.h>
19 #include <linux/module.h>
20 #include <linux/namei.h>
21 #include <linux/mount.h>
22 #include <linux/security.h>
23 #include <linux/syscalls.h>
24 #include <linux/tsacct_kern.h>
25 #include <linux/cn_proc.h>
26 #include <linux/audit.h>
27 #include <linux/tracehook.h>
28 #include <linux/kmod.h>
29 #include <linux/fsnotify.h>
30 #include <linux/fs_struct.h>
31 #include <linux/pipe_fs_i.h>
32 #include <linux/oom.h>
33 #include <linux/compat.h>
34
35 #include <asm/uaccess.h>
36 #include <asm/mmu_context.h>
37 #include <asm/tlb.h>
38 #include <asm/exec.h>
39
40 #include <trace/events/task.h>
41 #include "internal.h"
42
43 #include <trace/events/sched.h>
44
45 int core_uses_pid;
46 char core_pattern[CORENAME_MAX_SIZE] = "core";
47 unsigned int core_pipe_limit;
48
49 struct core_name {
50         char *corename;
51         int used, size;
52 };
53 static atomic_t call_count = ATOMIC_INIT(1);
54
55 /* The maximal length of core_pattern is also specified in sysctl.c */
56
57 static int expand_corename(struct core_name *cn)
58 {
59         char *old_corename = cn->corename;
60
61         cn->size = CORENAME_MAX_SIZE * atomic_inc_return(&call_count);
62         cn->corename = krealloc(old_corename, cn->size, GFP_KERNEL);
63
64         if (!cn->corename) {
65                 kfree(old_corename);
66                 return -ENOMEM;
67         }
68
69         return 0;
70 }
71
72 static int cn_printf(struct core_name *cn, const char *fmt, ...)
73 {
74         char *cur;
75         int need;
76         int ret;
77         va_list arg;
78
79         va_start(arg, fmt);
80         need = vsnprintf(NULL, 0, fmt, arg);
81         va_end(arg);
82
83         if (likely(need < cn->size - cn->used - 1))
84                 goto out_printf;
85
86         ret = expand_corename(cn);
87         if (ret)
88                 goto expand_fail;
89
90 out_printf:
91         cur = cn->corename + cn->used;
92         va_start(arg, fmt);
93         vsnprintf(cur, need + 1, fmt, arg);
94         va_end(arg);
95         cn->used += need;
96         return 0;
97
98 expand_fail:
99         return ret;
100 }
101
102 static void cn_escape(char *str)
103 {
104         for (; *str; str++)
105                 if (*str == '/')
106                         *str = '!';
107 }
108
109 static int cn_print_exe_file(struct core_name *cn)
110 {
111         struct file *exe_file;
112         char *pathbuf, *path;
113         int ret;
114
115         exe_file = get_mm_exe_file(current->mm);
116         if (!exe_file) {
117                 char *commstart = cn->corename + cn->used;
118                 ret = cn_printf(cn, "%s (path unknown)", current->comm);
119                 cn_escape(commstart);
120                 return ret;
121         }
122
123         pathbuf = kmalloc(PATH_MAX, GFP_TEMPORARY);
124         if (!pathbuf) {
125                 ret = -ENOMEM;
126                 goto put_exe_file;
127         }
128
129         path = d_path(&exe_file->f_path, pathbuf, PATH_MAX);
130         if (IS_ERR(path)) {
131                 ret = PTR_ERR(path);
132                 goto free_buf;
133         }
134
135         cn_escape(path);
136
137         ret = cn_printf(cn, "%s", path);
138
139 free_buf:
140         kfree(pathbuf);
141 put_exe_file:
142         fput(exe_file);
143         return ret;
144 }
145
146 /* format_corename will inspect the pattern parameter, and output a
147  * name into corename, which must have space for at least
148  * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator.
149  */
150 static int format_corename(struct core_name *cn, long signr)
151 {
152         const struct cred *cred = current_cred();
153         const char *pat_ptr = core_pattern;
154         int ispipe = (*pat_ptr == '|');
155         int pid_in_pattern = 0;
156         int err = 0;
157
158         cn->size = CORENAME_MAX_SIZE * atomic_read(&call_count);
159         cn->corename = kmalloc(cn->size, GFP_KERNEL);
160         cn->used = 0;
161
162         if (!cn->corename)
163                 return -ENOMEM;
164
165         /* Repeat as long as we have more pattern to process and more output
166            space */
167         while (*pat_ptr) {
168                 if (*pat_ptr != '%') {
169                         if (*pat_ptr == 0)
170                                 goto out;
171                         err = cn_printf(cn, "%c", *pat_ptr++);
172                 } else {
173                         switch (*++pat_ptr) {
174                         /* single % at the end, drop that */
175                         case 0:
176                                 goto out;
177                         /* Double percent, output one percent */
178                         case '%':
179                                 err = cn_printf(cn, "%c", '%');
180                                 break;
181                         /* pid */
182                         case 'p':
183                                 pid_in_pattern = 1;
184                                 err = cn_printf(cn, "%d",
185                                               task_tgid_vnr(current));
186                                 break;
187                         /* uid */
188                         case 'u':
189                                 err = cn_printf(cn, "%d", cred->uid);
190                                 break;
191                         /* gid */
192                         case 'g':
193                                 err = cn_printf(cn, "%d", cred->gid);
194                                 break;
195                         /* signal that caused the coredump */
196                         case 's':
197                                 err = cn_printf(cn, "%ld", signr);
198                                 break;
199                         /* UNIX time of coredump */
200                         case 't': {
201                                 struct timeval tv;
202                                 do_gettimeofday(&tv);
203                                 err = cn_printf(cn, "%lu", tv.tv_sec);
204                                 break;
205                         }
206                         /* hostname */
207                         case 'h': {
208                                 char *namestart = cn->corename + cn->used;
209                                 down_read(&uts_sem);
210                                 err = cn_printf(cn, "%s",
211                                               utsname()->nodename);
212                                 up_read(&uts_sem);
213                                 cn_escape(namestart);
214                                 break;
215                         }
216                         /* executable */
217                         case 'e': {
218                                 char *commstart = cn->corename + cn->used;
219                                 err = cn_printf(cn, "%s", current->comm);
220                                 cn_escape(commstart);
221                                 break;
222                         }
223                         case 'E':
224                                 err = cn_print_exe_file(cn);
225                                 break;
226                         /* core limit size */
227                         case 'c':
228                                 err = cn_printf(cn, "%lu",
229                                               rlimit(RLIMIT_CORE));
230                                 break;
231                         default:
232                                 break;
233                         }
234                         ++pat_ptr;
235                 }
236
237                 if (err)
238                         return err;
239         }
240
241         /* Backward compatibility with core_uses_pid:
242          *
243          * If core_pattern does not include a %p (as is the default)
244          * and core_uses_pid is set, then .%pid will be appended to
245          * the filename. Do not do this for piped commands. */
246         if (!ispipe && !pid_in_pattern && core_uses_pid) {
247                 err = cn_printf(cn, ".%d", task_tgid_vnr(current));
248                 if (err)
249                         return err;
250         }
251 out:
252         return ispipe;
253 }
254
255 static int zap_process(struct task_struct *start, int exit_code)
256 {
257         struct task_struct *t;
258         int nr = 0;
259
260         start->signal->flags = SIGNAL_GROUP_EXIT;
261         start->signal->group_exit_code = exit_code;
262         start->signal->group_stop_count = 0;
263
264         t = start;
265         do {
266                 task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
267                 if (t != current && t->mm) {
268                         sigaddset(&t->pending.signal, SIGKILL);
269                         signal_wake_up(t, 1);
270                         nr++;
271                 }
272         } while_each_thread(start, t);
273
274         return nr;
275 }
276
277 static inline int zap_threads(struct task_struct *tsk, struct mm_struct *mm,
278                                 struct core_state *core_state, int exit_code)
279 {
280         struct task_struct *g, *p;
281         unsigned long flags;
282         int nr = -EAGAIN;
283
284         spin_lock_irq(&tsk->sighand->siglock);
285         if (!signal_group_exit(tsk->signal)) {
286                 mm->core_state = core_state;
287                 nr = zap_process(tsk, exit_code);
288         }
289         spin_unlock_irq(&tsk->sighand->siglock);
290         if (unlikely(nr < 0))
291                 return nr;
292
293         if (atomic_read(&mm->mm_users) == nr + 1)
294                 goto done;
295         /*
296          * We should find and kill all tasks which use this mm, and we should
297          * count them correctly into ->nr_threads. We don't take tasklist
298          * lock, but this is safe wrt:
299          *
300          * fork:
301          *      None of sub-threads can fork after zap_process(leader). All
302          *      processes which were created before this point should be
303          *      visible to zap_threads() because copy_process() adds the new
304          *      process to the tail of init_task.tasks list, and lock/unlock
305          *      of ->siglock provides a memory barrier.
306          *
307          * do_exit:
308          *      The caller holds mm->mmap_sem. This means that the task which
309          *      uses this mm can't pass exit_mm(), so it can't exit or clear
310          *      its ->mm.
311          *
312          * de_thread:
313          *      It does list_replace_rcu(&leader->tasks, &current->tasks),
314          *      we must see either old or new leader, this does not matter.
315          *      However, it can change p->sighand, so lock_task_sighand(p)
316          *      must be used. Since p->mm != NULL and we hold ->mmap_sem
317          *      it can't fail.
318          *
319          *      Note also that "g" can be the old leader with ->mm == NULL
320          *      and already unhashed and thus removed from ->thread_group.
321          *      This is OK, __unhash_process()->list_del_rcu() does not
322          *      clear the ->next pointer, we will find the new leader via
323          *      next_thread().
324          */
325         rcu_read_lock();
326         for_each_process(g) {
327                 if (g == tsk->group_leader)
328                         continue;
329                 if (g->flags & PF_KTHREAD)
330                         continue;
331                 p = g;
332                 do {
333                         if (p->mm) {
334                                 if (unlikely(p->mm == mm)) {
335                                         lock_task_sighand(p, &flags);
336                                         nr += zap_process(p, exit_code);
337                                         unlock_task_sighand(p, &flags);
338                                 }
339                                 break;
340                         }
341                 } while_each_thread(g, p);
342         }
343         rcu_read_unlock();
344 done:
345         atomic_set(&core_state->nr_threads, nr);
346         return nr;
347 }
348
349 static int coredump_wait(int exit_code, struct core_state *core_state)
350 {
351         struct task_struct *tsk = current;
352         struct mm_struct *mm = tsk->mm;
353         int core_waiters = -EBUSY;
354
355         init_completion(&core_state->startup);
356         core_state->dumper.task = tsk;
357         core_state->dumper.next = NULL;
358
359         down_write(&mm->mmap_sem);
360         if (!mm->core_state)
361                 core_waiters = zap_threads(tsk, mm, core_state, exit_code);
362         up_write(&mm->mmap_sem);
363
364         if (core_waiters > 0) {
365                 struct core_thread *ptr;
366
367                 wait_for_completion(&core_state->startup);
368                 /*
369                  * Wait for all the threads to become inactive, so that
370                  * all the thread context (extended register state, like
371                  * fpu etc) gets copied to the memory.
372                  */
373                 ptr = core_state->dumper.next;
374                 while (ptr != NULL) {
375                         wait_task_inactive(ptr->task, 0);
376                         ptr = ptr->next;
377                 }
378         }
379
380         return core_waiters;
381 }
382
383 static void coredump_finish(struct mm_struct *mm)
384 {
385         struct core_thread *curr, *next;
386         struct task_struct *task;
387
388         next = mm->core_state->dumper.next;
389         while ((curr = next) != NULL) {
390                 next = curr->next;
391                 task = curr->task;
392                 /*
393                  * see exit_mm(), curr->task must not see
394                  * ->task == NULL before we read ->next.
395                  */
396                 smp_mb();
397                 curr->task = NULL;
398                 wake_up_process(task);
399         }
400
401         mm->core_state = NULL;
402 }
403
404 static void wait_for_dump_helpers(struct file *file)
405 {
406         struct pipe_inode_info *pipe;
407
408         pipe = file->f_path.dentry->d_inode->i_pipe;
409
410         pipe_lock(pipe);
411         pipe->readers++;
412         pipe->writers--;
413
414         while ((pipe->readers > 1) && (!signal_pending(current))) {
415                 wake_up_interruptible_sync(&pipe->wait);
416                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
417                 pipe_wait(pipe);
418         }
419
420         pipe->readers--;
421         pipe->writers++;
422         pipe_unlock(pipe);
423
424 }
425
426
427 /*
428  * umh_pipe_setup
429  * helper function to customize the process used
430  * to collect the core in userspace.  Specifically
431  * it sets up a pipe and installs it as fd 0 (stdin)
432  * for the process.  Returns 0 on success, or
433  * PTR_ERR on failure.
434  * Note that it also sets the core limit to 1.  This
435  * is a special value that we use to trap recursive
436  * core dumps
437  */
438 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
439 {
440         struct file *files[2];
441         struct fdtable *fdt;
442         struct coredump_params *cp = (struct coredump_params *)info->data;
443         struct files_struct *cf = current->files;
444         int err = create_pipe_files(files, 0);
445         if (err)
446                 return err;
447
448         cp->file = files[1];
449
450         sys_close(0);
451         fd_install(0, files[0]);
452         spin_lock(&cf->file_lock);
453         fdt = files_fdtable(cf);
454         __set_open_fd(0, fdt);
455         __clear_close_on_exec(0, fdt);
456         spin_unlock(&cf->file_lock);
457
458         /* and disallow core files too */
459         current->signal->rlim[RLIMIT_CORE] = (struct rlimit){1, 1};
460
461         return 0;
462 }
463
464 void do_coredump(long signr, int exit_code, struct pt_regs *regs)
465 {
466         struct core_state core_state;
467         struct core_name cn;
468         struct mm_struct *mm = current->mm;
469         struct linux_binfmt * binfmt;
470         const struct cred *old_cred;
471         struct cred *cred;
472         int retval = 0;
473         int flag = 0;
474         int ispipe;
475         bool need_nonrelative = false;
476         static atomic_t core_dump_count = ATOMIC_INIT(0);
477         struct coredump_params cprm = {
478                 .signr = signr,
479                 .regs = regs,
480                 .limit = rlimit(RLIMIT_CORE),
481                 /*
482                  * We must use the same mm->flags while dumping core to avoid
483                  * inconsistency of bit flags, since this flag is not protected
484                  * by any locks.
485                  */
486                 .mm_flags = mm->flags,
487         };
488
489         audit_core_dumps(signr);
490
491         binfmt = mm->binfmt;
492         if (!binfmt || !binfmt->core_dump)
493                 goto fail;
494         if (!__get_dumpable(cprm.mm_flags))
495                 goto fail;
496
497         cred = prepare_creds();
498         if (!cred)
499                 goto fail;
500         /*
501          * We cannot trust fsuid as being the "true" uid of the process
502          * nor do we know its entire history. We only know it was tainted
503          * so we dump it as root in mode 2, and only into a controlled
504          * environment (pipe handler or fully qualified path).
505          */
506         if (__get_dumpable(cprm.mm_flags) == SUID_DUMPABLE_SAFE) {
507                 /* Setuid core dump mode */
508                 flag = O_EXCL;          /* Stop rewrite attacks */
509                 cred->fsuid = GLOBAL_ROOT_UID;  /* Dump root private */
510                 need_nonrelative = true;
511         }
512
513         retval = coredump_wait(exit_code, &core_state);
514         if (retval < 0)
515                 goto fail_creds;
516
517         old_cred = override_creds(cred);
518
519         /*
520          * Clear any false indication of pending signals that might
521          * be seen by the filesystem code called to write the core file.
522          */
523         clear_thread_flag(TIF_SIGPENDING);
524
525         ispipe = format_corename(&cn, signr);
526
527         if (ispipe) {
528                 int dump_count;
529                 char **helper_argv;
530
531                 if (ispipe < 0) {
532                         printk(KERN_WARNING "format_corename failed\n");
533                         printk(KERN_WARNING "Aborting core\n");
534                         goto fail_corename;
535                 }
536
537                 if (cprm.limit == 1) {
538                         /* See umh_pipe_setup() which sets RLIMIT_CORE = 1.
539                          *
540                          * Normally core limits are irrelevant to pipes, since
541                          * we're not writing to the file system, but we use
542                          * cprm.limit of 1 here as a speacial value, this is a
543                          * consistent way to catch recursive crashes.
544                          * We can still crash if the core_pattern binary sets
545                          * RLIM_CORE = !1, but it runs as root, and can do
546                          * lots of stupid things.
547                          *
548                          * Note that we use task_tgid_vnr here to grab the pid
549                          * of the process group leader.  That way we get the
550                          * right pid if a thread in a multi-threaded
551                          * core_pattern process dies.
552                          */
553                         printk(KERN_WARNING
554                                 "Process %d(%s) has RLIMIT_CORE set to 1\n",
555                                 task_tgid_vnr(current), current->comm);
556                         printk(KERN_WARNING "Aborting core\n");
557                         goto fail_unlock;
558                 }
559                 cprm.limit = RLIM_INFINITY;
560
561                 dump_count = atomic_inc_return(&core_dump_count);
562                 if (core_pipe_limit && (core_pipe_limit < dump_count)) {
563                         printk(KERN_WARNING "Pid %d(%s) over core_pipe_limit\n",
564                                task_tgid_vnr(current), current->comm);
565                         printk(KERN_WARNING "Skipping core dump\n");
566                         goto fail_dropcount;
567                 }
568
569                 helper_argv = argv_split(GFP_KERNEL, cn.corename+1, NULL);
570                 if (!helper_argv) {
571                         printk(KERN_WARNING "%s failed to allocate memory\n",
572                                __func__);
573                         goto fail_dropcount;
574                 }
575
576                 retval = call_usermodehelper_fns(helper_argv[0], helper_argv,
577                                         NULL, UMH_WAIT_EXEC, umh_pipe_setup,
578                                         NULL, &cprm);
579                 argv_free(helper_argv);
580                 if (retval) {
581                         printk(KERN_INFO "Core dump to %s pipe failed\n",
582                                cn.corename);
583                         goto close_fail;
584                 }
585         } else {
586                 struct inode *inode;
587
588                 if (cprm.limit < binfmt->min_coredump)
589                         goto fail_unlock;
590
591                 if (need_nonrelative && cn.corename[0] != '/') {
592                         printk(KERN_WARNING "Pid %d(%s) can only dump core "\
593                                 "to fully qualified path!\n",
594                                 task_tgid_vnr(current), current->comm);
595                         printk(KERN_WARNING "Skipping core dump\n");
596                         goto fail_unlock;
597                 }
598
599                 cprm.file = filp_open(cn.corename,
600                                  O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE | flag,
601                                  0600);
602                 if (IS_ERR(cprm.file))
603                         goto fail_unlock;
604
605                 inode = cprm.file->f_path.dentry->d_inode;
606                 if (inode->i_nlink > 1)
607                         goto close_fail;
608                 if (d_unhashed(cprm.file->f_path.dentry))
609                         goto close_fail;
610                 /*
611                  * AK: actually i see no reason to not allow this for named
612                  * pipes etc, but keep the previous behaviour for now.
613                  */
614                 if (!S_ISREG(inode->i_mode))
615                         goto close_fail;
616                 /*
617                  * Dont allow local users get cute and trick others to coredump
618                  * into their pre-created files.
619                  */
620                 if (!uid_eq(inode->i_uid, current_fsuid()))
621                         goto close_fail;
622                 if (!cprm.file->f_op || !cprm.file->f_op->write)
623                         goto close_fail;
624                 if (do_truncate(cprm.file->f_path.dentry, 0, 0, cprm.file))
625                         goto close_fail;
626         }
627
628         retval = binfmt->core_dump(&cprm);
629         if (retval)
630                 current->signal->group_exit_code |= 0x80;
631
632         if (ispipe && core_pipe_limit)
633                 wait_for_dump_helpers(cprm.file);
634 close_fail:
635         if (cprm.file)
636                 filp_close(cprm.file, NULL);
637 fail_dropcount:
638         if (ispipe)
639                 atomic_dec(&core_dump_count);
640 fail_unlock:
641         kfree(cn.corename);
642 fail_corename:
643         coredump_finish(mm);
644         revert_creds(old_cred);
645 fail_creds:
646         put_cred(cred);
647 fail:
648         return;
649 }
650
651 /*
652  * Core dumping helper functions.  These are the only things you should
653  * do on a core-file: use only these functions to write out all the
654  * necessary info.
655  */
656 int dump_write(struct file *file, const void *addr, int nr)
657 {
658         return access_ok(VERIFY_READ, addr, nr) && file->f_op->write(file, addr, nr, &file->f_pos) == nr;
659 }
660 EXPORT_SYMBOL(dump_write);
661
662 int dump_seek(struct file *file, loff_t off)
663 {
664         int ret = 1;
665
666         if (file->f_op->llseek && file->f_op->llseek != no_llseek) {
667                 if (file->f_op->llseek(file, off, SEEK_CUR) < 0)
668                         return 0;
669         } else {
670                 char *buf = (char *)get_zeroed_page(GFP_KERNEL);
671
672                 if (!buf)
673                         return 0;
674                 while (off > 0) {
675                         unsigned long n = off;
676
677                         if (n > PAGE_SIZE)
678                                 n = PAGE_SIZE;
679                         if (!dump_write(file, buf, n)) {
680                                 ret = 0;
681                                 break;
682                         }
683                         off -= n;
684                 }
685                 free_page((unsigned long)buf);
686         }
687         return ret;
688 }
689 EXPORT_SYMBOL(dump_seek);