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