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