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