]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - security/selinux/ss/services.c
selinux: Delete mls_copy_context
[linux-2.6.git] / security / selinux / ss / services.c
1 /*
2  * Implementation of the security services.
3  *
4  * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
5  *           James Morris <jmorris@redhat.com>
6  *
7  * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
8  *
9  *      Support for enhanced MLS infrastructure.
10  *      Support for context based audit filters.
11  *
12  * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
13  *
14  *      Added conditional policy language extensions
15  *
16  * Updated: Hewlett-Packard <paul.moore@hp.com>
17  *
18  *      Added support for NetLabel
19  *
20  * Updated: Chad Sellers <csellers@tresys.com>
21  *
22  *  Added validation of kernel classes and permissions
23  *
24  * Copyright (C) 2006 Hewlett-Packard Development Company, L.P.
25  * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
26  * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
27  * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
28  *      This program is free software; you can redistribute it and/or modify
29  *      it under the terms of the GNU General Public License as published by
30  *      the Free Software Foundation, version 2.
31  */
32 #include <linux/kernel.h>
33 #include <linux/slab.h>
34 #include <linux/string.h>
35 #include <linux/spinlock.h>
36 #include <linux/rcupdate.h>
37 #include <linux/errno.h>
38 #include <linux/in.h>
39 #include <linux/sched.h>
40 #include <linux/audit.h>
41 #include <linux/mutex.h>
42 #include <net/sock.h>
43 #include <net/netlabel.h>
44
45 #include "flask.h"
46 #include "avc.h"
47 #include "avc_ss.h"
48 #include "security.h"
49 #include "context.h"
50 #include "policydb.h"
51 #include "sidtab.h"
52 #include "services.h"
53 #include "conditional.h"
54 #include "mls.h"
55 #include "objsec.h"
56 #include "selinux_netlabel.h"
57 #include "xfrm.h"
58 #include "ebitmap.h"
59
60 extern void selnl_notify_policyload(u32 seqno);
61 unsigned int policydb_loaded_version;
62
63 /*
64  * This is declared in avc.c
65  */
66 extern const struct selinux_class_perm selinux_class_perm;
67
68 static DEFINE_RWLOCK(policy_rwlock);
69 #define POLICY_RDLOCK read_lock(&policy_rwlock)
70 #define POLICY_WRLOCK write_lock_irq(&policy_rwlock)
71 #define POLICY_RDUNLOCK read_unlock(&policy_rwlock)
72 #define POLICY_WRUNLOCK write_unlock_irq(&policy_rwlock)
73
74 static DEFINE_MUTEX(load_mutex);
75 #define LOAD_LOCK mutex_lock(&load_mutex)
76 #define LOAD_UNLOCK mutex_unlock(&load_mutex)
77
78 static struct sidtab sidtab;
79 struct policydb policydb;
80 int ss_initialized = 0;
81
82 /*
83  * The largest sequence number that has been used when
84  * providing an access decision to the access vector cache.
85  * The sequence number only changes when a policy change
86  * occurs.
87  */
88 static u32 latest_granting = 0;
89
90 /* Forward declaration. */
91 static int context_struct_to_string(struct context *context, char **scontext,
92                                     u32 *scontext_len);
93
94 /*
95  * Return the boolean value of a constraint expression
96  * when it is applied to the specified source and target
97  * security contexts.
98  *
99  * xcontext is a special beast...  It is used by the validatetrans rules
100  * only.  For these rules, scontext is the context before the transition,
101  * tcontext is the context after the transition, and xcontext is the context
102  * of the process performing the transition.  All other callers of
103  * constraint_expr_eval should pass in NULL for xcontext.
104  */
105 static int constraint_expr_eval(struct context *scontext,
106                                 struct context *tcontext,
107                                 struct context *xcontext,
108                                 struct constraint_expr *cexpr)
109 {
110         u32 val1, val2;
111         struct context *c;
112         struct role_datum *r1, *r2;
113         struct mls_level *l1, *l2;
114         struct constraint_expr *e;
115         int s[CEXPR_MAXDEPTH];
116         int sp = -1;
117
118         for (e = cexpr; e; e = e->next) {
119                 switch (e->expr_type) {
120                 case CEXPR_NOT:
121                         BUG_ON(sp < 0);
122                         s[sp] = !s[sp];
123                         break;
124                 case CEXPR_AND:
125                         BUG_ON(sp < 1);
126                         sp--;
127                         s[sp] &= s[sp+1];
128                         break;
129                 case CEXPR_OR:
130                         BUG_ON(sp < 1);
131                         sp--;
132                         s[sp] |= s[sp+1];
133                         break;
134                 case CEXPR_ATTR:
135                         if (sp == (CEXPR_MAXDEPTH-1))
136                                 return 0;
137                         switch (e->attr) {
138                         case CEXPR_USER:
139                                 val1 = scontext->user;
140                                 val2 = tcontext->user;
141                                 break;
142                         case CEXPR_TYPE:
143                                 val1 = scontext->type;
144                                 val2 = tcontext->type;
145                                 break;
146                         case CEXPR_ROLE:
147                                 val1 = scontext->role;
148                                 val2 = tcontext->role;
149                                 r1 = policydb.role_val_to_struct[val1 - 1];
150                                 r2 = policydb.role_val_to_struct[val2 - 1];
151                                 switch (e->op) {
152                                 case CEXPR_DOM:
153                                         s[++sp] = ebitmap_get_bit(&r1->dominates,
154                                                                   val2 - 1);
155                                         continue;
156                                 case CEXPR_DOMBY:
157                                         s[++sp] = ebitmap_get_bit(&r2->dominates,
158                                                                   val1 - 1);
159                                         continue;
160                                 case CEXPR_INCOMP:
161                                         s[++sp] = ( !ebitmap_get_bit(&r1->dominates,
162                                                                      val2 - 1) &&
163                                                     !ebitmap_get_bit(&r2->dominates,
164                                                                      val1 - 1) );
165                                         continue;
166                                 default:
167                                         break;
168                                 }
169                                 break;
170                         case CEXPR_L1L2:
171                                 l1 = &(scontext->range.level[0]);
172                                 l2 = &(tcontext->range.level[0]);
173                                 goto mls_ops;
174                         case CEXPR_L1H2:
175                                 l1 = &(scontext->range.level[0]);
176                                 l2 = &(tcontext->range.level[1]);
177                                 goto mls_ops;
178                         case CEXPR_H1L2:
179                                 l1 = &(scontext->range.level[1]);
180                                 l2 = &(tcontext->range.level[0]);
181                                 goto mls_ops;
182                         case CEXPR_H1H2:
183                                 l1 = &(scontext->range.level[1]);
184                                 l2 = &(tcontext->range.level[1]);
185                                 goto mls_ops;
186                         case CEXPR_L1H1:
187                                 l1 = &(scontext->range.level[0]);
188                                 l2 = &(scontext->range.level[1]);
189                                 goto mls_ops;
190                         case CEXPR_L2H2:
191                                 l1 = &(tcontext->range.level[0]);
192                                 l2 = &(tcontext->range.level[1]);
193                                 goto mls_ops;
194 mls_ops:
195                         switch (e->op) {
196                         case CEXPR_EQ:
197                                 s[++sp] = mls_level_eq(l1, l2);
198                                 continue;
199                         case CEXPR_NEQ:
200                                 s[++sp] = !mls_level_eq(l1, l2);
201                                 continue;
202                         case CEXPR_DOM:
203                                 s[++sp] = mls_level_dom(l1, l2);
204                                 continue;
205                         case CEXPR_DOMBY:
206                                 s[++sp] = mls_level_dom(l2, l1);
207                                 continue;
208                         case CEXPR_INCOMP:
209                                 s[++sp] = mls_level_incomp(l2, l1);
210                                 continue;
211                         default:
212                                 BUG();
213                                 return 0;
214                         }
215                         break;
216                         default:
217                                 BUG();
218                                 return 0;
219                         }
220
221                         switch (e->op) {
222                         case CEXPR_EQ:
223                                 s[++sp] = (val1 == val2);
224                                 break;
225                         case CEXPR_NEQ:
226                                 s[++sp] = (val1 != val2);
227                                 break;
228                         default:
229                                 BUG();
230                                 return 0;
231                         }
232                         break;
233                 case CEXPR_NAMES:
234                         if (sp == (CEXPR_MAXDEPTH-1))
235                                 return 0;
236                         c = scontext;
237                         if (e->attr & CEXPR_TARGET)
238                                 c = tcontext;
239                         else if (e->attr & CEXPR_XTARGET) {
240                                 c = xcontext;
241                                 if (!c) {
242                                         BUG();
243                                         return 0;
244                                 }
245                         }
246                         if (e->attr & CEXPR_USER)
247                                 val1 = c->user;
248                         else if (e->attr & CEXPR_ROLE)
249                                 val1 = c->role;
250                         else if (e->attr & CEXPR_TYPE)
251                                 val1 = c->type;
252                         else {
253                                 BUG();
254                                 return 0;
255                         }
256
257                         switch (e->op) {
258                         case CEXPR_EQ:
259                                 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
260                                 break;
261                         case CEXPR_NEQ:
262                                 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
263                                 break;
264                         default:
265                                 BUG();
266                                 return 0;
267                         }
268                         break;
269                 default:
270                         BUG();
271                         return 0;
272                 }
273         }
274
275         BUG_ON(sp != 0);
276         return s[0];
277 }
278
279 /*
280  * Compute access vectors based on a context structure pair for
281  * the permissions in a particular class.
282  */
283 static int context_struct_compute_av(struct context *scontext,
284                                      struct context *tcontext,
285                                      u16 tclass,
286                                      u32 requested,
287                                      struct av_decision *avd)
288 {
289         struct constraint_node *constraint;
290         struct role_allow *ra;
291         struct avtab_key avkey;
292         struct avtab_node *node;
293         struct class_datum *tclass_datum;
294         struct ebitmap *sattr, *tattr;
295         struct ebitmap_node *snode, *tnode;
296         unsigned int i, j;
297
298         /*
299          * Remap extended Netlink classes for old policy versions.
300          * Do this here rather than socket_type_to_security_class()
301          * in case a newer policy version is loaded, allowing sockets
302          * to remain in the correct class.
303          */
304         if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
305                 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
306                     tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
307                         tclass = SECCLASS_NETLINK_SOCKET;
308
309         if (!tclass || tclass > policydb.p_classes.nprim) {
310                 printk(KERN_ERR "security_compute_av:  unrecognized class %d\n",
311                        tclass);
312                 return -EINVAL;
313         }
314         tclass_datum = policydb.class_val_to_struct[tclass - 1];
315
316         /*
317          * Initialize the access vectors to the default values.
318          */
319         avd->allowed = 0;
320         avd->decided = 0xffffffff;
321         avd->auditallow = 0;
322         avd->auditdeny = 0xffffffff;
323         avd->seqno = latest_granting;
324
325         /*
326          * If a specific type enforcement rule was defined for
327          * this permission check, then use it.
328          */
329         avkey.target_class = tclass;
330         avkey.specified = AVTAB_AV;
331         sattr = &policydb.type_attr_map[scontext->type - 1];
332         tattr = &policydb.type_attr_map[tcontext->type - 1];
333         ebitmap_for_each_bit(sattr, snode, i) {
334                 if (!ebitmap_node_get_bit(snode, i))
335                         continue;
336                 ebitmap_for_each_bit(tattr, tnode, j) {
337                         if (!ebitmap_node_get_bit(tnode, j))
338                                 continue;
339                         avkey.source_type = i + 1;
340                         avkey.target_type = j + 1;
341                         for (node = avtab_search_node(&policydb.te_avtab, &avkey);
342                              node != NULL;
343                              node = avtab_search_node_next(node, avkey.specified)) {
344                                 if (node->key.specified == AVTAB_ALLOWED)
345                                         avd->allowed |= node->datum.data;
346                                 else if (node->key.specified == AVTAB_AUDITALLOW)
347                                         avd->auditallow |= node->datum.data;
348                                 else if (node->key.specified == AVTAB_AUDITDENY)
349                                         avd->auditdeny &= node->datum.data;
350                         }
351
352                         /* Check conditional av table for additional permissions */
353                         cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
354
355                 }
356         }
357
358         /*
359          * Remove any permissions prohibited by a constraint (this includes
360          * the MLS policy).
361          */
362         constraint = tclass_datum->constraints;
363         while (constraint) {
364                 if ((constraint->permissions & (avd->allowed)) &&
365                     !constraint_expr_eval(scontext, tcontext, NULL,
366                                           constraint->expr)) {
367                         avd->allowed = (avd->allowed) & ~(constraint->permissions);
368                 }
369                 constraint = constraint->next;
370         }
371
372         /*
373          * If checking process transition permission and the
374          * role is changing, then check the (current_role, new_role)
375          * pair.
376          */
377         if (tclass == SECCLASS_PROCESS &&
378             (avd->allowed & (PROCESS__TRANSITION | PROCESS__DYNTRANSITION)) &&
379             scontext->role != tcontext->role) {
380                 for (ra = policydb.role_allow; ra; ra = ra->next) {
381                         if (scontext->role == ra->role &&
382                             tcontext->role == ra->new_role)
383                                 break;
384                 }
385                 if (!ra)
386                         avd->allowed = (avd->allowed) & ~(PROCESS__TRANSITION |
387                                                         PROCESS__DYNTRANSITION);
388         }
389
390         return 0;
391 }
392
393 static int security_validtrans_handle_fail(struct context *ocontext,
394                                            struct context *ncontext,
395                                            struct context *tcontext,
396                                            u16 tclass)
397 {
398         char *o = NULL, *n = NULL, *t = NULL;
399         u32 olen, nlen, tlen;
400
401         if (context_struct_to_string(ocontext, &o, &olen) < 0)
402                 goto out;
403         if (context_struct_to_string(ncontext, &n, &nlen) < 0)
404                 goto out;
405         if (context_struct_to_string(tcontext, &t, &tlen) < 0)
406                 goto out;
407         audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
408                   "security_validate_transition:  denied for"
409                   " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
410                   o, n, t, policydb.p_class_val_to_name[tclass-1]);
411 out:
412         kfree(o);
413         kfree(n);
414         kfree(t);
415
416         if (!selinux_enforcing)
417                 return 0;
418         return -EPERM;
419 }
420
421 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
422                                  u16 tclass)
423 {
424         struct context *ocontext;
425         struct context *ncontext;
426         struct context *tcontext;
427         struct class_datum *tclass_datum;
428         struct constraint_node *constraint;
429         int rc = 0;
430
431         if (!ss_initialized)
432                 return 0;
433
434         POLICY_RDLOCK;
435
436         /*
437          * Remap extended Netlink classes for old policy versions.
438          * Do this here rather than socket_type_to_security_class()
439          * in case a newer policy version is loaded, allowing sockets
440          * to remain in the correct class.
441          */
442         if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
443                 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
444                     tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
445                         tclass = SECCLASS_NETLINK_SOCKET;
446
447         if (!tclass || tclass > policydb.p_classes.nprim) {
448                 printk(KERN_ERR "security_validate_transition:  "
449                        "unrecognized class %d\n", tclass);
450                 rc = -EINVAL;
451                 goto out;
452         }
453         tclass_datum = policydb.class_val_to_struct[tclass - 1];
454
455         ocontext = sidtab_search(&sidtab, oldsid);
456         if (!ocontext) {
457                 printk(KERN_ERR "security_validate_transition: "
458                        " unrecognized SID %d\n", oldsid);
459                 rc = -EINVAL;
460                 goto out;
461         }
462
463         ncontext = sidtab_search(&sidtab, newsid);
464         if (!ncontext) {
465                 printk(KERN_ERR "security_validate_transition: "
466                        " unrecognized SID %d\n", newsid);
467                 rc = -EINVAL;
468                 goto out;
469         }
470
471         tcontext = sidtab_search(&sidtab, tasksid);
472         if (!tcontext) {
473                 printk(KERN_ERR "security_validate_transition: "
474                        " unrecognized SID %d\n", tasksid);
475                 rc = -EINVAL;
476                 goto out;
477         }
478
479         constraint = tclass_datum->validatetrans;
480         while (constraint) {
481                 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
482                                           constraint->expr)) {
483                         rc = security_validtrans_handle_fail(ocontext, ncontext,
484                                                              tcontext, tclass);
485                         goto out;
486                 }
487                 constraint = constraint->next;
488         }
489
490 out:
491         POLICY_RDUNLOCK;
492         return rc;
493 }
494
495 /**
496  * security_compute_av - Compute access vector decisions.
497  * @ssid: source security identifier
498  * @tsid: target security identifier
499  * @tclass: target security class
500  * @requested: requested permissions
501  * @avd: access vector decisions
502  *
503  * Compute a set of access vector decisions based on the
504  * SID pair (@ssid, @tsid) for the permissions in @tclass.
505  * Return -%EINVAL if any of the parameters are invalid or %0
506  * if the access vector decisions were computed successfully.
507  */
508 int security_compute_av(u32 ssid,
509                         u32 tsid,
510                         u16 tclass,
511                         u32 requested,
512                         struct av_decision *avd)
513 {
514         struct context *scontext = NULL, *tcontext = NULL;
515         int rc = 0;
516
517         if (!ss_initialized) {
518                 avd->allowed = 0xffffffff;
519                 avd->decided = 0xffffffff;
520                 avd->auditallow = 0;
521                 avd->auditdeny = 0xffffffff;
522                 avd->seqno = latest_granting;
523                 return 0;
524         }
525
526         POLICY_RDLOCK;
527
528         scontext = sidtab_search(&sidtab, ssid);
529         if (!scontext) {
530                 printk(KERN_ERR "security_compute_av:  unrecognized SID %d\n",
531                        ssid);
532                 rc = -EINVAL;
533                 goto out;
534         }
535         tcontext = sidtab_search(&sidtab, tsid);
536         if (!tcontext) {
537                 printk(KERN_ERR "security_compute_av:  unrecognized SID %d\n",
538                        tsid);
539                 rc = -EINVAL;
540                 goto out;
541         }
542
543         rc = context_struct_compute_av(scontext, tcontext, tclass,
544                                        requested, avd);
545 out:
546         POLICY_RDUNLOCK;
547         return rc;
548 }
549
550 /*
551  * Write the security context string representation of
552  * the context structure `context' into a dynamically
553  * allocated string of the correct size.  Set `*scontext'
554  * to point to this string and set `*scontext_len' to
555  * the length of the string.
556  */
557 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
558 {
559         char *scontextp;
560
561         *scontext = NULL;
562         *scontext_len = 0;
563
564         /* Compute the size of the context. */
565         *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
566         *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
567         *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
568         *scontext_len += mls_compute_context_len(context);
569
570         /* Allocate space for the context; caller must free this space. */
571         scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
572         if (!scontextp) {
573                 return -ENOMEM;
574         }
575         *scontext = scontextp;
576
577         /*
578          * Copy the user name, role name and type name into the context.
579          */
580         sprintf(scontextp, "%s:%s:%s",
581                 policydb.p_user_val_to_name[context->user - 1],
582                 policydb.p_role_val_to_name[context->role - 1],
583                 policydb.p_type_val_to_name[context->type - 1]);
584         scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
585                      1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
586                      1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
587
588         mls_sid_to_context(context, &scontextp);
589
590         *scontextp = 0;
591
592         return 0;
593 }
594
595 #include "initial_sid_to_string.h"
596
597 /**
598  * security_sid_to_context - Obtain a context for a given SID.
599  * @sid: security identifier, SID
600  * @scontext: security context
601  * @scontext_len: length in bytes
602  *
603  * Write the string representation of the context associated with @sid
604  * into a dynamically allocated string of the correct size.  Set @scontext
605  * to point to this string and set @scontext_len to the length of the string.
606  */
607 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
608 {
609         struct context *context;
610         int rc = 0;
611
612         if (!ss_initialized) {
613                 if (sid <= SECINITSID_NUM) {
614                         char *scontextp;
615
616                         *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
617                         scontextp = kmalloc(*scontext_len,GFP_ATOMIC);
618                         if (!scontextp) {
619                                 rc = -ENOMEM;
620                                 goto out;
621                         }
622                         strcpy(scontextp, initial_sid_to_string[sid]);
623                         *scontext = scontextp;
624                         goto out;
625                 }
626                 printk(KERN_ERR "security_sid_to_context:  called before initial "
627                        "load_policy on unknown SID %d\n", sid);
628                 rc = -EINVAL;
629                 goto out;
630         }
631         POLICY_RDLOCK;
632         context = sidtab_search(&sidtab, sid);
633         if (!context) {
634                 printk(KERN_ERR "security_sid_to_context:  unrecognized SID "
635                        "%d\n", sid);
636                 rc = -EINVAL;
637                 goto out_unlock;
638         }
639         rc = context_struct_to_string(context, scontext, scontext_len);
640 out_unlock:
641         POLICY_RDUNLOCK;
642 out:
643         return rc;
644
645 }
646
647 static int security_context_to_sid_core(char *scontext, u32 scontext_len, u32 *sid, u32 def_sid)
648 {
649         char *scontext2;
650         struct context context;
651         struct role_datum *role;
652         struct type_datum *typdatum;
653         struct user_datum *usrdatum;
654         char *scontextp, *p, oldc;
655         int rc = 0;
656
657         if (!ss_initialized) {
658                 int i;
659
660                 for (i = 1; i < SECINITSID_NUM; i++) {
661                         if (!strcmp(initial_sid_to_string[i], scontext)) {
662                                 *sid = i;
663                                 goto out;
664                         }
665                 }
666                 *sid = SECINITSID_KERNEL;
667                 goto out;
668         }
669         *sid = SECSID_NULL;
670
671         /* Copy the string so that we can modify the copy as we parse it.
672            The string should already by null terminated, but we append a
673            null suffix to the copy to avoid problems with the existing
674            attr package, which doesn't view the null terminator as part
675            of the attribute value. */
676         scontext2 = kmalloc(scontext_len+1,GFP_KERNEL);
677         if (!scontext2) {
678                 rc = -ENOMEM;
679                 goto out;
680         }
681         memcpy(scontext2, scontext, scontext_len);
682         scontext2[scontext_len] = 0;
683
684         context_init(&context);
685         *sid = SECSID_NULL;
686
687         POLICY_RDLOCK;
688
689         /* Parse the security context. */
690
691         rc = -EINVAL;
692         scontextp = (char *) scontext2;
693
694         /* Extract the user. */
695         p = scontextp;
696         while (*p && *p != ':')
697                 p++;
698
699         if (*p == 0)
700                 goto out_unlock;
701
702         *p++ = 0;
703
704         usrdatum = hashtab_search(policydb.p_users.table, scontextp);
705         if (!usrdatum)
706                 goto out_unlock;
707
708         context.user = usrdatum->value;
709
710         /* Extract role. */
711         scontextp = p;
712         while (*p && *p != ':')
713                 p++;
714
715         if (*p == 0)
716                 goto out_unlock;
717
718         *p++ = 0;
719
720         role = hashtab_search(policydb.p_roles.table, scontextp);
721         if (!role)
722                 goto out_unlock;
723         context.role = role->value;
724
725         /* Extract type. */
726         scontextp = p;
727         while (*p && *p != ':')
728                 p++;
729         oldc = *p;
730         *p++ = 0;
731
732         typdatum = hashtab_search(policydb.p_types.table, scontextp);
733         if (!typdatum)
734                 goto out_unlock;
735
736         context.type = typdatum->value;
737
738         rc = mls_context_to_sid(oldc, &p, &context, &sidtab, def_sid);
739         if (rc)
740                 goto out_unlock;
741
742         if ((p - scontext2) < scontext_len) {
743                 rc = -EINVAL;
744                 goto out_unlock;
745         }
746
747         /* Check the validity of the new context. */
748         if (!policydb_context_isvalid(&policydb, &context)) {
749                 rc = -EINVAL;
750                 goto out_unlock;
751         }
752         /* Obtain the new sid. */
753         rc = sidtab_context_to_sid(&sidtab, &context, sid);
754 out_unlock:
755         POLICY_RDUNLOCK;
756         context_destroy(&context);
757         kfree(scontext2);
758 out:
759         return rc;
760 }
761
762 /**
763  * security_context_to_sid - Obtain a SID for a given security context.
764  * @scontext: security context
765  * @scontext_len: length in bytes
766  * @sid: security identifier, SID
767  *
768  * Obtains a SID associated with the security context that
769  * has the string representation specified by @scontext.
770  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
771  * memory is available, or 0 on success.
772  */
773 int security_context_to_sid(char *scontext, u32 scontext_len, u32 *sid)
774 {
775         return security_context_to_sid_core(scontext, scontext_len,
776                                             sid, SECSID_NULL);
777 }
778
779 /**
780  * security_context_to_sid_default - Obtain a SID for a given security context,
781  * falling back to specified default if needed.
782  *
783  * @scontext: security context
784  * @scontext_len: length in bytes
785  * @sid: security identifier, SID
786  * @def_sid: default SID to assign on errror
787  *
788  * Obtains a SID associated with the security context that
789  * has the string representation specified by @scontext.
790  * The default SID is passed to the MLS layer to be used to allow
791  * kernel labeling of the MLS field if the MLS field is not present
792  * (for upgrading to MLS without full relabel).
793  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
794  * memory is available, or 0 on success.
795  */
796 int security_context_to_sid_default(char *scontext, u32 scontext_len, u32 *sid, u32 def_sid)
797 {
798         return security_context_to_sid_core(scontext, scontext_len,
799                                             sid, def_sid);
800 }
801
802 static int compute_sid_handle_invalid_context(
803         struct context *scontext,
804         struct context *tcontext,
805         u16 tclass,
806         struct context *newcontext)
807 {
808         char *s = NULL, *t = NULL, *n = NULL;
809         u32 slen, tlen, nlen;
810
811         if (context_struct_to_string(scontext, &s, &slen) < 0)
812                 goto out;
813         if (context_struct_to_string(tcontext, &t, &tlen) < 0)
814                 goto out;
815         if (context_struct_to_string(newcontext, &n, &nlen) < 0)
816                 goto out;
817         audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
818                   "security_compute_sid:  invalid context %s"
819                   " for scontext=%s"
820                   " tcontext=%s"
821                   " tclass=%s",
822                   n, s, t, policydb.p_class_val_to_name[tclass-1]);
823 out:
824         kfree(s);
825         kfree(t);
826         kfree(n);
827         if (!selinux_enforcing)
828                 return 0;
829         return -EACCES;
830 }
831
832 static int security_compute_sid(u32 ssid,
833                                 u32 tsid,
834                                 u16 tclass,
835                                 u32 specified,
836                                 u32 *out_sid)
837 {
838         struct context *scontext = NULL, *tcontext = NULL, newcontext;
839         struct role_trans *roletr = NULL;
840         struct avtab_key avkey;
841         struct avtab_datum *avdatum;
842         struct avtab_node *node;
843         int rc = 0;
844
845         if (!ss_initialized) {
846                 switch (tclass) {
847                 case SECCLASS_PROCESS:
848                         *out_sid = ssid;
849                         break;
850                 default:
851                         *out_sid = tsid;
852                         break;
853                 }
854                 goto out;
855         }
856
857         context_init(&newcontext);
858
859         POLICY_RDLOCK;
860
861         scontext = sidtab_search(&sidtab, ssid);
862         if (!scontext) {
863                 printk(KERN_ERR "security_compute_sid:  unrecognized SID %d\n",
864                        ssid);
865                 rc = -EINVAL;
866                 goto out_unlock;
867         }
868         tcontext = sidtab_search(&sidtab, tsid);
869         if (!tcontext) {
870                 printk(KERN_ERR "security_compute_sid:  unrecognized SID %d\n",
871                        tsid);
872                 rc = -EINVAL;
873                 goto out_unlock;
874         }
875
876         /* Set the user identity. */
877         switch (specified) {
878         case AVTAB_TRANSITION:
879         case AVTAB_CHANGE:
880                 /* Use the process user identity. */
881                 newcontext.user = scontext->user;
882                 break;
883         case AVTAB_MEMBER:
884                 /* Use the related object owner. */
885                 newcontext.user = tcontext->user;
886                 break;
887         }
888
889         /* Set the role and type to default values. */
890         switch (tclass) {
891         case SECCLASS_PROCESS:
892                 /* Use the current role and type of process. */
893                 newcontext.role = scontext->role;
894                 newcontext.type = scontext->type;
895                 break;
896         default:
897                 /* Use the well-defined object role. */
898                 newcontext.role = OBJECT_R_VAL;
899                 /* Use the type of the related object. */
900                 newcontext.type = tcontext->type;
901         }
902
903         /* Look for a type transition/member/change rule. */
904         avkey.source_type = scontext->type;
905         avkey.target_type = tcontext->type;
906         avkey.target_class = tclass;
907         avkey.specified = specified;
908         avdatum = avtab_search(&policydb.te_avtab, &avkey);
909
910         /* If no permanent rule, also check for enabled conditional rules */
911         if(!avdatum) {
912                 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
913                 for (; node != NULL; node = avtab_search_node_next(node, specified)) {
914                         if (node->key.specified & AVTAB_ENABLED) {
915                                 avdatum = &node->datum;
916                                 break;
917                         }
918                 }
919         }
920
921         if (avdatum) {
922                 /* Use the type from the type transition/member/change rule. */
923                 newcontext.type = avdatum->data;
924         }
925
926         /* Check for class-specific changes. */
927         switch (tclass) {
928         case SECCLASS_PROCESS:
929                 if (specified & AVTAB_TRANSITION) {
930                         /* Look for a role transition rule. */
931                         for (roletr = policydb.role_tr; roletr;
932                              roletr = roletr->next) {
933                                 if (roletr->role == scontext->role &&
934                                     roletr->type == tcontext->type) {
935                                         /* Use the role transition rule. */
936                                         newcontext.role = roletr->new_role;
937                                         break;
938                                 }
939                         }
940                 }
941                 break;
942         default:
943                 break;
944         }
945
946         /* Set the MLS attributes.
947            This is done last because it may allocate memory. */
948         rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
949         if (rc)
950                 goto out_unlock;
951
952         /* Check the validity of the context. */
953         if (!policydb_context_isvalid(&policydb, &newcontext)) {
954                 rc = compute_sid_handle_invalid_context(scontext,
955                                                         tcontext,
956                                                         tclass,
957                                                         &newcontext);
958                 if (rc)
959                         goto out_unlock;
960         }
961         /* Obtain the sid for the context. */
962         rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
963 out_unlock:
964         POLICY_RDUNLOCK;
965         context_destroy(&newcontext);
966 out:
967         return rc;
968 }
969
970 /**
971  * security_transition_sid - Compute the SID for a new subject/object.
972  * @ssid: source security identifier
973  * @tsid: target security identifier
974  * @tclass: target security class
975  * @out_sid: security identifier for new subject/object
976  *
977  * Compute a SID to use for labeling a new subject or object in the
978  * class @tclass based on a SID pair (@ssid, @tsid).
979  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
980  * if insufficient memory is available, or %0 if the new SID was
981  * computed successfully.
982  */
983 int security_transition_sid(u32 ssid,
984                             u32 tsid,
985                             u16 tclass,
986                             u32 *out_sid)
987 {
988         return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
989 }
990
991 /**
992  * security_member_sid - Compute the SID for member selection.
993  * @ssid: source security identifier
994  * @tsid: target security identifier
995  * @tclass: target security class
996  * @out_sid: security identifier for selected member
997  *
998  * Compute a SID to use when selecting a member of a polyinstantiated
999  * object of class @tclass based on a SID pair (@ssid, @tsid).
1000  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1001  * if insufficient memory is available, or %0 if the SID was
1002  * computed successfully.
1003  */
1004 int security_member_sid(u32 ssid,
1005                         u32 tsid,
1006                         u16 tclass,
1007                         u32 *out_sid)
1008 {
1009         return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1010 }
1011
1012 /**
1013  * security_change_sid - Compute the SID for object relabeling.
1014  * @ssid: source security identifier
1015  * @tsid: target security identifier
1016  * @tclass: target security class
1017  * @out_sid: security identifier for selected member
1018  *
1019  * Compute a SID to use for relabeling an object of class @tclass
1020  * based on a SID pair (@ssid, @tsid).
1021  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1022  * if insufficient memory is available, or %0 if the SID was
1023  * computed successfully.
1024  */
1025 int security_change_sid(u32 ssid,
1026                         u32 tsid,
1027                         u16 tclass,
1028                         u32 *out_sid)
1029 {
1030         return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1031 }
1032
1033 /*
1034  * Verify that each kernel class that is defined in the
1035  * policy is correct
1036  */
1037 static int validate_classes(struct policydb *p)
1038 {
1039         int i, j;
1040         struct class_datum *cladatum;
1041         struct perm_datum *perdatum;
1042         u32 nprim, tmp, common_pts_len, perm_val, pol_val;
1043         u16 class_val;
1044         const struct selinux_class_perm *kdefs = &selinux_class_perm;
1045         const char *def_class, *def_perm, *pol_class;
1046         struct symtab *perms;
1047
1048         for (i = 1; i < kdefs->cts_len; i++) {
1049                 def_class = kdefs->class_to_string[i];
1050                 if (i > p->p_classes.nprim) {
1051                         printk(KERN_INFO
1052                                "security:  class %s not defined in policy\n",
1053                                def_class);
1054                         continue;
1055                 }
1056                 pol_class = p->p_class_val_to_name[i-1];
1057                 if (strcmp(pol_class, def_class)) {
1058                         printk(KERN_ERR
1059                                "security:  class %d is incorrect, found %s but should be %s\n",
1060                                i, pol_class, def_class);
1061                         return -EINVAL;
1062                 }
1063         }
1064         for (i = 0; i < kdefs->av_pts_len; i++) {
1065                 class_val = kdefs->av_perm_to_string[i].tclass;
1066                 perm_val = kdefs->av_perm_to_string[i].value;
1067                 def_perm = kdefs->av_perm_to_string[i].name;
1068                 if (class_val > p->p_classes.nprim)
1069                         continue;
1070                 pol_class = p->p_class_val_to_name[class_val-1];
1071                 cladatum = hashtab_search(p->p_classes.table, pol_class);
1072                 BUG_ON(!cladatum);
1073                 perms = &cladatum->permissions;
1074                 nprim = 1 << (perms->nprim - 1);
1075                 if (perm_val > nprim) {
1076                         printk(KERN_INFO
1077                                "security:  permission %s in class %s not defined in policy\n",
1078                                def_perm, pol_class);
1079                         continue;
1080                 }
1081                 perdatum = hashtab_search(perms->table, def_perm);
1082                 if (perdatum == NULL) {
1083                         printk(KERN_ERR
1084                                "security:  permission %s in class %s not found in policy\n",
1085                                def_perm, pol_class);
1086                         return -EINVAL;
1087                 }
1088                 pol_val = 1 << (perdatum->value - 1);
1089                 if (pol_val != perm_val) {
1090                         printk(KERN_ERR
1091                                "security:  permission %s in class %s has incorrect value\n",
1092                                def_perm, pol_class);
1093                         return -EINVAL;
1094                 }
1095         }
1096         for (i = 0; i < kdefs->av_inherit_len; i++) {
1097                 class_val = kdefs->av_inherit[i].tclass;
1098                 if (class_val > p->p_classes.nprim)
1099                         continue;
1100                 pol_class = p->p_class_val_to_name[class_val-1];
1101                 cladatum = hashtab_search(p->p_classes.table, pol_class);
1102                 BUG_ON(!cladatum);
1103                 if (!cladatum->comdatum) {
1104                         printk(KERN_ERR
1105                                "security:  class %s should have an inherits clause but does not\n",
1106                                pol_class);
1107                         return -EINVAL;
1108                 }
1109                 tmp = kdefs->av_inherit[i].common_base;
1110                 common_pts_len = 0;
1111                 while (!(tmp & 0x01)) {
1112                         common_pts_len++;
1113                         tmp >>= 1;
1114                 }
1115                 perms = &cladatum->comdatum->permissions;
1116                 for (j = 0; j < common_pts_len; j++) {
1117                         def_perm = kdefs->av_inherit[i].common_pts[j];
1118                         if (j >= perms->nprim) {
1119                                 printk(KERN_INFO
1120                                        "security:  permission %s in class %s not defined in policy\n",
1121                                        def_perm, pol_class);
1122                                 continue;
1123                         }
1124                         perdatum = hashtab_search(perms->table, def_perm);
1125                         if (perdatum == NULL) {
1126                                 printk(KERN_ERR
1127                                        "security:  permission %s in class %s not found in policy\n",
1128                                        def_perm, pol_class);
1129                                 return -EINVAL;
1130                         }
1131                         if (perdatum->value != j + 1) {
1132                                 printk(KERN_ERR
1133                                        "security:  permission %s in class %s has incorrect value\n",
1134                                        def_perm, pol_class);
1135                                 return -EINVAL;
1136                         }
1137                 }
1138         }
1139         return 0;
1140 }
1141
1142 /* Clone the SID into the new SID table. */
1143 static int clone_sid(u32 sid,
1144                      struct context *context,
1145                      void *arg)
1146 {
1147         struct sidtab *s = arg;
1148
1149         return sidtab_insert(s, sid, context);
1150 }
1151
1152 static inline int convert_context_handle_invalid_context(struct context *context)
1153 {
1154         int rc = 0;
1155
1156         if (selinux_enforcing) {
1157                 rc = -EINVAL;
1158         } else {
1159                 char *s;
1160                 u32 len;
1161
1162                 context_struct_to_string(context, &s, &len);
1163                 printk(KERN_ERR "security:  context %s is invalid\n", s);
1164                 kfree(s);
1165         }
1166         return rc;
1167 }
1168
1169 struct convert_context_args {
1170         struct policydb *oldp;
1171         struct policydb *newp;
1172 };
1173
1174 /*
1175  * Convert the values in the security context
1176  * structure `c' from the values specified
1177  * in the policy `p->oldp' to the values specified
1178  * in the policy `p->newp'.  Verify that the
1179  * context is valid under the new policy.
1180  */
1181 static int convert_context(u32 key,
1182                            struct context *c,
1183                            void *p)
1184 {
1185         struct convert_context_args *args;
1186         struct context oldc;
1187         struct role_datum *role;
1188         struct type_datum *typdatum;
1189         struct user_datum *usrdatum;
1190         char *s;
1191         u32 len;
1192         int rc;
1193
1194         args = p;
1195
1196         rc = context_cpy(&oldc, c);
1197         if (rc)
1198                 goto out;
1199
1200         rc = -EINVAL;
1201
1202         /* Convert the user. */
1203         usrdatum = hashtab_search(args->newp->p_users.table,
1204                                   args->oldp->p_user_val_to_name[c->user - 1]);
1205         if (!usrdatum) {
1206                 goto bad;
1207         }
1208         c->user = usrdatum->value;
1209
1210         /* Convert the role. */
1211         role = hashtab_search(args->newp->p_roles.table,
1212                               args->oldp->p_role_val_to_name[c->role - 1]);
1213         if (!role) {
1214                 goto bad;
1215         }
1216         c->role = role->value;
1217
1218         /* Convert the type. */
1219         typdatum = hashtab_search(args->newp->p_types.table,
1220                                   args->oldp->p_type_val_to_name[c->type - 1]);
1221         if (!typdatum) {
1222                 goto bad;
1223         }
1224         c->type = typdatum->value;
1225
1226         rc = mls_convert_context(args->oldp, args->newp, c);
1227         if (rc)
1228                 goto bad;
1229
1230         /* Check the validity of the new context. */
1231         if (!policydb_context_isvalid(args->newp, c)) {
1232                 rc = convert_context_handle_invalid_context(&oldc);
1233                 if (rc)
1234                         goto bad;
1235         }
1236
1237         context_destroy(&oldc);
1238 out:
1239         return rc;
1240 bad:
1241         context_struct_to_string(&oldc, &s, &len);
1242         context_destroy(&oldc);
1243         printk(KERN_ERR "security:  invalidating context %s\n", s);
1244         kfree(s);
1245         goto out;
1246 }
1247
1248 extern void selinux_complete_init(void);
1249
1250 /**
1251  * security_load_policy - Load a security policy configuration.
1252  * @data: binary policy data
1253  * @len: length of data in bytes
1254  *
1255  * Load a new set of security policy configuration data,
1256  * validate it and convert the SID table as necessary.
1257  * This function will flush the access vector cache after
1258  * loading the new policy.
1259  */
1260 int security_load_policy(void *data, size_t len)
1261 {
1262         struct policydb oldpolicydb, newpolicydb;
1263         struct sidtab oldsidtab, newsidtab;
1264         struct convert_context_args args;
1265         u32 seqno;
1266         int rc = 0;
1267         struct policy_file file = { data, len }, *fp = &file;
1268
1269         LOAD_LOCK;
1270
1271         if (!ss_initialized) {
1272                 avtab_cache_init();
1273                 if (policydb_read(&policydb, fp)) {
1274                         LOAD_UNLOCK;
1275                         avtab_cache_destroy();
1276                         return -EINVAL;
1277                 }
1278                 if (policydb_load_isids(&policydb, &sidtab)) {
1279                         LOAD_UNLOCK;
1280                         policydb_destroy(&policydb);
1281                         avtab_cache_destroy();
1282                         return -EINVAL;
1283                 }
1284                 /* Verify that the kernel defined classes are correct. */
1285                 if (validate_classes(&policydb)) {
1286                         printk(KERN_ERR
1287                                "security:  the definition of a class is incorrect\n");
1288                         LOAD_UNLOCK;
1289                         sidtab_destroy(&sidtab);
1290                         policydb_destroy(&policydb);
1291                         avtab_cache_destroy();
1292                         return -EINVAL;
1293                 }
1294                 policydb_loaded_version = policydb.policyvers;
1295                 ss_initialized = 1;
1296                 seqno = ++latest_granting;
1297                 LOAD_UNLOCK;
1298                 selinux_complete_init();
1299                 avc_ss_reset(seqno);
1300                 selnl_notify_policyload(seqno);
1301                 selinux_netlbl_cache_invalidate();
1302                 return 0;
1303         }
1304
1305 #if 0
1306         sidtab_hash_eval(&sidtab, "sids");
1307 #endif
1308
1309         if (policydb_read(&newpolicydb, fp)) {
1310                 LOAD_UNLOCK;
1311                 return -EINVAL;
1312         }
1313
1314         sidtab_init(&newsidtab);
1315
1316         /* Verify that the kernel defined classes are correct. */
1317         if (validate_classes(&newpolicydb)) {
1318                 printk(KERN_ERR
1319                        "security:  the definition of a class is incorrect\n");
1320                 rc = -EINVAL;
1321                 goto err;
1322         }
1323
1324         /* Clone the SID table. */
1325         sidtab_shutdown(&sidtab);
1326         if (sidtab_map(&sidtab, clone_sid, &newsidtab)) {
1327                 rc = -ENOMEM;
1328                 goto err;
1329         }
1330
1331         /* Convert the internal representations of contexts
1332            in the new SID table and remove invalid SIDs. */
1333         args.oldp = &policydb;
1334         args.newp = &newpolicydb;
1335         sidtab_map_remove_on_error(&newsidtab, convert_context, &args);
1336
1337         /* Save the old policydb and SID table to free later. */
1338         memcpy(&oldpolicydb, &policydb, sizeof policydb);
1339         sidtab_set(&oldsidtab, &sidtab);
1340
1341         /* Install the new policydb and SID table. */
1342         POLICY_WRLOCK;
1343         memcpy(&policydb, &newpolicydb, sizeof policydb);
1344         sidtab_set(&sidtab, &newsidtab);
1345         seqno = ++latest_granting;
1346         policydb_loaded_version = policydb.policyvers;
1347         POLICY_WRUNLOCK;
1348         LOAD_UNLOCK;
1349
1350         /* Free the old policydb and SID table. */
1351         policydb_destroy(&oldpolicydb);
1352         sidtab_destroy(&oldsidtab);
1353
1354         avc_ss_reset(seqno);
1355         selnl_notify_policyload(seqno);
1356         selinux_netlbl_cache_invalidate();
1357
1358         return 0;
1359
1360 err:
1361         LOAD_UNLOCK;
1362         sidtab_destroy(&newsidtab);
1363         policydb_destroy(&newpolicydb);
1364         return rc;
1365
1366 }
1367
1368 /**
1369  * security_port_sid - Obtain the SID for a port.
1370  * @domain: communication domain aka address family
1371  * @type: socket type
1372  * @protocol: protocol number
1373  * @port: port number
1374  * @out_sid: security identifier
1375  */
1376 int security_port_sid(u16 domain,
1377                       u16 type,
1378                       u8 protocol,
1379                       u16 port,
1380                       u32 *out_sid)
1381 {
1382         struct ocontext *c;
1383         int rc = 0;
1384
1385         POLICY_RDLOCK;
1386
1387         c = policydb.ocontexts[OCON_PORT];
1388         while (c) {
1389                 if (c->u.port.protocol == protocol &&
1390                     c->u.port.low_port <= port &&
1391                     c->u.port.high_port >= port)
1392                         break;
1393                 c = c->next;
1394         }
1395
1396         if (c) {
1397                 if (!c->sid[0]) {
1398                         rc = sidtab_context_to_sid(&sidtab,
1399                                                    &c->context[0],
1400                                                    &c->sid[0]);
1401                         if (rc)
1402                                 goto out;
1403                 }
1404                 *out_sid = c->sid[0];
1405         } else {
1406                 *out_sid = SECINITSID_PORT;
1407         }
1408
1409 out:
1410         POLICY_RDUNLOCK;
1411         return rc;
1412 }
1413
1414 /**
1415  * security_netif_sid - Obtain the SID for a network interface.
1416  * @name: interface name
1417  * @if_sid: interface SID
1418  * @msg_sid: default SID for received packets
1419  */
1420 int security_netif_sid(char *name,
1421                        u32 *if_sid,
1422                        u32 *msg_sid)
1423 {
1424         int rc = 0;
1425         struct ocontext *c;
1426
1427         POLICY_RDLOCK;
1428
1429         c = policydb.ocontexts[OCON_NETIF];
1430         while (c) {
1431                 if (strcmp(name, c->u.name) == 0)
1432                         break;
1433                 c = c->next;
1434         }
1435
1436         if (c) {
1437                 if (!c->sid[0] || !c->sid[1]) {
1438                         rc = sidtab_context_to_sid(&sidtab,
1439                                                   &c->context[0],
1440                                                   &c->sid[0]);
1441                         if (rc)
1442                                 goto out;
1443                         rc = sidtab_context_to_sid(&sidtab,
1444                                                    &c->context[1],
1445                                                    &c->sid[1]);
1446                         if (rc)
1447                                 goto out;
1448                 }
1449                 *if_sid = c->sid[0];
1450                 *msg_sid = c->sid[1];
1451         } else {
1452                 *if_sid = SECINITSID_NETIF;
1453                 *msg_sid = SECINITSID_NETMSG;
1454         }
1455
1456 out:
1457         POLICY_RDUNLOCK;
1458         return rc;
1459 }
1460
1461 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1462 {
1463         int i, fail = 0;
1464
1465         for(i = 0; i < 4; i++)
1466                 if(addr[i] != (input[i] & mask[i])) {
1467                         fail = 1;
1468                         break;
1469                 }
1470
1471         return !fail;
1472 }
1473
1474 /**
1475  * security_node_sid - Obtain the SID for a node (host).
1476  * @domain: communication domain aka address family
1477  * @addrp: address
1478  * @addrlen: address length in bytes
1479  * @out_sid: security identifier
1480  */
1481 int security_node_sid(u16 domain,
1482                       void *addrp,
1483                       u32 addrlen,
1484                       u32 *out_sid)
1485 {
1486         int rc = 0;
1487         struct ocontext *c;
1488
1489         POLICY_RDLOCK;
1490
1491         switch (domain) {
1492         case AF_INET: {
1493                 u32 addr;
1494
1495                 if (addrlen != sizeof(u32)) {
1496                         rc = -EINVAL;
1497                         goto out;
1498                 }
1499
1500                 addr = *((u32 *)addrp);
1501
1502                 c = policydb.ocontexts[OCON_NODE];
1503                 while (c) {
1504                         if (c->u.node.addr == (addr & c->u.node.mask))
1505                                 break;
1506                         c = c->next;
1507                 }
1508                 break;
1509         }
1510
1511         case AF_INET6:
1512                 if (addrlen != sizeof(u64) * 2) {
1513                         rc = -EINVAL;
1514                         goto out;
1515                 }
1516                 c = policydb.ocontexts[OCON_NODE6];
1517                 while (c) {
1518                         if (match_ipv6_addrmask(addrp, c->u.node6.addr,
1519                                                 c->u.node6.mask))
1520                                 break;
1521                         c = c->next;
1522                 }
1523                 break;
1524
1525         default:
1526                 *out_sid = SECINITSID_NODE;
1527                 goto out;
1528         }
1529
1530         if (c) {
1531                 if (!c->sid[0]) {
1532                         rc = sidtab_context_to_sid(&sidtab,
1533                                                    &c->context[0],
1534                                                    &c->sid[0]);
1535                         if (rc)
1536                                 goto out;
1537                 }
1538                 *out_sid = c->sid[0];
1539         } else {
1540                 *out_sid = SECINITSID_NODE;
1541         }
1542
1543 out:
1544         POLICY_RDUNLOCK;
1545         return rc;
1546 }
1547
1548 #define SIDS_NEL 25
1549
1550 /**
1551  * security_get_user_sids - Obtain reachable SIDs for a user.
1552  * @fromsid: starting SID
1553  * @username: username
1554  * @sids: array of reachable SIDs for user
1555  * @nel: number of elements in @sids
1556  *
1557  * Generate the set of SIDs for legal security contexts
1558  * for a given user that can be reached by @fromsid.
1559  * Set *@sids to point to a dynamically allocated
1560  * array containing the set of SIDs.  Set *@nel to the
1561  * number of elements in the array.
1562  */
1563
1564 int security_get_user_sids(u32 fromsid,
1565                            char *username,
1566                            u32 **sids,
1567                            u32 *nel)
1568 {
1569         struct context *fromcon, usercon;
1570         u32 *mysids, *mysids2, sid;
1571         u32 mynel = 0, maxnel = SIDS_NEL;
1572         struct user_datum *user;
1573         struct role_datum *role;
1574         struct av_decision avd;
1575         struct ebitmap_node *rnode, *tnode;
1576         int rc = 0, i, j;
1577
1578         if (!ss_initialized) {
1579                 *sids = NULL;
1580                 *nel = 0;
1581                 goto out;
1582         }
1583
1584         POLICY_RDLOCK;
1585
1586         fromcon = sidtab_search(&sidtab, fromsid);
1587         if (!fromcon) {
1588                 rc = -EINVAL;
1589                 goto out_unlock;
1590         }
1591
1592         user = hashtab_search(policydb.p_users.table, username);
1593         if (!user) {
1594                 rc = -EINVAL;
1595                 goto out_unlock;
1596         }
1597         usercon.user = user->value;
1598
1599         mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
1600         if (!mysids) {
1601                 rc = -ENOMEM;
1602                 goto out_unlock;
1603         }
1604
1605         ebitmap_for_each_bit(&user->roles, rnode, i) {
1606                 if (!ebitmap_node_get_bit(rnode, i))
1607                         continue;
1608                 role = policydb.role_val_to_struct[i];
1609                 usercon.role = i+1;
1610                 ebitmap_for_each_bit(&role->types, tnode, j) {
1611                         if (!ebitmap_node_get_bit(tnode, j))
1612                                 continue;
1613                         usercon.type = j+1;
1614
1615                         if (mls_setup_user_range(fromcon, user, &usercon))
1616                                 continue;
1617
1618                         rc = context_struct_compute_av(fromcon, &usercon,
1619                                                        SECCLASS_PROCESS,
1620                                                        PROCESS__TRANSITION,
1621                                                        &avd);
1622                         if (rc ||  !(avd.allowed & PROCESS__TRANSITION))
1623                                 continue;
1624                         rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
1625                         if (rc) {
1626                                 kfree(mysids);
1627                                 goto out_unlock;
1628                         }
1629                         if (mynel < maxnel) {
1630                                 mysids[mynel++] = sid;
1631                         } else {
1632                                 maxnel += SIDS_NEL;
1633                                 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
1634                                 if (!mysids2) {
1635                                         rc = -ENOMEM;
1636                                         kfree(mysids);
1637                                         goto out_unlock;
1638                                 }
1639                                 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
1640                                 kfree(mysids);
1641                                 mysids = mysids2;
1642                                 mysids[mynel++] = sid;
1643                         }
1644                 }
1645         }
1646
1647         *sids = mysids;
1648         *nel = mynel;
1649
1650 out_unlock:
1651         POLICY_RDUNLOCK;
1652 out:
1653         return rc;
1654 }
1655
1656 /**
1657  * security_genfs_sid - Obtain a SID for a file in a filesystem
1658  * @fstype: filesystem type
1659  * @path: path from root of mount
1660  * @sclass: file security class
1661  * @sid: SID for path
1662  *
1663  * Obtain a SID to use for a file in a filesystem that
1664  * cannot support xattr or use a fixed labeling behavior like
1665  * transition SIDs or task SIDs.
1666  */
1667 int security_genfs_sid(const char *fstype,
1668                        char *path,
1669                        u16 sclass,
1670                        u32 *sid)
1671 {
1672         int len;
1673         struct genfs *genfs;
1674         struct ocontext *c;
1675         int rc = 0, cmp = 0;
1676
1677         POLICY_RDLOCK;
1678
1679         for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
1680                 cmp = strcmp(fstype, genfs->fstype);
1681                 if (cmp <= 0)
1682                         break;
1683         }
1684
1685         if (!genfs || cmp) {
1686                 *sid = SECINITSID_UNLABELED;
1687                 rc = -ENOENT;
1688                 goto out;
1689         }
1690
1691         for (c = genfs->head; c; c = c->next) {
1692                 len = strlen(c->u.name);
1693                 if ((!c->v.sclass || sclass == c->v.sclass) &&
1694                     (strncmp(c->u.name, path, len) == 0))
1695                         break;
1696         }
1697
1698         if (!c) {
1699                 *sid = SECINITSID_UNLABELED;
1700                 rc = -ENOENT;
1701                 goto out;
1702         }
1703
1704         if (!c->sid[0]) {
1705                 rc = sidtab_context_to_sid(&sidtab,
1706                                            &c->context[0],
1707                                            &c->sid[0]);
1708                 if (rc)
1709                         goto out;
1710         }
1711
1712         *sid = c->sid[0];
1713 out:
1714         POLICY_RDUNLOCK;
1715         return rc;
1716 }
1717
1718 /**
1719  * security_fs_use - Determine how to handle labeling for a filesystem.
1720  * @fstype: filesystem type
1721  * @behavior: labeling behavior
1722  * @sid: SID for filesystem (superblock)
1723  */
1724 int security_fs_use(
1725         const char *fstype,
1726         unsigned int *behavior,
1727         u32 *sid)
1728 {
1729         int rc = 0;
1730         struct ocontext *c;
1731
1732         POLICY_RDLOCK;
1733
1734         c = policydb.ocontexts[OCON_FSUSE];
1735         while (c) {
1736                 if (strcmp(fstype, c->u.name) == 0)
1737                         break;
1738                 c = c->next;
1739         }
1740
1741         if (c) {
1742                 *behavior = c->v.behavior;
1743                 if (!c->sid[0]) {
1744                         rc = sidtab_context_to_sid(&sidtab,
1745                                                    &c->context[0],
1746                                                    &c->sid[0]);
1747                         if (rc)
1748                                 goto out;
1749                 }
1750                 *sid = c->sid[0];
1751         } else {
1752                 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
1753                 if (rc) {
1754                         *behavior = SECURITY_FS_USE_NONE;
1755                         rc = 0;
1756                 } else {
1757                         *behavior = SECURITY_FS_USE_GENFS;
1758                 }
1759         }
1760
1761 out:
1762         POLICY_RDUNLOCK;
1763         return rc;
1764 }
1765
1766 int security_get_bools(int *len, char ***names, int **values)
1767 {
1768         int i, rc = -ENOMEM;
1769
1770         POLICY_RDLOCK;
1771         *names = NULL;
1772         *values = NULL;
1773
1774         *len = policydb.p_bools.nprim;
1775         if (!*len) {
1776                 rc = 0;
1777                 goto out;
1778         }
1779
1780        *names = kcalloc(*len, sizeof(char*), GFP_ATOMIC);
1781         if (!*names)
1782                 goto err;
1783
1784        *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
1785         if (!*values)
1786                 goto err;
1787
1788         for (i = 0; i < *len; i++) {
1789                 size_t name_len;
1790                 (*values)[i] = policydb.bool_val_to_struct[i]->state;
1791                 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
1792                (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
1793                 if (!(*names)[i])
1794                         goto err;
1795                 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
1796                 (*names)[i][name_len - 1] = 0;
1797         }
1798         rc = 0;
1799 out:
1800         POLICY_RDUNLOCK;
1801         return rc;
1802 err:
1803         if (*names) {
1804                 for (i = 0; i < *len; i++)
1805                         kfree((*names)[i]);
1806         }
1807         kfree(*values);
1808         goto out;
1809 }
1810
1811
1812 int security_set_bools(int len, int *values)
1813 {
1814         int i, rc = 0;
1815         int lenp, seqno = 0;
1816         struct cond_node *cur;
1817
1818         POLICY_WRLOCK;
1819
1820         lenp = policydb.p_bools.nprim;
1821         if (len != lenp) {
1822                 rc = -EFAULT;
1823                 goto out;
1824         }
1825
1826         for (i = 0; i < len; i++) {
1827                 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
1828                         audit_log(current->audit_context, GFP_ATOMIC,
1829                                 AUDIT_MAC_CONFIG_CHANGE,
1830                                 "bool=%s val=%d old_val=%d auid=%u",
1831                                 policydb.p_bool_val_to_name[i],
1832                                 !!values[i],
1833                                 policydb.bool_val_to_struct[i]->state,
1834                                 audit_get_loginuid(current->audit_context));
1835                 }
1836                 if (values[i]) {
1837                         policydb.bool_val_to_struct[i]->state = 1;
1838                 } else {
1839                         policydb.bool_val_to_struct[i]->state = 0;
1840                 }
1841         }
1842
1843         for (cur = policydb.cond_list; cur != NULL; cur = cur->next) {
1844                 rc = evaluate_cond_node(&policydb, cur);
1845                 if (rc)
1846                         goto out;
1847         }
1848
1849         seqno = ++latest_granting;
1850
1851 out:
1852         POLICY_WRUNLOCK;
1853         if (!rc) {
1854                 avc_ss_reset(seqno);
1855                 selnl_notify_policyload(seqno);
1856         }
1857         return rc;
1858 }
1859
1860 int security_get_bool_value(int bool)
1861 {
1862         int rc = 0;
1863         int len;
1864
1865         POLICY_RDLOCK;
1866
1867         len = policydb.p_bools.nprim;
1868         if (bool >= len) {
1869                 rc = -EFAULT;
1870                 goto out;
1871         }
1872
1873         rc = policydb.bool_val_to_struct[bool]->state;
1874 out:
1875         POLICY_RDUNLOCK;
1876         return rc;
1877 }
1878
1879 /*
1880  * security_sid_mls_copy() - computes a new sid based on the given
1881  * sid and the mls portion of mls_sid.
1882  */
1883 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
1884 {
1885         struct context *context1;
1886         struct context *context2;
1887         struct context newcon;
1888         char *s;
1889         u32 len;
1890         int rc = 0;
1891
1892         if (!ss_initialized || !selinux_mls_enabled) {
1893                 *new_sid = sid;
1894                 goto out;
1895         }
1896
1897         context_init(&newcon);
1898
1899         POLICY_RDLOCK;
1900         context1 = sidtab_search(&sidtab, sid);
1901         if (!context1) {
1902                 printk(KERN_ERR "security_sid_mls_copy:  unrecognized SID "
1903                        "%d\n", sid);
1904                 rc = -EINVAL;
1905                 goto out_unlock;
1906         }
1907
1908         context2 = sidtab_search(&sidtab, mls_sid);
1909         if (!context2) {
1910                 printk(KERN_ERR "security_sid_mls_copy:  unrecognized SID "
1911                        "%d\n", mls_sid);
1912                 rc = -EINVAL;
1913                 goto out_unlock;
1914         }
1915
1916         newcon.user = context1->user;
1917         newcon.role = context1->role;
1918         newcon.type = context1->type;
1919         rc = mls_context_cpy(&newcon, context2);
1920         if (rc)
1921                 goto out_unlock;
1922
1923         /* Check the validity of the new context. */
1924         if (!policydb_context_isvalid(&policydb, &newcon)) {
1925                 rc = convert_context_handle_invalid_context(&newcon);
1926                 if (rc)
1927                         goto bad;
1928         }
1929
1930         rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
1931         goto out_unlock;
1932
1933 bad:
1934         if (!context_struct_to_string(&newcon, &s, &len)) {
1935                 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1936                           "security_sid_mls_copy: invalid context %s", s);
1937                 kfree(s);
1938         }
1939
1940 out_unlock:
1941         POLICY_RDUNLOCK;
1942         context_destroy(&newcon);
1943 out:
1944         return rc;
1945 }
1946
1947 struct selinux_audit_rule {
1948         u32 au_seqno;
1949         struct context au_ctxt;
1950 };
1951
1952 void selinux_audit_rule_free(struct selinux_audit_rule *rule)
1953 {
1954         if (rule) {
1955                 context_destroy(&rule->au_ctxt);
1956                 kfree(rule);
1957         }
1958 }
1959
1960 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr,
1961                             struct selinux_audit_rule **rule)
1962 {
1963         struct selinux_audit_rule *tmprule;
1964         struct role_datum *roledatum;
1965         struct type_datum *typedatum;
1966         struct user_datum *userdatum;
1967         int rc = 0;
1968
1969         *rule = NULL;
1970
1971         if (!ss_initialized)
1972                 return -ENOTSUPP;
1973
1974         switch (field) {
1975         case AUDIT_SUBJ_USER:
1976         case AUDIT_SUBJ_ROLE:
1977         case AUDIT_SUBJ_TYPE:
1978         case AUDIT_OBJ_USER:
1979         case AUDIT_OBJ_ROLE:
1980         case AUDIT_OBJ_TYPE:
1981                 /* only 'equals' and 'not equals' fit user, role, and type */
1982                 if (op != AUDIT_EQUAL && op != AUDIT_NOT_EQUAL)
1983                         return -EINVAL;
1984                 break;
1985         case AUDIT_SUBJ_SEN:
1986         case AUDIT_SUBJ_CLR:
1987         case AUDIT_OBJ_LEV_LOW:
1988         case AUDIT_OBJ_LEV_HIGH:
1989                 /* we do not allow a range, indicated by the presense of '-' */
1990                 if (strchr(rulestr, '-'))
1991                         return -EINVAL;
1992                 break;
1993         default:
1994                 /* only the above fields are valid */
1995                 return -EINVAL;
1996         }
1997
1998         tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
1999         if (!tmprule)
2000                 return -ENOMEM;
2001
2002         context_init(&tmprule->au_ctxt);
2003
2004         POLICY_RDLOCK;
2005
2006         tmprule->au_seqno = latest_granting;
2007
2008         switch (field) {
2009         case AUDIT_SUBJ_USER:
2010         case AUDIT_OBJ_USER:
2011                 userdatum = hashtab_search(policydb.p_users.table, rulestr);
2012                 if (!userdatum)
2013                         rc = -EINVAL;
2014                 else
2015                         tmprule->au_ctxt.user = userdatum->value;
2016                 break;
2017         case AUDIT_SUBJ_ROLE:
2018         case AUDIT_OBJ_ROLE:
2019                 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
2020                 if (!roledatum)
2021                         rc = -EINVAL;
2022                 else
2023                         tmprule->au_ctxt.role = roledatum->value;
2024                 break;
2025         case AUDIT_SUBJ_TYPE:
2026         case AUDIT_OBJ_TYPE:
2027                 typedatum = hashtab_search(policydb.p_types.table, rulestr);
2028                 if (!typedatum)
2029                         rc = -EINVAL;
2030                 else
2031                         tmprule->au_ctxt.type = typedatum->value;
2032                 break;
2033         case AUDIT_SUBJ_SEN:
2034         case AUDIT_SUBJ_CLR:
2035         case AUDIT_OBJ_LEV_LOW:
2036         case AUDIT_OBJ_LEV_HIGH:
2037                 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
2038                 break;
2039         }
2040
2041         POLICY_RDUNLOCK;
2042
2043         if (rc) {
2044                 selinux_audit_rule_free(tmprule);
2045                 tmprule = NULL;
2046         }
2047
2048         *rule = tmprule;
2049
2050         return rc;
2051 }
2052
2053 int selinux_audit_rule_match(u32 sid, u32 field, u32 op,
2054                              struct selinux_audit_rule *rule,
2055                              struct audit_context *actx)
2056 {
2057         struct context *ctxt;
2058         struct mls_level *level;
2059         int match = 0;
2060
2061         if (!rule) {
2062                 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2063                           "selinux_audit_rule_match: missing rule\n");
2064                 return -ENOENT;
2065         }
2066
2067         POLICY_RDLOCK;
2068
2069         if (rule->au_seqno < latest_granting) {
2070                 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2071                           "selinux_audit_rule_match: stale rule\n");
2072                 match = -ESTALE;
2073                 goto out;
2074         }
2075
2076         ctxt = sidtab_search(&sidtab, sid);
2077         if (!ctxt) {
2078                 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
2079                           "selinux_audit_rule_match: unrecognized SID %d\n",
2080                           sid);
2081                 match = -ENOENT;
2082                 goto out;
2083         }
2084
2085         /* a field/op pair that is not caught here will simply fall through
2086            without a match */
2087         switch (field) {
2088         case AUDIT_SUBJ_USER:
2089         case AUDIT_OBJ_USER:
2090                 switch (op) {
2091                 case AUDIT_EQUAL:
2092                         match = (ctxt->user == rule->au_ctxt.user);
2093                         break;
2094                 case AUDIT_NOT_EQUAL:
2095                         match = (ctxt->user != rule->au_ctxt.user);
2096                         break;
2097                 }
2098                 break;
2099         case AUDIT_SUBJ_ROLE:
2100         case AUDIT_OBJ_ROLE:
2101                 switch (op) {
2102                 case AUDIT_EQUAL:
2103                         match = (ctxt->role == rule->au_ctxt.role);
2104                         break;
2105                 case AUDIT_NOT_EQUAL:
2106                         match = (ctxt->role != rule->au_ctxt.role);
2107                         break;
2108                 }
2109                 break;
2110         case AUDIT_SUBJ_TYPE:
2111         case AUDIT_OBJ_TYPE:
2112                 switch (op) {
2113                 case AUDIT_EQUAL:
2114                         match = (ctxt->type == rule->au_ctxt.type);
2115                         break;
2116                 case AUDIT_NOT_EQUAL:
2117                         match = (ctxt->type != rule->au_ctxt.type);
2118                         break;
2119                 }
2120                 break;
2121         case AUDIT_SUBJ_SEN:
2122         case AUDIT_SUBJ_CLR:
2123         case AUDIT_OBJ_LEV_LOW:
2124         case AUDIT_OBJ_LEV_HIGH:
2125                 level = ((field == AUDIT_SUBJ_SEN ||
2126                           field == AUDIT_OBJ_LEV_LOW) ?
2127                          &ctxt->range.level[0] : &ctxt->range.level[1]);
2128                 switch (op) {
2129                 case AUDIT_EQUAL:
2130                         match = mls_level_eq(&rule->au_ctxt.range.level[0],
2131                                              level);
2132                         break;
2133                 case AUDIT_NOT_EQUAL:
2134                         match = !mls_level_eq(&rule->au_ctxt.range.level[0],
2135                                               level);
2136                         break;
2137                 case AUDIT_LESS_THAN:
2138                         match = (mls_level_dom(&rule->au_ctxt.range.level[0],
2139                                                level) &&
2140                                  !mls_level_eq(&rule->au_ctxt.range.level[0],
2141                                                level));
2142                         break;
2143                 case AUDIT_LESS_THAN_OR_EQUAL:
2144                         match = mls_level_dom(&rule->au_ctxt.range.level[0],
2145                                               level);
2146                         break;
2147                 case AUDIT_GREATER_THAN:
2148                         match = (mls_level_dom(level,
2149                                               &rule->au_ctxt.range.level[0]) &&
2150                                  !mls_level_eq(level,
2151                                                &rule->au_ctxt.range.level[0]));
2152                         break;
2153                 case AUDIT_GREATER_THAN_OR_EQUAL:
2154                         match = mls_level_dom(level,
2155                                               &rule->au_ctxt.range.level[0]);
2156                         break;
2157                 }
2158         }
2159
2160 out:
2161         POLICY_RDUNLOCK;
2162         return match;
2163 }
2164
2165 static int (*aurule_callback)(void) = NULL;
2166
2167 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2168                                u16 class, u32 perms, u32 *retained)
2169 {
2170         int err = 0;
2171
2172         if (event == AVC_CALLBACK_RESET && aurule_callback)
2173                 err = aurule_callback();
2174         return err;
2175 }
2176
2177 static int __init aurule_init(void)
2178 {
2179         int err;
2180
2181         err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2182                                SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2183         if (err)
2184                 panic("avc_add_callback() failed, error %d\n", err);
2185
2186         return err;
2187 }
2188 __initcall(aurule_init);
2189
2190 void selinux_audit_set_callback(int (*callback)(void))
2191 {
2192         aurule_callback = callback;
2193 }
2194
2195 /**
2196  * security_skb_extlbl_sid - Determine the external label of a packet
2197  * @skb: the packet
2198  * @base_sid: the SELinux SID to use as a context for MLS only external labels
2199  * @sid: the packet's SID
2200  *
2201  * Description:
2202  * Check the various different forms of external packet labeling and determine
2203  * the external SID for the packet.
2204  *
2205  */
2206 void security_skb_extlbl_sid(struct sk_buff *skb, u32 base_sid, u32 *sid)
2207 {
2208         u32 xfrm_sid;
2209         u32 nlbl_sid;
2210
2211         selinux_skb_xfrm_sid(skb, &xfrm_sid);
2212         if (selinux_netlbl_skbuff_getsid(skb,
2213                                          (xfrm_sid == SECSID_NULL ?
2214                                           base_sid : xfrm_sid),
2215                                          &nlbl_sid) != 0)
2216                 nlbl_sid = SECSID_NULL;
2217
2218         *sid = (nlbl_sid == SECSID_NULL ? xfrm_sid : nlbl_sid);
2219 }
2220
2221 #ifdef CONFIG_NETLABEL
2222 /*
2223  * This is the structure we store inside the NetLabel cache block.
2224  */
2225 #define NETLBL_CACHE(x)           ((struct netlbl_cache *)(x))
2226 #define NETLBL_CACHE_T_NONE       0
2227 #define NETLBL_CACHE_T_SID        1
2228 #define NETLBL_CACHE_T_MLS        2
2229 struct netlbl_cache {
2230         u32 type;
2231         union {
2232                 u32 sid;
2233                 struct mls_range mls_label;
2234         } data;
2235 };
2236
2237 /**
2238  * selinux_netlbl_cache_free - Free the NetLabel cached data
2239  * @data: the data to free
2240  *
2241  * Description:
2242  * This function is intended to be used as the free() callback inside the
2243  * netlbl_lsm_cache structure.
2244  *
2245  */
2246 static void selinux_netlbl_cache_free(const void *data)
2247 {
2248         struct netlbl_cache *cache;
2249
2250         if (data == NULL)
2251                 return;
2252
2253         cache = NETLBL_CACHE(data);
2254         switch (cache->type) {
2255         case NETLBL_CACHE_T_MLS:
2256                 ebitmap_destroy(&cache->data.mls_label.level[0].cat);
2257                 break;
2258         }
2259         kfree(data);
2260 }
2261
2262 /**
2263  * selinux_netlbl_cache_add - Add an entry to the NetLabel cache
2264  * @skb: the packet
2265  * @ctx: the SELinux context
2266  *
2267  * Description:
2268  * Attempt to cache the context in @ctx, which was derived from the packet in
2269  * @skb, in the NetLabel subsystem cache.
2270  *
2271  */
2272 static void selinux_netlbl_cache_add(struct sk_buff *skb, struct context *ctx)
2273 {
2274         struct netlbl_cache *cache = NULL;
2275         struct netlbl_lsm_secattr secattr;
2276
2277         netlbl_secattr_init(&secattr);
2278         secattr.cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
2279         if (secattr.cache == NULL)
2280                 goto netlbl_cache_add_return;
2281
2282         cache = kzalloc(sizeof(*cache), GFP_ATOMIC);
2283         if (cache == NULL)
2284                 goto netlbl_cache_add_return;
2285
2286         cache->type = NETLBL_CACHE_T_MLS;
2287         if (ebitmap_cpy(&cache->data.mls_label.level[0].cat,
2288                         &ctx->range.level[0].cat) != 0)
2289                 goto netlbl_cache_add_return;
2290         cache->data.mls_label.level[1].cat.highbit =
2291                 cache->data.mls_label.level[0].cat.highbit;
2292         cache->data.mls_label.level[1].cat.node =
2293                 cache->data.mls_label.level[0].cat.node;
2294         cache->data.mls_label.level[0].sens = ctx->range.level[0].sens;
2295         cache->data.mls_label.level[1].sens = ctx->range.level[0].sens;
2296
2297         secattr.cache->free = selinux_netlbl_cache_free;
2298         secattr.cache->data = (void *)cache;
2299         secattr.flags = NETLBL_SECATTR_CACHE;
2300
2301         netlbl_cache_add(skb, &secattr);
2302
2303 netlbl_cache_add_return:
2304         netlbl_secattr_destroy(&secattr);
2305 }
2306
2307 /**
2308  * selinux_netlbl_cache_invalidate - Invalidate the NetLabel cache
2309  *
2310  * Description:
2311  * Invalidate the NetLabel security attribute mapping cache.
2312  *
2313  */
2314 void selinux_netlbl_cache_invalidate(void)
2315 {
2316         netlbl_cache_invalidate();
2317 }
2318
2319 /**
2320  * selinux_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
2321  * @skb: the network packet
2322  * @secattr: the NetLabel packet security attributes
2323  * @base_sid: the SELinux SID to use as a context for MLS only attributes
2324  * @sid: the SELinux SID
2325  *
2326  * Description:
2327  * Convert the given NetLabel packet security attributes in @secattr into a
2328  * SELinux SID.  If the @secattr field does not contain a full SELinux
2329  * SID/context then use the context in @base_sid as the foundation.  If @skb
2330  * is not NULL attempt to cache as much data as possibile.  Returns zero on
2331  * success, negative values on failure.
2332  *
2333  */
2334 static int selinux_netlbl_secattr_to_sid(struct sk_buff *skb,
2335                                          struct netlbl_lsm_secattr *secattr,
2336                                          u32 base_sid,
2337                                          u32 *sid)
2338 {
2339         int rc = -EIDRM;
2340         struct context *ctx;
2341         struct context ctx_new;
2342         struct netlbl_cache *cache;
2343
2344         POLICY_RDLOCK;
2345
2346         if (secattr->flags & NETLBL_SECATTR_CACHE) {
2347                 cache = NETLBL_CACHE(secattr->cache->data);
2348                 switch (cache->type) {
2349                 case NETLBL_CACHE_T_SID:
2350                         *sid = cache->data.sid;
2351                         rc = 0;
2352                         break;
2353                 case NETLBL_CACHE_T_MLS:
2354                         ctx = sidtab_search(&sidtab, base_sid);
2355                         if (ctx == NULL)
2356                                 goto netlbl_secattr_to_sid_return;
2357
2358                         ctx_new.user = ctx->user;
2359                         ctx_new.role = ctx->role;
2360                         ctx_new.type = ctx->type;
2361                         ctx_new.range.level[0].sens =
2362                                 cache->data.mls_label.level[0].sens;
2363                         ctx_new.range.level[0].cat.highbit =
2364                                 cache->data.mls_label.level[0].cat.highbit;
2365                         ctx_new.range.level[0].cat.node =
2366                                 cache->data.mls_label.level[0].cat.node;
2367                         ctx_new.range.level[1].sens =
2368                                 cache->data.mls_label.level[1].sens;
2369                         ctx_new.range.level[1].cat.highbit =
2370                                 cache->data.mls_label.level[1].cat.highbit;
2371                         ctx_new.range.level[1].cat.node =
2372                                 cache->data.mls_label.level[1].cat.node;
2373
2374                         rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
2375                         break;
2376                 default:
2377                         goto netlbl_secattr_to_sid_return;
2378                 }
2379         } else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
2380                 ctx = sidtab_search(&sidtab, base_sid);
2381                 if (ctx == NULL)
2382                         goto netlbl_secattr_to_sid_return;
2383
2384                 ctx_new.user = ctx->user;
2385                 ctx_new.role = ctx->role;
2386                 ctx_new.type = ctx->type;
2387                 mls_import_netlbl_lvl(&ctx_new, secattr);
2388                 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
2389                         if (ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
2390                                                   secattr->mls_cat) != 0)
2391                                 goto netlbl_secattr_to_sid_return;
2392                         ctx_new.range.level[1].cat.highbit =
2393                                 ctx_new.range.level[0].cat.highbit;
2394                         ctx_new.range.level[1].cat.node =
2395                                 ctx_new.range.level[0].cat.node;
2396                 } else {
2397                         ebitmap_init(&ctx_new.range.level[0].cat);
2398                         ebitmap_init(&ctx_new.range.level[1].cat);
2399                 }
2400                 if (mls_context_isvalid(&policydb, &ctx_new) != 1)
2401                         goto netlbl_secattr_to_sid_return_cleanup;
2402
2403                 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
2404                 if (rc != 0)
2405                         goto netlbl_secattr_to_sid_return_cleanup;
2406
2407                 if (skb != NULL)
2408                         selinux_netlbl_cache_add(skb, &ctx_new);
2409                 ebitmap_destroy(&ctx_new.range.level[0].cat);
2410         } else {
2411                 *sid = SECSID_NULL;
2412                 rc = 0;
2413         }
2414
2415 netlbl_secattr_to_sid_return:
2416         POLICY_RDUNLOCK;
2417         return rc;
2418 netlbl_secattr_to_sid_return_cleanup:
2419         ebitmap_destroy(&ctx_new.range.level[0].cat);
2420         goto netlbl_secattr_to_sid_return;
2421 }
2422
2423 /**
2424  * selinux_netlbl_skbuff_getsid - Get the sid of a packet using NetLabel
2425  * @skb: the packet
2426  * @base_sid: the SELinux SID to use as a context for MLS only attributes
2427  * @sid: the SID
2428  *
2429  * Description:
2430  * Call the NetLabel mechanism to get the security attributes of the given
2431  * packet and use those attributes to determine the correct context/SID to
2432  * assign to the packet.  Returns zero on success, negative values on failure.
2433  *
2434  */
2435 int selinux_netlbl_skbuff_getsid(struct sk_buff *skb, u32 base_sid, u32 *sid)
2436 {
2437         int rc;
2438         struct netlbl_lsm_secattr secattr;
2439
2440         netlbl_secattr_init(&secattr);
2441         rc = netlbl_skbuff_getattr(skb, &secattr);
2442         if (rc == 0 && secattr.flags != NETLBL_SECATTR_NONE)
2443                 rc = selinux_netlbl_secattr_to_sid(skb,
2444                                                    &secattr,
2445                                                    base_sid,
2446                                                    sid);
2447         else
2448                 *sid = SECSID_NULL;
2449         netlbl_secattr_destroy(&secattr);
2450
2451         return rc;
2452 }
2453
2454 /**
2455  * selinux_netlbl_socket_setsid - Label a socket using the NetLabel mechanism
2456  * @sock: the socket to label
2457  * @sid: the SID to use
2458  *
2459  * Description:
2460  * Attempt to label a socket using the NetLabel mechanism using the given
2461  * SID.  Returns zero values on success, negative values on failure.  The
2462  * caller is responsibile for calling rcu_read_lock() before calling this
2463  * this function and rcu_read_unlock() after this function returns.
2464  *
2465  */
2466 static int selinux_netlbl_socket_setsid(struct socket *sock, u32 sid)
2467 {
2468         int rc = -ENOENT;
2469         struct sk_security_struct *sksec = sock->sk->sk_security;
2470         struct netlbl_lsm_secattr secattr;
2471         struct context *ctx;
2472
2473         if (!ss_initialized)
2474                 return 0;
2475
2476         netlbl_secattr_init(&secattr);
2477
2478         POLICY_RDLOCK;
2479
2480         ctx = sidtab_search(&sidtab, sid);
2481         if (ctx == NULL)
2482                 goto netlbl_socket_setsid_return;
2483
2484         secattr.domain = kstrdup(policydb.p_type_val_to_name[ctx->type - 1],
2485                                  GFP_ATOMIC);
2486         secattr.flags |= NETLBL_SECATTR_DOMAIN;
2487         mls_export_netlbl_lvl(ctx, &secattr);
2488         rc = mls_export_netlbl_cat(ctx, &secattr);
2489         if (rc != 0)
2490                 goto netlbl_socket_setsid_return;
2491
2492         rc = netlbl_socket_setattr(sock, &secattr);
2493         if (rc == 0) {
2494                 spin_lock(&sksec->nlbl_lock);
2495                 sksec->nlbl_state = NLBL_LABELED;
2496                 spin_unlock(&sksec->nlbl_lock);
2497         }
2498
2499 netlbl_socket_setsid_return:
2500         POLICY_RDUNLOCK;
2501         netlbl_secattr_destroy(&secattr);
2502         return rc;
2503 }
2504
2505 /**
2506  * selinux_netlbl_sk_security_reset - Reset the NetLabel fields
2507  * @ssec: the sk_security_struct
2508  * @family: the socket family
2509  *
2510  * Description:
2511  * Called when the NetLabel state of a sk_security_struct needs to be reset.
2512  * The caller is responsibile for all the NetLabel sk_security_struct locking.
2513  *
2514  */
2515 void selinux_netlbl_sk_security_reset(struct sk_security_struct *ssec,
2516                                       int family)
2517 {
2518         if (family == PF_INET)
2519                 ssec->nlbl_state = NLBL_REQUIRE;
2520         else
2521                 ssec->nlbl_state = NLBL_UNSET;
2522 }
2523
2524 /**
2525  * selinux_netlbl_sk_security_init - Setup the NetLabel fields
2526  * @ssec: the sk_security_struct
2527  * @family: the socket family
2528  *
2529  * Description:
2530  * Called when a new sk_security_struct is allocated to initialize the NetLabel
2531  * fields.
2532  *
2533  */
2534 void selinux_netlbl_sk_security_init(struct sk_security_struct *ssec,
2535                                      int family)
2536 {
2537         /* No locking needed, we are the only one who has access to ssec */
2538         selinux_netlbl_sk_security_reset(ssec, family);
2539         spin_lock_init(&ssec->nlbl_lock);
2540 }
2541
2542 /**
2543  * selinux_netlbl_sk_security_clone - Copy the NetLabel fields
2544  * @ssec: the original sk_security_struct
2545  * @newssec: the cloned sk_security_struct
2546  *
2547  * Description:
2548  * Clone the NetLabel specific sk_security_struct fields from @ssec to
2549  * @newssec.
2550  *
2551  */
2552 void selinux_netlbl_sk_security_clone(struct sk_security_struct *ssec,
2553                                       struct sk_security_struct *newssec)
2554 {
2555         /* We don't need to take newssec->nlbl_lock because we are the only
2556          * thread with access to newssec, but we do need to take the RCU read
2557          * lock as other threads could have access to ssec */
2558         rcu_read_lock();
2559         selinux_netlbl_sk_security_reset(newssec, ssec->sk->sk_family);
2560         newssec->sclass = ssec->sclass;
2561         rcu_read_unlock();
2562 }
2563
2564 /**
2565  * selinux_netlbl_socket_post_create - Label a socket using NetLabel
2566  * @sock: the socket to label
2567  *
2568  * Description:
2569  * Attempt to label a socket using the NetLabel mechanism using the given
2570  * SID.  Returns zero values on success, negative values on failure.
2571  *
2572  */
2573 int selinux_netlbl_socket_post_create(struct socket *sock)
2574 {
2575         int rc = 0;
2576         struct inode_security_struct *isec = SOCK_INODE(sock)->i_security;
2577         struct sk_security_struct *sksec = sock->sk->sk_security;
2578
2579         sksec->sclass = isec->sclass;
2580
2581         rcu_read_lock();
2582         if (sksec->nlbl_state == NLBL_REQUIRE)
2583                 rc = selinux_netlbl_socket_setsid(sock, sksec->sid);
2584         rcu_read_unlock();
2585
2586         return rc;
2587 }
2588
2589 /**
2590  * selinux_netlbl_sock_graft - Netlabel the new socket
2591  * @sk: the new connection
2592  * @sock: the new socket
2593  *
2594  * Description:
2595  * The connection represented by @sk is being grafted onto @sock so set the
2596  * socket's NetLabel to match the SID of @sk.
2597  *
2598  */
2599 void selinux_netlbl_sock_graft(struct sock *sk, struct socket *sock)
2600 {
2601         struct inode_security_struct *isec = SOCK_INODE(sock)->i_security;
2602         struct sk_security_struct *sksec = sk->sk_security;
2603         struct netlbl_lsm_secattr secattr;
2604         u32 nlbl_peer_sid;
2605
2606         sksec->sclass = isec->sclass;
2607
2608         rcu_read_lock();
2609
2610         if (sksec->nlbl_state != NLBL_REQUIRE) {
2611                 rcu_read_unlock();
2612                 return;
2613         }
2614
2615         netlbl_secattr_init(&secattr);
2616         if (netlbl_sock_getattr(sk, &secattr) == 0 &&
2617             secattr.flags != NETLBL_SECATTR_NONE &&
2618             selinux_netlbl_secattr_to_sid(NULL,
2619                                           &secattr,
2620                                           SECINITSID_UNLABELED,
2621                                           &nlbl_peer_sid) == 0)
2622                 sksec->peer_sid = nlbl_peer_sid;
2623         netlbl_secattr_destroy(&secattr);
2624
2625         /* Try to set the NetLabel on the socket to save time later, if we fail
2626          * here we will pick up the pieces in later calls to
2627          * selinux_netlbl_inode_permission(). */
2628         selinux_netlbl_socket_setsid(sock, sksec->sid);
2629
2630         rcu_read_unlock();
2631 }
2632
2633 /**
2634  * selinux_netlbl_inode_permission - Verify the socket is NetLabel labeled
2635  * @inode: the file descriptor's inode
2636  * @mask: the permission mask
2637  *
2638  * Description:
2639  * Looks at a file's inode and if it is marked as a socket protected by
2640  * NetLabel then verify that the socket has been labeled, if not try to label
2641  * the socket now with the inode's SID.  Returns zero on success, negative
2642  * values on failure.
2643  *
2644  */
2645 int selinux_netlbl_inode_permission(struct inode *inode, int mask)
2646 {
2647         int rc;
2648         struct sk_security_struct *sksec;
2649         struct socket *sock;
2650
2651         if (!S_ISSOCK(inode->i_mode) ||
2652             ((mask & (MAY_WRITE | MAY_APPEND)) == 0))
2653                 return 0;
2654         sock = SOCKET_I(inode);
2655         sksec = sock->sk->sk_security;
2656
2657         rcu_read_lock();
2658         if (sksec->nlbl_state != NLBL_REQUIRE) {
2659                 rcu_read_unlock();
2660                 return 0;
2661         }
2662         local_bh_disable();
2663         bh_lock_sock_nested(sock->sk);
2664         rc = selinux_netlbl_socket_setsid(sock, sksec->sid);
2665         bh_unlock_sock(sock->sk);
2666         local_bh_enable();
2667         rcu_read_unlock();
2668
2669         return rc;
2670 }
2671
2672 /**
2673  * selinux_netlbl_sock_rcv_skb - Do an inbound access check using NetLabel
2674  * @sksec: the sock's sk_security_struct
2675  * @skb: the packet
2676  * @ad: the audit data
2677  *
2678  * Description:
2679  * Fetch the NetLabel security attributes from @skb and perform an access check
2680  * against the receiving socket.  Returns zero on success, negative values on
2681  * error.
2682  *
2683  */
2684 int selinux_netlbl_sock_rcv_skb(struct sk_security_struct *sksec,
2685                                 struct sk_buff *skb,
2686                                 struct avc_audit_data *ad)
2687 {
2688         int rc;
2689         u32 netlbl_sid;
2690         u32 recv_perm;
2691
2692         rc = selinux_netlbl_skbuff_getsid(skb,
2693                                           SECINITSID_UNLABELED,
2694                                           &netlbl_sid);
2695         if (rc != 0)
2696                 return rc;
2697
2698         if (netlbl_sid == SECSID_NULL)
2699                 return 0;
2700
2701         switch (sksec->sclass) {
2702         case SECCLASS_UDP_SOCKET:
2703                 recv_perm = UDP_SOCKET__RECVFROM;
2704                 break;
2705         case SECCLASS_TCP_SOCKET:
2706                 recv_perm = TCP_SOCKET__RECVFROM;
2707                 break;
2708         default:
2709                 recv_perm = RAWIP_SOCKET__RECVFROM;
2710         }
2711
2712         rc = avc_has_perm(sksec->sid,
2713                           netlbl_sid,
2714                           sksec->sclass,
2715                           recv_perm,
2716                           ad);
2717         if (rc == 0)
2718                 return 0;
2719
2720         netlbl_skbuff_err(skb, rc);
2721         return rc;
2722 }
2723
2724 /**
2725  * selinux_netlbl_socket_setsockopt - Do not allow users to remove a NetLabel
2726  * @sock: the socket
2727  * @level: the socket level or protocol
2728  * @optname: the socket option name
2729  *
2730  * Description:
2731  * Check the setsockopt() call and if the user is trying to replace the IP
2732  * options on a socket and a NetLabel is in place for the socket deny the
2733  * access; otherwise allow the access.  Returns zero when the access is
2734  * allowed, -EACCES when denied, and other negative values on error.
2735  *
2736  */
2737 int selinux_netlbl_socket_setsockopt(struct socket *sock,
2738                                      int level,
2739                                      int optname)
2740 {
2741         int rc = 0;
2742         struct sk_security_struct *sksec = sock->sk->sk_security;
2743         struct netlbl_lsm_secattr secattr;
2744
2745         rcu_read_lock();
2746         if (level == IPPROTO_IP && optname == IP_OPTIONS &&
2747             sksec->nlbl_state == NLBL_LABELED) {
2748                 netlbl_secattr_init(&secattr);
2749                 rc = netlbl_socket_getattr(sock, &secattr);
2750                 if (rc == 0 && secattr.flags != NETLBL_SECATTR_NONE)
2751                         rc = -EACCES;
2752                 netlbl_secattr_destroy(&secattr);
2753         }
2754         rcu_read_unlock();
2755
2756         return rc;
2757 }
2758 #endif /* CONFIG_NETLABEL */