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