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