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