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