[PATCH 1/2] audit: move extern declarations to audit.h
[linux-flexiantxendom0-natty.git] / 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 <linux/fs.h>
49 #include <linux/namei.h>
50 #include <linux/mm.h>
51 #include <linux/module.h>
52 #include <linux/mount.h>
53 #include <linux/socket.h>
54 #include <linux/mqueue.h>
55 #include <linux/audit.h>
56 #include <linux/personality.h>
57 #include <linux/time.h>
58 #include <linux/netlink.h>
59 #include <linux/compiler.h>
60 #include <asm/unistd.h>
61 #include <linux/security.h>
62 #include <linux/list.h>
63 #include <linux/tty.h>
64 #include <linux/binfmts.h>
65 #include <linux/highmem.h>
66 #include <linux/syscalls.h>
67 #include <linux/inotify.h>
68
69 #include "audit.h"
70
71 /* AUDIT_NAMES is the number of slots we reserve in the audit_context
72  * for saving names from getname(). */
73 #define AUDIT_NAMES    20
74
75 /* Indicates that audit should log the full pathname. */
76 #define AUDIT_NAME_FULL -1
77
78 /* no execve audit message should be longer than this (userspace limits) */
79 #define MAX_EXECVE_AUDIT_LEN 7500
80
81 /* number of audit rules */
82 int audit_n_rules;
83
84 /* determines whether we collect data for signals sent */
85 int audit_signals;
86
87 /* When fs/namei.c:getname() is called, we store the pointer in name and
88  * we don't let putname() free it (instead we free all of the saved
89  * pointers at syscall exit time).
90  *
91  * Further, in fs/namei.c:path_lookup() we store the inode and device. */
92 struct audit_names {
93         const char      *name;
94         int             name_len;       /* number of name's characters to log */
95         unsigned        name_put;       /* call __putname() for this name */
96         unsigned long   ino;
97         dev_t           dev;
98         umode_t         mode;
99         uid_t           uid;
100         gid_t           gid;
101         dev_t           rdev;
102         u32             osid;
103 };
104
105 struct audit_aux_data {
106         struct audit_aux_data   *next;
107         int                     type;
108 };
109
110 #define AUDIT_AUX_IPCPERM       0
111
112 /* Number of target pids per aux struct. */
113 #define AUDIT_AUX_PIDS  16
114
115 struct audit_aux_data_mq_open {
116         struct audit_aux_data   d;
117         int                     oflag;
118         mode_t                  mode;
119         struct mq_attr          attr;
120 };
121
122 struct audit_aux_data_mq_sendrecv {
123         struct audit_aux_data   d;
124         mqd_t                   mqdes;
125         size_t                  msg_len;
126         unsigned int            msg_prio;
127         struct timespec         abs_timeout;
128 };
129
130 struct audit_aux_data_mq_notify {
131         struct audit_aux_data   d;
132         mqd_t                   mqdes;
133         struct sigevent         notification;
134 };
135
136 struct audit_aux_data_mq_getsetattr {
137         struct audit_aux_data   d;
138         mqd_t                   mqdes;
139         struct mq_attr          mqstat;
140 };
141
142 struct audit_aux_data_ipcctl {
143         struct audit_aux_data   d;
144         struct ipc_perm         p;
145         unsigned long           qbytes;
146         uid_t                   uid;
147         gid_t                   gid;
148         mode_t                  mode;
149         u32                     osid;
150 };
151
152 struct audit_aux_data_execve {
153         struct audit_aux_data   d;
154         int argc;
155         int envc;
156         struct mm_struct *mm;
157 };
158
159 struct audit_aux_data_socketcall {
160         struct audit_aux_data   d;
161         int                     nargs;
162         unsigned long           args[0];
163 };
164
165 struct audit_aux_data_sockaddr {
166         struct audit_aux_data   d;
167         int                     len;
168         char                    a[0];
169 };
170
171 struct audit_aux_data_fd_pair {
172         struct  audit_aux_data d;
173         int     fd[2];
174 };
175
176 struct audit_aux_data_pids {
177         struct audit_aux_data   d;
178         pid_t                   target_pid[AUDIT_AUX_PIDS];
179         uid_t                   target_auid[AUDIT_AUX_PIDS];
180         uid_t                   target_uid[AUDIT_AUX_PIDS];
181         unsigned int            target_sessionid[AUDIT_AUX_PIDS];
182         u32                     target_sid[AUDIT_AUX_PIDS];
183         char                    target_comm[AUDIT_AUX_PIDS][TASK_COMM_LEN];
184         int                     pid_count;
185 };
186
187 struct audit_tree_refs {
188         struct audit_tree_refs *next;
189         struct audit_chunk *c[31];
190 };
191
192 /* The per-task audit context. */
193 struct audit_context {
194         int                 dummy;      /* must be the first element */
195         int                 in_syscall; /* 1 if task is in a syscall */
196         enum audit_state    state;
197         unsigned int        serial;     /* serial number for record */
198         struct timespec     ctime;      /* time of syscall entry */
199         int                 major;      /* syscall number */
200         unsigned long       argv[4];    /* syscall arguments */
201         int                 return_valid; /* return code is valid */
202         long                return_code;/* syscall return code */
203         int                 auditable;  /* 1 if record should be written */
204         int                 name_count;
205         struct audit_names  names[AUDIT_NAMES];
206         char *              filterkey;  /* key for rule that triggered record */
207         struct path         pwd;
208         struct audit_context *previous; /* For nested syscalls */
209         struct audit_aux_data *aux;
210         struct audit_aux_data *aux_pids;
211
212                                 /* Save things to print about task_struct */
213         pid_t               pid, ppid;
214         uid_t               uid, euid, suid, fsuid;
215         gid_t               gid, egid, sgid, fsgid;
216         unsigned long       personality;
217         int                 arch;
218
219         pid_t               target_pid;
220         uid_t               target_auid;
221         uid_t               target_uid;
222         unsigned int        target_sessionid;
223         u32                 target_sid;
224         char                target_comm[TASK_COMM_LEN];
225
226         struct audit_tree_refs *trees, *first_trees;
227         int tree_count;
228
229 #if AUDIT_DEBUG
230         int                 put_count;
231         int                 ino_count;
232 #endif
233 };
234
235 #define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE])
236 static inline int open_arg(int flags, int mask)
237 {
238         int n = ACC_MODE(flags);
239         if (flags & (O_TRUNC | O_CREAT))
240                 n |= AUDIT_PERM_WRITE;
241         return n & mask;
242 }
243
244 static int audit_match_perm(struct audit_context *ctx, int mask)
245 {
246         unsigned n = ctx->major;
247         switch (audit_classify_syscall(ctx->arch, n)) {
248         case 0: /* native */
249                 if ((mask & AUDIT_PERM_WRITE) &&
250                      audit_match_class(AUDIT_CLASS_WRITE, n))
251                         return 1;
252                 if ((mask & AUDIT_PERM_READ) &&
253                      audit_match_class(AUDIT_CLASS_READ, n))
254                         return 1;
255                 if ((mask & AUDIT_PERM_ATTR) &&
256                      audit_match_class(AUDIT_CLASS_CHATTR, n))
257                         return 1;
258                 return 0;
259         case 1: /* 32bit on biarch */
260                 if ((mask & AUDIT_PERM_WRITE) &&
261                      audit_match_class(AUDIT_CLASS_WRITE_32, n))
262                         return 1;
263                 if ((mask & AUDIT_PERM_READ) &&
264                      audit_match_class(AUDIT_CLASS_READ_32, n))
265                         return 1;
266                 if ((mask & AUDIT_PERM_ATTR) &&
267                      audit_match_class(AUDIT_CLASS_CHATTR_32, n))
268                         return 1;
269                 return 0;
270         case 2: /* open */
271                 return mask & ACC_MODE(ctx->argv[1]);
272         case 3: /* openat */
273                 return mask & ACC_MODE(ctx->argv[2]);
274         case 4: /* socketcall */
275                 return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
276         case 5: /* execve */
277                 return mask & AUDIT_PERM_EXEC;
278         default:
279                 return 0;
280         }
281 }
282
283 /*
284  * We keep a linked list of fixed-sized (31 pointer) arrays of audit_chunk *;
285  * ->first_trees points to its beginning, ->trees - to the current end of data.
286  * ->tree_count is the number of free entries in array pointed to by ->trees.
287  * Original condition is (NULL, NULL, 0); as soon as it grows we never revert to NULL,
288  * "empty" becomes (p, p, 31) afterwards.  We don't shrink the list (and seriously,
289  * it's going to remain 1-element for almost any setup) until we free context itself.
290  * References in it _are_ dropped - at the same time we free/drop aux stuff.
291  */
292
293 #ifdef CONFIG_AUDIT_TREE
294 static int put_tree_ref(struct audit_context *ctx, struct audit_chunk *chunk)
295 {
296         struct audit_tree_refs *p = ctx->trees;
297         int left = ctx->tree_count;
298         if (likely(left)) {
299                 p->c[--left] = chunk;
300                 ctx->tree_count = left;
301                 return 1;
302         }
303         if (!p)
304                 return 0;
305         p = p->next;
306         if (p) {
307                 p->c[30] = chunk;
308                 ctx->trees = p;
309                 ctx->tree_count = 30;
310                 return 1;
311         }
312         return 0;
313 }
314
315 static int grow_tree_refs(struct audit_context *ctx)
316 {
317         struct audit_tree_refs *p = ctx->trees;
318         ctx->trees = kzalloc(sizeof(struct audit_tree_refs), GFP_KERNEL);
319         if (!ctx->trees) {
320                 ctx->trees = p;
321                 return 0;
322         }
323         if (p)
324                 p->next = ctx->trees;
325         else
326                 ctx->first_trees = ctx->trees;
327         ctx->tree_count = 31;
328         return 1;
329 }
330 #endif
331
332 static void unroll_tree_refs(struct audit_context *ctx,
333                       struct audit_tree_refs *p, int count)
334 {
335 #ifdef CONFIG_AUDIT_TREE
336         struct audit_tree_refs *q;
337         int n;
338         if (!p) {
339                 /* we started with empty chain */
340                 p = ctx->first_trees;
341                 count = 31;
342                 /* if the very first allocation has failed, nothing to do */
343                 if (!p)
344                         return;
345         }
346         n = count;
347         for (q = p; q != ctx->trees; q = q->next, n = 31) {
348                 while (n--) {
349                         audit_put_chunk(q->c[n]);
350                         q->c[n] = NULL;
351                 }
352         }
353         while (n-- > ctx->tree_count) {
354                 audit_put_chunk(q->c[n]);
355                 q->c[n] = NULL;
356         }
357         ctx->trees = p;
358         ctx->tree_count = count;
359 #endif
360 }
361
362 static void free_tree_refs(struct audit_context *ctx)
363 {
364         struct audit_tree_refs *p, *q;
365         for (p = ctx->first_trees; p; p = q) {
366                 q = p->next;
367                 kfree(p);
368         }
369 }
370
371 static int match_tree_refs(struct audit_context *ctx, struct audit_tree *tree)
372 {
373 #ifdef CONFIG_AUDIT_TREE
374         struct audit_tree_refs *p;
375         int n;
376         if (!tree)
377                 return 0;
378         /* full ones */
379         for (p = ctx->first_trees; p != ctx->trees; p = p->next) {
380                 for (n = 0; n < 31; n++)
381                         if (audit_tree_match(p->c[n], tree))
382                                 return 1;
383         }
384         /* partial */
385         if (p) {
386                 for (n = ctx->tree_count; n < 31; n++)
387                         if (audit_tree_match(p->c[n], tree))
388                                 return 1;
389         }
390 #endif
391         return 0;
392 }
393
394 /* Determine if any context name data matches a rule's watch data */
395 /* Compare a task_struct with an audit_rule.  Return 1 on match, 0
396  * otherwise. */
397 static int audit_filter_rules(struct task_struct *tsk,
398                               struct audit_krule *rule,
399                               struct audit_context *ctx,
400                               struct audit_names *name,
401                               enum audit_state *state)
402 {
403         int i, j, need_sid = 1;
404         u32 sid;
405
406         for (i = 0; i < rule->field_count; i++) {
407                 struct audit_field *f = &rule->fields[i];
408                 int result = 0;
409
410                 switch (f->type) {
411                 case AUDIT_PID:
412                         result = audit_comparator(tsk->pid, f->op, f->val);
413                         break;
414                 case AUDIT_PPID:
415                         if (ctx) {
416                                 if (!ctx->ppid)
417                                         ctx->ppid = sys_getppid();
418                                 result = audit_comparator(ctx->ppid, f->op, f->val);
419                         }
420                         break;
421                 case AUDIT_UID:
422                         result = audit_comparator(tsk->uid, f->op, f->val);
423                         break;
424                 case AUDIT_EUID:
425                         result = audit_comparator(tsk->euid, f->op, f->val);
426                         break;
427                 case AUDIT_SUID:
428                         result = audit_comparator(tsk->suid, f->op, f->val);
429                         break;
430                 case AUDIT_FSUID:
431                         result = audit_comparator(tsk->fsuid, f->op, f->val);
432                         break;
433                 case AUDIT_GID:
434                         result = audit_comparator(tsk->gid, f->op, f->val);
435                         break;
436                 case AUDIT_EGID:
437                         result = audit_comparator(tsk->egid, f->op, f->val);
438                         break;
439                 case AUDIT_SGID:
440                         result = audit_comparator(tsk->sgid, f->op, f->val);
441                         break;
442                 case AUDIT_FSGID:
443                         result = audit_comparator(tsk->fsgid, f->op, f->val);
444                         break;
445                 case AUDIT_PERS:
446                         result = audit_comparator(tsk->personality, f->op, f->val);
447                         break;
448                 case AUDIT_ARCH:
449                         if (ctx)
450                                 result = audit_comparator(ctx->arch, f->op, f->val);
451                         break;
452
453                 case AUDIT_EXIT:
454                         if (ctx && ctx->return_valid)
455                                 result = audit_comparator(ctx->return_code, f->op, f->val);
456                         break;
457                 case AUDIT_SUCCESS:
458                         if (ctx && ctx->return_valid) {
459                                 if (f->val)
460                                         result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
461                                 else
462                                         result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
463                         }
464                         break;
465                 case AUDIT_DEVMAJOR:
466                         if (name)
467                                 result = audit_comparator(MAJOR(name->dev),
468                                                           f->op, f->val);
469                         else if (ctx) {
470                                 for (j = 0; j < ctx->name_count; j++) {
471                                         if (audit_comparator(MAJOR(ctx->names[j].dev),  f->op, f->val)) {
472                                                 ++result;
473                                                 break;
474                                         }
475                                 }
476                         }
477                         break;
478                 case AUDIT_DEVMINOR:
479                         if (name)
480                                 result = audit_comparator(MINOR(name->dev),
481                                                           f->op, f->val);
482                         else if (ctx) {
483                                 for (j = 0; j < ctx->name_count; j++) {
484                                         if (audit_comparator(MINOR(ctx->names[j].dev), f->op, f->val)) {
485                                                 ++result;
486                                                 break;
487                                         }
488                                 }
489                         }
490                         break;
491                 case AUDIT_INODE:
492                         if (name)
493                                 result = (name->ino == f->val);
494                         else if (ctx) {
495                                 for (j = 0; j < ctx->name_count; j++) {
496                                         if (audit_comparator(ctx->names[j].ino, f->op, f->val)) {
497                                                 ++result;
498                                                 break;
499                                         }
500                                 }
501                         }
502                         break;
503                 case AUDIT_WATCH:
504                         if (name && rule->watch->ino != (unsigned long)-1)
505                                 result = (name->dev == rule->watch->dev &&
506                                           name->ino == rule->watch->ino);
507                         break;
508                 case AUDIT_DIR:
509                         if (ctx)
510                                 result = match_tree_refs(ctx, rule->tree);
511                         break;
512                 case AUDIT_LOGINUID:
513                         result = 0;
514                         if (ctx)
515                                 result = audit_comparator(tsk->loginuid, f->op, f->val);
516                         break;
517                 case AUDIT_SUBJ_USER:
518                 case AUDIT_SUBJ_ROLE:
519                 case AUDIT_SUBJ_TYPE:
520                 case AUDIT_SUBJ_SEN:
521                 case AUDIT_SUBJ_CLR:
522                         /* NOTE: this may return negative values indicating
523                            a temporary error.  We simply treat this as a
524                            match for now to avoid losing information that
525                            may be wanted.   An error message will also be
526                            logged upon error */
527                         if (f->lsm_rule) {
528                                 if (need_sid) {
529                                         security_task_getsecid(tsk, &sid);
530                                         need_sid = 0;
531                                 }
532                                 result = security_audit_rule_match(sid, f->type,
533                                                                   f->op,
534                                                                   f->lsm_rule,
535                                                                   ctx);
536                         }
537                         break;
538                 case AUDIT_OBJ_USER:
539                 case AUDIT_OBJ_ROLE:
540                 case AUDIT_OBJ_TYPE:
541                 case AUDIT_OBJ_LEV_LOW:
542                 case AUDIT_OBJ_LEV_HIGH:
543                         /* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
544                            also applies here */
545                         if (f->lsm_rule) {
546                                 /* Find files that match */
547                                 if (name) {
548                                         result = security_audit_rule_match(
549                                                    name->osid, f->type, f->op,
550                                                    f->lsm_rule, ctx);
551                                 } else if (ctx) {
552                                         for (j = 0; j < ctx->name_count; j++) {
553                                                 if (security_audit_rule_match(
554                                                       ctx->names[j].osid,
555                                                       f->type, f->op,
556                                                       f->lsm_rule, ctx)) {
557                                                         ++result;
558                                                         break;
559                                                 }
560                                         }
561                                 }
562                                 /* Find ipc objects that match */
563                                 if (ctx) {
564                                         struct audit_aux_data *aux;
565                                         for (aux = ctx->aux; aux;
566                                              aux = aux->next) {
567                                                 if (aux->type == AUDIT_IPC) {
568                                                         struct audit_aux_data_ipcctl *axi = (void *)aux;
569                                                         if (security_audit_rule_match(axi->osid, f->type, f->op, f->lsm_rule, ctx)) {
570                                                                 ++result;
571                                                                 break;
572                                                         }
573                                                 }
574                                         }
575                                 }
576                         }
577                         break;
578                 case AUDIT_ARG0:
579                 case AUDIT_ARG1:
580                 case AUDIT_ARG2:
581                 case AUDIT_ARG3:
582                         if (ctx)
583                                 result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
584                         break;
585                 case AUDIT_FILTERKEY:
586                         /* ignore this field for filtering */
587                         result = 1;
588                         break;
589                 case AUDIT_PERM:
590                         result = audit_match_perm(ctx, f->val);
591                         break;
592                 }
593
594                 if (!result)
595                         return 0;
596         }
597         if (rule->filterkey)
598                 ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
599         switch (rule->action) {
600         case AUDIT_NEVER:    *state = AUDIT_DISABLED;       break;
601         case AUDIT_ALWAYS:   *state = AUDIT_RECORD_CONTEXT; break;
602         }
603         return 1;
604 }
605
606 /* At process creation time, we can determine if system-call auditing is
607  * completely disabled for this task.  Since we only have the task
608  * structure at this point, we can only check uid and gid.
609  */
610 static enum audit_state audit_filter_task(struct task_struct *tsk)
611 {
612         struct audit_entry *e;
613         enum audit_state   state;
614
615         rcu_read_lock();
616         list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
617                 if (audit_filter_rules(tsk, &e->rule, NULL, NULL, &state)) {
618                         rcu_read_unlock();
619                         return state;
620                 }
621         }
622         rcu_read_unlock();
623         return AUDIT_BUILD_CONTEXT;
624 }
625
626 /* At syscall entry and exit time, this filter is called if the
627  * audit_state is not low enough that auditing cannot take place, but is
628  * also not high enough that we already know we have to write an audit
629  * record (i.e., the state is AUDIT_SETUP_CONTEXT or AUDIT_BUILD_CONTEXT).
630  */
631 static enum audit_state audit_filter_syscall(struct task_struct *tsk,
632                                              struct audit_context *ctx,
633                                              struct list_head *list)
634 {
635         struct audit_entry *e;
636         enum audit_state state;
637
638         if (audit_pid && tsk->tgid == audit_pid)
639                 return AUDIT_DISABLED;
640
641         rcu_read_lock();
642         if (!list_empty(list)) {
643                 int word = AUDIT_WORD(ctx->major);
644                 int bit  = AUDIT_BIT(ctx->major);
645
646                 list_for_each_entry_rcu(e, list, list) {
647                         if ((e->rule.mask[word] & bit) == bit &&
648                             audit_filter_rules(tsk, &e->rule, ctx, NULL,
649                                                &state)) {
650                                 rcu_read_unlock();
651                                 return state;
652                         }
653                 }
654         }
655         rcu_read_unlock();
656         return AUDIT_BUILD_CONTEXT;
657 }
658
659 /* At syscall exit time, this filter is called if any audit_names[] have been
660  * collected during syscall processing.  We only check rules in sublists at hash
661  * buckets applicable to the inode numbers in audit_names[].
662  * Regarding audit_state, same rules apply as for audit_filter_syscall().
663  */
664 enum audit_state audit_filter_inodes(struct task_struct *tsk,
665                                      struct audit_context *ctx)
666 {
667         int i;
668         struct audit_entry *e;
669         enum audit_state state;
670
671         if (audit_pid && tsk->tgid == audit_pid)
672                 return AUDIT_DISABLED;
673
674         rcu_read_lock();
675         for (i = 0; i < ctx->name_count; i++) {
676                 int word = AUDIT_WORD(ctx->major);
677                 int bit  = AUDIT_BIT(ctx->major);
678                 struct audit_names *n = &ctx->names[i];
679                 int h = audit_hash_ino((u32)n->ino);
680                 struct list_head *list = &audit_inode_hash[h];
681
682                 if (list_empty(list))
683                         continue;
684
685                 list_for_each_entry_rcu(e, list, list) {
686                         if ((e->rule.mask[word] & bit) == bit &&
687                             audit_filter_rules(tsk, &e->rule, ctx, n, &state)) {
688                                 rcu_read_unlock();
689                                 return state;
690                         }
691                 }
692         }
693         rcu_read_unlock();
694         return AUDIT_BUILD_CONTEXT;
695 }
696
697 void audit_set_auditable(struct audit_context *ctx)
698 {
699         ctx->auditable = 1;
700 }
701
702 static inline struct audit_context *audit_get_context(struct task_struct *tsk,
703                                                       int return_valid,
704                                                       int return_code)
705 {
706         struct audit_context *context = tsk->audit_context;
707
708         if (likely(!context))
709                 return NULL;
710         context->return_valid = return_valid;
711
712         /*
713          * we need to fix up the return code in the audit logs if the actual
714          * return codes are later going to be fixed up by the arch specific
715          * signal handlers
716          *
717          * This is actually a test for:
718          * (rc == ERESTARTSYS ) || (rc == ERESTARTNOINTR) ||
719          * (rc == ERESTARTNOHAND) || (rc == ERESTART_RESTARTBLOCK)
720          *
721          * but is faster than a bunch of ||
722          */
723         if (unlikely(return_code <= -ERESTARTSYS) &&
724             (return_code >= -ERESTART_RESTARTBLOCK) &&
725             (return_code != -ENOIOCTLCMD))
726                 context->return_code = -EINTR;
727         else
728                 context->return_code  = return_code;
729
730         if (context->in_syscall && !context->dummy && !context->auditable) {
731                 enum audit_state state;
732
733                 state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]);
734                 if (state == AUDIT_RECORD_CONTEXT) {
735                         context->auditable = 1;
736                         goto get_context;
737                 }
738
739                 state = audit_filter_inodes(tsk, context);
740                 if (state == AUDIT_RECORD_CONTEXT)
741                         context->auditable = 1;
742
743         }
744
745 get_context:
746
747         tsk->audit_context = NULL;
748         return context;
749 }
750
751 static inline void audit_free_names(struct audit_context *context)
752 {
753         int i;
754
755 #if AUDIT_DEBUG == 2
756         if (context->auditable
757             ||context->put_count + context->ino_count != context->name_count) {
758                 printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d"
759                        " name_count=%d put_count=%d"
760                        " ino_count=%d [NOT freeing]\n",
761                        __FILE__, __LINE__,
762                        context->serial, context->major, context->in_syscall,
763                        context->name_count, context->put_count,
764                        context->ino_count);
765                 for (i = 0; i < context->name_count; i++) {
766                         printk(KERN_ERR "names[%d] = %p = %s\n", i,
767                                context->names[i].name,
768                                context->names[i].name ?: "(null)");
769                 }
770                 dump_stack();
771                 return;
772         }
773 #endif
774 #if AUDIT_DEBUG
775         context->put_count  = 0;
776         context->ino_count  = 0;
777 #endif
778
779         for (i = 0; i < context->name_count; i++) {
780                 if (context->names[i].name && context->names[i].name_put)
781                         __putname(context->names[i].name);
782         }
783         context->name_count = 0;
784         path_put(&context->pwd);
785         context->pwd.dentry = NULL;
786         context->pwd.mnt = NULL;
787 }
788
789 static inline void audit_free_aux(struct audit_context *context)
790 {
791         struct audit_aux_data *aux;
792
793         while ((aux = context->aux)) {
794                 context->aux = aux->next;
795                 kfree(aux);
796         }
797         while ((aux = context->aux_pids)) {
798                 context->aux_pids = aux->next;
799                 kfree(aux);
800         }
801 }
802
803 static inline void audit_zero_context(struct audit_context *context,
804                                       enum audit_state state)
805 {
806         memset(context, 0, sizeof(*context));
807         context->state      = state;
808 }
809
810 static inline struct audit_context *audit_alloc_context(enum audit_state state)
811 {
812         struct audit_context *context;
813
814         if (!(context = kmalloc(sizeof(*context), GFP_KERNEL)))
815                 return NULL;
816         audit_zero_context(context, state);
817         return context;
818 }
819
820 /**
821  * audit_alloc - allocate an audit context block for a task
822  * @tsk: task
823  *
824  * Filter on the task information and allocate a per-task audit context
825  * if necessary.  Doing so turns on system call auditing for the
826  * specified task.  This is called from copy_process, so no lock is
827  * needed.
828  */
829 int audit_alloc(struct task_struct *tsk)
830 {
831         struct audit_context *context;
832         enum audit_state     state;
833
834         if (likely(!audit_ever_enabled))
835                 return 0; /* Return if not auditing. */
836
837         state = audit_filter_task(tsk);
838         if (likely(state == AUDIT_DISABLED))
839                 return 0;
840
841         if (!(context = audit_alloc_context(state))) {
842                 audit_log_lost("out of memory in audit_alloc");
843                 return -ENOMEM;
844         }
845
846         tsk->audit_context  = context;
847         set_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
848         return 0;
849 }
850
851 static inline void audit_free_context(struct audit_context *context)
852 {
853         struct audit_context *previous;
854         int                  count = 0;
855
856         do {
857                 previous = context->previous;
858                 if (previous || (count &&  count < 10)) {
859                         ++count;
860                         printk(KERN_ERR "audit(:%d): major=%d name_count=%d:"
861                                " freeing multiple contexts (%d)\n",
862                                context->serial, context->major,
863                                context->name_count, count);
864                 }
865                 audit_free_names(context);
866                 unroll_tree_refs(context, NULL, 0);
867                 free_tree_refs(context);
868                 audit_free_aux(context);
869                 kfree(context->filterkey);
870                 kfree(context);
871                 context  = previous;
872         } while (context);
873         if (count >= 10)
874                 printk(KERN_ERR "audit: freed %d contexts\n", count);
875 }
876
877 void audit_log_task_context(struct audit_buffer *ab)
878 {
879         char *ctx = NULL;
880         unsigned len;
881         int error;
882         u32 sid;
883
884         security_task_getsecid(current, &sid);
885         if (!sid)
886                 return;
887
888         error = security_secid_to_secctx(sid, &ctx, &len);
889         if (error) {
890                 if (error != -EINVAL)
891                         goto error_path;
892                 return;
893         }
894
895         audit_log_format(ab, " subj=%s", ctx);
896         security_release_secctx(ctx, len);
897         return;
898
899 error_path:
900         audit_panic("error in audit_log_task_context");
901         return;
902 }
903
904 EXPORT_SYMBOL(audit_log_task_context);
905
906 static void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
907 {
908         char name[sizeof(tsk->comm)];
909         struct mm_struct *mm = tsk->mm;
910         struct vm_area_struct *vma;
911
912         /* tsk == current */
913
914         get_task_comm(name, tsk);
915         audit_log_format(ab, " comm=");
916         audit_log_untrustedstring(ab, name);
917
918         if (mm) {
919                 down_read(&mm->mmap_sem);
920                 vma = mm->mmap;
921                 while (vma) {
922                         if ((vma->vm_flags & VM_EXECUTABLE) &&
923                             vma->vm_file) {
924                                 audit_log_d_path(ab, "exe=",
925                                                  &vma->vm_file->f_path);
926                                 break;
927                         }
928                         vma = vma->vm_next;
929                 }
930                 up_read(&mm->mmap_sem);
931         }
932         audit_log_task_context(ab);
933 }
934
935 static int audit_log_pid_context(struct audit_context *context, pid_t pid,
936                                  uid_t auid, uid_t uid, unsigned int sessionid,
937                                  u32 sid, char *comm)
938 {
939         struct audit_buffer *ab;
940         char *ctx = NULL;
941         u32 len;
942         int rc = 0;
943
944         ab = audit_log_start(context, GFP_KERNEL, AUDIT_OBJ_PID);
945         if (!ab)
946                 return rc;
947
948         audit_log_format(ab, "opid=%d oauid=%d ouid=%d oses=%d", pid, auid,
949                          uid, sessionid);
950         if (security_secid_to_secctx(sid, &ctx, &len)) {
951                 audit_log_format(ab, " obj=(none)");
952                 rc = 1;
953         } else {
954                 audit_log_format(ab, " obj=%s", ctx);
955                 security_release_secctx(ctx, len);
956         }
957         audit_log_format(ab, " ocomm=");
958         audit_log_untrustedstring(ab, comm);
959         audit_log_end(ab);
960
961         return rc;
962 }
963
964 /*
965  * to_send and len_sent accounting are very loose estimates.  We aren't
966  * really worried about a hard cap to MAX_EXECVE_AUDIT_LEN so much as being
967  * within about 500 bytes (next page boundry)
968  *
969  * why snprintf?  an int is up to 12 digits long.  if we just assumed when
970  * logging that a[%d]= was going to be 16 characters long we would be wasting
971  * space in every audit message.  In one 7500 byte message we can log up to
972  * about 1000 min size arguments.  That comes down to about 50% waste of space
973  * if we didn't do the snprintf to find out how long arg_num_len was.
974  */
975 static int audit_log_single_execve_arg(struct audit_context *context,
976                                         struct audit_buffer **ab,
977                                         int arg_num,
978                                         size_t *len_sent,
979                                         const char __user *p,
980                                         char *buf)
981 {
982         char arg_num_len_buf[12];
983         const char __user *tmp_p = p;
984         /* how many digits are in arg_num? 3 is the length of a=\n */
985         size_t arg_num_len = snprintf(arg_num_len_buf, 12, "%d", arg_num) + 3;
986         size_t len, len_left, to_send;
987         size_t max_execve_audit_len = MAX_EXECVE_AUDIT_LEN;
988         unsigned int i, has_cntl = 0, too_long = 0;
989         int ret;
990
991         /* strnlen_user includes the null we don't want to send */
992         len_left = len = strnlen_user(p, MAX_ARG_STRLEN) - 1;
993
994         /*
995          * We just created this mm, if we can't find the strings
996          * we just copied into it something is _very_ wrong. Similar
997          * for strings that are too long, we should not have created
998          * any.
999          */
1000         if (unlikely((len == -1) || len > MAX_ARG_STRLEN - 1)) {
1001                 WARN_ON(1);
1002                 send_sig(SIGKILL, current, 0);
1003                 return -1;
1004         }
1005
1006         /* walk the whole argument looking for non-ascii chars */
1007         do {
1008                 if (len_left > MAX_EXECVE_AUDIT_LEN)
1009                         to_send = MAX_EXECVE_AUDIT_LEN;
1010                 else
1011                         to_send = len_left;
1012                 ret = copy_from_user(buf, tmp_p, to_send);
1013                 /*
1014                  * There is no reason for this copy to be short. We just
1015                  * copied them here, and the mm hasn't been exposed to user-
1016                  * space yet.
1017                  */
1018                 if (ret) {
1019                         WARN_ON(1);
1020                         send_sig(SIGKILL, current, 0);
1021                         return -1;
1022                 }
1023                 buf[to_send] = '\0';
1024                 has_cntl = audit_string_contains_control(buf, to_send);
1025                 if (has_cntl) {
1026                         /*
1027                          * hex messages get logged as 2 bytes, so we can only
1028                          * send half as much in each message
1029                          */
1030                         max_execve_audit_len = MAX_EXECVE_AUDIT_LEN / 2;
1031                         break;
1032                 }
1033                 len_left -= to_send;
1034                 tmp_p += to_send;
1035         } while (len_left > 0);
1036
1037         len_left = len;
1038
1039         if (len > max_execve_audit_len)
1040                 too_long = 1;
1041
1042         /* rewalk the argument actually logging the message */
1043         for (i = 0; len_left > 0; i++) {
1044                 int room_left;
1045
1046                 if (len_left > max_execve_audit_len)
1047                         to_send = max_execve_audit_len;
1048                 else
1049                         to_send = len_left;
1050
1051                 /* do we have space left to send this argument in this ab? */
1052                 room_left = MAX_EXECVE_AUDIT_LEN - arg_num_len - *len_sent;
1053                 if (has_cntl)
1054                         room_left -= (to_send * 2);
1055                 else
1056                         room_left -= to_send;
1057                 if (room_left < 0) {
1058                         *len_sent = 0;
1059                         audit_log_end(*ab);
1060                         *ab = audit_log_start(context, GFP_KERNEL, AUDIT_EXECVE);
1061                         if (!*ab)
1062                                 return 0;
1063                 }
1064
1065                 /*
1066                  * first record needs to say how long the original string was
1067                  * so we can be sure nothing was lost.
1068                  */
1069                 if ((i == 0) && (too_long))
1070                         audit_log_format(*ab, "a%d_len=%zu ", arg_num,
1071                                          has_cntl ? 2*len : len);
1072
1073                 /*
1074                  * normally arguments are small enough to fit and we already
1075                  * filled buf above when we checked for control characters
1076                  * so don't bother with another copy_from_user
1077                  */
1078                 if (len >= max_execve_audit_len)
1079                         ret = copy_from_user(buf, p, to_send);
1080                 else
1081                         ret = 0;
1082                 if (ret) {
1083                         WARN_ON(1);
1084                         send_sig(SIGKILL, current, 0);
1085                         return -1;
1086                 }
1087                 buf[to_send] = '\0';
1088
1089                 /* actually log it */
1090                 audit_log_format(*ab, "a%d", arg_num);
1091                 if (too_long)
1092                         audit_log_format(*ab, "[%d]", i);
1093                 audit_log_format(*ab, "=");
1094                 if (has_cntl)
1095                         audit_log_n_hex(*ab, buf, to_send);
1096                 else
1097                         audit_log_format(*ab, "\"%s\"", buf);
1098                 audit_log_format(*ab, "\n");
1099
1100                 p += to_send;
1101                 len_left -= to_send;
1102                 *len_sent += arg_num_len;
1103                 if (has_cntl)
1104                         *len_sent += to_send * 2;
1105                 else
1106                         *len_sent += to_send;
1107         }
1108         /* include the null we didn't log */
1109         return len + 1;
1110 }
1111
1112 static void audit_log_execve_info(struct audit_context *context,
1113                                   struct audit_buffer **ab,
1114                                   struct audit_aux_data_execve *axi)
1115 {
1116         int i;
1117         size_t len, len_sent = 0;
1118         const char __user *p;
1119         char *buf;
1120
1121         if (axi->mm != current->mm)
1122                 return; /* execve failed, no additional info */
1123
1124         p = (const char __user *)axi->mm->arg_start;
1125
1126         audit_log_format(*ab, "argc=%d ", axi->argc);
1127
1128         /*
1129          * we need some kernel buffer to hold the userspace args.  Just
1130          * allocate one big one rather than allocating one of the right size
1131          * for every single argument inside audit_log_single_execve_arg()
1132          * should be <8k allocation so should be pretty safe.
1133          */
1134         buf = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
1135         if (!buf) {
1136                 audit_panic("out of memory for argv string\n");
1137                 return;
1138         }
1139
1140         for (i = 0; i < axi->argc; i++) {
1141                 len = audit_log_single_execve_arg(context, ab, i,
1142                                                   &len_sent, p, buf);
1143                 if (len <= 0)
1144                         break;
1145                 p += len;
1146         }
1147         kfree(buf);
1148 }
1149
1150 static void audit_log_exit(struct audit_context *context, struct task_struct *tsk)
1151 {
1152         int i, call_panic = 0;
1153         struct audit_buffer *ab;
1154         struct audit_aux_data *aux;
1155         const char *tty;
1156
1157         /* tsk == current */
1158         context->pid = tsk->pid;
1159         if (!context->ppid)
1160                 context->ppid = sys_getppid();
1161         context->uid = tsk->uid;
1162         context->gid = tsk->gid;
1163         context->euid = tsk->euid;
1164         context->suid = tsk->suid;
1165         context->fsuid = tsk->fsuid;
1166         context->egid = tsk->egid;
1167         context->sgid = tsk->sgid;
1168         context->fsgid = tsk->fsgid;
1169         context->personality = tsk->personality;
1170
1171         ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
1172         if (!ab)
1173                 return;         /* audit_panic has been called */
1174         audit_log_format(ab, "arch=%x syscall=%d",
1175                          context->arch, context->major);
1176         if (context->personality != PER_LINUX)
1177                 audit_log_format(ab, " per=%lx", context->personality);
1178         if (context->return_valid)
1179                 audit_log_format(ab, " success=%s exit=%ld",
1180                                  (context->return_valid==AUDITSC_SUCCESS)?"yes":"no",
1181                                  context->return_code);
1182
1183         mutex_lock(&tty_mutex);
1184         read_lock(&tasklist_lock);
1185         if (tsk->signal && tsk->signal->tty && tsk->signal->tty->name)
1186                 tty = tsk->signal->tty->name;
1187         else
1188                 tty = "(none)";
1189         read_unlock(&tasklist_lock);
1190         audit_log_format(ab,
1191                   " a0=%lx a1=%lx a2=%lx a3=%lx items=%d"
1192                   " ppid=%d pid=%d auid=%u uid=%u gid=%u"
1193                   " euid=%u suid=%u fsuid=%u"
1194                   " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
1195                   context->argv[0],
1196                   context->argv[1],
1197                   context->argv[2],
1198                   context->argv[3],
1199                   context->name_count,
1200                   context->ppid,
1201                   context->pid,
1202                   tsk->loginuid,
1203                   context->uid,
1204                   context->gid,
1205                   context->euid, context->suid, context->fsuid,
1206                   context->egid, context->sgid, context->fsgid, tty,
1207                   tsk->sessionid);
1208
1209         mutex_unlock(&tty_mutex);
1210
1211         audit_log_task_info(ab, tsk);
1212         if (context->filterkey) {
1213                 audit_log_format(ab, " key=");
1214                 audit_log_untrustedstring(ab, context->filterkey);
1215         } else
1216                 audit_log_format(ab, " key=(null)");
1217         audit_log_end(ab);
1218
1219         for (aux = context->aux; aux; aux = aux->next) {
1220
1221                 ab = audit_log_start(context, GFP_KERNEL, aux->type);
1222                 if (!ab)
1223                         continue; /* audit_panic has been called */
1224
1225                 switch (aux->type) {
1226                 case AUDIT_MQ_OPEN: {
1227                         struct audit_aux_data_mq_open *axi = (void *)aux;
1228                         audit_log_format(ab,
1229                                 "oflag=0x%x mode=%#o mq_flags=0x%lx mq_maxmsg=%ld "
1230                                 "mq_msgsize=%ld mq_curmsgs=%ld",
1231                                 axi->oflag, axi->mode, axi->attr.mq_flags,
1232                                 axi->attr.mq_maxmsg, axi->attr.mq_msgsize,
1233                                 axi->attr.mq_curmsgs);
1234                         break; }
1235
1236                 case AUDIT_MQ_SENDRECV: {
1237                         struct audit_aux_data_mq_sendrecv *axi = (void *)aux;
1238                         audit_log_format(ab,
1239                                 "mqdes=%d msg_len=%zd msg_prio=%u "
1240                                 "abs_timeout_sec=%ld abs_timeout_nsec=%ld",
1241                                 axi->mqdes, axi->msg_len, axi->msg_prio,
1242                                 axi->abs_timeout.tv_sec, axi->abs_timeout.tv_nsec);
1243                         break; }
1244
1245                 case AUDIT_MQ_NOTIFY: {
1246                         struct audit_aux_data_mq_notify *axi = (void *)aux;
1247                         audit_log_format(ab,
1248                                 "mqdes=%d sigev_signo=%d",
1249                                 axi->mqdes,
1250                                 axi->notification.sigev_signo);
1251                         break; }
1252
1253                 case AUDIT_MQ_GETSETATTR: {
1254                         struct audit_aux_data_mq_getsetattr *axi = (void *)aux;
1255                         audit_log_format(ab,
1256                                 "mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
1257                                 "mq_curmsgs=%ld ",
1258                                 axi->mqdes,
1259                                 axi->mqstat.mq_flags, axi->mqstat.mq_maxmsg,
1260                                 axi->mqstat.mq_msgsize, axi->mqstat.mq_curmsgs);
1261                         break; }
1262
1263                 case AUDIT_IPC: {
1264                         struct audit_aux_data_ipcctl *axi = (void *)aux;
1265                         audit_log_format(ab, 
1266                                  "ouid=%u ogid=%u mode=%#o",
1267                                  axi->uid, axi->gid, axi->mode);
1268                         if (axi->osid != 0) {
1269                                 char *ctx = NULL;
1270                                 u32 len;
1271                                 if (security_secid_to_secctx(
1272                                                 axi->osid, &ctx, &len)) {
1273                                         audit_log_format(ab, " osid=%u",
1274                                                         axi->osid);
1275                                         call_panic = 1;
1276                                 } else {
1277                                         audit_log_format(ab, " obj=%s", ctx);
1278                                         security_release_secctx(ctx, len);
1279                                 }
1280                         }
1281                         break; }
1282
1283                 case AUDIT_IPC_SET_PERM: {
1284                         struct audit_aux_data_ipcctl *axi = (void *)aux;
1285                         audit_log_format(ab,
1286                                 "qbytes=%lx ouid=%u ogid=%u mode=%#o",
1287                                 axi->qbytes, axi->uid, axi->gid, axi->mode);
1288                         break; }
1289
1290                 case AUDIT_EXECVE: {
1291                         struct audit_aux_data_execve *axi = (void *)aux;
1292                         audit_log_execve_info(context, &ab, axi);
1293                         break; }
1294
1295                 case AUDIT_SOCKETCALL: {
1296                         int i;
1297                         struct audit_aux_data_socketcall *axs = (void *)aux;
1298                         audit_log_format(ab, "nargs=%d", axs->nargs);
1299                         for (i=0; i<axs->nargs; i++)
1300                                 audit_log_format(ab, " a%d=%lx", i, axs->args[i]);
1301                         break; }
1302
1303                 case AUDIT_SOCKADDR: {
1304                         struct audit_aux_data_sockaddr *axs = (void *)aux;
1305
1306                         audit_log_format(ab, "saddr=");
1307                         audit_log_n_hex(ab, axs->a, axs->len);
1308                         break; }
1309
1310                 case AUDIT_FD_PAIR: {
1311                         struct audit_aux_data_fd_pair *axs = (void *)aux;
1312                         audit_log_format(ab, "fd0=%d fd1=%d", axs->fd[0], axs->fd[1]);
1313                         break; }
1314
1315                 }
1316                 audit_log_end(ab);
1317         }
1318
1319         for (aux = context->aux_pids; aux; aux = aux->next) {
1320                 struct audit_aux_data_pids *axs = (void *)aux;
1321                 int i;
1322
1323                 for (i = 0; i < axs->pid_count; i++)
1324                         if (audit_log_pid_context(context, axs->target_pid[i],
1325                                                   axs->target_auid[i],
1326                                                   axs->target_uid[i],
1327                                                   axs->target_sessionid[i],
1328                                                   axs->target_sid[i],
1329                                                   axs->target_comm[i]))
1330                                 call_panic = 1;
1331         }
1332
1333         if (context->target_pid &&
1334             audit_log_pid_context(context, context->target_pid,
1335                                   context->target_auid, context->target_uid,
1336                                   context->target_sessionid,
1337                                   context->target_sid, context->target_comm))
1338                         call_panic = 1;
1339
1340         if (context->pwd.dentry && context->pwd.mnt) {
1341                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
1342                 if (ab) {
1343                         audit_log_d_path(ab, "cwd=", &context->pwd);
1344                         audit_log_end(ab);
1345                 }
1346         }
1347         for (i = 0; i < context->name_count; i++) {
1348                 struct audit_names *n = &context->names[i];
1349
1350                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
1351                 if (!ab)
1352                         continue; /* audit_panic has been called */
1353
1354                 audit_log_format(ab, "item=%d", i);
1355
1356                 if (n->name) {
1357                         switch(n->name_len) {
1358                         case AUDIT_NAME_FULL:
1359                                 /* log the full path */
1360                                 audit_log_format(ab, " name=");
1361                                 audit_log_untrustedstring(ab, n->name);
1362                                 break;
1363                         case 0:
1364                                 /* name was specified as a relative path and the
1365                                  * directory component is the cwd */
1366                                 audit_log_d_path(ab, " name=", &context->pwd);
1367                                 break;
1368                         default:
1369                                 /* log the name's directory component */
1370                                 audit_log_format(ab, " name=");
1371                                 audit_log_n_untrustedstring(ab, n->name,
1372                                                             n->name_len);
1373                         }
1374                 } else
1375                         audit_log_format(ab, " name=(null)");
1376
1377                 if (n->ino != (unsigned long)-1) {
1378                         audit_log_format(ab, " inode=%lu"
1379                                          " dev=%02x:%02x mode=%#o"
1380                                          " ouid=%u ogid=%u rdev=%02x:%02x",
1381                                          n->ino,
1382                                          MAJOR(n->dev),
1383                                          MINOR(n->dev),
1384                                          n->mode,
1385                                          n->uid,
1386                                          n->gid,
1387                                          MAJOR(n->rdev),
1388                                          MINOR(n->rdev));
1389                 }
1390                 if (n->osid != 0) {
1391                         char *ctx = NULL;
1392                         u32 len;
1393                         if (security_secid_to_secctx(
1394                                 n->osid, &ctx, &len)) {
1395                                 audit_log_format(ab, " osid=%u", n->osid);
1396                                 call_panic = 2;
1397                         } else {
1398                                 audit_log_format(ab, " obj=%s", ctx);
1399                                 security_release_secctx(ctx, len);
1400                         }
1401                 }
1402
1403                 audit_log_end(ab);
1404         }
1405
1406         /* Send end of event record to help user space know we are finished */
1407         ab = audit_log_start(context, GFP_KERNEL, AUDIT_EOE);
1408         if (ab)
1409                 audit_log_end(ab);
1410         if (call_panic)
1411                 audit_panic("error converting sid to string");
1412 }
1413
1414 /**
1415  * audit_free - free a per-task audit context
1416  * @tsk: task whose audit context block to free
1417  *
1418  * Called from copy_process and do_exit
1419  */
1420 void audit_free(struct task_struct *tsk)
1421 {
1422         struct audit_context *context;
1423
1424         context = audit_get_context(tsk, 0, 0);
1425         if (likely(!context))
1426                 return;
1427
1428         /* Check for system calls that do not go through the exit
1429          * function (e.g., exit_group), then free context block.
1430          * We use GFP_ATOMIC here because we might be doing this
1431          * in the context of the idle thread */
1432         /* that can happen only if we are called from do_exit() */
1433         if (context->in_syscall && context->auditable)
1434                 audit_log_exit(context, tsk);
1435
1436         audit_free_context(context);
1437 }
1438
1439 /**
1440  * audit_syscall_entry - fill in an audit record at syscall entry
1441  * @tsk: task being audited
1442  * @arch: architecture type
1443  * @major: major syscall type (function)
1444  * @a1: additional syscall register 1
1445  * @a2: additional syscall register 2
1446  * @a3: additional syscall register 3
1447  * @a4: additional syscall register 4
1448  *
1449  * Fill in audit context at syscall entry.  This only happens if the
1450  * audit context was created when the task was created and the state or
1451  * filters demand the audit context be built.  If the state from the
1452  * per-task filter or from the per-syscall filter is AUDIT_RECORD_CONTEXT,
1453  * then the record will be written at syscall exit time (otherwise, it
1454  * will only be written if another part of the kernel requests that it
1455  * be written).
1456  */
1457 void audit_syscall_entry(int arch, int major,
1458                          unsigned long a1, unsigned long a2,
1459                          unsigned long a3, unsigned long a4)
1460 {
1461         struct task_struct *tsk = current;
1462         struct audit_context *context = tsk->audit_context;
1463         enum audit_state     state;
1464
1465         BUG_ON(!context);
1466
1467         /*
1468          * This happens only on certain architectures that make system
1469          * calls in kernel_thread via the entry.S interface, instead of
1470          * with direct calls.  (If you are porting to a new
1471          * architecture, hitting this condition can indicate that you
1472          * got the _exit/_leave calls backward in entry.S.)
1473          *
1474          * i386     no
1475          * x86_64   no
1476          * ppc64    yes (see arch/powerpc/platforms/iseries/misc.S)
1477          *
1478          * This also happens with vm86 emulation in a non-nested manner
1479          * (entries without exits), so this case must be caught.
1480          */
1481         if (context->in_syscall) {
1482                 struct audit_context *newctx;
1483
1484 #if AUDIT_DEBUG
1485                 printk(KERN_ERR
1486                        "audit(:%d) pid=%d in syscall=%d;"
1487                        " entering syscall=%d\n",
1488                        context->serial, tsk->pid, context->major, major);
1489 #endif
1490                 newctx = audit_alloc_context(context->state);
1491                 if (newctx) {
1492                         newctx->previous   = context;
1493                         context            = newctx;
1494                         tsk->audit_context = newctx;
1495                 } else  {
1496                         /* If we can't alloc a new context, the best we
1497                          * can do is to leak memory (any pending putname
1498                          * will be lost).  The only other alternative is
1499                          * to abandon auditing. */
1500                         audit_zero_context(context, context->state);
1501                 }
1502         }
1503         BUG_ON(context->in_syscall || context->name_count);
1504
1505         if (!audit_enabled)
1506                 return;
1507
1508         context->arch       = arch;
1509         context->major      = major;
1510         context->argv[0]    = a1;
1511         context->argv[1]    = a2;
1512         context->argv[2]    = a3;
1513         context->argv[3]    = a4;
1514
1515         state = context->state;
1516         context->dummy = !audit_n_rules;
1517         if (!context->dummy && (state == AUDIT_SETUP_CONTEXT || state == AUDIT_BUILD_CONTEXT))
1518                 state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]);
1519         if (likely(state == AUDIT_DISABLED))
1520                 return;
1521
1522         context->serial     = 0;
1523         context->ctime      = CURRENT_TIME;
1524         context->in_syscall = 1;
1525         context->auditable  = !!(state == AUDIT_RECORD_CONTEXT);
1526         context->ppid       = 0;
1527 }
1528
1529 /**
1530  * audit_syscall_exit - deallocate audit context after a system call
1531  * @tsk: task being audited
1532  * @valid: success/failure flag
1533  * @return_code: syscall return value
1534  *
1535  * Tear down after system call.  If the audit context has been marked as
1536  * auditable (either because of the AUDIT_RECORD_CONTEXT state from
1537  * filtering, or because some other part of the kernel write an audit
1538  * message), then write out the syscall information.  In call cases,
1539  * free the names stored from getname().
1540  */
1541 void audit_syscall_exit(int valid, long return_code)
1542 {
1543         struct task_struct *tsk = current;
1544         struct audit_context *context;
1545
1546         context = audit_get_context(tsk, valid, return_code);
1547
1548         if (likely(!context))
1549                 return;
1550
1551         if (context->in_syscall && context->auditable)
1552                 audit_log_exit(context, tsk);
1553
1554         context->in_syscall = 0;
1555         context->auditable  = 0;
1556
1557         if (context->previous) {
1558                 struct audit_context *new_context = context->previous;
1559                 context->previous  = NULL;
1560                 audit_free_context(context);
1561                 tsk->audit_context = new_context;
1562         } else {
1563                 audit_free_names(context);
1564                 unroll_tree_refs(context, NULL, 0);
1565                 audit_free_aux(context);
1566                 context->aux = NULL;
1567                 context->aux_pids = NULL;
1568                 context->target_pid = 0;
1569                 context->target_sid = 0;
1570                 kfree(context->filterkey);
1571                 context->filterkey = NULL;
1572                 tsk->audit_context = context;
1573         }
1574 }
1575
1576 static inline void handle_one(const struct inode *inode)
1577 {
1578 #ifdef CONFIG_AUDIT_TREE
1579         struct audit_context *context;
1580         struct audit_tree_refs *p;
1581         struct audit_chunk *chunk;
1582         int count;
1583         if (likely(list_empty(&inode->inotify_watches)))
1584                 return;
1585         context = current->audit_context;
1586         p = context->trees;
1587         count = context->tree_count;
1588         rcu_read_lock();
1589         chunk = audit_tree_lookup(inode);
1590         rcu_read_unlock();
1591         if (!chunk)
1592                 return;
1593         if (likely(put_tree_ref(context, chunk)))
1594                 return;
1595         if (unlikely(!grow_tree_refs(context))) {
1596                 printk(KERN_WARNING "out of memory, audit has lost a tree reference\n");
1597                 audit_set_auditable(context);
1598                 audit_put_chunk(chunk);
1599                 unroll_tree_refs(context, p, count);
1600                 return;
1601         }
1602         put_tree_ref(context, chunk);
1603 #endif
1604 }
1605
1606 static void handle_path(const struct dentry *dentry)
1607 {
1608 #ifdef CONFIG_AUDIT_TREE
1609         struct audit_context *context;
1610         struct audit_tree_refs *p;
1611         const struct dentry *d, *parent;
1612         struct audit_chunk *drop;
1613         unsigned long seq;
1614         int count;
1615
1616         context = current->audit_context;
1617         p = context->trees;
1618         count = context->tree_count;
1619 retry:
1620         drop = NULL;
1621         d = dentry;
1622         rcu_read_lock();
1623         seq = read_seqbegin(&rename_lock);
1624         for(;;) {
1625                 struct inode *inode = d->d_inode;
1626                 if (inode && unlikely(!list_empty(&inode->inotify_watches))) {
1627                         struct audit_chunk *chunk;
1628                         chunk = audit_tree_lookup(inode);
1629                         if (chunk) {
1630                                 if (unlikely(!put_tree_ref(context, chunk))) {
1631                                         drop = chunk;
1632                                         break;
1633                                 }
1634                         }
1635                 }
1636                 parent = d->d_parent;
1637                 if (parent == d)
1638                         break;
1639                 d = parent;
1640         }
1641         if (unlikely(read_seqretry(&rename_lock, seq) || drop)) {  /* in this order */
1642                 rcu_read_unlock();
1643                 if (!drop) {
1644                         /* just a race with rename */
1645                         unroll_tree_refs(context, p, count);
1646                         goto retry;
1647                 }
1648                 audit_put_chunk(drop);
1649                 if (grow_tree_refs(context)) {
1650                         /* OK, got more space */
1651                         unroll_tree_refs(context, p, count);
1652                         goto retry;
1653                 }
1654                 /* too bad */
1655                 printk(KERN_WARNING
1656                         "out of memory, audit has lost a tree reference\n");
1657                 unroll_tree_refs(context, p, count);
1658                 audit_set_auditable(context);
1659                 return;
1660         }
1661         rcu_read_unlock();
1662 #endif
1663 }
1664
1665 /**
1666  * audit_getname - add a name to the list
1667  * @name: name to add
1668  *
1669  * Add a name to the list of audit names for this context.
1670  * Called from fs/namei.c:getname().
1671  */
1672 void __audit_getname(const char *name)
1673 {
1674         struct audit_context *context = current->audit_context;
1675
1676         if (IS_ERR(name) || !name)
1677                 return;
1678
1679         if (!context->in_syscall) {
1680 #if AUDIT_DEBUG == 2
1681                 printk(KERN_ERR "%s:%d(:%d): ignoring getname(%p)\n",
1682                        __FILE__, __LINE__, context->serial, name);
1683                 dump_stack();
1684 #endif
1685                 return;
1686         }
1687         BUG_ON(context->name_count >= AUDIT_NAMES);
1688         context->names[context->name_count].name = name;
1689         context->names[context->name_count].name_len = AUDIT_NAME_FULL;
1690         context->names[context->name_count].name_put = 1;
1691         context->names[context->name_count].ino  = (unsigned long)-1;
1692         context->names[context->name_count].osid = 0;
1693         ++context->name_count;
1694         if (!context->pwd.dentry) {
1695                 read_lock(&current->fs->lock);
1696                 context->pwd = current->fs->pwd;
1697                 path_get(&current->fs->pwd);
1698                 read_unlock(&current->fs->lock);
1699         }
1700
1701 }
1702
1703 /* audit_putname - intercept a putname request
1704  * @name: name to intercept and delay for putname
1705  *
1706  * If we have stored the name from getname in the audit context,
1707  * then we delay the putname until syscall exit.
1708  * Called from include/linux/fs.h:putname().
1709  */
1710 void audit_putname(const char *name)
1711 {
1712         struct audit_context *context = current->audit_context;
1713
1714         BUG_ON(!context);
1715         if (!context->in_syscall) {
1716 #if AUDIT_DEBUG == 2
1717                 printk(KERN_ERR "%s:%d(:%d): __putname(%p)\n",
1718                        __FILE__, __LINE__, context->serial, name);
1719                 if (context->name_count) {
1720                         int i;
1721                         for (i = 0; i < context->name_count; i++)
1722                                 printk(KERN_ERR "name[%d] = %p = %s\n", i,
1723                                        context->names[i].name,
1724                                        context->names[i].name ?: "(null)");
1725                 }
1726 #endif
1727                 __putname(name);
1728         }
1729 #if AUDIT_DEBUG
1730         else {
1731                 ++context->put_count;
1732                 if (context->put_count > context->name_count) {
1733                         printk(KERN_ERR "%s:%d(:%d): major=%d"
1734                                " in_syscall=%d putname(%p) name_count=%d"
1735                                " put_count=%d\n",
1736                                __FILE__, __LINE__,
1737                                context->serial, context->major,
1738                                context->in_syscall, name, context->name_count,
1739                                context->put_count);
1740                         dump_stack();
1741                 }
1742         }
1743 #endif
1744 }
1745
1746 static int audit_inc_name_count(struct audit_context *context,
1747                                 const struct inode *inode)
1748 {
1749         if (context->name_count >= AUDIT_NAMES) {
1750                 if (inode)
1751                         printk(KERN_DEBUG "name_count maxed, losing inode data: "
1752                                "dev=%02x:%02x, inode=%lu\n",
1753                                MAJOR(inode->i_sb->s_dev),
1754                                MINOR(inode->i_sb->s_dev),
1755                                inode->i_ino);
1756
1757                 else
1758                         printk(KERN_DEBUG "name_count maxed, losing inode data\n");
1759                 return 1;
1760         }
1761         context->name_count++;
1762 #if AUDIT_DEBUG
1763         context->ino_count++;
1764 #endif
1765         return 0;
1766 }
1767
1768 /* Copy inode data into an audit_names. */
1769 static void audit_copy_inode(struct audit_names *name, const struct inode *inode)
1770 {
1771         name->ino   = inode->i_ino;
1772         name->dev   = inode->i_sb->s_dev;
1773         name->mode  = inode->i_mode;
1774         name->uid   = inode->i_uid;
1775         name->gid   = inode->i_gid;
1776         name->rdev  = inode->i_rdev;
1777         security_inode_getsecid(inode, &name->osid);
1778 }
1779
1780 /**
1781  * audit_inode - store the inode and device from a lookup
1782  * @name: name being audited
1783  * @dentry: dentry being audited
1784  *
1785  * Called from fs/namei.c:path_lookup().
1786  */
1787 void __audit_inode(const char *name, const struct dentry *dentry)
1788 {
1789         int idx;
1790         struct audit_context *context = current->audit_context;
1791         const struct inode *inode = dentry->d_inode;
1792
1793         if (!context->in_syscall)
1794                 return;
1795         if (context->name_count
1796             && context->names[context->name_count-1].name
1797             && context->names[context->name_count-1].name == name)
1798                 idx = context->name_count - 1;
1799         else if (context->name_count > 1
1800                  && context->names[context->name_count-2].name
1801                  && context->names[context->name_count-2].name == name)
1802                 idx = context->name_count - 2;
1803         else {
1804                 /* FIXME: how much do we care about inodes that have no
1805                  * associated name? */
1806                 if (audit_inc_name_count(context, inode))
1807                         return;
1808                 idx = context->name_count - 1;
1809                 context->names[idx].name = NULL;
1810         }
1811         handle_path(dentry);
1812         audit_copy_inode(&context->names[idx], inode);
1813 }
1814
1815 /**
1816  * audit_inode_child - collect inode info for created/removed objects
1817  * @dname: inode's dentry name
1818  * @dentry: dentry being audited
1819  * @parent: inode of dentry parent
1820  *
1821  * For syscalls that create or remove filesystem objects, audit_inode
1822  * can only collect information for the filesystem object's parent.
1823  * This call updates the audit context with the child's information.
1824  * Syscalls that create a new filesystem object must be hooked after
1825  * the object is created.  Syscalls that remove a filesystem object
1826  * must be hooked prior, in order to capture the target inode during
1827  * unsuccessful attempts.
1828  */
1829 void __audit_inode_child(const char *dname, const struct dentry *dentry,
1830                          const struct inode *parent)
1831 {
1832         int idx;
1833         struct audit_context *context = current->audit_context;
1834         const char *found_parent = NULL, *found_child = NULL;
1835         const struct inode *inode = dentry->d_inode;
1836         int dirlen = 0;
1837
1838         if (!context->in_syscall)
1839                 return;
1840
1841         if (inode)
1842                 handle_one(inode);
1843         /* determine matching parent */
1844         if (!dname)
1845                 goto add_names;
1846
1847         /* parent is more likely, look for it first */
1848         for (idx = 0; idx < context->name_count; idx++) {
1849                 struct audit_names *n = &context->names[idx];
1850
1851                 if (!n->name)
1852                         continue;
1853
1854                 if (n->ino == parent->i_ino &&
1855                     !audit_compare_dname_path(dname, n->name, &dirlen)) {
1856                         n->name_len = dirlen; /* update parent data in place */
1857                         found_parent = n->name;
1858                         goto add_names;
1859                 }
1860         }
1861
1862         /* no matching parent, look for matching child */
1863         for (idx = 0; idx < context->name_count; idx++) {
1864                 struct audit_names *n = &context->names[idx];
1865
1866                 if (!n->name)
1867                         continue;
1868
1869                 /* strcmp() is the more likely scenario */
1870                 if (!strcmp(dname, n->name) ||
1871                      !audit_compare_dname_path(dname, n->name, &dirlen)) {
1872                         if (inode)
1873                                 audit_copy_inode(n, inode);
1874                         else
1875                                 n->ino = (unsigned long)-1;
1876                         found_child = n->name;
1877                         goto add_names;
1878                 }
1879         }
1880
1881 add_names:
1882         if (!found_parent) {
1883                 if (audit_inc_name_count(context, parent))
1884                         return;
1885                 idx = context->name_count - 1;
1886                 context->names[idx].name = NULL;
1887                 audit_copy_inode(&context->names[idx], parent);
1888         }
1889
1890         if (!found_child) {
1891                 if (audit_inc_name_count(context, inode))
1892                         return;
1893                 idx = context->name_count - 1;
1894
1895                 /* Re-use the name belonging to the slot for a matching parent
1896                  * directory. All names for this context are relinquished in
1897                  * audit_free_names() */
1898                 if (found_parent) {
1899                         context->names[idx].name = found_parent;
1900                         context->names[idx].name_len = AUDIT_NAME_FULL;
1901                         /* don't call __putname() */
1902                         context->names[idx].name_put = 0;
1903                 } else {
1904                         context->names[idx].name = NULL;
1905                 }
1906
1907                 if (inode)
1908                         audit_copy_inode(&context->names[idx], inode);
1909                 else
1910                         context->names[idx].ino = (unsigned long)-1;
1911         }
1912 }
1913 EXPORT_SYMBOL_GPL(__audit_inode_child);
1914
1915 /**
1916  * auditsc_get_stamp - get local copies of audit_context values
1917  * @ctx: audit_context for the task
1918  * @t: timespec to store time recorded in the audit_context
1919  * @serial: serial value that is recorded in the audit_context
1920  *
1921  * Also sets the context as auditable.
1922  */
1923 void auditsc_get_stamp(struct audit_context *ctx,
1924                        struct timespec *t, unsigned int *serial)
1925 {
1926         if (!ctx->serial)
1927                 ctx->serial = audit_serial();
1928         t->tv_sec  = ctx->ctime.tv_sec;
1929         t->tv_nsec = ctx->ctime.tv_nsec;
1930         *serial    = ctx->serial;
1931         ctx->auditable = 1;
1932 }
1933
1934 /* global counter which is incremented every time something logs in */
1935 static atomic_t session_id = ATOMIC_INIT(0);
1936
1937 /**
1938  * audit_set_loginuid - set a task's audit_context loginuid
1939  * @task: task whose audit context is being modified
1940  * @loginuid: loginuid value
1941  *
1942  * Returns 0.
1943  *
1944  * Called (set) from fs/proc/base.c::proc_loginuid_write().
1945  */
1946 int audit_set_loginuid(struct task_struct *task, uid_t loginuid)
1947 {
1948         unsigned int sessionid = atomic_inc_return(&session_id);
1949         struct audit_context *context = task->audit_context;
1950
1951         if (context && context->in_syscall) {
1952                 struct audit_buffer *ab;
1953
1954                 ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_LOGIN);
1955                 if (ab) {
1956                         audit_log_format(ab, "login pid=%d uid=%u "
1957                                 "old auid=%u new auid=%u"
1958                                 " old ses=%u new ses=%u",
1959                                 task->pid, task->uid,
1960                                 task->loginuid, loginuid,
1961                                 task->sessionid, sessionid);
1962                         audit_log_end(ab);
1963                 }
1964         }
1965         task->sessionid = sessionid;
1966         task->loginuid = loginuid;
1967         return 0;
1968 }
1969
1970 /**
1971  * __audit_mq_open - record audit data for a POSIX MQ open
1972  * @oflag: open flag
1973  * @mode: mode bits
1974  * @u_attr: queue attributes
1975  *
1976  * Returns 0 for success or NULL context or < 0 on error.
1977  */
1978 int __audit_mq_open(int oflag, mode_t mode, struct mq_attr __user *u_attr)
1979 {
1980         struct audit_aux_data_mq_open *ax;
1981         struct audit_context *context = current->audit_context;
1982
1983         if (!audit_enabled)
1984                 return 0;
1985
1986         if (likely(!context))
1987                 return 0;
1988
1989         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1990         if (!ax)
1991                 return -ENOMEM;
1992
1993         if (u_attr != NULL) {
1994                 if (copy_from_user(&ax->attr, u_attr, sizeof(ax->attr))) {
1995                         kfree(ax);
1996                         return -EFAULT;
1997                 }
1998         } else
1999                 memset(&ax->attr, 0, sizeof(ax->attr));
2000
2001         ax->oflag = oflag;
2002         ax->mode = mode;
2003
2004         ax->d.type = AUDIT_MQ_OPEN;
2005         ax->d.next = context->aux;
2006         context->aux = (void *)ax;
2007         return 0;
2008 }
2009
2010 /**
2011  * __audit_mq_timedsend - record audit data for a POSIX MQ timed send
2012  * @mqdes: MQ descriptor
2013  * @msg_len: Message length
2014  * @msg_prio: Message priority
2015  * @u_abs_timeout: Message timeout in absolute time
2016  *
2017  * Returns 0 for success or NULL context or < 0 on error.
2018  */
2019 int __audit_mq_timedsend(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
2020                         const struct timespec __user *u_abs_timeout)
2021 {
2022         struct audit_aux_data_mq_sendrecv *ax;
2023         struct audit_context *context = current->audit_context;
2024
2025         if (!audit_enabled)
2026                 return 0;
2027
2028         if (likely(!context))
2029                 return 0;
2030
2031         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
2032         if (!ax)
2033                 return -ENOMEM;
2034
2035         if (u_abs_timeout != NULL) {
2036                 if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
2037                         kfree(ax);
2038                         return -EFAULT;
2039                 }
2040         } else
2041                 memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
2042
2043         ax->mqdes = mqdes;
2044         ax->msg_len = msg_len;
2045         ax->msg_prio = msg_prio;
2046
2047         ax->d.type = AUDIT_MQ_SENDRECV;
2048         ax->d.next = context->aux;
2049         context->aux = (void *)ax;
2050         return 0;
2051 }
2052
2053 /**
2054  * __audit_mq_timedreceive - record audit data for a POSIX MQ timed receive
2055  * @mqdes: MQ descriptor
2056  * @msg_len: Message length
2057  * @u_msg_prio: Message priority
2058  * @u_abs_timeout: Message timeout in absolute time
2059  *
2060  * Returns 0 for success or NULL context or < 0 on error.
2061  */
2062 int __audit_mq_timedreceive(mqd_t mqdes, size_t msg_len,
2063                                 unsigned int __user *u_msg_prio,
2064                                 const struct timespec __user *u_abs_timeout)
2065 {
2066         struct audit_aux_data_mq_sendrecv *ax;
2067         struct audit_context *context = current->audit_context;
2068
2069         if (!audit_enabled)
2070                 return 0;
2071
2072         if (likely(!context))
2073                 return 0;
2074
2075         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
2076         if (!ax)
2077                 return -ENOMEM;
2078
2079         if (u_msg_prio != NULL) {
2080                 if (get_user(ax->msg_prio, u_msg_prio)) {
2081                         kfree(ax);
2082                         return -EFAULT;
2083                 }
2084         } else
2085                 ax->msg_prio = 0;
2086
2087         if (u_abs_timeout != NULL) {
2088                 if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
2089                         kfree(ax);
2090                         return -EFAULT;
2091                 }
2092         } else
2093                 memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
2094
2095         ax->mqdes = mqdes;
2096         ax->msg_len = msg_len;
2097
2098         ax->d.type = AUDIT_MQ_SENDRECV;
2099         ax->d.next = context->aux;
2100         context->aux = (void *)ax;
2101         return 0;
2102 }
2103
2104 /**
2105  * __audit_mq_notify - record audit data for a POSIX MQ notify
2106  * @mqdes: MQ descriptor
2107  * @u_notification: Notification event
2108  *
2109  * Returns 0 for success or NULL context or < 0 on error.
2110  */
2111
2112 int __audit_mq_notify(mqd_t mqdes, const struct sigevent __user *u_notification)
2113 {
2114         struct audit_aux_data_mq_notify *ax;
2115         struct audit_context *context = current->audit_context;
2116
2117         if (!audit_enabled)
2118                 return 0;
2119
2120         if (likely(!context))
2121                 return 0;
2122
2123         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
2124         if (!ax)
2125                 return -ENOMEM;
2126
2127         if (u_notification != NULL) {
2128                 if (copy_from_user(&ax->notification, u_notification, sizeof(ax->notification))) {
2129                         kfree(ax);
2130                         return -EFAULT;
2131                 }
2132         } else
2133                 memset(&ax->notification, 0, sizeof(ax->notification));
2134
2135         ax->mqdes = mqdes;
2136
2137         ax->d.type = AUDIT_MQ_NOTIFY;
2138         ax->d.next = context->aux;
2139         context->aux = (void *)ax;
2140         return 0;
2141 }
2142
2143 /**
2144  * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
2145  * @mqdes: MQ descriptor
2146  * @mqstat: MQ flags
2147  *
2148  * Returns 0 for success or NULL context or < 0 on error.
2149  */
2150 int __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
2151 {
2152         struct audit_aux_data_mq_getsetattr *ax;
2153         struct audit_context *context = current->audit_context;
2154
2155         if (!audit_enabled)
2156                 return 0;
2157
2158         if (likely(!context))
2159                 return 0;
2160
2161         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
2162         if (!ax)
2163                 return -ENOMEM;
2164
2165         ax->mqdes = mqdes;
2166         ax->mqstat = *mqstat;
2167
2168         ax->d.type = AUDIT_MQ_GETSETATTR;
2169         ax->d.next = context->aux;
2170         context->aux = (void *)ax;
2171         return 0;
2172 }
2173
2174 /**
2175  * audit_ipc_obj - record audit data for ipc object
2176  * @ipcp: ipc permissions
2177  *
2178  * Returns 0 for success or NULL context or < 0 on error.
2179  */
2180 int __audit_ipc_obj(struct kern_ipc_perm *ipcp)
2181 {
2182         struct audit_aux_data_ipcctl *ax;
2183         struct audit_context *context = current->audit_context;
2184
2185         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
2186         if (!ax)
2187                 return -ENOMEM;
2188
2189         ax->uid = ipcp->uid;
2190         ax->gid = ipcp->gid;
2191         ax->mode = ipcp->mode;
2192         security_ipc_getsecid(ipcp, &ax->osid);
2193         ax->d.type = AUDIT_IPC;
2194         ax->d.next = context->aux;
2195         context->aux = (void *)ax;
2196         return 0;
2197 }
2198
2199 /**
2200  * audit_ipc_set_perm - record audit data for new ipc permissions
2201  * @qbytes: msgq bytes
2202  * @uid: msgq user id
2203  * @gid: msgq group id
2204  * @mode: msgq mode (permissions)
2205  *
2206  * Returns 0 for success or NULL context or < 0 on error.
2207  */
2208 int __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, mode_t mode)
2209 {
2210         struct audit_aux_data_ipcctl *ax;
2211         struct audit_context *context = current->audit_context;
2212
2213         ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
2214         if (!ax)
2215                 return -ENOMEM;
2216
2217         ax->qbytes = qbytes;
2218         ax->uid = uid;
2219         ax->gid = gid;
2220         ax->mode = mode;
2221
2222         ax->d.type = AUDIT_IPC_SET_PERM;
2223         ax->d.next = context->aux;
2224         context->aux = (void *)ax;
2225         return 0;
2226 }
2227
2228 int audit_bprm(struct linux_binprm *bprm)
2229 {
2230         struct audit_aux_data_execve *ax;
2231         struct audit_context *context = current->audit_context;
2232
2233         if (likely(!audit_enabled || !context || context->dummy))
2234                 return 0;
2235
2236         ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2237         if (!ax)
2238                 return -ENOMEM;
2239
2240         ax->argc = bprm->argc;
2241         ax->envc = bprm->envc;
2242         ax->mm = bprm->mm;
2243         ax->d.type = AUDIT_EXECVE;
2244         ax->d.next = context->aux;
2245         context->aux = (void *)ax;
2246         return 0;
2247 }
2248
2249
2250 /**
2251  * audit_socketcall - record audit data for sys_socketcall
2252  * @nargs: number of args
2253  * @args: args array
2254  *
2255  * Returns 0 for success or NULL context or < 0 on error.
2256  */
2257 int audit_socketcall(int nargs, unsigned long *args)
2258 {
2259         struct audit_aux_data_socketcall *ax;
2260         struct audit_context *context = current->audit_context;
2261
2262         if (likely(!context || context->dummy))
2263                 return 0;
2264
2265         ax = kmalloc(sizeof(*ax) + nargs * sizeof(unsigned long), GFP_KERNEL);
2266         if (!ax)
2267                 return -ENOMEM;
2268
2269         ax->nargs = nargs;
2270         memcpy(ax->args, args, nargs * sizeof(unsigned long));
2271
2272         ax->d.type = AUDIT_SOCKETCALL;
2273         ax->d.next = context->aux;
2274         context->aux = (void *)ax;
2275         return 0;
2276 }
2277
2278 /**
2279  * __audit_fd_pair - record audit data for pipe and socketpair
2280  * @fd1: the first file descriptor
2281  * @fd2: the second file descriptor
2282  *
2283  * Returns 0 for success or NULL context or < 0 on error.
2284  */
2285 int __audit_fd_pair(int fd1, int fd2)
2286 {
2287         struct audit_context *context = current->audit_context;
2288         struct audit_aux_data_fd_pair *ax;
2289
2290         if (likely(!context)) {
2291                 return 0;
2292         }
2293
2294         ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2295         if (!ax) {
2296                 return -ENOMEM;
2297         }
2298
2299         ax->fd[0] = fd1;
2300         ax->fd[1] = fd2;
2301
2302         ax->d.type = AUDIT_FD_PAIR;
2303         ax->d.next = context->aux;
2304         context->aux = (void *)ax;
2305         return 0;
2306 }
2307
2308 /**
2309  * audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
2310  * @len: data length in user space
2311  * @a: data address in kernel space
2312  *
2313  * Returns 0 for success or NULL context or < 0 on error.
2314  */
2315 int audit_sockaddr(int len, void *a)
2316 {
2317         struct audit_aux_data_sockaddr *ax;
2318         struct audit_context *context = current->audit_context;
2319
2320         if (likely(!context || context->dummy))
2321                 return 0;
2322
2323         ax = kmalloc(sizeof(*ax) + len, GFP_KERNEL);
2324         if (!ax)
2325                 return -ENOMEM;
2326
2327         ax->len = len;
2328         memcpy(ax->a, a, len);
2329
2330         ax->d.type = AUDIT_SOCKADDR;
2331         ax->d.next = context->aux;
2332         context->aux = (void *)ax;
2333         return 0;
2334 }
2335
2336 void __audit_ptrace(struct task_struct *t)
2337 {
2338         struct audit_context *context = current->audit_context;
2339
2340         context->target_pid = t->pid;
2341         context->target_auid = audit_get_loginuid(t);
2342         context->target_uid = t->uid;
2343         context->target_sessionid = audit_get_sessionid(t);
2344         security_task_getsecid(t, &context->target_sid);
2345         memcpy(context->target_comm, t->comm, TASK_COMM_LEN);
2346 }
2347
2348 /**
2349  * audit_signal_info - record signal info for shutting down audit subsystem
2350  * @sig: signal value
2351  * @t: task being signaled
2352  *
2353  * If the audit subsystem is being terminated, record the task (pid)
2354  * and uid that is doing that.
2355  */
2356 int __audit_signal_info(int sig, struct task_struct *t)
2357 {
2358         struct audit_aux_data_pids *axp;
2359         struct task_struct *tsk = current;
2360         struct audit_context *ctx = tsk->audit_context;
2361
2362         if (audit_pid && t->tgid == audit_pid) {
2363                 if (sig == SIGTERM || sig == SIGHUP || sig == SIGUSR1) {
2364                         audit_sig_pid = tsk->pid;
2365                         if (tsk->loginuid != -1)
2366                                 audit_sig_uid = tsk->loginuid;
2367                         else
2368                                 audit_sig_uid = tsk->uid;
2369                         security_task_getsecid(tsk, &audit_sig_sid);
2370                 }
2371                 if (!audit_signals || audit_dummy_context())
2372                         return 0;
2373         }
2374
2375         /* optimize the common case by putting first signal recipient directly
2376          * in audit_context */
2377         if (!ctx->target_pid) {
2378                 ctx->target_pid = t->tgid;
2379                 ctx->target_auid = audit_get_loginuid(t);
2380                 ctx->target_uid = t->uid;
2381                 ctx->target_sessionid = audit_get_sessionid(t);
2382                 security_task_getsecid(t, &ctx->target_sid);
2383                 memcpy(ctx->target_comm, t->comm, TASK_COMM_LEN);
2384                 return 0;
2385         }
2386
2387         axp = (void *)ctx->aux_pids;
2388         if (!axp || axp->pid_count == AUDIT_AUX_PIDS) {
2389                 axp = kzalloc(sizeof(*axp), GFP_ATOMIC);
2390                 if (!axp)
2391                         return -ENOMEM;
2392
2393                 axp->d.type = AUDIT_OBJ_PID;
2394                 axp->d.next = ctx->aux_pids;
2395                 ctx->aux_pids = (void *)axp;
2396         }
2397         BUG_ON(axp->pid_count >= AUDIT_AUX_PIDS);
2398
2399         axp->target_pid[axp->pid_count] = t->tgid;
2400         axp->target_auid[axp->pid_count] = audit_get_loginuid(t);
2401         axp->target_uid[axp->pid_count] = t->uid;
2402         axp->target_sessionid[axp->pid_count] = audit_get_sessionid(t);
2403         security_task_getsecid(t, &axp->target_sid[axp->pid_count]);
2404         memcpy(axp->target_comm[axp->pid_count], t->comm, TASK_COMM_LEN);
2405         axp->pid_count++;
2406
2407         return 0;
2408 }
2409
2410 /**
2411  * audit_core_dumps - record information about processes that end abnormally
2412  * @signr: signal value
2413  *
2414  * If a process ends with a core dump, something fishy is going on and we
2415  * should record the event for investigation.
2416  */
2417 void audit_core_dumps(long signr)
2418 {
2419         struct audit_buffer *ab;
2420         u32 sid;
2421         uid_t auid = audit_get_loginuid(current);
2422         unsigned int sessionid = audit_get_sessionid(current);
2423
2424         if (!audit_enabled)
2425                 return;
2426
2427         if (signr == SIGQUIT)   /* don't care for those */
2428                 return;
2429
2430         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_ANOM_ABEND);
2431         audit_log_format(ab, "auid=%u uid=%u gid=%u ses=%u",
2432                         auid, current->uid, current->gid, sessionid);
2433         security_task_getsecid(current, &sid);
2434         if (sid) {
2435                 char *ctx = NULL;
2436                 u32 len;
2437
2438                 if (security_secid_to_secctx(sid, &ctx, &len))
2439                         audit_log_format(ab, " ssid=%u", sid);
2440                 else {
2441                         audit_log_format(ab, " subj=%s", ctx);
2442                         security_release_secctx(ctx, len);
2443                 }
2444         }
2445         audit_log_format(ab, " pid=%d comm=", current->pid);
2446         audit_log_untrustedstring(ab, current->comm);
2447         audit_log_format(ab, " sig=%ld", signr);
2448         audit_log_end(ab);
2449 }