[PATCH] auditing ptrace
[safe/jmp/linux-2.6] / kernel / auditsc.c
1 /* auditsc.c -- System-call auditing support
2  * Handles all system-call specific auditing features.
3  *
4  * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina.
5  * Copyright 2005 Hewlett-Packard Development Company, L.P.
6  * Copyright (C) 2005, 2006 IBM Corporation
7  * All Rights Reserved.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
24  *
25  * Many of the ideas implemented here are from Stephen C. Tweedie,
26  * especially the idea of avoiding a copy by using getname.
27  *
28  * The method for actual interception of syscall entry and exit (not in
29  * this file -- see entry.S) is based on a GPL'd patch written by
30  * okir@suse.de and Copyright 2003 SuSE Linux AG.
31  *
32  * POSIX message queue support added by George Wilson <ltcgcw@us.ibm.com>,
33  * 2006.
34  *
35  * The support of additional filter rules compares (>, <, >=, <=) was
36  * added by Dustin Kirkland <dustin.kirkland@us.ibm.com>, 2005.
37  *
38  * Modified by Amy Griffis <amy.griffis@hp.com> to collect additional
39  * filesystem information.
40  *
41  * Subject and object context labeling support added by <danjones@us.ibm.com>
42  * and <dustin.kirkland@us.ibm.com> for LSPP certification compliance.
43  */
44
45 #include <linux/init.h>
46 #include <asm/types.h>
47 #include <asm/atomic.h>
48 #include <asm/types.h>
49 #include <linux/fs.h>
50 #include <linux/namei.h>
51 #include <linux/mm.h>
52 #include <linux/module.h>
53 #include <linux/mount.h>
54 #include <linux/socket.h>
55 #include <linux/mqueue.h>
56 #include <linux/audit.h>
57 #include <linux/personality.h>
58 #include <linux/time.h>
59 #include <linux/netlink.h>
60 #include <linux/compiler.h>
61 #include <asm/unistd.h>
62 #include <linux/security.h>
63 #include <linux/list.h>
64 #include <linux/tty.h>
65 #include <linux/selinux.h>
66 #include <linux/binfmts.h>
67 #include <linux/highmem.h>
68 #include <linux/syscalls.h>
69
70 #include "audit.h"
71
72 extern struct list_head audit_filter_list[];
73
74 /* No syscall auditing will take place unless audit_enabled != 0. */
75 extern int audit_enabled;
76
77 /* AUDIT_NAMES is the number of slots we reserve in the audit_context
78  * for saving names from getname(). */
79 #define AUDIT_NAMES    20
80
81 /* AUDIT_NAMES_RESERVED is the number of slots we reserve in the
82  * audit_context from being used for nameless inodes from
83  * path_lookup. */
84 #define AUDIT_NAMES_RESERVED 7
85
86 /* Indicates that audit should log the full pathname. */
87 #define AUDIT_NAME_FULL -1
88
89 /* number of audit rules */
90 int audit_n_rules;
91
92 /* When fs/namei.c:getname() is called, we store the pointer in name and
93  * we don't let putname() free it (instead we free all of the saved
94  * pointers at syscall exit time).
95  *
96  * Further, in fs/namei.c:path_lookup() we store the inode and device. */
97 struct audit_names {
98         const char      *name;
99         int             name_len;       /* number of name's characters to log */
100         unsigned        name_put;       /* call __putname() for this name */
101         unsigned long   ino;
102         dev_t           dev;
103         umode_t         mode;
104         uid_t           uid;
105         gid_t           gid;
106         dev_t           rdev;
107         u32             osid;
108 };
109
110 struct audit_aux_data {
111         struct audit_aux_data   *next;
112         int                     type;
113 };
114
115 #define AUDIT_AUX_IPCPERM       0
116
117 struct audit_aux_data_mq_open {
118         struct audit_aux_data   d;
119         int                     oflag;
120         mode_t                  mode;
121         struct mq_attr          attr;
122 };
123
124 struct audit_aux_data_mq_sendrecv {
125         struct audit_aux_data   d;
126         mqd_t                   mqdes;
127         size_t                  msg_len;
128         unsigned int            msg_prio;
129         struct timespec         abs_timeout;
130 };
131
132 struct audit_aux_data_mq_notify {
133         struct audit_aux_data   d;
134         mqd_t                   mqdes;
135         struct sigevent         notification;
136 };
137
138 struct audit_aux_data_mq_getsetattr {
139         struct audit_aux_data   d;
140         mqd_t                   mqdes;
141         struct mq_attr          mqstat;
142 };
143
144 struct audit_aux_data_ipcctl {
145         struct audit_aux_data   d;
146         struct ipc_perm         p;
147         unsigned long           qbytes;
148         uid_t                   uid;
149         gid_t                   gid;
150         mode_t                  mode;
151         u32                     osid;
152 };
153
154 struct audit_aux_data_execve {
155         struct audit_aux_data   d;
156         int argc;
157         int envc;
158         char mem[0];
159 };
160
161 struct audit_aux_data_socketcall {
162         struct audit_aux_data   d;
163         int                     nargs;
164         unsigned long           args[0];
165 };
166
167 struct audit_aux_data_sockaddr {
168         struct audit_aux_data   d;
169         int                     len;
170         char                    a[0];
171 };
172
173 struct audit_aux_data_fd_pair {
174         struct  audit_aux_data d;
175         int     fd[2];
176 };
177
178 struct audit_aux_data_path {
179         struct audit_aux_data   d;
180         struct dentry           *dentry;
181         struct vfsmount         *mnt;
182 };
183
184 /* The per-task audit context. */
185 struct audit_context {
186         int                 dummy;      /* must be the first element */
187         int                 in_syscall; /* 1 if task is in a syscall */
188         enum audit_state    state;
189         unsigned int        serial;     /* serial number for record */
190         struct timespec     ctime;      /* time of syscall entry */
191         uid_t               loginuid;   /* login uid (identity) */
192         int                 major;      /* syscall number */
193         unsigned long       argv[4];    /* syscall arguments */
194         int                 return_valid; /* return code is valid */
195         long                return_code;/* syscall return code */
196         int                 auditable;  /* 1 if record should be written */
197         int                 name_count;
198         struct audit_names  names[AUDIT_NAMES];
199         char *              filterkey;  /* key for rule that triggered record */
200         struct dentry *     pwd;
201         struct vfsmount *   pwdmnt;
202         struct audit_context *previous; /* For nested syscalls */
203         struct audit_aux_data *aux;
204
205                                 /* Save things to print about task_struct */
206         pid_t               pid, ppid;
207         uid_t               uid, euid, suid, fsuid;
208         gid_t               gid, egid, sgid, fsgid;
209         unsigned long       personality;
210         int                 arch;
211
212         pid_t               target_pid;
213         u32                 target_sid;
214
215 #if AUDIT_DEBUG
216         int                 put_count;
217         int                 ino_count;
218 #endif
219 };
220
221 #define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE])
222 static inline int open_arg(int flags, int mask)
223 {
224         int n = ACC_MODE(flags);
225         if (flags & (O_TRUNC | O_CREAT))
226                 n |= AUDIT_PERM_WRITE;
227         return n & mask;
228 }
229
230 static int audit_match_perm(struct audit_context *ctx, int mask)
231 {
232         unsigned n = ctx->major;
233         switch (audit_classify_syscall(ctx->arch, n)) {
234         case 0: /* native */
235                 if ((mask & AUDIT_PERM_WRITE) &&
236                      audit_match_class(AUDIT_CLASS_WRITE, n))
237                         return 1;
238                 if ((mask & AUDIT_PERM_READ) &&
239                      audit_match_class(AUDIT_CLASS_READ, n))
240                         return 1;
241                 if ((mask & AUDIT_PERM_ATTR) &&
242                      audit_match_class(AUDIT_CLASS_CHATTR, n))
243                         return 1;
244                 return 0;
245         case 1: /* 32bit on biarch */
246                 if ((mask & AUDIT_PERM_WRITE) &&
247                      audit_match_class(AUDIT_CLASS_WRITE_32, n))
248                         return 1;
249                 if ((mask & AUDIT_PERM_READ) &&
250                      audit_match_class(AUDIT_CLASS_READ_32, n))
251                         return 1;
252                 if ((mask & AUDIT_PERM_ATTR) &&
253                      audit_match_class(AUDIT_CLASS_CHATTR_32, n))
254                         return 1;
255                 return 0;
256         case 2: /* open */
257                 return mask & ACC_MODE(ctx->argv[1]);
258         case 3: /* openat */
259                 return mask & ACC_MODE(ctx->argv[2]);
260         case 4: /* socketcall */
261                 return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
262         case 5: /* execve */
263                 return mask & AUDIT_PERM_EXEC;
264         default:
265                 return 0;
266         }
267 }
268
269 /* Determine if any context name data matches a rule's watch data */
270 /* Compare a task_struct with an audit_rule.  Return 1 on match, 0
271  * otherwise. */
272 static int audit_filter_rules(struct task_struct *tsk,
273                               struct audit_krule *rule,
274                               struct audit_context *ctx,
275                               struct audit_names *name,
276                               enum audit_state *state)
277 {
278         int i, j, need_sid = 1;
279         u32 sid;
280
281         for (i = 0; i < rule->field_count; i++) {
282                 struct audit_field *f = &rule->fields[i];
283                 int result = 0;
284
285                 switch (f->type) {
286                 case AUDIT_PID:
287                         result = audit_comparator(tsk->pid, f->op, f->val);
288                         break;
289                 case AUDIT_PPID:
290                         if (ctx) {
291                                 if (!ctx->ppid)
292                                         ctx->ppid = sys_getppid();
293                                 result = audit_comparator(ctx->ppid, f->op, f->val);
294                         }
295                         break;
296                 case AUDIT_UID:
297                         result = audit_comparator(tsk->uid, f->op, f->val);
298                         break;
299                 case AUDIT_EUID:
300                         result = audit_comparator(tsk->euid, f->op, f->val);
301                         break;
302                 case AUDIT_SUID:
303                         result = audit_comparator(tsk->suid, f->op, f->val);
304                         break;
305                 case AUDIT_FSUID:
306                         result = audit_comparator(tsk->fsuid, f->op, f->val);
307                         break;
308                 case AUDIT_GID:
309                         result = audit_comparator(tsk->gid, f->op, f->val);
310                         break;
311                 case AUDIT_EGID:
312                         result = audit_comparator(tsk->egid, f->op, f->val);
313                         break;
314                 case AUDIT_SGID:
315                         result = audit_comparator(tsk->sgid, f->op, f->val);
316                         break;
317                 case AUDIT_FSGID:
318                         result = audit_comparator(tsk->fsgid, f->op, f->val);
319                         break;
320                 case AUDIT_PERS:
321                         result = audit_comparator(tsk->personality, f->op, f->val);
322                         break;
323                 case AUDIT_ARCH:
324                         if (ctx)
325                                 result = audit_comparator(ctx->arch, f->op, f->val);
326                         break;
327
328                 case AUDIT_EXIT:
329                         if (ctx && ctx->return_valid)
330                                 result = audit_comparator(ctx->return_code, f->op, f->val);
331                         break;
332                 case AUDIT_SUCCESS:
333                         if (ctx && ctx->return_valid) {
334                                 if (f->val)
335                                         result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
336                                 else
337                                         result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
338                         }
339                         break;
340                 case AUDIT_DEVMAJOR:
341                         if (name)
342                                 result = audit_comparator(MAJOR(name->dev),
343                                                           f->op, f->val);
344                         else if (ctx) {
345                                 for (j = 0; j < ctx->name_count; j++) {
346                                         if (audit_comparator(MAJOR(ctx->names[j].dev),  f->op, f->val)) {
347                                                 ++result;
348                                                 break;
349                                         }
350                                 }
351                         }
352                         break;
353                 case AUDIT_DEVMINOR:
354                         if (name)
355                                 result = audit_comparator(MINOR(name->dev),
356                                                           f->op, f->val);
357                         else if (ctx) {
358                                 for (j = 0; j < ctx->name_count; j++) {
359                                         if (audit_comparator(MINOR(ctx->names[j].dev), f->op, f->val)) {
360                                                 ++result;
361                                                 break;
362                                         }
363                                 }
364                         }
365                         break;
366                 case AUDIT_INODE:
367                         if (name)
368                                 result = (name->ino == f->val);
369                         else if (ctx) {
370                                 for (j = 0; j < ctx->name_count; j++) {
371                                         if (audit_comparator(ctx->names[j].ino, f->op, f->val)) {
372                                                 ++result;
373                                                 break;
374                                         }
375                                 }
376                         }
377                         break;
378                 case AUDIT_WATCH:
379                         if (name && rule->watch->ino != (unsigned long)-1)
380                                 result = (name->dev == rule->watch->dev &&
381                                           name->ino == rule->watch->ino);
382                         break;
383                 case AUDIT_LOGINUID:
384                         result = 0;
385                         if (ctx)
386                                 result = audit_comparator(ctx->loginuid, f->op, f->val);
387                         break;
388                 case AUDIT_SUBJ_USER:
389                 case AUDIT_SUBJ_ROLE:
390                 case AUDIT_SUBJ_TYPE:
391                 case AUDIT_SUBJ_SEN:
392                 case AUDIT_SUBJ_CLR:
393                         /* NOTE: this may return negative values indicating
394                            a temporary error.  We simply treat this as a
395                            match for now to avoid losing information that
396                            may be wanted.   An error message will also be
397                            logged upon error */
398                         if (f->se_rule) {
399                                 if (need_sid) {
400                                         selinux_get_task_sid(tsk, &sid);
401                                         need_sid = 0;
402                                 }
403                                 result = selinux_audit_rule_match(sid, f->type,
404                                                                   f->op,
405                                                                   f->se_rule,
406                                                                   ctx);
407                         }
408                         break;
409                 case AUDIT_OBJ_USER:
410                 case AUDIT_OBJ_ROLE:
411                 case AUDIT_OBJ_TYPE:
412                 case AUDIT_OBJ_LEV_LOW:
413                 case AUDIT_OBJ_LEV_HIGH:
414                         /* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
415                            also applies here */
416                         if (f->se_rule) {
417                                 /* Find files that match */
418                                 if (name) {
419                                         result = selinux_audit_rule_match(
420                                                    name->osid, f->type, f->op,
421                                                    f->se_rule, ctx);
422                                 } else if (ctx) {
423                                         for (j = 0; j < ctx->name_count; j++) {
424                                                 if (selinux_audit_rule_match(
425                                                       ctx->names[j].osid,
426                                                       f->type, f->op,
427                                                       f->se_rule, ctx)) {
428                                                         ++result;
429                                                         break;
430                                                 }
431                                         }
432                                 }
433                                 /* Find ipc objects that match */
434                                 if (ctx) {
435                                         struct audit_aux_data *aux;
436                                         for (aux = ctx->aux; aux;
437                                              aux = aux->next) {
438                                                 if (aux->type == AUDIT_IPC) {
439                                                         struct audit_aux_data_ipcctl *axi = (void *)aux;
440                                                         if (selinux_audit_rule_match(axi->osid, f->type, f->op, f->se_rule, ctx)) {
441                                                                 ++result;
442                                                                 break;
443                                                         }
444                                                 }
445                                         }
446                                 }
447                         }
448                         break;
449                 case AUDIT_ARG0:
450                 case AUDIT_ARG1:
451                 case AUDIT_ARG2:
452                 case AUDIT_ARG3:
453                         if (ctx)
454                                 result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
455                         break;
456                 case AUDIT_FILTERKEY:
457                         /* ignore this field for filtering */
458                         result = 1;
459                         break;
460                 case AUDIT_PERM:
461                         result = audit_match_perm(ctx, f->val);
462                         break;
463                 }
464
465                 if (!result)
466                         return 0;
467         }
468         if (rule->filterkey)
469                 ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
470         switch (rule->action) {
471         case AUDIT_NEVER:    *state = AUDIT_DISABLED;       break;
472         case AUDIT_ALWAYS:   *state = AUDIT_RECORD_CONTEXT; break;
473         }
474         return 1;
475 }
476
477 /* At process creation time, we can determine if system-call auditing is
478  * completely disabled for this task.  Since we only have the task
479  * structure at this point, we can only check uid and gid.
480  */
481 static enum audit_state audit_filter_task(struct task_struct *tsk)
482 {
483         struct audit_entry *e;
484         enum audit_state   state;
485
486         rcu_read_lock();
487         list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
488                 if (audit_filter_rules(tsk, &e->rule, NULL, NULL, &state)) {
489                         rcu_read_unlock();
490                         return state;
491                 }
492         }
493         rcu_read_unlock();
494         return AUDIT_BUILD_CONTEXT;
495 }
496
497 /* At syscall entry and exit time, this filter is called if the
498  * audit_state is not low enough that auditing cannot take place, but is
499  * also not high enough that we already know we have to write an audit
500  * record (i.e., the state is AUDIT_SETUP_CONTEXT or AUDIT_BUILD_CONTEXT).
501  */
502 static enum audit_state audit_filter_syscall(struct task_struct *tsk,
503                                              struct audit_context *ctx,
504                                              struct list_head *list)
505 {
506         struct audit_entry *e;
507         enum audit_state state;
508
509         if (audit_pid && tsk->tgid == audit_pid)
510                 return AUDIT_DISABLED;
511
512         rcu_read_lock();
513         if (!list_empty(list)) {
514                 int word = AUDIT_WORD(ctx->major);
515                 int bit  = AUDIT_BIT(ctx->major);
516
517                 list_for_each_entry_rcu(e, list, list) {
518                         if ((e->rule.mask[word] & bit) == bit &&
519                             audit_filter_rules(tsk, &e->rule, ctx, NULL,
520                                                &state)) {
521                                 rcu_read_unlock();
522                                 return state;
523                         }
524                 }
525         }
526         rcu_read_unlock();
527         return AUDIT_BUILD_CONTEXT;
528 }
529
530 /* At syscall exit time, this filter is called if any audit_names[] have been
531  * collected during syscall processing.  We only check rules in sublists at hash
532  * buckets applicable to the inode numbers in audit_names[].
533  * Regarding audit_state, same rules apply as for audit_filter_syscall().
534  */
535 enum audit_state audit_filter_inodes(struct task_struct *tsk,
536                                      struct audit_context *ctx)
537 {
538         int i;
539         struct audit_entry *e;
540         enum audit_state state;
541
542         if (audit_pid && tsk->tgid == audit_pid)
543                 return AUDIT_DISABLED;
544
545         rcu_read_lock();
546         for (i = 0; i < ctx->name_count; i++) {
547                 int word = AUDIT_WORD(ctx->major);
548                 int bit  = AUDIT_BIT(ctx->major);
549                 struct audit_names *n = &ctx->names[i];
550                 int h = audit_hash_ino((u32)n->ino);
551                 struct list_head *list = &audit_inode_hash[h];
552
553                 if (list_empty(list))
554                         continue;
555
556                 list_for_each_entry_rcu(e, list, list) {
557                         if ((e->rule.mask[word] & bit) == bit &&
558                             audit_filter_rules(tsk, &e->rule, ctx, n, &state)) {
559                                 rcu_read_unlock();
560                                 return state;
561                         }
562                 }
563         }
564         rcu_read_unlock();
565         return AUDIT_BUILD_CONTEXT;
566 }
567
568 void audit_set_auditable(struct audit_context *ctx)
569 {
570         ctx->auditable = 1;
571 }
572
573 static inline struct audit_context *audit_get_context(struct task_struct *tsk,
574                                                       int return_valid,
575                                                       int return_code)
576 {
577         struct audit_context *context = tsk->audit_context;
578
579         if (likely(!context))
580                 return NULL;
581         context->return_valid = return_valid;
582         context->return_code  = return_code;
583
584         if (context->in_syscall && !context->dummy && !context->auditable) {
585                 enum audit_state state;
586
587                 state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]);
588                 if (state == AUDIT_RECORD_CONTEXT) {
589                         context->auditable = 1;
590                         goto get_context;
591                 }
592
593                 state = audit_filter_inodes(tsk, context);
594                 if (state == AUDIT_RECORD_CONTEXT)
595                         context->auditable = 1;
596
597         }
598
599 get_context:
600
601         tsk->audit_context = NULL;
602         return context;
603 }
604
605 static inline void audit_free_names(struct audit_context *context)
606 {
607         int i;
608
609 #if AUDIT_DEBUG == 2
610         if (context->auditable
611             ||context->put_count + context->ino_count != context->name_count) {
612                 printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d"
613                        " name_count=%d put_count=%d"
614                        " ino_count=%d [NOT freeing]\n",
615                        __FILE__, __LINE__,
616                        context->serial, context->major, context->in_syscall,
617                        context->name_count, context->put_count,
618                        context->ino_count);
619                 for (i = 0; i < context->name_count; i++) {
620                         printk(KERN_ERR "names[%d] = %p = %s\n", i,
621                                context->names[i].name,
622                                context->names[i].name ?: "(null)");
623                 }
624                 dump_stack();
625                 return;
626         }
627 #endif
628 #if AUDIT_DEBUG
629         context->put_count  = 0;
630         context->ino_count  = 0;
631 #endif
632
633         for (i = 0; i < context->name_count; i++) {
634                 if (context->names[i].name && context->names[i].name_put)
635                         __putname(context->names[i].name);
636         }
637         context->name_count = 0;
638         if (context->pwd)
639                 dput(context->pwd);
640         if (context->pwdmnt)
641                 mntput(context->pwdmnt);
642         context->pwd = NULL;
643         context->pwdmnt = NULL;
644 }
645
646 static inline void audit_free_aux(struct audit_context *context)
647 {
648         struct audit_aux_data *aux;
649
650         while ((aux = context->aux)) {
651                 if (aux->type == AUDIT_AVC_PATH) {
652                         struct audit_aux_data_path *axi = (void *)aux;
653                         dput(axi->dentry);
654                         mntput(axi->mnt);
655                 }
656
657                 context->aux = aux->next;
658                 kfree(aux);
659         }
660 }
661
662 static inline void audit_zero_context(struct audit_context *context,
663                                       enum audit_state state)
664 {
665         uid_t loginuid = context->loginuid;
666
667         memset(context, 0, sizeof(*context));
668         context->state      = state;
669         context->loginuid   = loginuid;
670 }
671
672 static inline struct audit_context *audit_alloc_context(enum audit_state state)
673 {
674         struct audit_context *context;
675
676         if (!(context = kmalloc(sizeof(*context), GFP_KERNEL)))
677                 return NULL;
678         audit_zero_context(context, state);
679         return context;
680 }
681
682 /**
683  * audit_alloc - allocate an audit context block for a task
684  * @tsk: task
685  *
686  * Filter on the task information and allocate a per-task audit context
687  * if necessary.  Doing so turns on system call auditing for the
688  * specified task.  This is called from copy_process, so no lock is
689  * needed.
690  */
691 int audit_alloc(struct task_struct *tsk)
692 {
693         struct audit_context *context;
694         enum audit_state     state;
695
696         if (likely(!audit_enabled))
697                 return 0; /* Return if not auditing. */
698
699         state = audit_filter_task(tsk);
700         if (likely(state == AUDIT_DISABLED))
701                 return 0;
702
703         if (!(context = audit_alloc_context(state))) {
704                 audit_log_lost("out of memory in audit_alloc");
705                 return -ENOMEM;
706         }
707
708                                 /* Preserve login uid */
709         context->loginuid = -1;
710         if (current->audit_context)
711                 context->loginuid = current->audit_context->loginuid;
712
713         tsk->audit_context  = context;
714         set_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
715         return 0;
716 }
717
718 static inline void audit_free_context(struct audit_context *context)
719 {
720         struct audit_context *previous;
721         int                  count = 0;
722
723         do {
724                 previous = context->previous;
725                 if (previous || (count &&  count < 10)) {
726                         ++count;
727                         printk(KERN_ERR "audit(:%d): major=%d name_count=%d:"
728                                " freeing multiple contexts (%d)\n",
729                                context->serial, context->major,
730                                context->name_count, count);
731                 }
732                 audit_free_names(context);
733                 audit_free_aux(context);
734                 kfree(context->filterkey);
735                 kfree(context);
736                 context  = previous;
737         } while (context);
738         if (count >= 10)
739                 printk(KERN_ERR "audit: freed %d contexts\n", count);
740 }
741
742 void audit_log_task_context(struct audit_buffer *ab)
743 {
744         char *ctx = NULL;
745         unsigned len;
746         int error;
747         u32 sid;
748
749         selinux_get_task_sid(current, &sid);
750         if (!sid)
751                 return;
752
753         error = selinux_sid_to_string(sid, &ctx, &len);
754         if (error) {
755                 if (error != -EINVAL)
756                         goto error_path;
757                 return;
758         }
759
760         audit_log_format(ab, " subj=%s", ctx);
761         kfree(ctx);
762         return;
763
764 error_path:
765         audit_panic("error in audit_log_task_context");
766         return;
767 }
768
769 EXPORT_SYMBOL(audit_log_task_context);
770
771 static void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
772 {
773         char name[sizeof(tsk->comm)];
774         struct mm_struct *mm = tsk->mm;
775         struct vm_area_struct *vma;
776
777         /* tsk == current */
778
779         get_task_comm(name, tsk);
780         audit_log_format(ab, " comm=");
781         audit_log_untrustedstring(ab, name);
782
783         if (mm) {
784                 down_read(&mm->mmap_sem);
785                 vma = mm->mmap;
786                 while (vma) {
787                         if ((vma->vm_flags & VM_EXECUTABLE) &&
788                             vma->vm_file) {
789                                 audit_log_d_path(ab, "exe=",
790                                                  vma->vm_file->f_path.dentry,
791                                                  vma->vm_file->f_path.mnt);
792                                 break;
793                         }
794                         vma = vma->vm_next;
795                 }
796                 up_read(&mm->mmap_sem);
797         }
798         audit_log_task_context(ab);
799 }
800
801 static void audit_log_exit(struct audit_context *context, struct task_struct *tsk)
802 {
803         int i, call_panic = 0;
804         struct audit_buffer *ab;
805         struct audit_aux_data *aux;
806         const char *tty;
807
808         /* tsk == current */
809         context->pid = tsk->pid;
810         if (!context->ppid)
811                 context->ppid = sys_getppid();
812         context->uid = tsk->uid;
813         context->gid = tsk->gid;
814         context->euid = tsk->euid;
815         context->suid = tsk->suid;
816         context->fsuid = tsk->fsuid;
817         context->egid = tsk->egid;
818         context->sgid = tsk->sgid;
819         context->fsgid = tsk->fsgid;
820         context->personality = tsk->personality;
821
822         ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
823         if (!ab)
824                 return;         /* audit_panic has been called */
825         audit_log_format(ab, "arch=%x syscall=%d",
826                          context->arch, context->major);
827         if (context->personality != PER_LINUX)
828                 audit_log_format(ab, " per=%lx", context->personality);
829         if (context->return_valid)
830                 audit_log_format(ab, " success=%s exit=%ld", 
831                                  (context->return_valid==AUDITSC_SUCCESS)?"yes":"no",
832                                  context->return_code);
833
834         mutex_lock(&tty_mutex);
835         read_lock(&tasklist_lock);
836         if (tsk->signal && tsk->signal->tty && tsk->signal->tty->name)
837                 tty = tsk->signal->tty->name;
838         else
839                 tty = "(none)";
840         read_unlock(&tasklist_lock);
841         audit_log_format(ab,
842                   " a0=%lx a1=%lx a2=%lx a3=%lx items=%d"
843                   " ppid=%d pid=%d auid=%u uid=%u gid=%u"
844                   " euid=%u suid=%u fsuid=%u"
845                   " egid=%u sgid=%u fsgid=%u tty=%s",
846                   context->argv[0],
847                   context->argv[1],
848                   context->argv[2],
849                   context->argv[3],
850                   context->name_count,
851                   context->ppid,
852                   context->pid,
853                   context->loginuid,
854                   context->uid,
855                   context->gid,
856                   context->euid, context->suid, context->fsuid,
857                   context->egid, context->sgid, context->fsgid, tty);
858
859         mutex_unlock(&tty_mutex);
860
861         audit_log_task_info(ab, tsk);
862         if (context->filterkey) {
863                 audit_log_format(ab, " key=");
864                 audit_log_untrustedstring(ab, context->filterkey);
865         } else
866                 audit_log_format(ab, " key=(null)");
867         audit_log_end(ab);
868
869         for (aux = context->aux; aux; aux = aux->next) {
870
871                 ab = audit_log_start(context, GFP_KERNEL, aux->type);
872                 if (!ab)
873                         continue; /* audit_panic has been called */
874
875                 switch (aux->type) {
876                 case AUDIT_MQ_OPEN: {
877                         struct audit_aux_data_mq_open *axi = (void *)aux;
878                         audit_log_format(ab,
879                                 "oflag=0x%x mode=%#o mq_flags=0x%lx mq_maxmsg=%ld "
880                                 "mq_msgsize=%ld mq_curmsgs=%ld",
881                                 axi->oflag, axi->mode, axi->attr.mq_flags,
882                                 axi->attr.mq_maxmsg, axi->attr.mq_msgsize,
883                                 axi->attr.mq_curmsgs);
884                         break; }
885
886                 case AUDIT_MQ_SENDRECV: {
887                         struct audit_aux_data_mq_sendrecv *axi = (void *)aux;
888                         audit_log_format(ab,
889                                 "mqdes=%d msg_len=%zd msg_prio=%u "
890                                 "abs_timeout_sec=%ld abs_timeout_nsec=%ld",
891                                 axi->mqdes, axi->msg_len, axi->msg_prio,
892                                 axi->abs_timeout.tv_sec, axi->abs_timeout.tv_nsec);
893                         break; }
894
895                 case AUDIT_MQ_NOTIFY: {
896                         struct audit_aux_data_mq_notify *axi = (void *)aux;
897                         audit_log_format(ab,
898                                 "mqdes=%d sigev_signo=%d",
899                                 axi->mqdes,
900                                 axi->notification.sigev_signo);
901                         break; }
902
903                 case AUDIT_MQ_GETSETATTR: {
904                         struct audit_aux_data_mq_getsetattr *axi = (void *)aux;
905                         audit_log_format(ab,
906                                 "mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
907                                 "mq_curmsgs=%ld ",
908                                 axi->mqdes,
909                                 axi->mqstat.mq_flags, axi->mqstat.mq_maxmsg,
910                                 axi->mqstat.mq_msgsize, axi->mqstat.mq_curmsgs);
911                         break; }
912
913                 case AUDIT_IPC: {
914                         struct audit_aux_data_ipcctl *axi = (void *)aux;
915                         audit_log_format(ab, 
916                                  "ouid=%u ogid=%u mode=%x",
917                                  axi->uid, axi->gid, axi->mode);
918                         if (axi->osid != 0) {
919                                 char *ctx = NULL;
920                                 u32 len;
921                                 if (selinux_sid_to_string(
922                                                 axi->osid, &ctx, &len)) {
923                                         audit_log_format(ab, " osid=%u",
924                                                         axi->osid);
925                                         call_panic = 1;
926                                 } else
927                                         audit_log_format(ab, " obj=%s", ctx);
928                                 kfree(ctx);
929                         }
930                         break; }
931
932                 case AUDIT_IPC_SET_PERM: {
933                         struct audit_aux_data_ipcctl *axi = (void *)aux;
934                         audit_log_format(ab,
935                                 "qbytes=%lx ouid=%u ogid=%u mode=%x",
936                                 axi->qbytes, axi->uid, axi->gid, axi->mode);
937                         break; }
938
939                 case AUDIT_EXECVE: {
940                         struct audit_aux_data_execve *axi = (void *)aux;
941                         int i;
942                         const char *p;
943                         for (i = 0, p = axi->mem; i < axi->argc; i++) {
944                                 audit_log_format(ab, "a%d=", i);
945                                 p = audit_log_untrustedstring(ab, p);
946                                 audit_log_format(ab, "\n");
947                         }
948                         break; }
949
950                 case AUDIT_SOCKETCALL: {
951                         int i;
952                         struct audit_aux_data_socketcall *axs = (void *)aux;
953                         audit_log_format(ab, "nargs=%d", axs->nargs);
954                         for (i=0; i<axs->nargs; i++)
955                                 audit_log_format(ab, " a%d=%lx", i, axs->args[i]);
956                         break; }
957
958                 case AUDIT_SOCKADDR: {
959                         struct audit_aux_data_sockaddr *axs = (void *)aux;
960
961                         audit_log_format(ab, "saddr=");
962                         audit_log_hex(ab, axs->a, axs->len);
963                         break; }
964
965                 case AUDIT_AVC_PATH: {
966                         struct audit_aux_data_path *axi = (void *)aux;
967                         audit_log_d_path(ab, "path=", axi->dentry, axi->mnt);
968                         break; }
969
970                 case AUDIT_FD_PAIR: {
971                         struct audit_aux_data_fd_pair *axs = (void *)aux;
972                         audit_log_format(ab, "fd0=%d fd1=%d", axs->fd[0], axs->fd[1]);
973                         break; }
974
975                 }
976                 audit_log_end(ab);
977         }
978
979         if (context->target_pid) {
980                 ab =audit_log_start(context, GFP_KERNEL, AUDIT_OBJ_PID);
981                 if (ab) {
982                         char *s = NULL, *t;
983                         u32 len;
984                         if (selinux_sid_to_string(context->target_sid,
985                                                     &s, &len))
986                                 t = "(none)";
987                         else
988                                 t = s;
989                         audit_log_format(ab, "opid=%d obj=%s",
990                                         context->target_pid, t);
991                         audit_log_end(ab);
992                         kfree(s);
993                 }
994         }
995
996         if (context->pwd && context->pwdmnt) {
997                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
998                 if (ab) {
999                         audit_log_d_path(ab, "cwd=", context->pwd, context->pwdmnt);
1000                         audit_log_end(ab);
1001                 }
1002         }
1003         for (i = 0; i < context->name_count; i++) {
1004                 struct audit_names *n = &context->names[i];
1005
1006                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
1007                 if (!ab)
1008                         continue; /* audit_panic has been called */
1009
1010                 audit_log_format(ab, "item=%d", i);
1011
1012                 if (n->name) {
1013                         switch(n->name_len) {
1014                         case AUDIT_NAME_FULL:
1015                                 /* log the full path */
1016                                 audit_log_format(ab, " name=");
1017                                 audit_log_untrustedstring(ab, n->name);
1018                                 break;
1019                         case 0:
1020                                 /* name was specified as a relative path and the
1021                                  * directory component is the cwd */
1022                                 audit_log_d_path(ab, " name=", context->pwd,
1023                                                  context->pwdmnt);
1024                                 break;
1025                         default:
1026                                 /* log the name's directory component */
1027                                 audit_log_format(ab, " name=");
1028                                 audit_log_n_untrustedstring(ab, n->name_len,
1029                                                             n->name);
1030                         }
1031                 } else
1032                         audit_log_format(ab, " name=(null)");
1033
1034                 if (n->ino != (unsigned long)-1) {
1035                         audit_log_format(ab, " inode=%lu"
1036                                          " dev=%02x:%02x mode=%#o"
1037                                          " ouid=%u ogid=%u rdev=%02x:%02x",
1038                                          n->ino,
1039                                          MAJOR(n->dev),
1040                                          MINOR(n->dev),
1041                                          n->mode,
1042                                          n->uid,
1043                                          n->gid,
1044                                          MAJOR(n->rdev),
1045                                          MINOR(n->rdev));
1046                 }
1047                 if (n->osid != 0) {
1048                         char *ctx = NULL;
1049                         u32 len;
1050                         if (selinux_sid_to_string(
1051                                 n->osid, &ctx, &len)) {
1052                                 audit_log_format(ab, " osid=%u", n->osid);
1053                                 call_panic = 2;
1054                         } else
1055                                 audit_log_format(ab, " obj=%s", ctx);
1056                         kfree(ctx);
1057                 }
1058
1059                 audit_log_end(ab);
1060         }
1061         if (call_panic)
1062                 audit_panic("error converting sid to string");
1063 }
1064
1065 /**
1066  * audit_free - free a per-task audit context
1067  * @tsk: task whose audit context block to free
1068  *
1069  * Called from copy_process and do_exit
1070  */
1071 void audit_free(struct task_struct *tsk)
1072 {
1073         struct audit_context *context;
1074
1075         context = audit_get_context(tsk, 0, 0);
1076         if (likely(!context))
1077                 return;
1078
1079         /* Check for system calls that do not go through the exit
1080          * function (e.g., exit_group), then free context block. 
1081          * We use GFP_ATOMIC here because we might be doing this 
1082          * in the context of the idle thread */
1083         /* that can happen only if we are called from do_exit() */
1084         if (context->in_syscall && context->auditable)
1085                 audit_log_exit(context, tsk);
1086
1087         audit_free_context(context);
1088 }
1089
1090 /**
1091  * audit_syscall_entry - fill in an audit record at syscall entry
1092  * @tsk: task being audited
1093  * @arch: architecture type
1094  * @major: major syscall type (function)
1095  * @a1: additional syscall register 1
1096  * @a2: additional syscall register 2
1097  * @a3: additional syscall register 3
1098  * @a4: additional syscall register 4
1099  *
1100  * Fill in audit context at syscall entry.  This only happens if the
1101  * audit context was created when the task was created and the state or
1102  * filters demand the audit context be built.  If the state from the
1103  * per-task filter or from the per-syscall filter is AUDIT_RECORD_CONTEXT,
1104  * then the record will be written at syscall exit time (otherwise, it
1105  * will only be written if another part of the kernel requests that it
1106  * be written).
1107  */
1108 void audit_syscall_entry(int arch, int major,
1109                          unsigned long a1, unsigned long a2,
1110                          unsigned long a3, unsigned long a4)
1111 {
1112         struct task_struct *tsk = current;
1113         struct audit_context *context = tsk->audit_context;
1114         enum audit_state     state;
1115
1116         BUG_ON(!context);
1117
1118         /*
1119          * This happens only on certain architectures that make system
1120          * calls in kernel_thread via the entry.S interface, instead of
1121          * with direct calls.  (If you are porting to a new
1122          * architecture, hitting this condition can indicate that you
1123          * got the _exit/_leave calls backward in entry.S.)
1124          *
1125          * i386     no
1126          * x86_64   no
1127          * ppc64    yes (see arch/powerpc/platforms/iseries/misc.S)
1128          *
1129          * This also happens with vm86 emulation in a non-nested manner
1130          * (entries without exits), so this case must be caught.
1131          */
1132         if (context->in_syscall) {
1133                 struct audit_context *newctx;
1134
1135 #if AUDIT_DEBUG
1136                 printk(KERN_ERR
1137                        "audit(:%d) pid=%d in syscall=%d;"
1138                        " entering syscall=%d\n",
1139                        context->serial, tsk->pid, context->major, major);
1140 #endif
1141                 newctx = audit_alloc_context(context->state);
1142                 if (newctx) {
1143                         newctx->previous   = context;
1144                         context            = newctx;
1145                         tsk->audit_context = newctx;
1146                 } else  {
1147                         /* If we can't alloc a new context, the best we
1148                          * can do is to leak memory (any pending putname
1149                          * will be lost).  The only other alternative is
1150                          * to abandon auditing. */
1151                         audit_zero_context(context, context->state);
1152                 }
1153         }
1154         BUG_ON(context->in_syscall || context->name_count);
1155
1156         if (!audit_enabled)
1157                 return;
1158
1159         context->arch       = arch;
1160         context->major      = major;
1161         context->argv[0]    = a1;
1162         context->argv[1]    = a2;
1163         context->argv[2]    = a3;
1164         context->argv[3]    = a4;
1165
1166         state = context->state;
1167         context->dummy = !audit_n_rules;
1168         if (!context->dummy && (state == AUDIT_SETUP_CONTEXT || state == AUDIT_BUILD_CONTEXT))
1169                 state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]);
1170         if (likely(state == AUDIT_DISABLED))
1171                 return;
1172
1173         context->serial     = 0;
1174         context->ctime      = CURRENT_TIME;
1175         context->in_syscall = 1;
1176         context->auditable  = !!(state == AUDIT_RECORD_CONTEXT);
1177         context->ppid       = 0;
1178 }
1179
1180 /**
1181  * audit_syscall_exit - deallocate audit context after a system call
1182  * @tsk: task being audited
1183  * @valid: success/failure flag
1184  * @return_code: syscall return value
1185  *
1186  * Tear down after system call.  If the audit context has been marked as
1187  * auditable (either because of the AUDIT_RECORD_CONTEXT state from
1188  * filtering, or because some other part of the kernel write an audit
1189  * message), then write out the syscall information.  In call cases,
1190  * free the names stored from getname().
1191  */
1192 void audit_syscall_exit(int valid, long return_code)
1193 {
1194         struct task_struct *tsk = current;
1195         struct audit_context *context;
1196
1197         context = audit_get_context(tsk, valid, return_code);
1198
1199         if (likely(!context))
1200                 return;
1201
1202         if (context->in_syscall && context->auditable)
1203                 audit_log_exit(context, tsk);
1204
1205         context->in_syscall = 0;
1206         context->auditable  = 0;
1207
1208         if (context->previous) {
1209                 struct audit_context *new_context = context->previous;
1210                 context->previous  = NULL;
1211                 audit_free_context(context);
1212                 tsk->audit_context = new_context;
1213         } else {
1214                 audit_free_names(context);
1215                 audit_free_aux(context);
1216                 context->target_pid = 0;
1217                 kfree(context->filterkey);
1218                 context->filterkey = NULL;
1219                 tsk->audit_context = context;
1220         }
1221 }
1222
1223 /**
1224  * audit_getname - add a name to the list
1225  * @name: name to add
1226  *
1227  * Add a name to the list of audit names for this context.
1228  * Called from fs/namei.c:getname().
1229  */
1230 void __audit_getname(const char *name)
1231 {
1232         struct audit_context *context = current->audit_context;
1233
1234         if (IS_ERR(name) || !name)
1235                 return;
1236
1237         if (!context->in_syscall) {
1238 #if AUDIT_DEBUG == 2
1239                 printk(KERN_ERR "%s:%d(:%d): ignoring getname(%p)\n",
1240                        __FILE__, __LINE__, context->serial, name);
1241                 dump_stack();
1242 #endif
1243                 return;
1244         }
1245         BUG_ON(context->name_count >= AUDIT_NAMES);
1246         context->names[context->name_count].name = name;
1247         context->names[context->name_count].name_len = AUDIT_NAME_FULL;
1248         context->names[context->name_count].name_put = 1;
1249         context->names[context->name_count].ino  = (unsigned long)-1;
1250         ++context->name_count;
1251         if (!context->pwd) {
1252                 read_lock(&current->fs->lock);
1253                 context->pwd = dget(current->fs->pwd);
1254                 context->pwdmnt = mntget(current->fs->pwdmnt);
1255                 read_unlock(&current->fs->lock);
1256         }
1257                 
1258 }
1259
1260 /* audit_putname - intercept a putname request
1261  * @name: name to intercept and delay for putname
1262  *
1263  * If we have stored the name from getname in the audit context,
1264  * then we delay the putname until syscall exit.
1265  * Called from include/linux/fs.h:putname().
1266  */
1267 void audit_putname(const char *name)
1268 {
1269         struct audit_context *context = current->audit_context;
1270
1271         BUG_ON(!context);
1272         if (!context->in_syscall) {
1273 #if AUDIT_DEBUG == 2
1274                 printk(KERN_ERR "%s:%d(:%d): __putname(%p)\n",
1275                        __FILE__, __LINE__, context->serial, name);
1276                 if (context->name_count) {
1277                         int i;
1278                         for (i = 0; i < context->name_count; i++)
1279                                 printk(KERN_ERR "name[%d] = %p = %s\n", i,
1280                                        context->names[i].name,
1281                                        context->names[i].name ?: "(null)");
1282                 }
1283 #endif
1284                 __putname(name);
1285         }
1286 #if AUDIT_DEBUG
1287         else {
1288                 ++context->put_count;
1289                 if (context->put_count > context->name_count) {
1290                         printk(KERN_ERR "%s:%d(:%d): major=%d"
1291                                " in_syscall=%d putname(%p) name_count=%d"
1292                                " put_count=%d\n",
1293                                __FILE__, __LINE__,
1294                                context->serial, context->major,
1295                                context->in_syscall, name, context->name_count,
1296                                context->put_count);
1297                         dump_stack();
1298                 }
1299         }
1300 #endif
1301 }
1302
1303 /* Copy inode data into an audit_names. */
1304 static void audit_copy_inode(struct audit_names *name, const struct inode *inode)
1305 {
1306         name->ino   = inode->i_ino;
1307         name->dev   = inode->i_sb->s_dev;
1308         name->mode  = inode->i_mode;
1309         name->uid   = inode->i_uid;
1310         name->gid   = inode->i_gid;
1311         name->rdev  = inode->i_rdev;
1312         selinux_get_inode_sid(inode, &name->osid);
1313 }
1314
1315 /**
1316  * audit_inode - store the inode and device from a lookup
1317  * @name: name being audited
1318  * @inode: inode being audited
1319  *
1320  * Called from fs/namei.c:path_lookup().
1321  */
1322 void __audit_inode(const char *name, const struct inode *inode)
1323 {
1324         int idx;
1325         struct audit_context *context = current->audit_context;
1326
1327         if (!context->in_syscall)
1328                 return;
1329         if (context->name_count
1330             && context->names[context->name_count-1].name
1331             && context->names[context->name_count-1].name == name)
1332                 idx = context->name_count - 1;
1333         else if (context->name_count > 1
1334                  && context->names[context->name_count-2].name
1335                  && context->names[context->name_count-2].name == name)
1336                 idx = context->name_count - 2;
1337         else {
1338                 /* FIXME: how much do we care about inodes that have no
1339                  * associated name? */
1340                 if (context->name_count >= AUDIT_NAMES - AUDIT_NAMES_RESERVED)
1341                         return;
1342                 idx = context->name_count++;
1343                 context->names[idx].name = NULL;
1344 #if AUDIT_DEBUG
1345                 ++context->ino_count;
1346 #endif
1347         }
1348         audit_copy_inode(&context->names[idx], inode);
1349 }
1350
1351 /**
1352  * audit_inode_child - collect inode info for created/removed objects
1353  * @dname: inode's dentry name
1354  * @inode: inode being audited
1355  * @parent: inode of dentry parent
1356  *
1357  * For syscalls that create or remove filesystem objects, audit_inode
1358  * can only collect information for the filesystem object's parent.
1359  * This call updates the audit context with the child's information.
1360  * Syscalls that create a new filesystem object must be hooked after
1361  * the object is created.  Syscalls that remove a filesystem object
1362  * must be hooked prior, in order to capture the target inode during
1363  * unsuccessful attempts.
1364  */
1365 void __audit_inode_child(const char *dname, const struct inode *inode,
1366                          const struct inode *parent)
1367 {
1368         int idx;
1369         struct audit_context *context = current->audit_context;
1370         const char *found_name = NULL;
1371         int dirlen = 0;
1372
1373         if (!context->in_syscall)
1374                 return;
1375
1376         /* determine matching parent */
1377         if (!dname)
1378                 goto update_context;
1379         for (idx = 0; idx < context->name_count; idx++)
1380                 if (context->names[idx].ino == parent->i_ino) {
1381                         const char *name = context->names[idx].name;
1382
1383                         if (!name)
1384                                 continue;
1385
1386                         if (audit_compare_dname_path(dname, name, &dirlen) == 0) {
1387                                 context->names[idx].name_len = dirlen;
1388                                 found_name = name;
1389                                 break;
1390                         }
1391                 }
1392
1393 update_context:
1394         idx = context->name_count;
1395         if (context->name_count == AUDIT_NAMES) {
1396                 printk(KERN_DEBUG "name_count maxed and losing %s\n",
1397                         found_name ?: "(null)");
1398                 return;
1399         }
1400         context->name_count++;
1401 #if AUDIT_DEBUG
1402         context->ino_count++;
1403 #endif
1404         /* Re-use the name belonging to the slot for a matching parent directory.
1405          * All names for this context are relinquished in audit_free_names() */
1406         context->names[idx].name = found_name;
1407         context->names[idx].name_len = AUDIT_NAME_FULL;
1408         context->names[idx].name_put = 0;       /* don't call __putname() */
1409
1410         if (!inode)
1411                 context->names[idx].ino = (unsigned long)-1;
1412         else
1413                 audit_copy_inode(&context->names[idx], inode);
1414
1415         /* A parent was not found in audit_names, so copy the inode data for the
1416          * provided parent. */
1417         if (!found_name) {
1418                 idx = context->name_count;
1419                 if (context->name_count == AUDIT_NAMES) {
1420                         printk(KERN_DEBUG
1421                                 "name_count maxed and losing parent inode data: dev=%02x:%02x, inode=%lu",
1422                                 MAJOR(parent->i_sb->s_dev),
1423                                 MINOR(parent->i_sb->s_dev),
1424                                 parent->i_ino);
1425                         return;
1426                 }
1427                 context->name_count++;
1428 #if AUDIT_DEBUG
1429                 context->ino_count++;
1430 #endif
1431                 audit_copy_inode(&context->names[idx], parent);
1432         }
1433 }
1434
1435 /**
1436  * audit_inode_update - update inode info for last collected name
1437  * @inode: inode being audited
1438  *
1439  * When open() is called on an existing object with the O_CREAT flag, the inode
1440  * data audit initially collects is incorrect.  This additional hook ensures
1441  * audit has the inode data for the actual object to be opened.
1442  */
1443 void __audit_inode_update(const struct inode *inode)
1444 {
1445         struct audit_context *context = current->audit_context;
1446         int idx;
1447
1448         if (!context->in_syscall || !inode)
1449                 return;
1450
1451         if (context->name_count == 0) {
1452                 context->name_count++;
1453 #if AUDIT_DEBUG
1454                 context->ino_count++;
1455 #endif
1456         }
1457         idx = context->name_count - 1;
1458
1459         audit_copy_inode(&context->names[idx], inode);
1460 }
1461
1462 /**
1463  * auditsc_get_stamp - get local copies of audit_context values
1464  * @ctx: audit_context for the task
1465  * @t: timespec to store time recorded in the audit_context
1466  * @serial: serial value that is recorded in the audit_context
1467  *
1468  * Also sets the context as auditable.
1469  */
1470 void auditsc_get_stamp(struct audit_context *ctx,
1471                        struct timespec *t, unsigned int *serial)
1472 {
1473         if (!ctx->serial)
1474                 ctx->serial = audit_serial();
1475         t->tv_sec  = ctx->ctime.tv_sec;
1476         t->tv_nsec = ctx->ctime.tv_nsec;
1477         *serial    = ctx->serial;
1478         ctx->auditable = 1;
1479 }
1480
1481 /**
1482  * audit_set_loginuid - set a task's audit_context loginuid
1483  * @task: task whose audit context is being modified
1484  * @loginuid: loginuid value
1485  *
1486  * Returns 0.
1487  *
1488  * Called (set) from fs/proc/base.c::proc_loginuid_write().
1489  */
1490 int audit_set_loginuid(struct task_struct *task, uid_t loginuid)
1491 {
1492         struct audit_context *context = task->audit_context;
1493
1494         if (context) {
1495                 /* Only log if audit is enabled */
1496                 if (context->in_syscall) {
1497                         struct audit_buffer *ab;
1498
1499                         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_LOGIN);
1500                         if (ab) {
1501                                 audit_log_format(ab, "login pid=%d uid=%u "
1502                                         "old auid=%u new auid=%u",
1503                                         task->pid, task->uid,
1504                                         context->loginuid, loginuid);
1505                                 audit_log_end(ab);
1506                         }
1507                 }
1508                 context->loginuid = loginuid;
1509         }
1510         return 0;
1511 }
1512
1513 /**
1514  * audit_get_loginuid - get the loginuid for an audit_context
1515  * @ctx: the audit_context
1516  *
1517  * Returns the context's loginuid or -1 if @ctx is NULL.
1518  */
1519 uid_t audit_get_loginuid(struct audit_context *ctx)
1520 {
1521         return ctx ? ctx->loginuid : -1;
1522 }
1523
1524 EXPORT_SYMBOL(audit_get_loginuid);
1525
1526 /**
1527  * __audit_mq_open - record audit data for a POSIX MQ open
1528  * @oflag: open flag
1529  * @mode: mode bits
1530  * @u_attr: queue attributes
1531  *
1532  * Returns 0 for success or NULL context or < 0 on error.
1533  */
1534 int __audit_mq_open(int oflag, mode_t mode, struct mq_attr __user *u_attr)
1535 {
1536         struct audit_aux_data_mq_open *ax;
1537         struct audit_context *context = current->audit_context;
1538
1539         if (!audit_enabled)
1540                 return 0;
1541
1542         if (likely(!context))
1543                 return 0;
1544
1545         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1546         if (!ax)
1547                 return -ENOMEM;
1548
1549         if (u_attr != NULL) {
1550                 if (copy_from_user(&ax->attr, u_attr, sizeof(ax->attr))) {
1551                         kfree(ax);
1552                         return -EFAULT;
1553                 }
1554         } else
1555                 memset(&ax->attr, 0, sizeof(ax->attr));
1556
1557         ax->oflag = oflag;
1558         ax->mode = mode;
1559
1560         ax->d.type = AUDIT_MQ_OPEN;
1561         ax->d.next = context->aux;
1562         context->aux = (void *)ax;
1563         return 0;
1564 }
1565
1566 /**
1567  * __audit_mq_timedsend - record audit data for a POSIX MQ timed send
1568  * @mqdes: MQ descriptor
1569  * @msg_len: Message length
1570  * @msg_prio: Message priority
1571  * @u_abs_timeout: Message timeout in absolute time
1572  *
1573  * Returns 0 for success or NULL context or < 0 on error.
1574  */
1575 int __audit_mq_timedsend(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
1576                         const struct timespec __user *u_abs_timeout)
1577 {
1578         struct audit_aux_data_mq_sendrecv *ax;
1579         struct audit_context *context = current->audit_context;
1580
1581         if (!audit_enabled)
1582                 return 0;
1583
1584         if (likely(!context))
1585                 return 0;
1586
1587         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1588         if (!ax)
1589                 return -ENOMEM;
1590
1591         if (u_abs_timeout != NULL) {
1592                 if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
1593                         kfree(ax);
1594                         return -EFAULT;
1595                 }
1596         } else
1597                 memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
1598
1599         ax->mqdes = mqdes;
1600         ax->msg_len = msg_len;
1601         ax->msg_prio = msg_prio;
1602
1603         ax->d.type = AUDIT_MQ_SENDRECV;
1604         ax->d.next = context->aux;
1605         context->aux = (void *)ax;
1606         return 0;
1607 }
1608
1609 /**
1610  * __audit_mq_timedreceive - record audit data for a POSIX MQ timed receive
1611  * @mqdes: MQ descriptor
1612  * @msg_len: Message length
1613  * @u_msg_prio: Message priority
1614  * @u_abs_timeout: Message timeout in absolute time
1615  *
1616  * Returns 0 for success or NULL context or < 0 on error.
1617  */
1618 int __audit_mq_timedreceive(mqd_t mqdes, size_t msg_len,
1619                                 unsigned int __user *u_msg_prio,
1620                                 const struct timespec __user *u_abs_timeout)
1621 {
1622         struct audit_aux_data_mq_sendrecv *ax;
1623         struct audit_context *context = current->audit_context;
1624
1625         if (!audit_enabled)
1626                 return 0;
1627
1628         if (likely(!context))
1629                 return 0;
1630
1631         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1632         if (!ax)
1633                 return -ENOMEM;
1634
1635         if (u_msg_prio != NULL) {
1636                 if (get_user(ax->msg_prio, u_msg_prio)) {
1637                         kfree(ax);
1638                         return -EFAULT;
1639                 }
1640         } else
1641                 ax->msg_prio = 0;
1642
1643         if (u_abs_timeout != NULL) {
1644                 if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
1645                         kfree(ax);
1646                         return -EFAULT;
1647                 }
1648         } else
1649                 memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
1650
1651         ax->mqdes = mqdes;
1652         ax->msg_len = msg_len;
1653
1654         ax->d.type = AUDIT_MQ_SENDRECV;
1655         ax->d.next = context->aux;
1656         context->aux = (void *)ax;
1657         return 0;
1658 }
1659
1660 /**
1661  * __audit_mq_notify - record audit data for a POSIX MQ notify
1662  * @mqdes: MQ descriptor
1663  * @u_notification: Notification event
1664  *
1665  * Returns 0 for success or NULL context or < 0 on error.
1666  */
1667
1668 int __audit_mq_notify(mqd_t mqdes, const struct sigevent __user *u_notification)
1669 {
1670         struct audit_aux_data_mq_notify *ax;
1671         struct audit_context *context = current->audit_context;
1672
1673         if (!audit_enabled)
1674                 return 0;
1675
1676         if (likely(!context))
1677                 return 0;
1678
1679         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1680         if (!ax)
1681                 return -ENOMEM;
1682
1683         if (u_notification != NULL) {
1684                 if (copy_from_user(&ax->notification, u_notification, sizeof(ax->notification))) {
1685                         kfree(ax);
1686                         return -EFAULT;
1687                 }
1688         } else
1689                 memset(&ax->notification, 0, sizeof(ax->notification));
1690
1691         ax->mqdes = mqdes;
1692
1693         ax->d.type = AUDIT_MQ_NOTIFY;
1694         ax->d.next = context->aux;
1695         context->aux = (void *)ax;
1696         return 0;
1697 }
1698
1699 /**
1700  * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
1701  * @mqdes: MQ descriptor
1702  * @mqstat: MQ flags
1703  *
1704  * Returns 0 for success or NULL context or < 0 on error.
1705  */
1706 int __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
1707 {
1708         struct audit_aux_data_mq_getsetattr *ax;
1709         struct audit_context *context = current->audit_context;
1710
1711         if (!audit_enabled)
1712                 return 0;
1713
1714         if (likely(!context))
1715                 return 0;
1716
1717         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1718         if (!ax)
1719                 return -ENOMEM;
1720
1721         ax->mqdes = mqdes;
1722         ax->mqstat = *mqstat;
1723
1724         ax->d.type = AUDIT_MQ_GETSETATTR;
1725         ax->d.next = context->aux;
1726         context->aux = (void *)ax;
1727         return 0;
1728 }
1729
1730 /**
1731  * audit_ipc_obj - record audit data for ipc object
1732  * @ipcp: ipc permissions
1733  *
1734  * Returns 0 for success or NULL context or < 0 on error.
1735  */
1736 int __audit_ipc_obj(struct kern_ipc_perm *ipcp)
1737 {
1738         struct audit_aux_data_ipcctl *ax;
1739         struct audit_context *context = current->audit_context;
1740
1741         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1742         if (!ax)
1743                 return -ENOMEM;
1744
1745         ax->uid = ipcp->uid;
1746         ax->gid = ipcp->gid;
1747         ax->mode = ipcp->mode;
1748         selinux_get_ipc_sid(ipcp, &ax->osid);
1749
1750         ax->d.type = AUDIT_IPC;
1751         ax->d.next = context->aux;
1752         context->aux = (void *)ax;
1753         return 0;
1754 }
1755
1756 /**
1757  * audit_ipc_set_perm - record audit data for new ipc permissions
1758  * @qbytes: msgq bytes
1759  * @uid: msgq user id
1760  * @gid: msgq group id
1761  * @mode: msgq mode (permissions)
1762  *
1763  * Returns 0 for success or NULL context or < 0 on error.
1764  */
1765 int __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, mode_t mode)
1766 {
1767         struct audit_aux_data_ipcctl *ax;
1768         struct audit_context *context = current->audit_context;
1769
1770         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1771         if (!ax)
1772                 return -ENOMEM;
1773
1774         ax->qbytes = qbytes;
1775         ax->uid = uid;
1776         ax->gid = gid;
1777         ax->mode = mode;
1778
1779         ax->d.type = AUDIT_IPC_SET_PERM;
1780         ax->d.next = context->aux;
1781         context->aux = (void *)ax;
1782         return 0;
1783 }
1784
1785 int audit_bprm(struct linux_binprm *bprm)
1786 {
1787         struct audit_aux_data_execve *ax;
1788         struct audit_context *context = current->audit_context;
1789         unsigned long p, next;
1790         void *to;
1791
1792         if (likely(!audit_enabled || !context || context->dummy))
1793                 return 0;
1794
1795         ax = kmalloc(sizeof(*ax) + PAGE_SIZE * MAX_ARG_PAGES - bprm->p,
1796                                 GFP_KERNEL);
1797         if (!ax)
1798                 return -ENOMEM;
1799
1800         ax->argc = bprm->argc;
1801         ax->envc = bprm->envc;
1802         for (p = bprm->p, to = ax->mem; p < MAX_ARG_PAGES*PAGE_SIZE; p = next) {
1803                 struct page *page = bprm->page[p / PAGE_SIZE];
1804                 void *kaddr = kmap(page);
1805                 next = (p + PAGE_SIZE) & ~(PAGE_SIZE - 1);
1806                 memcpy(to, kaddr + (p & (PAGE_SIZE - 1)), next - p);
1807                 to += next - p;
1808                 kunmap(page);
1809         }
1810
1811         ax->d.type = AUDIT_EXECVE;
1812         ax->d.next = context->aux;
1813         context->aux = (void *)ax;
1814         return 0;
1815 }
1816
1817
1818 /**
1819  * audit_socketcall - record audit data for sys_socketcall
1820  * @nargs: number of args
1821  * @args: args array
1822  *
1823  * Returns 0 for success or NULL context or < 0 on error.
1824  */
1825 int audit_socketcall(int nargs, unsigned long *args)
1826 {
1827         struct audit_aux_data_socketcall *ax;
1828         struct audit_context *context = current->audit_context;
1829
1830         if (likely(!context || context->dummy))
1831                 return 0;
1832
1833         ax = kmalloc(sizeof(*ax) + nargs * sizeof(unsigned long), GFP_KERNEL);
1834         if (!ax)
1835                 return -ENOMEM;
1836
1837         ax->nargs = nargs;
1838         memcpy(ax->args, args, nargs * sizeof(unsigned long));
1839
1840         ax->d.type = AUDIT_SOCKETCALL;
1841         ax->d.next = context->aux;
1842         context->aux = (void *)ax;
1843         return 0;
1844 }
1845
1846 /**
1847  * __audit_fd_pair - record audit data for pipe and socketpair
1848  * @fd1: the first file descriptor
1849  * @fd2: the second file descriptor
1850  *
1851  * Returns 0 for success or NULL context or < 0 on error.
1852  */
1853 int __audit_fd_pair(int fd1, int fd2)
1854 {
1855         struct audit_context *context = current->audit_context;
1856         struct audit_aux_data_fd_pair *ax;
1857
1858         if (likely(!context)) {
1859                 return 0;
1860         }
1861
1862         ax = kmalloc(sizeof(*ax), GFP_KERNEL);
1863         if (!ax) {
1864                 return -ENOMEM;
1865         }
1866
1867         ax->fd[0] = fd1;
1868         ax->fd[1] = fd2;
1869
1870         ax->d.type = AUDIT_FD_PAIR;
1871         ax->d.next = context->aux;
1872         context->aux = (void *)ax;
1873         return 0;
1874 }
1875
1876 /**
1877  * audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
1878  * @len: data length in user space
1879  * @a: data address in kernel space
1880  *
1881  * Returns 0 for success or NULL context or < 0 on error.
1882  */
1883 int audit_sockaddr(int len, void *a)
1884 {
1885         struct audit_aux_data_sockaddr *ax;
1886         struct audit_context *context = current->audit_context;
1887
1888         if (likely(!context || context->dummy))
1889                 return 0;
1890
1891         ax = kmalloc(sizeof(*ax) + len, GFP_KERNEL);
1892         if (!ax)
1893                 return -ENOMEM;
1894
1895         ax->len = len;
1896         memcpy(ax->a, a, len);
1897
1898         ax->d.type = AUDIT_SOCKADDR;
1899         ax->d.next = context->aux;
1900         context->aux = (void *)ax;
1901         return 0;
1902 }
1903
1904 void __audit_ptrace(struct task_struct *t)
1905 {
1906         struct audit_context *context = current->audit_context;
1907
1908         context->target_pid = t->pid;
1909         selinux_get_task_sid(t, &context->target_sid);
1910 }
1911
1912 /**
1913  * audit_avc_path - record the granting or denial of permissions
1914  * @dentry: dentry to record
1915  * @mnt: mnt to record
1916  *
1917  * Returns 0 for success or NULL context or < 0 on error.
1918  *
1919  * Called from security/selinux/avc.c::avc_audit()
1920  */
1921 int audit_avc_path(struct dentry *dentry, struct vfsmount *mnt)
1922 {
1923         struct audit_aux_data_path *ax;
1924         struct audit_context *context = current->audit_context;
1925
1926         if (likely(!context))
1927                 return 0;
1928
1929         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1930         if (!ax)
1931                 return -ENOMEM;
1932
1933         ax->dentry = dget(dentry);
1934         ax->mnt = mntget(mnt);
1935
1936         ax->d.type = AUDIT_AVC_PATH;
1937         ax->d.next = context->aux;
1938         context->aux = (void *)ax;
1939         return 0;
1940 }
1941
1942 /**
1943  * audit_signal_info - record signal info for shutting down audit subsystem
1944  * @sig: signal value
1945  * @t: task being signaled
1946  *
1947  * If the audit subsystem is being terminated, record the task (pid)
1948  * and uid that is doing that.
1949  */
1950 void __audit_signal_info(int sig, struct task_struct *t)
1951 {
1952         extern pid_t audit_sig_pid;
1953         extern uid_t audit_sig_uid;
1954         extern u32 audit_sig_sid;
1955
1956         if (sig == SIGTERM || sig == SIGHUP || sig == SIGUSR1) {
1957                 struct task_struct *tsk = current;
1958                 struct audit_context *ctx = tsk->audit_context;
1959                 audit_sig_pid = tsk->pid;
1960                 if (ctx)
1961                         audit_sig_uid = ctx->loginuid;
1962                 else
1963                         audit_sig_uid = tsk->uid;
1964                 selinux_get_task_sid(tsk, &audit_sig_sid);
1965         }
1966 }