e4cafc11c510aab8ded1d48e0cdefe556eb0322b
[safe/jmp/linux-2.6] / kernel / auditfilter.c
1 /* auditfilter.c -- filtering of audit events
2  *
3  * Copyright 2003-2004 Red Hat, Inc.
4  * Copyright 2005 Hewlett-Packard Development Company, L.P.
5  * Copyright 2005 IBM Corporation
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <linux/kernel.h>
23 #include <linux/audit.h>
24 #include <linux/kthread.h>
25 #include <linux/mutex.h>
26 #include <linux/fs.h>
27 #include <linux/namei.h>
28 #include <linux/netlink.h>
29 #include <linux/sched.h>
30 #include <linux/inotify.h>
31 #include <linux/selinux.h>
32 #include "audit.h"
33
34 /*
35  * Locking model:
36  *
37  * audit_filter_mutex:
38  *              Synchronizes writes and blocking reads of audit's filterlist
39  *              data.  Rcu is used to traverse the filterlist and access
40  *              contents of structs audit_entry, audit_watch and opaque
41  *              selinux rules during filtering.  If modified, these structures
42  *              must be copied and replace their counterparts in the filterlist.
43  *              An audit_parent struct is not accessed during filtering, so may
44  *              be written directly provided audit_filter_mutex is held.
45  */
46
47 /*
48  * Reference counting:
49  *
50  * audit_parent: lifetime is from audit_init_parent() to receipt of an IN_IGNORED
51  *      event.  Each audit_watch holds a reference to its associated parent.
52  *
53  * audit_watch: if added to lists, lifetime is from audit_init_watch() to
54  *      audit_remove_watch().  Additionally, an audit_watch may exist
55  *      temporarily to assist in searching existing filter data.  Each
56  *      audit_krule holds a reference to its associated watch.
57  */
58
59 struct audit_parent {
60         struct list_head        ilist;  /* entry in inotify registration list */
61         struct list_head        watches; /* associated watches */
62         struct inotify_watch    wdata;  /* inotify watch data */
63         unsigned                flags;  /* status flags */
64 };
65
66 /*
67  * audit_parent status flags:
68  *
69  * AUDIT_PARENT_INVALID - set anytime rules/watches are auto-removed due to
70  * a filesystem event to ensure we're adding audit watches to a valid parent.
71  * Technically not needed for IN_DELETE_SELF or IN_UNMOUNT events, as we cannot
72  * receive them while we have nameidata, but must be used for IN_MOVE_SELF which
73  * we can receive while holding nameidata.
74  */
75 #define AUDIT_PARENT_INVALID    0x001
76
77 /* Audit filter lists, defined in <linux/audit.h> */
78 struct list_head audit_filter_list[AUDIT_NR_FILTERS] = {
79         LIST_HEAD_INIT(audit_filter_list[0]),
80         LIST_HEAD_INIT(audit_filter_list[1]),
81         LIST_HEAD_INIT(audit_filter_list[2]),
82         LIST_HEAD_INIT(audit_filter_list[3]),
83         LIST_HEAD_INIT(audit_filter_list[4]),
84         LIST_HEAD_INIT(audit_filter_list[5]),
85 #if AUDIT_NR_FILTERS != 6
86 #error Fix audit_filter_list initialiser
87 #endif
88 };
89
90 static DEFINE_MUTEX(audit_filter_mutex);
91
92 /* Inotify handle */
93 extern struct inotify_handle *audit_ih;
94
95 /* Inotify events we care about. */
96 #define AUDIT_IN_WATCH IN_MOVE|IN_CREATE|IN_DELETE|IN_DELETE_SELF|IN_MOVE_SELF
97
98 void audit_free_parent(struct inotify_watch *i_watch)
99 {
100         struct audit_parent *parent;
101
102         parent = container_of(i_watch, struct audit_parent, wdata);
103         WARN_ON(!list_empty(&parent->watches));
104         kfree(parent);
105 }
106
107 static inline void audit_get_watch(struct audit_watch *watch)
108 {
109         atomic_inc(&watch->count);
110 }
111
112 static void audit_put_watch(struct audit_watch *watch)
113 {
114         if (atomic_dec_and_test(&watch->count)) {
115                 WARN_ON(watch->parent);
116                 WARN_ON(!list_empty(&watch->rules));
117                 kfree(watch->path);
118                 kfree(watch);
119         }
120 }
121
122 static void audit_remove_watch(struct audit_watch *watch)
123 {
124         list_del(&watch->wlist);
125         put_inotify_watch(&watch->parent->wdata);
126         watch->parent = NULL;
127         audit_put_watch(watch); /* match initial get */
128 }
129
130 static inline void audit_free_rule(struct audit_entry *e)
131 {
132         int i;
133
134         /* some rules don't have associated watches */
135         if (e->rule.watch)
136                 audit_put_watch(e->rule.watch);
137         if (e->rule.fields)
138                 for (i = 0; i < e->rule.field_count; i++) {
139                         struct audit_field *f = &e->rule.fields[i];
140                         kfree(f->se_str);
141                         selinux_audit_rule_free(f->se_rule);
142                 }
143         kfree(e->rule.fields);
144         kfree(e->rule.filterkey);
145         kfree(e);
146 }
147
148 static inline void audit_free_rule_rcu(struct rcu_head *head)
149 {
150         struct audit_entry *e = container_of(head, struct audit_entry, rcu);
151         audit_free_rule(e);
152 }
153
154 /* Initialize a parent watch entry. */
155 static struct audit_parent *audit_init_parent(struct nameidata *ndp)
156 {
157         struct audit_parent *parent;
158         s32 wd;
159
160         parent = kzalloc(sizeof(*parent), GFP_KERNEL);
161         if (unlikely(!parent))
162                 return ERR_PTR(-ENOMEM);
163
164         INIT_LIST_HEAD(&parent->watches);
165         parent->flags = 0;
166
167         inotify_init_watch(&parent->wdata);
168         /* grab a ref so inotify watch hangs around until we take audit_filter_mutex */
169         get_inotify_watch(&parent->wdata);
170         wd = inotify_add_watch(audit_ih, &parent->wdata, ndp->dentry->d_inode,
171                                AUDIT_IN_WATCH);
172         if (wd < 0) {
173                 audit_free_parent(&parent->wdata);
174                 return ERR_PTR(wd);
175         }
176
177         return parent;
178 }
179
180 /* Initialize a watch entry. */
181 static struct audit_watch *audit_init_watch(char *path)
182 {
183         struct audit_watch *watch;
184
185         watch = kzalloc(sizeof(*watch), GFP_KERNEL);
186         if (unlikely(!watch))
187                 return ERR_PTR(-ENOMEM);
188
189         INIT_LIST_HEAD(&watch->rules);
190         atomic_set(&watch->count, 1);
191         watch->path = path;
192         watch->dev = (dev_t)-1;
193         watch->ino = (unsigned long)-1;
194
195         return watch;
196 }
197
198 /* Initialize an audit filterlist entry. */
199 static inline struct audit_entry *audit_init_entry(u32 field_count)
200 {
201         struct audit_entry *entry;
202         struct audit_field *fields;
203
204         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
205         if (unlikely(!entry))
206                 return NULL;
207
208         fields = kzalloc(sizeof(*fields) * field_count, GFP_KERNEL);
209         if (unlikely(!fields)) {
210                 kfree(entry);
211                 return NULL;
212         }
213         entry->rule.fields = fields;
214
215         return entry;
216 }
217
218 /* Unpack a filter field's string representation from user-space
219  * buffer. */
220 static char *audit_unpack_string(void **bufp, size_t *remain, size_t len)
221 {
222         char *str;
223
224         if (!*bufp || (len == 0) || (len > *remain))
225                 return ERR_PTR(-EINVAL);
226
227         /* Of the currently implemented string fields, PATH_MAX
228          * defines the longest valid length.
229          */
230         if (len > PATH_MAX)
231                 return ERR_PTR(-ENAMETOOLONG);
232
233         str = kmalloc(len + 1, GFP_KERNEL);
234         if (unlikely(!str))
235                 return ERR_PTR(-ENOMEM);
236
237         memcpy(str, *bufp, len);
238         str[len] = 0;
239         *bufp += len;
240         *remain -= len;
241
242         return str;
243 }
244
245 /* Translate an inode field to kernel respresentation. */
246 static inline int audit_to_inode(struct audit_krule *krule,
247                                  struct audit_field *f)
248 {
249         if (krule->listnr != AUDIT_FILTER_EXIT ||
250             krule->watch || krule->inode_f)
251                 return -EINVAL;
252
253         krule->inode_f = f;
254         return 0;
255 }
256
257 /* Translate a watch string to kernel respresentation. */
258 static int audit_to_watch(struct audit_krule *krule, char *path, int len,
259                           u32 op)
260 {
261         struct audit_watch *watch;
262
263         if (!audit_ih)
264                 return -EOPNOTSUPP;
265
266         if (path[0] != '/' || path[len-1] == '/' ||
267             krule->listnr != AUDIT_FILTER_EXIT ||
268             op & ~AUDIT_EQUAL ||
269             krule->inode_f || krule->watch) /* 1 inode # per rule, for hash */
270                 return -EINVAL;
271
272         watch = audit_init_watch(path);
273         if (unlikely(IS_ERR(watch)))
274                 return PTR_ERR(watch);
275
276         audit_get_watch(watch);
277         krule->watch = watch;
278
279         return 0;
280 }
281
282 static __u32 *classes[AUDIT_SYSCALL_CLASSES];
283
284 int __init audit_register_class(int class, unsigned *list)
285 {
286         __u32 *p = kzalloc(AUDIT_BITMASK_SIZE * sizeof(__u32), GFP_KERNEL);
287         if (!p)
288                 return -ENOMEM;
289         while (*list != ~0U) {
290                 unsigned n = *list++;
291                 if (n >= AUDIT_BITMASK_SIZE * 32 - AUDIT_SYSCALL_CLASSES) {
292                         kfree(p);
293                         return -EINVAL;
294                 }
295                 p[AUDIT_WORD(n)] |= AUDIT_BIT(n);
296         }
297         if (class >= AUDIT_SYSCALL_CLASSES || classes[class]) {
298                 kfree(p);
299                 return -EINVAL;
300         }
301         classes[class] = p;
302         return 0;
303 }
304
305 /* Common user-space to kernel rule translation. */
306 static inline struct audit_entry *audit_to_entry_common(struct audit_rule *rule)
307 {
308         unsigned listnr;
309         struct audit_entry *entry;
310         int i, err;
311
312         err = -EINVAL;
313         listnr = rule->flags & ~AUDIT_FILTER_PREPEND;
314         switch(listnr) {
315         default:
316                 goto exit_err;
317         case AUDIT_FILTER_USER:
318         case AUDIT_FILTER_TYPE:
319 #ifdef CONFIG_AUDITSYSCALL
320         case AUDIT_FILTER_ENTRY:
321         case AUDIT_FILTER_EXIT:
322         case AUDIT_FILTER_TASK:
323 #endif
324                 ;
325         }
326         if (unlikely(rule->action == AUDIT_POSSIBLE)) {
327                 printk(KERN_ERR "AUDIT_POSSIBLE is deprecated\n");
328                 goto exit_err;
329         }
330         if (rule->action != AUDIT_NEVER && rule->action != AUDIT_ALWAYS)
331                 goto exit_err;
332         if (rule->field_count > AUDIT_MAX_FIELDS)
333                 goto exit_err;
334
335         err = -ENOMEM;
336         entry = audit_init_entry(rule->field_count);
337         if (!entry)
338                 goto exit_err;
339
340         entry->rule.flags = rule->flags & AUDIT_FILTER_PREPEND;
341         entry->rule.listnr = listnr;
342         entry->rule.action = rule->action;
343         entry->rule.field_count = rule->field_count;
344
345         for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
346                 entry->rule.mask[i] = rule->mask[i];
347
348         for (i = 0; i < AUDIT_SYSCALL_CLASSES; i++) {
349                 int bit = AUDIT_BITMASK_SIZE * 32 - i - 1;
350                 __u32 *p = &entry->rule.mask[AUDIT_WORD(bit)];
351                 __u32 *class;
352
353                 if (!(*p & AUDIT_BIT(bit)))
354                         continue;
355                 *p &= ~AUDIT_BIT(bit);
356                 class = classes[i];
357                 if (class) {
358                         int j;
359                         for (j = 0; j < AUDIT_BITMASK_SIZE; j++)
360                                 entry->rule.mask[j] |= class[j];
361                 }
362         }
363
364         return entry;
365
366 exit_err:
367         return ERR_PTR(err);
368 }
369
370 /* Translate struct audit_rule to kernel's rule respresentation.
371  * Exists for backward compatibility with userspace. */
372 static struct audit_entry *audit_rule_to_entry(struct audit_rule *rule)
373 {
374         struct audit_entry *entry;
375         struct audit_field *f;
376         int err = 0;
377         int i;
378
379         entry = audit_to_entry_common(rule);
380         if (IS_ERR(entry))
381                 goto exit_nofree;
382
383         for (i = 0; i < rule->field_count; i++) {
384                 struct audit_field *f = &entry->rule.fields[i];
385
386                 f->op = rule->fields[i] & (AUDIT_NEGATE|AUDIT_OPERATORS);
387                 f->type = rule->fields[i] & ~(AUDIT_NEGATE|AUDIT_OPERATORS);
388                 f->val = rule->values[i];
389
390                 err = -EINVAL;
391                 switch(f->type) {
392                 default:
393                         goto exit_free;
394                 case AUDIT_PID:
395                 case AUDIT_UID:
396                 case AUDIT_EUID:
397                 case AUDIT_SUID:
398                 case AUDIT_FSUID:
399                 case AUDIT_GID:
400                 case AUDIT_EGID:
401                 case AUDIT_SGID:
402                 case AUDIT_FSGID:
403                 case AUDIT_LOGINUID:
404                 case AUDIT_PERS:
405                 case AUDIT_ARCH:
406                 case AUDIT_MSGTYPE:
407                 case AUDIT_PPID:
408                 case AUDIT_DEVMAJOR:
409                 case AUDIT_DEVMINOR:
410                 case AUDIT_EXIT:
411                 case AUDIT_SUCCESS:
412                 case AUDIT_ARG0:
413                 case AUDIT_ARG1:
414                 case AUDIT_ARG2:
415                 case AUDIT_ARG3:
416                         break;
417                 case AUDIT_INODE:
418                         err = audit_to_inode(&entry->rule, f);
419                         if (err)
420                                 goto exit_free;
421                         break;
422                 }
423
424                 entry->rule.vers_ops = (f->op & AUDIT_OPERATORS) ? 2 : 1;
425
426                 /* Support for legacy operators where
427                  * AUDIT_NEGATE bit signifies != and otherwise assumes == */
428                 if (f->op & AUDIT_NEGATE)
429                         f->op = AUDIT_NOT_EQUAL;
430                 else if (!f->op)
431                         f->op = AUDIT_EQUAL;
432                 else if (f->op == AUDIT_OPERATORS) {
433                         err = -EINVAL;
434                         goto exit_free;
435                 }
436         }
437
438         f = entry->rule.inode_f;
439         if (f) {
440                 switch(f->op) {
441                 case AUDIT_NOT_EQUAL:
442                         entry->rule.inode_f = NULL;
443                 case AUDIT_EQUAL:
444                         break;
445                 default:
446                         err = -EINVAL;
447                         goto exit_free;
448                 }
449         }
450
451 exit_nofree:
452         return entry;
453
454 exit_free:
455         audit_free_rule(entry);
456         return ERR_PTR(err);
457 }
458
459 /* Translate struct audit_rule_data to kernel's rule respresentation. */
460 static struct audit_entry *audit_data_to_entry(struct audit_rule_data *data,
461                                                size_t datasz)
462 {
463         int err = 0;
464         struct audit_entry *entry;
465         struct audit_field *f;
466         void *bufp;
467         size_t remain = datasz - sizeof(struct audit_rule_data);
468         int i;
469         char *str;
470
471         entry = audit_to_entry_common((struct audit_rule *)data);
472         if (IS_ERR(entry))
473                 goto exit_nofree;
474
475         bufp = data->buf;
476         entry->rule.vers_ops = 2;
477         for (i = 0; i < data->field_count; i++) {
478                 struct audit_field *f = &entry->rule.fields[i];
479
480                 err = -EINVAL;
481                 if (!(data->fieldflags[i] & AUDIT_OPERATORS) ||
482                     data->fieldflags[i] & ~AUDIT_OPERATORS)
483                         goto exit_free;
484
485                 f->op = data->fieldflags[i] & AUDIT_OPERATORS;
486                 f->type = data->fields[i];
487                 f->val = data->values[i];
488                 f->se_str = NULL;
489                 f->se_rule = NULL;
490                 switch(f->type) {
491                 case AUDIT_PID:
492                 case AUDIT_UID:
493                 case AUDIT_EUID:
494                 case AUDIT_SUID:
495                 case AUDIT_FSUID:
496                 case AUDIT_GID:
497                 case AUDIT_EGID:
498                 case AUDIT_SGID:
499                 case AUDIT_FSGID:
500                 case AUDIT_LOGINUID:
501                 case AUDIT_PERS:
502                 case AUDIT_ARCH:
503                 case AUDIT_MSGTYPE:
504                 case AUDIT_PPID:
505                 case AUDIT_DEVMAJOR:
506                 case AUDIT_DEVMINOR:
507                 case AUDIT_EXIT:
508                 case AUDIT_SUCCESS:
509                 case AUDIT_ARG0:
510                 case AUDIT_ARG1:
511                 case AUDIT_ARG2:
512                 case AUDIT_ARG3:
513                         break;
514                 case AUDIT_SUBJ_USER:
515                 case AUDIT_SUBJ_ROLE:
516                 case AUDIT_SUBJ_TYPE:
517                 case AUDIT_SUBJ_SEN:
518                 case AUDIT_SUBJ_CLR:
519                 case AUDIT_OBJ_USER:
520                 case AUDIT_OBJ_ROLE:
521                 case AUDIT_OBJ_TYPE:
522                 case AUDIT_OBJ_LEV_LOW:
523                 case AUDIT_OBJ_LEV_HIGH:
524                         str = audit_unpack_string(&bufp, &remain, f->val);
525                         if (IS_ERR(str))
526                                 goto exit_free;
527                         entry->rule.buflen += f->val;
528
529                         err = selinux_audit_rule_init(f->type, f->op, str,
530                                                       &f->se_rule);
531                         /* Keep currently invalid fields around in case they
532                          * become valid after a policy reload. */
533                         if (err == -EINVAL) {
534                                 printk(KERN_WARNING "audit rule for selinux "
535                                        "\'%s\' is invalid\n",  str);
536                                 err = 0;
537                         }
538                         if (err) {
539                                 kfree(str);
540                                 goto exit_free;
541                         } else
542                                 f->se_str = str;
543                         break;
544                 case AUDIT_WATCH:
545                         str = audit_unpack_string(&bufp, &remain, f->val);
546                         if (IS_ERR(str))
547                                 goto exit_free;
548                         entry->rule.buflen += f->val;
549
550                         err = audit_to_watch(&entry->rule, str, f->val, f->op);
551                         if (err) {
552                                 kfree(str);
553                                 goto exit_free;
554                         }
555                         break;
556                 case AUDIT_INODE:
557                         err = audit_to_inode(&entry->rule, f);
558                         if (err)
559                                 goto exit_free;
560                         break;
561                 case AUDIT_FILTERKEY:
562                         err = -EINVAL;
563                         if (entry->rule.filterkey || f->val > AUDIT_MAX_KEY_LEN)
564                                 goto exit_free;
565                         str = audit_unpack_string(&bufp, &remain, f->val);
566                         if (IS_ERR(str))
567                                 goto exit_free;
568                         entry->rule.buflen += f->val;
569                         entry->rule.filterkey = str;
570                         break;
571                 default:
572                         goto exit_free;
573                 }
574         }
575
576         f = entry->rule.inode_f;
577         if (f) {
578                 switch(f->op) {
579                 case AUDIT_NOT_EQUAL:
580                         entry->rule.inode_f = NULL;
581                 case AUDIT_EQUAL:
582                         break;
583                 default:
584                         err = -EINVAL;
585                         goto exit_free;
586                 }
587         }
588
589 exit_nofree:
590         return entry;
591
592 exit_free:
593         audit_free_rule(entry);
594         return ERR_PTR(err);
595 }
596
597 /* Pack a filter field's string representation into data block. */
598 static inline size_t audit_pack_string(void **bufp, char *str)
599 {
600         size_t len = strlen(str);
601
602         memcpy(*bufp, str, len);
603         *bufp += len;
604
605         return len;
606 }
607
608 /* Translate kernel rule respresentation to struct audit_rule.
609  * Exists for backward compatibility with userspace. */
610 static struct audit_rule *audit_krule_to_rule(struct audit_krule *krule)
611 {
612         struct audit_rule *rule;
613         int i;
614
615         rule = kmalloc(sizeof(*rule), GFP_KERNEL);
616         if (unlikely(!rule))
617                 return NULL;
618         memset(rule, 0, sizeof(*rule));
619
620         rule->flags = krule->flags | krule->listnr;
621         rule->action = krule->action;
622         rule->field_count = krule->field_count;
623         for (i = 0; i < rule->field_count; i++) {
624                 rule->values[i] = krule->fields[i].val;
625                 rule->fields[i] = krule->fields[i].type;
626
627                 if (krule->vers_ops == 1) {
628                         if (krule->fields[i].op & AUDIT_NOT_EQUAL)
629                                 rule->fields[i] |= AUDIT_NEGATE;
630                 } else {
631                         rule->fields[i] |= krule->fields[i].op;
632                 }
633         }
634         for (i = 0; i < AUDIT_BITMASK_SIZE; i++) rule->mask[i] = krule->mask[i];
635
636         return rule;
637 }
638
639 /* Translate kernel rule respresentation to struct audit_rule_data. */
640 static struct audit_rule_data *audit_krule_to_data(struct audit_krule *krule)
641 {
642         struct audit_rule_data *data;
643         void *bufp;
644         int i;
645
646         data = kmalloc(sizeof(*data) + krule->buflen, GFP_KERNEL);
647         if (unlikely(!data))
648                 return NULL;
649         memset(data, 0, sizeof(*data));
650
651         data->flags = krule->flags | krule->listnr;
652         data->action = krule->action;
653         data->field_count = krule->field_count;
654         bufp = data->buf;
655         for (i = 0; i < data->field_count; i++) {
656                 struct audit_field *f = &krule->fields[i];
657
658                 data->fields[i] = f->type;
659                 data->fieldflags[i] = f->op;
660                 switch(f->type) {
661                 case AUDIT_SUBJ_USER:
662                 case AUDIT_SUBJ_ROLE:
663                 case AUDIT_SUBJ_TYPE:
664                 case AUDIT_SUBJ_SEN:
665                 case AUDIT_SUBJ_CLR:
666                 case AUDIT_OBJ_USER:
667                 case AUDIT_OBJ_ROLE:
668                 case AUDIT_OBJ_TYPE:
669                 case AUDIT_OBJ_LEV_LOW:
670                 case AUDIT_OBJ_LEV_HIGH:
671                         data->buflen += data->values[i] =
672                                 audit_pack_string(&bufp, f->se_str);
673                         break;
674                 case AUDIT_WATCH:
675                         data->buflen += data->values[i] =
676                                 audit_pack_string(&bufp, krule->watch->path);
677                         break;
678                 case AUDIT_FILTERKEY:
679                         data->buflen += data->values[i] =
680                                 audit_pack_string(&bufp, krule->filterkey);
681                         break;
682                 default:
683                         data->values[i] = f->val;
684                 }
685         }
686         for (i = 0; i < AUDIT_BITMASK_SIZE; i++) data->mask[i] = krule->mask[i];
687
688         return data;
689 }
690
691 /* Compare two rules in kernel format.  Considered success if rules
692  * don't match. */
693 static int audit_compare_rule(struct audit_krule *a, struct audit_krule *b)
694 {
695         int i;
696
697         if (a->flags != b->flags ||
698             a->listnr != b->listnr ||
699             a->action != b->action ||
700             a->field_count != b->field_count)
701                 return 1;
702
703         for (i = 0; i < a->field_count; i++) {
704                 if (a->fields[i].type != b->fields[i].type ||
705                     a->fields[i].op != b->fields[i].op)
706                         return 1;
707
708                 switch(a->fields[i].type) {
709                 case AUDIT_SUBJ_USER:
710                 case AUDIT_SUBJ_ROLE:
711                 case AUDIT_SUBJ_TYPE:
712                 case AUDIT_SUBJ_SEN:
713                 case AUDIT_SUBJ_CLR:
714                 case AUDIT_OBJ_USER:
715                 case AUDIT_OBJ_ROLE:
716                 case AUDIT_OBJ_TYPE:
717                 case AUDIT_OBJ_LEV_LOW:
718                 case AUDIT_OBJ_LEV_HIGH:
719                         if (strcmp(a->fields[i].se_str, b->fields[i].se_str))
720                                 return 1;
721                         break;
722                 case AUDIT_WATCH:
723                         if (strcmp(a->watch->path, b->watch->path))
724                                 return 1;
725                         break;
726                 case AUDIT_FILTERKEY:
727                         /* both filterkeys exist based on above type compare */
728                         if (strcmp(a->filterkey, b->filterkey))
729                                 return 1;
730                         break;
731                 default:
732                         if (a->fields[i].val != b->fields[i].val)
733                                 return 1;
734                 }
735         }
736
737         for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
738                 if (a->mask[i] != b->mask[i])
739                         return 1;
740
741         return 0;
742 }
743
744 /* Duplicate the given audit watch.  The new watch's rules list is initialized
745  * to an empty list and wlist is undefined. */
746 static struct audit_watch *audit_dupe_watch(struct audit_watch *old)
747 {
748         char *path;
749         struct audit_watch *new;
750
751         path = kstrdup(old->path, GFP_KERNEL);
752         if (unlikely(!path))
753                 return ERR_PTR(-ENOMEM);
754
755         new = audit_init_watch(path);
756         if (unlikely(IS_ERR(new))) {
757                 kfree(path);
758                 goto out;
759         }
760
761         new->dev = old->dev;
762         new->ino = old->ino;
763         get_inotify_watch(&old->parent->wdata);
764         new->parent = old->parent;
765
766 out:
767         return new;
768 }
769
770 /* Duplicate selinux field information.  The se_rule is opaque, so must be
771  * re-initialized. */
772 static inline int audit_dupe_selinux_field(struct audit_field *df,
773                                            struct audit_field *sf)
774 {
775         int ret = 0;
776         char *se_str;
777
778         /* our own copy of se_str */
779         se_str = kstrdup(sf->se_str, GFP_KERNEL);
780         if (unlikely(IS_ERR(se_str)))
781             return -ENOMEM;
782         df->se_str = se_str;
783
784         /* our own (refreshed) copy of se_rule */
785         ret = selinux_audit_rule_init(df->type, df->op, df->se_str,
786                                       &df->se_rule);
787         /* Keep currently invalid fields around in case they
788          * become valid after a policy reload. */
789         if (ret == -EINVAL) {
790                 printk(KERN_WARNING "audit rule for selinux \'%s\' is "
791                        "invalid\n", df->se_str);
792                 ret = 0;
793         }
794
795         return ret;
796 }
797
798 /* Duplicate an audit rule.  This will be a deep copy with the exception
799  * of the watch - that pointer is carried over.  The selinux specific fields
800  * will be updated in the copy.  The point is to be able to replace the old
801  * rule with the new rule in the filterlist, then free the old rule.
802  * The rlist element is undefined; list manipulations are handled apart from
803  * the initial copy. */
804 static struct audit_entry *audit_dupe_rule(struct audit_krule *old,
805                                            struct audit_watch *watch)
806 {
807         u32 fcount = old->field_count;
808         struct audit_entry *entry;
809         struct audit_krule *new;
810         char *fk;
811         int i, err = 0;
812
813         entry = audit_init_entry(fcount);
814         if (unlikely(!entry))
815                 return ERR_PTR(-ENOMEM);
816
817         new = &entry->rule;
818         new->vers_ops = old->vers_ops;
819         new->flags = old->flags;
820         new->listnr = old->listnr;
821         new->action = old->action;
822         for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
823                 new->mask[i] = old->mask[i];
824         new->buflen = old->buflen;
825         new->inode_f = old->inode_f;
826         new->watch = NULL;
827         new->field_count = old->field_count;
828         memcpy(new->fields, old->fields, sizeof(struct audit_field) * fcount);
829
830         /* deep copy this information, updating the se_rule fields, because
831          * the originals will all be freed when the old rule is freed. */
832         for (i = 0; i < fcount; i++) {
833                 switch (new->fields[i].type) {
834                 case AUDIT_SUBJ_USER:
835                 case AUDIT_SUBJ_ROLE:
836                 case AUDIT_SUBJ_TYPE:
837                 case AUDIT_SUBJ_SEN:
838                 case AUDIT_SUBJ_CLR:
839                 case AUDIT_OBJ_USER:
840                 case AUDIT_OBJ_ROLE:
841                 case AUDIT_OBJ_TYPE:
842                 case AUDIT_OBJ_LEV_LOW:
843                 case AUDIT_OBJ_LEV_HIGH:
844                         err = audit_dupe_selinux_field(&new->fields[i],
845                                                        &old->fields[i]);
846                         break;
847                 case AUDIT_FILTERKEY:
848                         fk = kstrdup(old->filterkey, GFP_KERNEL);
849                         if (unlikely(!fk))
850                                 err = -ENOMEM;
851                         else
852                                 new->filterkey = fk;
853                 }
854                 if (err) {
855                         audit_free_rule(entry);
856                         return ERR_PTR(err);
857                 }
858         }
859
860         if (watch) {
861                 audit_get_watch(watch);
862                 new->watch = watch;
863         }
864
865         return entry;
866 }
867
868 /* Update inode info in audit rules based on filesystem event. */
869 static void audit_update_watch(struct audit_parent *parent,
870                                const char *dname, dev_t dev,
871                                unsigned long ino, unsigned invalidating)
872 {
873         struct audit_watch *owatch, *nwatch, *nextw;
874         struct audit_krule *r, *nextr;
875         struct audit_entry *oentry, *nentry;
876         struct audit_buffer *ab;
877
878         mutex_lock(&audit_filter_mutex);
879         list_for_each_entry_safe(owatch, nextw, &parent->watches, wlist) {
880                 if (audit_compare_dname_path(dname, owatch->path, NULL))
881                         continue;
882
883                 /* If the update involves invalidating rules, do the inode-based
884                  * filtering now, so we don't omit records. */
885                 if (invalidating &&
886                     audit_filter_inodes(current, current->audit_context) == AUDIT_RECORD_CONTEXT)
887                         audit_set_auditable(current->audit_context);
888
889                 nwatch = audit_dupe_watch(owatch);
890                 if (unlikely(IS_ERR(nwatch))) {
891                         mutex_unlock(&audit_filter_mutex);
892                         audit_panic("error updating watch, skipping");
893                         return;
894                 }
895                 nwatch->dev = dev;
896                 nwatch->ino = ino;
897
898                 list_for_each_entry_safe(r, nextr, &owatch->rules, rlist) {
899
900                         oentry = container_of(r, struct audit_entry, rule);
901                         list_del(&oentry->rule.rlist);
902                         list_del_rcu(&oentry->list);
903
904                         nentry = audit_dupe_rule(&oentry->rule, nwatch);
905                         if (unlikely(IS_ERR(nentry)))
906                                 audit_panic("error updating watch, removing");
907                         else {
908                                 int h = audit_hash_ino((u32)ino);
909                                 list_add(&nentry->rule.rlist, &nwatch->rules);
910                                 list_add_rcu(&nentry->list, &audit_inode_hash[h]);
911                         }
912
913                         call_rcu(&oentry->rcu, audit_free_rule_rcu);
914                 }
915
916                 ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
917                 audit_log_format(ab, "audit updated rules specifying path=");
918                 audit_log_untrustedstring(ab, owatch->path);
919                 audit_log_format(ab, " with dev=%u ino=%lu\n", dev, ino);
920                 audit_log_end(ab);
921
922                 audit_remove_watch(owatch);
923                 goto add_watch_to_parent; /* event applies to a single watch */
924         }
925         mutex_unlock(&audit_filter_mutex);
926         return;
927
928 add_watch_to_parent:
929         list_add(&nwatch->wlist, &parent->watches);
930         mutex_unlock(&audit_filter_mutex);
931         return;
932 }
933
934 /* Remove all watches & rules associated with a parent that is going away. */
935 static void audit_remove_parent_watches(struct audit_parent *parent)
936 {
937         struct audit_watch *w, *nextw;
938         struct audit_krule *r, *nextr;
939         struct audit_entry *e;
940         struct audit_buffer *ab;
941
942         mutex_lock(&audit_filter_mutex);
943         parent->flags |= AUDIT_PARENT_INVALID;
944         list_for_each_entry_safe(w, nextw, &parent->watches, wlist) {
945                 list_for_each_entry_safe(r, nextr, &w->rules, rlist) {
946                         e = container_of(r, struct audit_entry, rule);
947
948                         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
949                         audit_log_format(ab, "audit implicitly removed rule path=");
950                         audit_log_untrustedstring(ab, w->path);
951                         if (r->filterkey) {
952                                 audit_log_format(ab, " key=");
953                                 audit_log_untrustedstring(ab, r->filterkey);
954                         } else
955                                 audit_log_format(ab, " key=(null)");
956                         audit_log_format(ab, " list=%d", r->listnr);
957                         audit_log_end(ab);
958
959                         list_del(&r->rlist);
960                         list_del_rcu(&e->list);
961                         call_rcu(&e->rcu, audit_free_rule_rcu);
962                 }
963                 audit_remove_watch(w);
964         }
965         mutex_unlock(&audit_filter_mutex);
966 }
967
968 /* Unregister inotify watches for parents on in_list.
969  * Generates an IN_IGNORED event. */
970 static void audit_inotify_unregister(struct list_head *in_list)
971 {
972         struct audit_parent *p, *n;
973
974         list_for_each_entry_safe(p, n, in_list, ilist) {
975                 list_del(&p->ilist);
976                 inotify_rm_watch(audit_ih, &p->wdata);
977                 /* the put matching the get in audit_do_del_rule() */
978                 put_inotify_watch(&p->wdata);
979         }
980 }
981
982 /* Find an existing audit rule.
983  * Caller must hold audit_filter_mutex to prevent stale rule data. */
984 static struct audit_entry *audit_find_rule(struct audit_entry *entry,
985                                            struct list_head *list)
986 {
987         struct audit_entry *e, *found = NULL;
988         int h;
989
990         if (entry->rule.watch) {
991                 /* we don't know the inode number, so must walk entire hash */
992                 for (h = 0; h < AUDIT_INODE_BUCKETS; h++) {
993                         list = &audit_inode_hash[h];
994                         list_for_each_entry(e, list, list)
995                                 if (!audit_compare_rule(&entry->rule, &e->rule)) {
996                                         found = e;
997                                         goto out;
998                                 }
999                 }
1000                 goto out;
1001         }
1002
1003         list_for_each_entry(e, list, list)
1004                 if (!audit_compare_rule(&entry->rule, &e->rule)) {
1005                         found = e;
1006                         goto out;
1007                 }
1008
1009 out:
1010         return found;
1011 }
1012
1013 /* Get path information necessary for adding watches. */
1014 static int audit_get_nd(char *path, struct nameidata **ndp,
1015                         struct nameidata **ndw)
1016 {
1017         struct nameidata *ndparent, *ndwatch;
1018         int err;
1019
1020         ndparent = kmalloc(sizeof(*ndparent), GFP_KERNEL);
1021         if (unlikely(!ndparent))
1022                 return -ENOMEM;
1023
1024         ndwatch = kmalloc(sizeof(*ndwatch), GFP_KERNEL);
1025         if (unlikely(!ndwatch)) {
1026                 kfree(ndparent);
1027                 return -ENOMEM;
1028         }
1029
1030         err = path_lookup(path, LOOKUP_PARENT, ndparent);
1031         if (err) {
1032                 kfree(ndparent);
1033                 kfree(ndwatch);
1034                 return err;
1035         }
1036
1037         err = path_lookup(path, 0, ndwatch);
1038         if (err) {
1039                 kfree(ndwatch);
1040                 ndwatch = NULL;
1041         }
1042
1043         *ndp = ndparent;
1044         *ndw = ndwatch;
1045
1046         return 0;
1047 }
1048
1049 /* Release resources used for watch path information. */
1050 static void audit_put_nd(struct nameidata *ndp, struct nameidata *ndw)
1051 {
1052         if (ndp) {
1053                 path_release(ndp);
1054                 kfree(ndp);
1055         }
1056         if (ndw) {
1057                 path_release(ndw);
1058                 kfree(ndw);
1059         }
1060 }
1061
1062 /* Associate the given rule with an existing parent inotify_watch.
1063  * Caller must hold audit_filter_mutex. */
1064 static void audit_add_to_parent(struct audit_krule *krule,
1065                                 struct audit_parent *parent)
1066 {
1067         struct audit_watch *w, *watch = krule->watch;
1068         int watch_found = 0;
1069
1070         list_for_each_entry(w, &parent->watches, wlist) {
1071                 if (strcmp(watch->path, w->path))
1072                         continue;
1073
1074                 watch_found = 1;
1075
1076                 /* put krule's and initial refs to temporary watch */
1077                 audit_put_watch(watch);
1078                 audit_put_watch(watch);
1079
1080                 audit_get_watch(w);
1081                 krule->watch = watch = w;
1082                 break;
1083         }
1084
1085         if (!watch_found) {
1086                 get_inotify_watch(&parent->wdata);
1087                 watch->parent = parent;
1088
1089                 list_add(&watch->wlist, &parent->watches);
1090         }
1091         list_add(&krule->rlist, &watch->rules);
1092 }
1093
1094 /* Find a matching watch entry, or add this one.
1095  * Caller must hold audit_filter_mutex. */
1096 static int audit_add_watch(struct audit_krule *krule, struct nameidata *ndp,
1097                            struct nameidata *ndw)
1098 {
1099         struct audit_watch *watch = krule->watch;
1100         struct inotify_watch *i_watch;
1101         struct audit_parent *parent;
1102         int ret = 0;
1103
1104         /* update watch filter fields */
1105         if (ndw) {
1106                 watch->dev = ndw->dentry->d_inode->i_sb->s_dev;
1107                 watch->ino = ndw->dentry->d_inode->i_ino;
1108         }
1109
1110         /* The audit_filter_mutex must not be held during inotify calls because
1111          * we hold it during inotify event callback processing.  If an existing
1112          * inotify watch is found, inotify_find_watch() grabs a reference before
1113          * returning.
1114          */
1115         mutex_unlock(&audit_filter_mutex);
1116
1117         if (inotify_find_watch(audit_ih, ndp->dentry->d_inode, &i_watch) < 0) {
1118                 parent = audit_init_parent(ndp);
1119                 if (IS_ERR(parent)) {
1120                         /* caller expects mutex locked */
1121                         mutex_lock(&audit_filter_mutex);
1122                         return PTR_ERR(parent);
1123                 }
1124         } else
1125                 parent = container_of(i_watch, struct audit_parent, wdata);
1126
1127         mutex_lock(&audit_filter_mutex);
1128
1129         /* parent was moved before we took audit_filter_mutex */
1130         if (parent->flags & AUDIT_PARENT_INVALID)
1131                 ret = -ENOENT;
1132         else
1133                 audit_add_to_parent(krule, parent);
1134
1135         /* match get in audit_init_parent or inotify_find_watch */
1136         put_inotify_watch(&parent->wdata);
1137         return ret;
1138 }
1139
1140 /* Add rule to given filterlist if not a duplicate. */
1141 static inline int audit_add_rule(struct audit_entry *entry,
1142                                  struct list_head *list)
1143 {
1144         struct audit_entry *e;
1145         struct audit_field *inode_f = entry->rule.inode_f;
1146         struct audit_watch *watch = entry->rule.watch;
1147         struct nameidata *ndp, *ndw;
1148         int h, err, putnd_needed = 0;
1149 #ifdef CONFIG_AUDITSYSCALL
1150         int dont_count = 0;
1151
1152         /* If either of these, don't count towards total */
1153         if (entry->rule.listnr == AUDIT_FILTER_USER ||
1154                 entry->rule.listnr == AUDIT_FILTER_TYPE)
1155                 dont_count = 1;
1156 #endif
1157
1158         if (inode_f) {
1159                 h = audit_hash_ino(inode_f->val);
1160                 list = &audit_inode_hash[h];
1161         }
1162
1163         mutex_lock(&audit_filter_mutex);
1164         e = audit_find_rule(entry, list);
1165         mutex_unlock(&audit_filter_mutex);
1166         if (e) {
1167                 err = -EEXIST;
1168                 goto error;
1169         }
1170
1171         /* Avoid calling path_lookup under audit_filter_mutex. */
1172         if (watch) {
1173                 err = audit_get_nd(watch->path, &ndp, &ndw);
1174                 if (err)
1175                         goto error;
1176                 putnd_needed = 1;
1177         }
1178
1179         mutex_lock(&audit_filter_mutex);
1180         if (watch) {
1181                 /* audit_filter_mutex is dropped and re-taken during this call */
1182                 err = audit_add_watch(&entry->rule, ndp, ndw);
1183                 if (err) {
1184                         mutex_unlock(&audit_filter_mutex);
1185                         goto error;
1186                 }
1187                 h = audit_hash_ino((u32)watch->ino);
1188                 list = &audit_inode_hash[h];
1189         }
1190
1191         if (entry->rule.flags & AUDIT_FILTER_PREPEND) {
1192                 list_add_rcu(&entry->list, list);
1193                 entry->rule.flags &= ~AUDIT_FILTER_PREPEND;
1194         } else {
1195                 list_add_tail_rcu(&entry->list, list);
1196         }
1197 #ifdef CONFIG_AUDITSYSCALL
1198         if (!dont_count)
1199                 audit_n_rules++;
1200 #endif
1201         mutex_unlock(&audit_filter_mutex);
1202
1203         if (putnd_needed)
1204                 audit_put_nd(ndp, ndw);
1205
1206         return 0;
1207
1208 error:
1209         if (putnd_needed)
1210                 audit_put_nd(ndp, ndw);
1211         if (watch)
1212                 audit_put_watch(watch); /* tmp watch, matches initial get */
1213         return err;
1214 }
1215
1216 /* Remove an existing rule from filterlist. */
1217 static inline int audit_del_rule(struct audit_entry *entry,
1218                                  struct list_head *list)
1219 {
1220         struct audit_entry  *e;
1221         struct audit_field *inode_f = entry->rule.inode_f;
1222         struct audit_watch *watch, *tmp_watch = entry->rule.watch;
1223         LIST_HEAD(inotify_list);
1224         int h, ret = 0;
1225 #ifdef CONFIG_AUDITSYSCALL
1226         int dont_count = 0;
1227
1228         /* If either of these, don't count towards total */
1229         if (entry->rule.listnr == AUDIT_FILTER_USER ||
1230                 entry->rule.listnr == AUDIT_FILTER_TYPE)
1231                 dont_count = 1;
1232 #endif
1233
1234         if (inode_f) {
1235                 h = audit_hash_ino(inode_f->val);
1236                 list = &audit_inode_hash[h];
1237         }
1238
1239         mutex_lock(&audit_filter_mutex);
1240         e = audit_find_rule(entry, list);
1241         if (!e) {
1242                 mutex_unlock(&audit_filter_mutex);
1243                 ret = -ENOENT;
1244                 goto out;
1245         }
1246
1247         watch = e->rule.watch;
1248         if (watch) {
1249                 struct audit_parent *parent = watch->parent;
1250
1251                 list_del(&e->rule.rlist);
1252
1253                 if (list_empty(&watch->rules)) {
1254                         audit_remove_watch(watch);
1255
1256                         if (list_empty(&parent->watches)) {
1257                                 /* Put parent on the inotify un-registration
1258                                  * list.  Grab a reference before releasing
1259                                  * audit_filter_mutex, to be released in
1260                                  * audit_inotify_unregister(). */
1261                                 list_add(&parent->ilist, &inotify_list);
1262                                 get_inotify_watch(&parent->wdata);
1263                         }
1264                 }
1265         }
1266
1267         list_del_rcu(&e->list);
1268         call_rcu(&e->rcu, audit_free_rule_rcu);
1269
1270 #ifdef CONFIG_AUDITSYSCALL
1271         if (!dont_count)
1272                 audit_n_rules--;
1273 #endif
1274         mutex_unlock(&audit_filter_mutex);
1275
1276         if (!list_empty(&inotify_list))
1277                 audit_inotify_unregister(&inotify_list);
1278
1279 out:
1280         if (tmp_watch)
1281                 audit_put_watch(tmp_watch); /* match initial get */
1282
1283         return ret;
1284 }
1285
1286 /* List rules using struct audit_rule.  Exists for backward
1287  * compatibility with userspace. */
1288 static void audit_list(int pid, int seq, struct sk_buff_head *q)
1289 {
1290         struct sk_buff *skb;
1291         struct audit_entry *entry;
1292         int i;
1293
1294         /* This is a blocking read, so use audit_filter_mutex instead of rcu
1295          * iterator to sync with list writers. */
1296         for (i=0; i<AUDIT_NR_FILTERS; i++) {
1297                 list_for_each_entry(entry, &audit_filter_list[i], list) {
1298                         struct audit_rule *rule;
1299
1300                         rule = audit_krule_to_rule(&entry->rule);
1301                         if (unlikely(!rule))
1302                                 break;
1303                         skb = audit_make_reply(pid, seq, AUDIT_LIST, 0, 1,
1304                                          rule, sizeof(*rule));
1305                         if (skb)
1306                                 skb_queue_tail(q, skb);
1307                         kfree(rule);
1308                 }
1309         }
1310         for (i = 0; i < AUDIT_INODE_BUCKETS; i++) {
1311                 list_for_each_entry(entry, &audit_inode_hash[i], list) {
1312                         struct audit_rule *rule;
1313
1314                         rule = audit_krule_to_rule(&entry->rule);
1315                         if (unlikely(!rule))
1316                                 break;
1317                         skb = audit_make_reply(pid, seq, AUDIT_LIST, 0, 1,
1318                                          rule, sizeof(*rule));
1319                         if (skb)
1320                                 skb_queue_tail(q, skb);
1321                         kfree(rule);
1322                 }
1323         }
1324         skb = audit_make_reply(pid, seq, AUDIT_LIST, 1, 1, NULL, 0);
1325         if (skb)
1326                 skb_queue_tail(q, skb);
1327 }
1328
1329 /* List rules using struct audit_rule_data. */
1330 static void audit_list_rules(int pid, int seq, struct sk_buff_head *q)
1331 {
1332         struct sk_buff *skb;
1333         struct audit_entry *e;
1334         int i;
1335
1336         /* This is a blocking read, so use audit_filter_mutex instead of rcu
1337          * iterator to sync with list writers. */
1338         for (i=0; i<AUDIT_NR_FILTERS; i++) {
1339                 list_for_each_entry(e, &audit_filter_list[i], list) {
1340                         struct audit_rule_data *data;
1341
1342                         data = audit_krule_to_data(&e->rule);
1343                         if (unlikely(!data))
1344                                 break;
1345                         skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 0, 1,
1346                                          data, sizeof(*data) + data->buflen);
1347                         if (skb)
1348                                 skb_queue_tail(q, skb);
1349                         kfree(data);
1350                 }
1351         }
1352         for (i=0; i< AUDIT_INODE_BUCKETS; i++) {
1353                 list_for_each_entry(e, &audit_inode_hash[i], list) {
1354                         struct audit_rule_data *data;
1355
1356                         data = audit_krule_to_data(&e->rule);
1357                         if (unlikely(!data))
1358                                 break;
1359                         skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 0, 1,
1360                                          data, sizeof(*data) + data->buflen);
1361                         if (skb)
1362                                 skb_queue_tail(q, skb);
1363                         kfree(data);
1364                 }
1365         }
1366         skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 1, 1, NULL, 0);
1367         if (skb)
1368                 skb_queue_tail(q, skb);
1369 }
1370
1371 /* Log rule additions and removals */
1372 static void audit_log_rule_change(uid_t loginuid, u32 sid, char *action,
1373                                   struct audit_krule *rule, int res)
1374 {
1375         struct audit_buffer *ab;
1376
1377         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
1378         if (!ab)
1379                 return;
1380         audit_log_format(ab, "auid=%u", loginuid);
1381         if (sid) {
1382                 char *ctx = NULL;
1383                 u32 len;
1384                 if (selinux_ctxid_to_string(sid, &ctx, &len))
1385                         audit_log_format(ab, " ssid=%u", sid);
1386                 else
1387                         audit_log_format(ab, " subj=%s", ctx);
1388                 kfree(ctx);
1389         }
1390         audit_log_format(ab, " %s rule key=", action);
1391         if (rule->filterkey)
1392                 audit_log_untrustedstring(ab, rule->filterkey);
1393         else
1394                 audit_log_format(ab, "(null)");
1395         audit_log_format(ab, " list=%d res=%d", rule->listnr, res);
1396         audit_log_end(ab);
1397 }
1398
1399 /**
1400  * audit_receive_filter - apply all rules to the specified message type
1401  * @type: audit message type
1402  * @pid: target pid for netlink audit messages
1403  * @uid: target uid for netlink audit messages
1404  * @seq: netlink audit message sequence (serial) number
1405  * @data: payload data
1406  * @datasz: size of payload data
1407  * @loginuid: loginuid of sender
1408  * @sid: SE Linux Security ID of sender
1409  */
1410 int audit_receive_filter(int type, int pid, int uid, int seq, void *data,
1411                          size_t datasz, uid_t loginuid, u32 sid)
1412 {
1413         struct task_struct *tsk;
1414         struct audit_netlink_list *dest;
1415         int err = 0;
1416         struct audit_entry *entry;
1417
1418         switch (type) {
1419         case AUDIT_LIST:
1420         case AUDIT_LIST_RULES:
1421                 /* We can't just spew out the rules here because we might fill
1422                  * the available socket buffer space and deadlock waiting for
1423                  * auditctl to read from it... which isn't ever going to
1424                  * happen if we're actually running in the context of auditctl
1425                  * trying to _send_ the stuff */
1426                  
1427                 dest = kmalloc(sizeof(struct audit_netlink_list), GFP_KERNEL);
1428                 if (!dest)
1429                         return -ENOMEM;
1430                 dest->pid = pid;
1431                 skb_queue_head_init(&dest->q);
1432
1433                 mutex_lock(&audit_filter_mutex);
1434                 if (type == AUDIT_LIST)
1435                         audit_list(pid, seq, &dest->q);
1436                 else
1437                         audit_list_rules(pid, seq, &dest->q);
1438                 mutex_unlock(&audit_filter_mutex);
1439
1440                 tsk = kthread_run(audit_send_list, dest, "audit_send_list");
1441                 if (IS_ERR(tsk)) {
1442                         skb_queue_purge(&dest->q);
1443                         kfree(dest);
1444                         err = PTR_ERR(tsk);
1445                 }
1446                 break;
1447         case AUDIT_ADD:
1448         case AUDIT_ADD_RULE:
1449                 if (type == AUDIT_ADD)
1450                         entry = audit_rule_to_entry(data);
1451                 else
1452                         entry = audit_data_to_entry(data, datasz);
1453                 if (IS_ERR(entry))
1454                         return PTR_ERR(entry);
1455
1456                 err = audit_add_rule(entry,
1457                                      &audit_filter_list[entry->rule.listnr]);
1458                 audit_log_rule_change(loginuid, sid, "add", &entry->rule, !err);
1459
1460                 if (err)
1461                         audit_free_rule(entry);
1462                 break;
1463         case AUDIT_DEL:
1464         case AUDIT_DEL_RULE:
1465                 if (type == AUDIT_DEL)
1466                         entry = audit_rule_to_entry(data);
1467                 else
1468                         entry = audit_data_to_entry(data, datasz);
1469                 if (IS_ERR(entry))
1470                         return PTR_ERR(entry);
1471
1472                 err = audit_del_rule(entry,
1473                                      &audit_filter_list[entry->rule.listnr]);
1474                 audit_log_rule_change(loginuid, sid, "remove", &entry->rule,
1475                                       !err);
1476
1477                 audit_free_rule(entry);
1478                 break;
1479         default:
1480                 return -EINVAL;
1481         }
1482
1483         return err;
1484 }
1485
1486 int audit_comparator(const u32 left, const u32 op, const u32 right)
1487 {
1488         switch (op) {
1489         case AUDIT_EQUAL:
1490                 return (left == right);
1491         case AUDIT_NOT_EQUAL:
1492                 return (left != right);
1493         case AUDIT_LESS_THAN:
1494                 return (left < right);
1495         case AUDIT_LESS_THAN_OR_EQUAL:
1496                 return (left <= right);
1497         case AUDIT_GREATER_THAN:
1498                 return (left > right);
1499         case AUDIT_GREATER_THAN_OR_EQUAL:
1500                 return (left >= right);
1501         }
1502         BUG();
1503         return 0;
1504 }
1505
1506 /* Compare given dentry name with last component in given path,
1507  * return of 0 indicates a match. */
1508 int audit_compare_dname_path(const char *dname, const char *path,
1509                              int *dirlen)
1510 {
1511         int dlen, plen;
1512         const char *p;
1513
1514         if (!dname || !path)
1515                 return 1;
1516
1517         dlen = strlen(dname);
1518         plen = strlen(path);
1519         if (plen < dlen)
1520                 return 1;
1521
1522         /* disregard trailing slashes */
1523         p = path + plen - 1;
1524         while ((*p == '/') && (p > path))
1525                 p--;
1526
1527         /* find last path component */
1528         p = p - dlen + 1;
1529         if (p < path)
1530                 return 1;
1531         else if (p > path) {
1532                 if (*--p != '/')
1533                         return 1;
1534                 else
1535                         p++;
1536         }
1537
1538         /* return length of path's directory component */
1539         if (dirlen)
1540                 *dirlen = p - path;
1541         return strncmp(p, dname, dlen);
1542 }
1543
1544 static int audit_filter_user_rules(struct netlink_skb_parms *cb,
1545                                    struct audit_krule *rule,
1546                                    enum audit_state *state)
1547 {
1548         int i;
1549
1550         for (i = 0; i < rule->field_count; i++) {
1551                 struct audit_field *f = &rule->fields[i];
1552                 int result = 0;
1553
1554                 switch (f->type) {
1555                 case AUDIT_PID:
1556                         result = audit_comparator(cb->creds.pid, f->op, f->val);
1557                         break;
1558                 case AUDIT_UID:
1559                         result = audit_comparator(cb->creds.uid, f->op, f->val);
1560                         break;
1561                 case AUDIT_GID:
1562                         result = audit_comparator(cb->creds.gid, f->op, f->val);
1563                         break;
1564                 case AUDIT_LOGINUID:
1565                         result = audit_comparator(cb->loginuid, f->op, f->val);
1566                         break;
1567                 }
1568
1569                 if (!result)
1570                         return 0;
1571         }
1572         switch (rule->action) {
1573         case AUDIT_NEVER:    *state = AUDIT_DISABLED;       break;
1574         case AUDIT_ALWAYS:   *state = AUDIT_RECORD_CONTEXT; break;
1575         }
1576         return 1;
1577 }
1578
1579 int audit_filter_user(struct netlink_skb_parms *cb, int type)
1580 {
1581         struct audit_entry *e;
1582         enum audit_state   state;
1583         int ret = 1;
1584
1585         rcu_read_lock();
1586         list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_USER], list) {
1587                 if (audit_filter_user_rules(cb, &e->rule, &state)) {
1588                         if (state == AUDIT_DISABLED)
1589                                 ret = 0;
1590                         break;
1591                 }
1592         }
1593         rcu_read_unlock();
1594
1595         return ret; /* Audit by default */
1596 }
1597
1598 int audit_filter_type(int type)
1599 {
1600         struct audit_entry *e;
1601         int result = 0;
1602         
1603         rcu_read_lock();
1604         if (list_empty(&audit_filter_list[AUDIT_FILTER_TYPE]))
1605                 goto unlock_and_return;
1606
1607         list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TYPE],
1608                                 list) {
1609                 int i;
1610                 for (i = 0; i < e->rule.field_count; i++) {
1611                         struct audit_field *f = &e->rule.fields[i];
1612                         if (f->type == AUDIT_MSGTYPE) {
1613                                 result = audit_comparator(type, f->op, f->val);
1614                                 if (!result)
1615                                         break;
1616                         }
1617                 }
1618                 if (result)
1619                         goto unlock_and_return;
1620         }
1621 unlock_and_return:
1622         rcu_read_unlock();
1623         return result;
1624 }
1625
1626 /* Check to see if the rule contains any selinux fields.  Returns 1 if there
1627    are selinux fields specified in the rule, 0 otherwise. */
1628 static inline int audit_rule_has_selinux(struct audit_krule *rule)
1629 {
1630         int i;
1631
1632         for (i = 0; i < rule->field_count; i++) {
1633                 struct audit_field *f = &rule->fields[i];
1634                 switch (f->type) {
1635                 case AUDIT_SUBJ_USER:
1636                 case AUDIT_SUBJ_ROLE:
1637                 case AUDIT_SUBJ_TYPE:
1638                 case AUDIT_SUBJ_SEN:
1639                 case AUDIT_SUBJ_CLR:
1640                 case AUDIT_OBJ_USER:
1641                 case AUDIT_OBJ_ROLE:
1642                 case AUDIT_OBJ_TYPE:
1643                 case AUDIT_OBJ_LEV_LOW:
1644                 case AUDIT_OBJ_LEV_HIGH:
1645                         return 1;
1646                 }
1647         }
1648
1649         return 0;
1650 }
1651
1652 /* This function will re-initialize the se_rule field of all applicable rules.
1653  * It will traverse the filter lists serarching for rules that contain selinux
1654  * specific filter fields.  When such a rule is found, it is copied, the
1655  * selinux field is re-initialized, and the old rule is replaced with the
1656  * updated rule. */
1657 int selinux_audit_rule_update(void)
1658 {
1659         struct audit_entry *entry, *n, *nentry;
1660         struct audit_watch *watch;
1661         int i, err = 0;
1662
1663         /* audit_filter_mutex synchronizes the writers */
1664         mutex_lock(&audit_filter_mutex);
1665
1666         for (i = 0; i < AUDIT_NR_FILTERS; i++) {
1667                 list_for_each_entry_safe(entry, n, &audit_filter_list[i], list) {
1668                         if (!audit_rule_has_selinux(&entry->rule))
1669                                 continue;
1670
1671                         watch = entry->rule.watch;
1672                         nentry = audit_dupe_rule(&entry->rule, watch);
1673                         if (unlikely(IS_ERR(nentry))) {
1674                                 /* save the first error encountered for the
1675                                  * return value */
1676                                 if (!err)
1677                                         err = PTR_ERR(nentry);
1678                                 audit_panic("error updating selinux filters");
1679                                 if (watch)
1680                                         list_del(&entry->rule.rlist);
1681                                 list_del_rcu(&entry->list);
1682                         } else {
1683                                 if (watch) {
1684                                         list_add(&nentry->rule.rlist,
1685                                                  &watch->rules);
1686                                         list_del(&entry->rule.rlist);
1687                                 }
1688                                 list_replace_rcu(&entry->list, &nentry->list);
1689                         }
1690                         call_rcu(&entry->rcu, audit_free_rule_rcu);
1691                 }
1692         }
1693
1694         mutex_unlock(&audit_filter_mutex);
1695
1696         return err;
1697 }
1698
1699 /* Update watch data in audit rules based on inotify events. */
1700 void audit_handle_ievent(struct inotify_watch *i_watch, u32 wd, u32 mask,
1701                          u32 cookie, const char *dname, struct inode *inode)
1702 {
1703         struct audit_parent *parent;
1704
1705         parent = container_of(i_watch, struct audit_parent, wdata);
1706
1707         if (mask & (IN_CREATE|IN_MOVED_TO) && inode)
1708                 audit_update_watch(parent, dname, inode->i_sb->s_dev,
1709                                    inode->i_ino, 0);
1710         else if (mask & (IN_DELETE|IN_MOVED_FROM))
1711                 audit_update_watch(parent, dname, (dev_t)-1, (unsigned long)-1, 1);
1712         /* inotify automatically removes the watch and sends IN_IGNORED */
1713         else if (mask & (IN_DELETE_SELF|IN_UNMOUNT))
1714                 audit_remove_parent_watches(parent);
1715         /* inotify does not remove the watch, so remove it manually */
1716         else if(mask & IN_MOVE_SELF) {
1717                 audit_remove_parent_watches(parent);
1718                 inotify_remove_watch_locked(audit_ih, i_watch);
1719         } else if (mask & IN_IGNORED)
1720                 put_inotify_watch(i_watch);
1721 }