upgrade to linux 2.6.9-1.11_FC2
[linux-2.6.git] / security / selinux / avc.c
1 /*
2  * Implementation of the kernel access vector cache (AVC).
3  *
4  * Authors:  Stephen Smalley, <sds@epoch.ncsc.mil>
5  *           James Morris <jmorris@redhat.com>
6  *
7  * Update:   KaiGai, Kohei <kaigai@ak.jp.nec.com>
8  *     Replaced the avc_lock spinlock by RCU.
9  *
10  * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
11  *
12  *      This program is free software; you can redistribute it and/or modify
13  *      it under the terms of the GNU General Public License version 2,
14  *      as published by the Free Software Foundation.
15  */
16 #include <linux/types.h>
17 #include <linux/stddef.h>
18 #include <linux/kernel.h>
19 #include <linux/slab.h>
20 #include <linux/fs.h>
21 #include <linux/dcache.h>
22 #include <linux/init.h>
23 #include <linux/skbuff.h>
24 #include <linux/percpu.h>
25 #include <net/sock.h>
26 #include <linux/un.h>
27 #include <net/af_unix.h>
28 #include <linux/ip.h>
29 #include <linux/audit.h>
30 #include <linux/ipv6.h>
31 #include <net/ipv6.h>
32 #include "avc.h"
33 #include "avc_ss.h"
34 #ifdef CONFIG_AUDIT
35 #include "class_to_string.h"
36 #endif
37 #include "common_perm_to_string.h"
38 #include "av_inherit.h"
39 #include "av_perm_to_string.h"
40 #include "objsec.h"
41
42 #define AVC_CACHE_SLOTS                 512
43 #define AVC_DEF_CACHE_THRESHOLD         512
44 #define AVC_CACHE_RECLAIM               16
45
46 #ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
47 #define avc_cache_stats_incr(field)                             \
48 do {                                                            \
49         per_cpu(avc_cache_stats, get_cpu()).field++;            \
50         put_cpu();                                              \
51 } while (0)
52 #else
53 #define avc_cache_stats_incr(field)     do {} while (0)
54 #endif
55
56 struct avc_entry {
57         u32                     ssid;
58         u32                     tsid;
59         u16                     tclass;
60         struct av_decision      avd;
61         atomic_t                used;   /* used recently */
62 };
63
64 struct avc_node {
65         struct avc_entry        ae;
66         struct list_head        list;
67         struct rcu_head         rhead;
68 };
69
70 struct avc_cache {
71         struct list_head        slots[AVC_CACHE_SLOTS];
72         spinlock_t              slots_lock[AVC_CACHE_SLOTS]; /* lock for writes */
73         atomic_t                lru_hint;       /* LRU hint for reclaim scan */
74         atomic_t                active_nodes;
75         u32                     latest_notif;   /* latest revocation notification */
76 };
77
78 struct avc_callback_node {
79         int (*callback) (u32 event, u32 ssid, u32 tsid,
80                          u16 tclass, u32 perms,
81                          u32 *out_retained);
82         u32 events;
83         u32 ssid;
84         u32 tsid;
85         u16 tclass;
86         u32 perms;
87         struct avc_callback_node *next;
88 };
89
90 /* Exported via selinufs */
91 unsigned int avc_cache_threshold = AVC_DEF_CACHE_THRESHOLD;
92
93 #ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
94 DEFINE_PER_CPU(struct avc_cache_stats, avc_cache_stats) = { 0 };
95 #endif
96
97 static struct avc_cache avc_cache;
98 static struct avc_callback_node *avc_callbacks;
99 static kmem_cache_t *avc_node_cachep;
100
101 static inline int avc_hash(u32 ssid, u32 tsid, u16 tclass)
102 {
103         return (ssid ^ (tsid<<2) ^ (tclass<<4)) & (AVC_CACHE_SLOTS - 1);
104 }
105
106 /**
107  * avc_dump_av - Display an access vector in human-readable form.
108  * @tclass: target security class
109  * @av: access vector
110  */
111 void avc_dump_av(struct audit_buffer *ab, u16 tclass, u32 av)
112 {
113         char **common_pts = NULL;
114         u32 common_base = 0;
115         int i, i2, perm;
116
117         if (av == 0) {
118                 audit_log_format(ab, " null");
119                 return;
120         }
121
122         for (i = 0; i < ARRAY_SIZE(av_inherit); i++) {
123                 if (av_inherit[i].tclass == tclass) {
124                         common_pts = av_inherit[i].common_pts;
125                         common_base = av_inherit[i].common_base;
126                         break;
127                 }
128         }
129
130         audit_log_format(ab, " {");
131         i = 0;
132         perm = 1;
133         while (perm < common_base) {
134                 if (perm & av)
135                         audit_log_format(ab, " %s", common_pts[i]);
136                 i++;
137                 perm <<= 1;
138         }
139
140         while (i < sizeof(av) * 8) {
141                 if (perm & av) {
142                         for (i2 = 0; i2 < ARRAY_SIZE(av_perm_to_string); i2++) {
143                                 if ((av_perm_to_string[i2].tclass == tclass) &&
144                                     (av_perm_to_string[i2].value == perm))
145                                         break;
146                         }
147                         if (i2 < ARRAY_SIZE(av_perm_to_string))
148                                 audit_log_format(ab, " %s",
149                                                  av_perm_to_string[i2].name);
150                 }
151                 i++;
152                 perm <<= 1;
153         }
154
155         audit_log_format(ab, " }");
156 }
157
158 /**
159  * avc_dump_query - Display a SID pair and a class in human-readable form.
160  * @ssid: source security identifier
161  * @tsid: target security identifier
162  * @tclass: target security class
163  */
164 void avc_dump_query(struct audit_buffer *ab, u32 ssid, u32 tsid, u16 tclass)
165 {
166         int rc;
167         char *scontext;
168         u32 scontext_len;
169
170         rc = security_sid_to_context(ssid, &scontext, &scontext_len);
171         if (rc)
172                 audit_log_format(ab, "ssid=%d", ssid);
173         else {
174                 audit_log_format(ab, "scontext=%s", scontext);
175                 kfree(scontext);
176         }
177
178         rc = security_sid_to_context(tsid, &scontext, &scontext_len);
179         if (rc)
180                 audit_log_format(ab, " tsid=%d", tsid);
181         else {
182                 audit_log_format(ab, " tcontext=%s", scontext);
183                 kfree(scontext);
184         }
185         audit_log_format(ab, " tclass=%s", class_to_string[tclass]);
186 }
187
188 /**
189  * avc_init - Initialize the AVC.
190  *
191  * Initialize the access vector cache.
192  */
193 void __init avc_init(void)
194 {
195         int i;
196
197         for (i = 0; i < AVC_CACHE_SLOTS; i++) {
198                 INIT_LIST_HEAD(&avc_cache.slots[i]);
199                 avc_cache.slots_lock[i] = SPIN_LOCK_UNLOCKED;
200         }
201         atomic_set(&avc_cache.active_nodes, 0);
202         atomic_set(&avc_cache.lru_hint, 0);
203         
204         avc_node_cachep = kmem_cache_create("avc_node", sizeof(struct avc_node),
205                                              0, SLAB_PANIC, NULL, NULL);
206
207         audit_log(current->audit_context, "AVC INITIALIZED\n");
208 }
209
210 int avc_get_hash_stats(char *page)
211 {
212         int i, chain_len, max_chain_len, slots_used;
213         struct avc_node *node;
214
215         rcu_read_lock();
216
217         slots_used = 0;
218         max_chain_len = 0;
219         for (i = 0; i < AVC_CACHE_SLOTS; i++) {
220                 if (!list_empty(&avc_cache.slots[i])) {
221                         slots_used++;
222                         chain_len = 0;
223                         list_for_each_entry_rcu(node, &avc_cache.slots[i], list)
224                                 chain_len++;
225                         if (chain_len > max_chain_len)
226                                 max_chain_len = chain_len;
227                 }
228         }
229
230         rcu_read_unlock();
231
232         return scnprintf(page, PAGE_SIZE, "entries: %d\nbuckets used: %d/%d\n"
233                          "longest chain: %d\n",
234                          atomic_read(&avc_cache.active_nodes),
235                          slots_used, AVC_CACHE_SLOTS, max_chain_len);
236 }
237
238 static void avc_node_free(struct rcu_head *rhead)
239 {
240         struct avc_node *node = container_of(rhead, struct avc_node, rhead);
241         kmem_cache_free(avc_node_cachep, node);
242         avc_cache_stats_incr(frees);
243 }
244
245 static void avc_node_delete(struct avc_node *node)
246 {
247         list_del_rcu(&node->list);
248         call_rcu(&node->rhead, avc_node_free);
249         atomic_dec(&avc_cache.active_nodes);
250 }
251
252 static void avc_node_kill(struct avc_node *node)
253 {
254         kmem_cache_free(avc_node_cachep, node);
255         avc_cache_stats_incr(frees);
256         atomic_dec(&avc_cache.active_nodes);
257 }
258
259 static void avc_node_replace(struct avc_node *new, struct avc_node *old)
260 {
261         list_replace_rcu(&old->list, &new->list);
262         call_rcu(&old->rhead, avc_node_free);
263         atomic_dec(&avc_cache.active_nodes);
264 }
265
266 static inline int avc_reclaim_node(void)
267 {
268         struct avc_node *node;
269         int hvalue, try, ecx;
270         unsigned long flags;
271
272         for (try = 0, ecx = 0; try < AVC_CACHE_SLOTS; try++ ) {
273                 hvalue = atomic_inc_return(&avc_cache.lru_hint) & (AVC_CACHE_SLOTS - 1);
274
275                 if (!spin_trylock_irqsave(&avc_cache.slots_lock[hvalue], flags))
276                         continue;
277
278                 list_for_each_entry(node, &avc_cache.slots[hvalue], list) {
279                         if (atomic_dec_and_test(&node->ae.used)) {
280                                 /* Recently Unused */
281                                 avc_node_delete(node);
282                                 avc_cache_stats_incr(reclaims);
283                                 ecx++;
284                                 if (ecx >= AVC_CACHE_RECLAIM) {
285                                         spin_unlock_irqrestore(&avc_cache.slots_lock[hvalue], flags);
286                                         goto out;
287                                 }
288                         }
289                 }
290                 spin_unlock_irqrestore(&avc_cache.slots_lock[hvalue], flags);
291         }
292 out:
293         return ecx;
294 }
295
296 static struct avc_node *avc_alloc_node(void)
297 {
298         struct avc_node *node;
299         
300         node = kmem_cache_alloc(avc_node_cachep, SLAB_ATOMIC);
301         if (!node)
302                 goto out;
303                 
304         memset(node, 0, sizeof(*node));
305         INIT_RCU_HEAD(&node->rhead);
306         INIT_LIST_HEAD(&node->list);
307         atomic_set(&node->ae.used, 1);
308         avc_cache_stats_incr(allocations);
309         
310         if (atomic_inc_return(&avc_cache.active_nodes) > avc_cache_threshold)
311                 avc_reclaim_node();
312
313 out:
314         return node;
315 }
316
317 static void avc_node_populate(struct avc_node *node, u32 ssid, u32 tsid, u16 tclass, struct avc_entry *ae)
318 {
319         node->ae.ssid = ssid;
320         node->ae.tsid = tsid;
321         node->ae.tclass = tclass;
322         memcpy(&node->ae.avd, &ae->avd, sizeof(node->ae.avd));
323 }
324
325 static inline struct avc_node *avc_search_node(u32 ssid, u32 tsid, u16 tclass)
326 {
327         struct avc_node *node, *ret = NULL;
328         int hvalue;
329
330         hvalue = avc_hash(ssid, tsid, tclass);
331         list_for_each_entry_rcu(node, &avc_cache.slots[hvalue], list) {
332                 if (ssid == node->ae.ssid &&
333                     tclass == node->ae.tclass &&
334                     tsid == node->ae.tsid) {
335                         ret = node;
336                         break;
337                 }
338         }
339
340         if (ret == NULL) {
341                 /* cache miss */
342                 goto out;
343         }
344
345         /* cache hit */
346         if (atomic_read(&ret->ae.used) != 1)
347                 atomic_set(&ret->ae.used, 1);
348 out:
349         return ret;
350 }
351
352 /**
353  * avc_lookup - Look up an AVC entry.
354  * @ssid: source security identifier
355  * @tsid: target security identifier
356  * @tclass: target security class
357  * @requested: requested permissions, interpreted based on @tclass
358  *
359  * Look up an AVC entry that is valid for the
360  * @requested permissions between the SID pair
361  * (@ssid, @tsid), interpreting the permissions
362  * based on @tclass.  If a valid AVC entry exists,
363  * then this function return the avc_node.
364  * Otherwise, this function returns NULL.
365  */
366 static struct avc_node *avc_lookup(u32 ssid, u32 tsid, u16 tclass, u32 requested)
367 {
368         struct avc_node *node;
369
370         avc_cache_stats_incr(lookups);
371         node = avc_search_node(ssid, tsid, tclass);
372
373         if (node && ((node->ae.avd.decided & requested) == requested)) {
374                 avc_cache_stats_incr(hits);
375                 goto out;
376         }
377
378         node = NULL;
379         avc_cache_stats_incr(misses);
380 out:
381         return node;
382 }
383
384 static int avc_latest_notif_update(int seqno, int is_insert)
385 {
386         int ret = 0;
387         static spinlock_t notif_lock = SPIN_LOCK_UNLOCKED;
388         unsigned long flag;
389
390         spin_lock_irqsave(&notif_lock, flag);
391         if (is_insert) {
392                 if (seqno < avc_cache.latest_notif) {
393                         printk(KERN_WARNING "avc:  seqno %d < latest_notif %d\n",
394                                seqno, avc_cache.latest_notif);
395                         ret = -EAGAIN;
396                 }
397         } else {
398                 if (seqno > avc_cache.latest_notif)
399                         avc_cache.latest_notif = seqno;
400         }
401         spin_unlock_irqrestore(&notif_lock, flag);
402
403         return ret;
404 }
405
406 /**
407  * avc_insert - Insert an AVC entry.
408  * @ssid: source security identifier
409  * @tsid: target security identifier
410  * @tclass: target security class
411  * @ae: AVC entry
412  *
413  * Insert an AVC entry for the SID pair
414  * (@ssid, @tsid) and class @tclass.
415  * The access vectors and the sequence number are
416  * normally provided by the security server in
417  * response to a security_compute_av() call.  If the
418  * sequence number @ae->avd.seqno is not less than the latest
419  * revocation notification, then the function copies
420  * the access vectors into a cache entry, returns
421  * avc_node inserted. Otherwise, this function returns NULL.
422  */
423 static struct avc_node *avc_insert(u32 ssid, u32 tsid, u16 tclass, struct avc_entry *ae)
424 {
425         struct avc_node *pos, *node = NULL;
426         int hvalue;
427         unsigned long flag;
428
429         if (avc_latest_notif_update(ae->avd.seqno, 1))
430                 goto out;
431
432         node = avc_alloc_node();
433         if (node) {
434                 hvalue = avc_hash(ssid, tsid, tclass);
435                 avc_node_populate(node, ssid, tsid, tclass, ae);
436
437                 spin_lock_irqsave(&avc_cache.slots_lock[hvalue], flag);
438                 list_for_each_entry(pos, &avc_cache.slots[hvalue], list) {
439                         if (pos->ae.ssid == ssid &&
440                             pos->ae.tsid == tsid &&
441                             pos->ae.tclass == tclass) {
442                                 avc_node_replace(node, pos);
443                                 goto found;
444                         }
445                 }
446                 list_add_rcu(&node->list, &avc_cache.slots[hvalue]);
447 found:
448                 spin_unlock_irqrestore(&avc_cache.slots_lock[hvalue], flag);
449         }
450 out:
451         return node;
452 }
453
454 static inline void avc_print_ipv6_addr(struct audit_buffer *ab,
455                                        struct in6_addr *addr, u16 port,
456                                        char *name1, char *name2)
457 {
458         if (!ipv6_addr_any(addr))
459                 audit_log_format(ab, " %s=%04x:%04x:%04x:%04x:%04x:"
460                                  "%04x:%04x:%04x", name1, NIP6(*addr));
461         if (port)
462                 audit_log_format(ab, " %s=%d", name2, ntohs(port));
463 }
464
465 static inline void avc_print_ipv4_addr(struct audit_buffer *ab, u32 addr,
466                                        u16 port, char *name1, char *name2)
467 {
468         if (addr)
469                 audit_log_format(ab, " %s=%d.%d.%d.%d", name1, NIPQUAD(addr));
470         if (port)
471                 audit_log_format(ab, " %s=%d", name2, ntohs(port));
472 }
473
474 /**
475  * avc_audit - Audit the granting or denial of permissions.
476  * @ssid: source security identifier
477  * @tsid: target security identifier
478  * @tclass: target security class
479  * @requested: requested permissions
480  * @avd: access vector decisions
481  * @result: result from avc_has_perm_noaudit
482  * @a:  auxiliary audit data
483  *
484  * Audit the granting or denial of permissions in accordance
485  * with the policy.  This function is typically called by
486  * avc_has_perm() after a permission check, but can also be
487  * called directly by callers who use avc_has_perm_noaudit()
488  * in order to separate the permission check from the auditing.
489  * For example, this separation is useful when the permission check must
490  * be performed under a lock, to allow the lock to be released
491  * before calling the auditing code.
492  */
493 void avc_audit(u32 ssid, u32 tsid,
494                u16 tclass, u32 requested,
495                struct av_decision *avd, int result, struct avc_audit_data *a)
496 {
497         struct task_struct *tsk = current;
498         struct inode *inode = NULL;
499         u32 denied, audited;
500         struct audit_buffer *ab;
501
502         denied = requested & ~avd->allowed;
503         if (denied) {
504                 audited = denied;
505                 if (!(audited & avd->auditdeny))
506                         return;
507         } else if (result) {
508                 audited = denied = requested;
509         } else {
510                 audited = requested;
511                 if (!(audited & avd->auditallow))
512                         return;
513         }
514
515         ab = audit_log_start(current->audit_context);
516         if (!ab)
517                 return;         /* audit_panic has been called */
518         audit_log_format(ab, "avc:  %s ", denied ? "denied" : "granted");
519         avc_dump_av(ab, tclass,audited);
520         audit_log_format(ab, " for ");
521         if (a && a->tsk)
522                 tsk = a->tsk;
523         if (tsk && tsk->pid) {
524                 struct mm_struct *mm;
525                 struct vm_area_struct *vma;
526                 audit_log_format(ab, " pid=%d", tsk->pid);
527                 if (tsk == current)
528                         mm = current->mm;
529                 else
530                         mm = get_task_mm(tsk);
531                 if (mm) {
532                         if (down_read_trylock(&mm->mmap_sem)) {
533                                 vma = mm->mmap;
534                                 while (vma) {
535                                         if ((vma->vm_flags & VM_EXECUTABLE) &&
536                                             vma->vm_file) {
537                                                 audit_log_d_path(ab, "exe=",
538                                                         vma->vm_file->f_dentry,
539                                                         vma->vm_file->f_vfsmnt);
540                                                 break;
541                                         }
542                                         vma = vma->vm_next;
543                                 }
544                                 up_read(&mm->mmap_sem);
545                         }
546                         if (tsk != current)
547                                 mmput(mm);
548                 } else {
549                         audit_log_format(ab, " comm=%s", tsk->comm);
550                 }
551         }
552         if (a) {
553                 switch (a->type) {
554                 case AVC_AUDIT_DATA_IPC:
555                         audit_log_format(ab, " key=%d", a->u.ipc_id);
556                         break;
557                 case AVC_AUDIT_DATA_CAP:
558                         audit_log_format(ab, " capability=%d", a->u.cap);
559                         break;
560                 case AVC_AUDIT_DATA_FS:
561                         if (a->u.fs.dentry) {
562                                 struct dentry *dentry = a->u.fs.dentry;
563                                 if (a->u.fs.mnt) {
564                                         audit_log_d_path(ab, "path=", dentry,
565                                                         a->u.fs.mnt);
566                                 } else {
567                                         audit_log_format(ab, " name=%s",
568                                                          dentry->d_name.name);
569                                 }
570                                 inode = dentry->d_inode;
571                         } else if (a->u.fs.inode) {
572                                 struct dentry *dentry;
573                                 inode = a->u.fs.inode;
574                                 dentry = d_find_alias(inode);
575                                 if (dentry) {
576                                         audit_log_format(ab, " name=%s",
577                                                          dentry->d_name.name);
578                                         dput(dentry);
579                                 }
580                         }
581                         if (inode)
582                                 audit_log_format(ab, " dev=%s ino=%ld",
583                                                  inode->i_sb->s_id,
584                                                  inode->i_ino);
585                         break;
586                 case AVC_AUDIT_DATA_NET:
587                         if (a->u.net.sk) {
588                                 struct sock *sk = a->u.net.sk;
589                                 struct unix_sock *u;
590                                 int len = 0;
591                                 char *p = NULL;
592
593                                 switch (sk->sk_family) {
594                                 case AF_INET: {
595                                         struct inet_opt *inet = inet_sk(sk);
596
597                                         avc_print_ipv4_addr(ab, inet->rcv_saddr,
598                                                             inet->sport,
599                                                             "laddr", "lport");
600                                         avc_print_ipv4_addr(ab, inet->daddr,
601                                                             inet->dport,
602                                                             "faddr", "fport");
603                                         break;
604                                 }
605                                 case AF_INET6: {
606                                         struct inet_opt *inet = inet_sk(sk);
607                                         struct ipv6_pinfo *inet6 = inet6_sk(sk);
608
609                                         avc_print_ipv6_addr(ab, &inet6->rcv_saddr,
610                                                             inet->sport,
611                                                             "laddr", "lport");
612                                         avc_print_ipv6_addr(ab, &inet6->daddr,
613                                                             inet->dport,
614                                                             "faddr", "fport");
615                                         break;
616                                 }
617                                 case AF_UNIX:
618                                         u = unix_sk(sk);
619                                         if (u->dentry) {
620                                                 audit_log_d_path(ab, "path=",
621                                                         u->dentry, u->mnt);
622                                                 break;
623                                         }
624                                         if (!u->addr)
625                                                 break;
626                                         len = u->addr->len-sizeof(short);
627                                         p = &u->addr->name->sun_path[0];
628                                         if (*p)
629                                                 audit_log_format(ab,
630                                                         "path=%*.*s", len,
631                                                         len, p);
632                                         else
633                                                 audit_log_format(ab,
634                                                         "path=@%*.*s", len-1,
635                                                         len-1, p+1);
636                                         break;
637                                 }
638                         }
639                         
640                         switch (a->u.net.family) {
641                         case AF_INET:
642                                 avc_print_ipv4_addr(ab, a->u.net.v4info.saddr,
643                                                     a->u.net.sport,
644                                                     "saddr", "src");
645                                 avc_print_ipv4_addr(ab, a->u.net.v4info.daddr,
646                                                     a->u.net.dport,
647                                                     "daddr", "dest");
648                                 break;
649                         case AF_INET6:
650                                 avc_print_ipv6_addr(ab, &a->u.net.v6info.saddr,
651                                                     a->u.net.sport,
652                                                     "saddr", "src");
653                                 avc_print_ipv6_addr(ab, &a->u.net.v6info.daddr,
654                                                     a->u.net.dport,
655                                                     "daddr", "dest");
656                                 break;
657                         }
658                         if (a->u.net.netif)
659                                 audit_log_format(ab, " netif=%s",
660                                         a->u.net.netif);
661                         break;
662                 }
663         }
664         audit_log_format(ab, " ");
665         avc_dump_query(ab, ssid, tsid, tclass);
666         audit_log_end(ab);
667 }
668
669 /**
670  * avc_add_callback - Register a callback for security events.
671  * @callback: callback function
672  * @events: security events
673  * @ssid: source security identifier or %SECSID_WILD
674  * @tsid: target security identifier or %SECSID_WILD
675  * @tclass: target security class
676  * @perms: permissions
677  *
678  * Register a callback function for events in the set @events
679  * related to the SID pair (@ssid, @tsid) and
680  * and the permissions @perms, interpreting
681  * @perms based on @tclass.  Returns %0 on success or
682  * -%ENOMEM if insufficient memory exists to add the callback.
683  */
684 int avc_add_callback(int (*callback)(u32 event, u32 ssid, u32 tsid,
685                                      u16 tclass, u32 perms,
686                                      u32 *out_retained),
687                      u32 events, u32 ssid, u32 tsid,
688                      u16 tclass, u32 perms)
689 {
690         struct avc_callback_node *c;
691         int rc = 0;
692
693         c = kmalloc(sizeof(*c), GFP_ATOMIC);
694         if (!c) {
695                 rc = -ENOMEM;
696                 goto out;
697         }
698
699         c->callback = callback;
700         c->events = events;
701         c->ssid = ssid;
702         c->tsid = tsid;
703         c->perms = perms;
704         c->next = avc_callbacks;
705         avc_callbacks = c;
706 out:
707         return rc;
708 }
709
710 static inline int avc_sidcmp(u32 x, u32 y)
711 {
712         return (x == y || x == SECSID_WILD || y == SECSID_WILD);
713 }
714
715 /**
716  * avc_update_node Update an AVC entry
717  * @event : Updating event
718  * @perms : Permission mask bits
719  * @ssid,@tsid,@tclass : identifier of an AVC entry
720  * 
721  * if a valid AVC entry doesn't exist,this function returns -ENOENT.
722  * if kmalloc() called internal returns NULL, this function returns -ENOMEM.
723  * otherwise, this function update the AVC entry. The original AVC-entry object
724  * will release later by RCU.
725  */
726 static int avc_update_node(u32 event, u32 perms, u32 ssid, u32 tsid, u16 tclass)
727 {
728         int hvalue, rc = 0;
729         unsigned long flag;
730         struct avc_node *pos, *node, *orig = NULL;
731
732         node = avc_alloc_node();
733         if (!node) {
734                 rc = -ENOMEM;
735                 goto out;
736         }
737
738         /* Lock the target slot */
739         hvalue = avc_hash(ssid, tsid, tclass);
740         spin_lock_irqsave(&avc_cache.slots_lock[hvalue], flag);
741
742         list_for_each_entry(pos, &avc_cache.slots[hvalue], list){
743                 if ( ssid==pos->ae.ssid &&
744                      tsid==pos->ae.tsid &&
745                      tclass==pos->ae.tclass ){
746                         orig = pos;
747                         break;
748                 }
749         }
750
751         if (!orig) {
752                 rc = -ENOENT;
753                 avc_node_kill(node);
754                 goto out_unlock;
755         }
756
757         /*
758          * Copy and replace original node.
759          */
760
761         avc_node_populate(node, ssid, tsid, tclass, &orig->ae);
762         
763         switch (event) {
764         case AVC_CALLBACK_GRANT:
765                 node->ae.avd.allowed |= perms;
766                 break;
767         case AVC_CALLBACK_TRY_REVOKE:
768         case AVC_CALLBACK_REVOKE:
769                 node->ae.avd.allowed &= ~perms;
770                 break;
771         case AVC_CALLBACK_AUDITALLOW_ENABLE:
772                 node->ae.avd.auditallow |= perms;
773                 break;
774         case AVC_CALLBACK_AUDITALLOW_DISABLE:
775                 node->ae.avd.auditallow &= ~perms;
776                 break;
777         case AVC_CALLBACK_AUDITDENY_ENABLE:
778                 node->ae.avd.auditdeny |= perms;
779                 break;
780         case AVC_CALLBACK_AUDITDENY_DISABLE:
781                 node->ae.avd.auditdeny &= ~perms;
782                 break;
783         }
784         avc_node_replace(node, orig);
785 out_unlock:
786         spin_unlock_irqrestore(&avc_cache.slots_lock[hvalue], flag);
787 out:
788         return rc;
789 }
790
791 static int avc_update_cache(u32 event, u32 ssid, u32 tsid,
792                             u16 tclass, u32 perms)
793 {
794         struct avc_node *node;
795         int i;
796
797         rcu_read_lock();
798
799         if (ssid == SECSID_WILD || tsid == SECSID_WILD) {
800                 /* apply to all matching nodes */
801                 for (i = 0; i < AVC_CACHE_SLOTS; i++) {
802                         list_for_each_entry_rcu(node, &avc_cache.slots[i], list) {
803                                 if (avc_sidcmp(ssid, node->ae.ssid) &&
804                                     avc_sidcmp(tsid, node->ae.tsid) &&
805                                     tclass == node->ae.tclass ) {
806                                         avc_update_node(event, perms, node->ae.ssid,
807                                                         node->ae.tsid, node->ae.tclass);
808                                 }
809                         }
810                 }
811         } else {
812                 /* apply to one node */
813                 avc_update_node(event, perms, ssid, tsid, tclass);
814         }
815
816         rcu_read_unlock();
817
818         return 0;
819 }
820
821 static int avc_control(u32 event, u32 ssid, u32 tsid,
822                        u16 tclass, u32 perms,
823                        u32 seqno, u32 *out_retained)
824 {
825         struct avc_callback_node *c;
826         u32 tretained = 0, cretained = 0;
827         int rc = 0;
828
829         /*
830          * try_revoke only removes permissions from the cache
831          * state if they are not retained by the object manager.
832          * Hence, try_revoke must wait until after the callbacks have
833          * been invoked to update the cache state.
834          */
835         if (event != AVC_CALLBACK_TRY_REVOKE)
836                 avc_update_cache(event,ssid,tsid,tclass,perms);
837
838         for (c = avc_callbacks; c; c = c->next)
839         {
840                 if ((c->events & event) &&
841                     avc_sidcmp(c->ssid, ssid) &&
842                     avc_sidcmp(c->tsid, tsid) &&
843                     c->tclass == tclass &&
844                     (c->perms & perms)) {
845                         cretained = 0;
846                         rc = c->callback(event, ssid, tsid, tclass,
847                                          (c->perms & perms),
848                                          &cretained);
849                         if (rc)
850                                 goto out;
851                         tretained |= cretained;
852                 }
853         }
854
855         if (event == AVC_CALLBACK_TRY_REVOKE) {
856                 /* revoke any unretained permissions */
857                 perms &= ~tretained;
858                 avc_update_cache(event,ssid,tsid,tclass,perms);
859                 *out_retained = tretained;
860         }
861
862         avc_latest_notif_update(seqno, 0);
863
864 out:
865         return rc;
866 }
867
868 /**
869  * avc_ss_grant - Grant previously denied permissions.
870  * @ssid: source security identifier or %SECSID_WILD
871  * @tsid: target security identifier or %SECSID_WILD
872  * @tclass: target security class
873  * @perms: permissions to grant
874  * @seqno: policy sequence number
875  */
876 int avc_ss_grant(u32 ssid, u32 tsid, u16 tclass,
877                  u32 perms, u32 seqno)
878 {
879         return avc_control(AVC_CALLBACK_GRANT,
880                            ssid, tsid, tclass, perms, seqno, NULL);
881 }
882
883 /**
884  * avc_ss_try_revoke - Try to revoke previously granted permissions.
885  * @ssid: source security identifier or %SECSID_WILD
886  * @tsid: target security identifier or %SECSID_WILD
887  * @tclass: target security class
888  * @perms: permissions to grant
889  * @seqno: policy sequence number
890  * @out_retained: subset of @perms that are retained
891  *
892  * Try to revoke previously granted permissions, but
893  * only if they are not retained as migrated permissions.
894  * Return the subset of permissions that are retained via @out_retained.
895  */
896 int avc_ss_try_revoke(u32 ssid, u32 tsid, u16 tclass,
897                       u32 perms, u32 seqno, u32 *out_retained)
898 {
899         return avc_control(AVC_CALLBACK_TRY_REVOKE,
900                            ssid, tsid, tclass, perms, seqno, out_retained);
901 }
902
903 /**
904  * avc_ss_revoke - Revoke previously granted permissions.
905  * @ssid: source security identifier or %SECSID_WILD
906  * @tsid: target security identifier or %SECSID_WILD
907  * @tclass: target security class
908  * @perms: permissions to grant
909  * @seqno: policy sequence number
910  *
911  * Revoke previously granted permissions, even if
912  * they are retained as migrated permissions.
913  */
914 int avc_ss_revoke(u32 ssid, u32 tsid, u16 tclass,
915                   u32 perms, u32 seqno)
916 {
917         return avc_control(AVC_CALLBACK_REVOKE,
918                            ssid, tsid, tclass, perms, seqno, NULL);
919 }
920
921 /**
922  * avc_ss_reset - Flush the cache and revalidate migrated permissions.
923  * @seqno: policy sequence number
924  */
925 int avc_ss_reset(u32 seqno)
926 {
927         struct avc_callback_node *c;
928         int i, rc = 0;
929         unsigned long flag;
930         struct avc_node *node;
931
932         for (i = 0; i < AVC_CACHE_SLOTS; i++) {
933                 spin_lock_irqsave(&avc_cache.slots_lock[i], flag);
934                 list_for_each_entry(node, &avc_cache.slots[i], list)
935                         avc_node_delete(node);
936                 spin_unlock_irqrestore(&avc_cache.slots_lock[i], flag);
937         }
938
939         for (c = avc_callbacks; c; c = c->next) {
940                 if (c->events & AVC_CALLBACK_RESET) {
941                         rc = c->callback(AVC_CALLBACK_RESET,
942                                          0, 0, 0, 0, NULL);
943                         if (rc)
944                                 goto out;
945                 }
946         }
947
948         avc_latest_notif_update(seqno, 0);
949 out:
950         return rc;
951 }
952
953 /**
954  * avc_ss_set_auditallow - Enable or disable auditing of granted permissions.
955  * @ssid: source security identifier or %SECSID_WILD
956  * @tsid: target security identifier or %SECSID_WILD
957  * @tclass: target security class
958  * @perms: permissions to grant
959  * @seqno: policy sequence number
960  * @enable: enable flag.
961  */
962 int avc_ss_set_auditallow(u32 ssid, u32 tsid, u16 tclass,
963                           u32 perms, u32 seqno, u32 enable)
964 {
965         if (enable)
966                 return avc_control(AVC_CALLBACK_AUDITALLOW_ENABLE,
967                                    ssid, tsid, tclass, perms, seqno, NULL);
968         else
969                 return avc_control(AVC_CALLBACK_AUDITALLOW_DISABLE,
970                                    ssid, tsid, tclass, perms, seqno, NULL);
971 }
972
973 /**
974  * avc_ss_set_auditdeny - Enable or disable auditing of denied permissions.
975  * @ssid: source security identifier or %SECSID_WILD
976  * @tsid: target security identifier or %SECSID_WILD
977  * @tclass: target security class
978  * @perms: permissions to grant
979  * @seqno: policy sequence number
980  * @enable: enable flag.
981  */
982 int avc_ss_set_auditdeny(u32 ssid, u32 tsid, u16 tclass,
983                          u32 perms, u32 seqno, u32 enable)
984 {
985         if (enable)
986                 return avc_control(AVC_CALLBACK_AUDITDENY_ENABLE,
987                                    ssid, tsid, tclass, perms, seqno, NULL);
988         else
989                 return avc_control(AVC_CALLBACK_AUDITDENY_DISABLE,
990                                    ssid, tsid, tclass, perms, seqno, NULL);
991 }
992
993 /**
994  * avc_has_perm_noaudit - Check permissions but perform no auditing.
995  * @ssid: source security identifier
996  * @tsid: target security identifier
997  * @tclass: target security class
998  * @requested: requested permissions, interpreted based on @tclass
999  * @avd: access vector decisions
1000  *
1001  * Check the AVC to determine whether the @requested permissions are granted
1002  * for the SID pair (@ssid, @tsid), interpreting the permissions
1003  * based on @tclass, and call the security server on a cache miss to obtain
1004  * a new decision and add it to the cache.  Return a copy of the decisions
1005  * in @avd.  Return %0 if all @requested permissions are granted,
1006  * -%EACCES if any permissions are denied, or another -errno upon
1007  * other errors.  This function is typically called by avc_has_perm(),
1008  * but may also be called directly to separate permission checking from
1009  * auditing, e.g. in cases where a lock must be held for the check but
1010  * should be released for the auditing.
1011  */
1012 int avc_has_perm_noaudit(u32 ssid, u32 tsid,
1013                          u16 tclass, u32 requested,
1014                          struct av_decision *avd)
1015 {
1016         struct avc_node *node;
1017         struct avc_entry entry, *p_ae;
1018         int rc = 0;
1019         u32 denied;
1020
1021         rcu_read_lock();
1022
1023         node = avc_lookup(ssid, tsid, tclass, requested);
1024         if (!node) {
1025                 rcu_read_unlock();
1026                 rc = security_compute_av(ssid,tsid,tclass,requested,&entry.avd);
1027                 if (rc)
1028                         goto out;
1029                 rcu_read_lock();
1030                 node = avc_insert(ssid,tsid,tclass,&entry);
1031         }
1032
1033         p_ae = node ? &node->ae : &entry;
1034
1035         if (avd)
1036                 memcpy(avd, &p_ae->avd, sizeof(*avd));
1037
1038         denied = requested & ~(p_ae->avd.allowed);
1039
1040         if (!requested || denied) {
1041                 if (selinux_enforcing)
1042                         rc = -EACCES;
1043                 else
1044                         if (node)
1045                                 avc_update_node(AVC_CALLBACK_GRANT,requested,
1046                                                 ssid,tsid,tclass);
1047         }
1048         
1049         rcu_read_unlock();
1050 out:
1051         return rc;
1052 }
1053
1054 /**
1055  * avc_has_perm - Check permissions and perform any appropriate auditing.
1056  * @ssid: source security identifier
1057  * @tsid: target security identifier
1058  * @tclass: target security class
1059  * @requested: requested permissions, interpreted based on @tclass
1060  * @auditdata: auxiliary audit data
1061  *
1062  * Check the AVC to determine whether the @requested permissions are granted
1063  * for the SID pair (@ssid, @tsid), interpreting the permissions
1064  * based on @tclass, and call the security server on a cache miss to obtain
1065  * a new decision and add it to the cache.  Audit the granting or denial of
1066  * permissions in accordance with the policy.  Return %0 if all @requested
1067  * permissions are granted, -%EACCES if any permissions are denied, or
1068  * another -errno upon other errors.
1069  */
1070 int avc_has_perm(u32 ssid, u32 tsid, u16 tclass,
1071                  u32 requested, struct avc_audit_data *auditdata)
1072 {
1073         struct av_decision avd;
1074         int rc;
1075
1076         rc = avc_has_perm_noaudit(ssid, tsid, tclass, requested, &avd);
1077         avc_audit(ssid, tsid, tclass, requested, &avd, rc, auditdata);
1078         return rc;
1079 }