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