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