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