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